5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "68"
7 #define RELEASE_DATE "15 November 2004"
8 #define VERSION VERSION_MAJOR "." VERSION_MINOR
15 #include <sys/types.h>
25 #define MAX_CWD_SIZE 4096
26 #define MAX_ALLOCATION_PASSES 100
28 #define DEBUG_CONSISTENCY 1
29 #define DEBUG_SDP_BLOCKS 0
30 #define DEBUG_TRIPLE_COLOR 0
32 #define DEBUG_DISPLAY_USES 1
33 #define DEBUG_DISPLAY_TYPES 1
34 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
35 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
36 #define DEBUG_DECOMPOSE_HIRES 0
37 #define DEBUG_INITIALIZER 0
38 #define DEBUG_UPDATE_CLOSURE_TYPE 0
39 #define DEBUG_LOCAL_TRIPLE 0
40 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
41 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
42 #define DEBUG_SIMPLIFY_HIRES 0
43 #define DEBUG_SHRINKING 0
44 #define DEBUG_COALESCE_HITCHES 0
45 #define DEBUG_CODE_ELIMINATION 0
47 #define DEBUG_EXPLICIT_CLOSURES 0
49 #warning "FIXME give clear error messages about unused variables"
50 #warning "FIXME properly handle multi dimensional arrays"
51 #warning "FIXME handle multiple register sizes"
53 /* Control flow graph of a loop without goto.
64 * |\ GGG HHH | continue;
92 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
93 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
96 * [] == DFlocal(X) U DF(X)
99 * Dominator graph of the same nodes.
103 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
105 * CCC CCC: [ ] ( BBB, JJJ )
107 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
109 * FFF FFF: [ ] ( BBB )
111 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
113 * III III: [ BBB ] ()
116 * BBB and JJJ are definitely the dominance frontier.
117 * Where do I place phi functions and how do I make that decision.
120 static void die(char *fmt, ...)
125 vfprintf(stderr, fmt, args);
132 static void *xmalloc(size_t size, const char *name)
137 die("Cannot malloc %ld bytes to hold %s: %s\n",
138 size + 0UL, name, strerror(errno));
143 static void *xcmalloc(size_t size, const char *name)
146 buf = xmalloc(size, name);
147 memset(buf, 0, size);
151 static void *xrealloc(void *ptr, size_t size, const char *name)
154 buf = realloc(ptr, size);
156 die("Cannot realloc %ld bytes to hold %s: %s\n",
157 size + 0UL, name, strerror(errno));
162 static void xfree(const void *ptr)
167 static char *xstrdup(const char *str)
172 new = xmalloc(len + 1, "xstrdup string");
173 memcpy(new, str, len);
178 static void xchdir(const char *path)
180 if (chdir(path) != 0) {
181 die("chdir to `%s' failed: %s\n",
182 path, strerror(errno));
186 static int exists(const char *dirname, const char *filename)
188 char cwd[MAX_CWD_SIZE];
191 if (getcwd(cwd, sizeof(cwd)) == 0) {
192 die("cwd buffer to small");
196 if (chdir(dirname) != 0) {
199 if (does_exist && (access(filename, O_RDONLY) < 0)) {
200 if ((errno != EACCES) && (errno != EROFS)) {
209 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
211 char cwd[MAX_CWD_SIZE];
214 off_t size, progress;
222 if (getcwd(cwd, sizeof(cwd)) == 0) {
223 die("cwd buffer to small");
226 fd = open(filename, O_RDONLY);
229 die("Cannot open '%s' : %s\n",
230 filename, strerror(errno));
232 result = fstat(fd, &stats);
234 die("Cannot stat: %s: %s\n",
235 filename, strerror(errno));
237 size = stats.st_size;
239 buf = xmalloc(size +2, filename);
240 buf[size] = '\n'; /* Make certain the file is newline terminated */
241 buf[size+1] = '\0'; /* Null terminate the file for good measure */
243 while(progress < size) {
244 result = read(fd, buf + progress, size - progress);
246 if ((errno == EINTR) || (errno == EAGAIN))
248 die("read on %s of %ld bytes failed: %s\n",
249 filename, (size - progress)+ 0UL, strerror(errno));
255 die("Close of %s failed: %s\n",
256 filename, strerror(errno));
261 /* Types on the destination platform */
262 #warning "FIXME this assumes 32bit x86 is the destination"
263 typedef int8_t schar_t;
264 typedef uint8_t uchar_t;
265 typedef int8_t char_t;
266 typedef int16_t short_t;
267 typedef uint16_t ushort_t;
268 typedef int32_t int_t;
269 typedef uint32_t uint_t;
270 typedef int32_t long_t;
271 typedef uint32_t ulong_t;
273 #define SCHAR_T_MIN (-128)
274 #define SCHAR_T_MAX 127
275 #define UCHAR_T_MAX 255
276 #define CHAR_T_MIN SCHAR_T_MIN
277 #define CHAR_T_MAX SCHAR_T_MAX
278 #define SHRT_T_MIN (-32768)
279 #define SHRT_T_MAX 32767
280 #define USHRT_T_MAX 65535
281 #define INT_T_MIN (-LONG_T_MAX - 1)
282 #define INT_T_MAX 2147483647
283 #define UINT_T_MAX 4294967295U
284 #define LONG_T_MIN (-LONG_T_MAX - 1)
285 #define LONG_T_MAX 2147483647
286 #define ULONG_T_MAX 4294967295U
289 #define SIZEOF_I16 16
290 #define SIZEOF_I32 32
291 #define SIZEOF_I64 64
293 #define SIZEOF_CHAR 8
294 #define SIZEOF_SHORT 16
295 #define SIZEOF_INT 32
296 #define SIZEOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
299 #define ALIGNOF_CHAR 8
300 #define ALIGNOF_SHORT 16
301 #define ALIGNOF_INT 32
302 #define ALIGNOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
304 #define REG_SIZEOF_REG 32
305 #define REG_SIZEOF_CHAR REG_SIZEOF_REG
306 #define REG_SIZEOF_SHORT REG_SIZEOF_REG
307 #define REG_SIZEOF_INT REG_SIZEOF_REG
308 #define REG_SIZEOF_LONG REG_SIZEOF_REG
310 #define REG_ALIGNOF_REG REG_SIZEOF_REG
311 #define REG_ALIGNOF_CHAR REG_SIZEOF_REG
312 #define REG_ALIGNOF_SHORT REG_SIZEOF_REG
313 #define REG_ALIGNOF_INT REG_SIZEOF_REG
314 #define REG_ALIGNOF_LONG REG_SIZEOF_REG
316 /* Additional definitions for clarity.
317 * I currently assume a long is the largest native
318 * machine word and that a pointer fits into it.
320 #define SIZEOF_WORD SIZEOF_LONG
321 #define SIZEOF_POINTER SIZEOF_LONG
322 #define ALIGNOF_WORD ALIGNOF_LONG
323 #define ALIGNOF_POINTER ALIGNOF_LONG
324 #define REG_SIZEOF_POINTER REG_SIZEOF_LONG
325 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
328 struct file_state *prev;
329 const char *basename;
335 const char *line_start;
337 const char *report_name;
338 const char *report_dir;
346 struct hash_entry *ident;
356 /* I have two classes of types:
358 * Logical types. (The type the C standard says the operation is of)
360 * The operational types are:
375 * No memory is useable by the compiler.
376 * There is no floating point support.
377 * All operations take place in general purpose registers.
378 * There is one type of general purpose register.
379 * Unsigned longs are stored in that general purpose register.
382 /* Operations on general purpose registers.
401 #define OP_POS 16 /* Dummy positive operator don't use it */
411 #define OP_SLESSEQ 26
412 #define OP_ULESSEQ 27
413 #define OP_SMOREEQ 28
414 #define OP_UMOREEQ 29
416 #define OP_LFALSE 30 /* Test if the expression is logically false */
417 #define OP_LTRUE 31 /* Test if the expression is logcially true */
421 /* For OP_STORE ->type holds the type
422 * RHS(0) holds the destination address
423 * RHS(1) holds the value to store.
426 #define OP_UEXTRACT 34
427 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
428 * RHS(0) holds the psuedo register to extract from
429 * ->type holds the size of the bitfield.
430 * ->u.bitfield.size holds the size of the bitfield.
431 * ->u.bitfield.offset holds the offset to extract from
433 #define OP_SEXTRACT 35
434 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
435 * RHS(0) holds the psuedo register to extract from
436 * ->type holds the size of the bitfield.
437 * ->u.bitfield.size holds the size of the bitfield.
438 * ->u.bitfield.offset holds the offset to extract from
440 #define OP_DEPOSIT 36
441 /* OP_DEPOSIT replaces a bitfield with a new value.
442 * RHS(0) holds the value to replace a bitifield in.
443 * RHS(1) holds the replacement value
444 * ->u.bitfield.size holds the size of the bitfield.
445 * ->u.bitfield.offset holds the deposit into
450 #define OP_MIN_CONST 50
451 #define OP_MAX_CONST 58
452 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
453 #define OP_INTCONST 50
454 /* For OP_INTCONST ->type holds the type.
455 * ->u.cval holds the constant value.
457 #define OP_BLOBCONST 51
458 /* For OP_BLOBCONST ->type holds the layout and size
459 * information. u.blob holds a pointer to the raw binary
460 * data for the constant initializer.
462 #define OP_ADDRCONST 52
463 /* For OP_ADDRCONST ->type holds the type.
464 * MISC(0) holds the reference to the static variable.
465 * ->u.cval holds an offset from that value.
467 #define OP_UNKNOWNVAL 59
468 /* For OP_UNKNOWNAL ->type holds the type.
469 * For some reason we don't know what value this type has.
470 * This allows for variables that have don't have values
471 * assigned yet, or variables whose value we simply do not know.
475 /* OP_WRITE moves one pseudo register to another.
476 * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
477 * RHS(0) holds the psuedo to move.
481 /* OP_READ reads the value of a variable and makes
482 * it available for the pseudo operation.
483 * Useful for things like def-use chains.
484 * RHS(0) holds points to the triple to read from.
487 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
489 #define OP_CONVERT 63
490 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
491 * And then the type is converted appropriately.
494 /* OP_PIECE returns one piece of a instruction that returns a structure.
495 * MISC(0) is the instruction
496 * u.cval is the LHS piece of the instruction to return.
499 /* OP_ASM holds a sequence of assembly instructions, the result
500 * of a C asm directive.
501 * RHS(x) holds input value x to the assembly sequence.
502 * LHS(x) holds the output value x from the assembly sequence.
503 * u.blob holds the string of assembly instructions.
507 /* OP_DEREF generates an lvalue from a pointer.
508 * RHS(0) holds the pointer value.
509 * OP_DEREF serves as a place holder to indicate all necessary
510 * checks have been done to indicate a value is an lvalue.
513 /* OP_DOT references a submember of a structure lvalue.
514 * MISC(0) holds the lvalue.
515 * ->u.field holds the name of the field we want.
517 * Not seen after structures are flattened.
520 /* OP_INDEX references a submember of a tuple or array lvalue.
521 * MISC(0) holds the lvalue.
522 * ->u.cval holds the index into the lvalue.
524 * Not seen after structures are flattened.
527 /* OP_VAL returns the value of a subexpression of the current expression.
528 * Useful for operators that have side effects.
529 * RHS(0) holds the expression.
530 * MISC(0) holds the subexpression of RHS(0) that is the
531 * value of the expression.
533 * Not seen outside of expressions.
537 /* OP_TUPLE is an array of triples that are either variable
538 * or values for a structure or an array. It is used as
539 * a place holder when flattening compound types.
540 * The value represented by an OP_TUPLE is held in N registers.
541 * LHS(0..N-1) refer to those registers.
542 * ->use is a list of statements that use the value.
544 * Although OP_TUPLE always has register sized pieces they are not
545 * used until structures are flattened/decomposed into their register
547 * ???? registers ????
551 /* OP_BITREF describes a bitfield as an lvalue.
552 * RHS(0) holds the register value.
553 * ->type holds the type of the bitfield.
554 * ->u.bitfield.size holds the size of the bitfield.
555 * ->u.bitfield.offset holds the offset of the bitfield in the register
560 /* OP_FCALL performs a procedure call.
561 * MISC(0) holds a pointer to the OP_LIST of a function
562 * RHS(x) holds argument x of a function
564 * Currently not seen outside of expressions.
567 /* OP_PROG is an expression that holds a list of statements, or
568 * expressions. The final expression is the value of the expression.
569 * RHS(0) holds the start of the list.
574 /* OP_LIST Holds a list of statements that compose a function, and a result value.
575 * RHS(0) holds the list of statements.
576 * A list of all functions is maintained.
579 #define OP_BRANCH 81 /* an unconditional branch */
580 /* For branch instructions
581 * TARG(0) holds the branch target.
582 * ->next holds where to branch to if the branch is not taken.
583 * The branch target can only be a label
586 #define OP_CBRANCH 82 /* a conditional branch */
587 /* For conditional branch instructions
588 * RHS(0) holds the branch condition.
589 * TARG(0) holds the branch target.
590 * ->next holds where to branch to if the branch is not taken.
591 * The branch target can only be a label
594 #define OP_CALL 83 /* an uncontional branch that will return */
595 /* For call instructions
596 * MISC(0) holds the OP_RET that returns from the branch
597 * TARG(0) holds the branch target.
598 * ->next holds where to branch to if the branch is not taken.
599 * The branch target can only be a label
602 #define OP_RET 84 /* an uncontinonal branch through a variable back to an OP_CALL */
603 /* For call instructions
604 * RHS(0) holds the variable with the return address
605 * The branch target can only be a label
609 /* OP_LABEL is a triple that establishes an target for branches.
610 * ->use is the list of all branches that use this label.
614 /* OP_ADECL is a triple that establishes an lvalue for assignments.
615 * A variable takes N registers to contain.
616 * LHS(0..N-1) refer to an OP_PIECE triple that represents
617 * the Xth register that the variable is stored in.
618 * ->use is a list of statements that use the variable.
620 * Although OP_ADECL always has register sized pieces they are not
621 * used until structures are flattened/decomposed into their register
626 /* OP_SDECL is a triple that establishes a variable of static
628 * ->use is a list of statements that use the variable.
629 * MISC(0) holds the initializer expression.
634 /* OP_PHI is a triple used in SSA form code.
635 * It is used when multiple code paths merge and a variable needs
636 * a single assignment from any of those code paths.
637 * The operation is a cross between OP_DECL and OP_WRITE, which
638 * is what OP_PHI is generated from.
640 * RHS(x) points to the value from code path x
641 * The number of RHS entries is the number of control paths into the block
642 * in which OP_PHI resides. The elements of the array point to point
643 * to the variables OP_PHI is derived from.
645 * MISC(0) holds a pointer to the orginal OP_DECL node.
649 /* continuation helpers
651 #define OP_CPS_BRANCH 90 /* an unconditional branch */
652 /* OP_CPS_BRANCH calls a continuation
653 * RHS(x) holds argument x of the function
654 * TARG(0) holds OP_CPS_START target
656 #define OP_CPS_CBRANCH 91 /* a conditional branch */
657 /* OP_CPS_CBRANCH conditionally calls one of two continuations
658 * RHS(0) holds the branch condition
659 * RHS(x + 1) holds argument x of the function
660 * TARG(0) holds the OP_CPS_START to jump to when true
661 * ->next holds the OP_CPS_START to jump to when false
663 #define OP_CPS_CALL 92 /* an uncontional branch that will return */
664 /* For OP_CPS_CALL instructions
665 * RHS(x) holds argument x of the function
666 * MISC(0) holds the OP_CPS_RET that returns from the branch
667 * TARG(0) holds the branch target.
668 * ->next holds where the OP_CPS_RET will return to.
670 #define OP_CPS_RET 93
671 /* OP_CPS_RET conditionally calls one of two continuations
672 * RHS(0) holds the variable with the return function address
673 * RHS(x + 1) holds argument x of the function
674 * The branch target may be any OP_CPS_START
676 #define OP_CPS_END 94
677 /* OP_CPS_END is the triple at the end of the program.
678 * For most practical purposes it is a branch.
680 #define OP_CPS_START 95
681 /* OP_CPS_START is a triple at the start of a continuation
682 * The arguments variables takes N registers to contain.
683 * LHS(0..N-1) refer to an OP_PIECE triple that represents
684 * the Xth register that the arguments are stored in.
688 /* Architecture specific instructions */
691 #define OP_SET_EQ 102
692 #define OP_SET_NOTEQ 103
693 #define OP_SET_SLESS 104
694 #define OP_SET_ULESS 105
695 #define OP_SET_SMORE 106
696 #define OP_SET_UMORE 107
697 #define OP_SET_SLESSEQ 108
698 #define OP_SET_ULESSEQ 109
699 #define OP_SET_SMOREEQ 110
700 #define OP_SET_UMOREEQ 111
703 #define OP_JMP_EQ 113
704 #define OP_JMP_NOTEQ 114
705 #define OP_JMP_SLESS 115
706 #define OP_JMP_ULESS 116
707 #define OP_JMP_SMORE 117
708 #define OP_JMP_UMORE 118
709 #define OP_JMP_SLESSEQ 119
710 #define OP_JMP_ULESSEQ 120
711 #define OP_JMP_SMOREEQ 121
712 #define OP_JMP_UMOREEQ 122
714 /* Builtin operators that it is just simpler to use the compiler for */
730 #define PURE 0x001 /* Triple has no side effects */
731 #define IMPURE 0x002 /* Triple has side effects */
732 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
733 #define DEF 0x004 /* Triple is a variable definition */
734 #define BLOCK 0x008 /* Triple stores the current block */
735 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
736 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
737 #define UBRANCH 0x020 /* Triple is an unconditional branch instruction */
738 #define CBRANCH 0x040 /* Triple is a conditional branch instruction */
739 #define RETBRANCH 0x060 /* Triple is a return instruction */
740 #define CALLBRANCH 0x080 /* Triple is a call instruction */
741 #define ENDBRANCH 0x0a0 /* Triple is an end instruction */
742 #define PART 0x100 /* Triple is really part of another triple */
743 #define BITFIELD 0x200 /* Triple manipulates a bitfield */
744 signed char lhs, rhs, misc, targ;
747 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
755 static const struct op_info table_ops[] = {
756 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
757 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
758 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
759 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
760 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
761 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
762 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
763 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
764 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
765 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
766 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
767 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
768 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
769 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
770 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
771 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
772 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
773 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
774 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
776 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
777 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
778 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
779 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
780 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
781 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
782 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
783 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
784 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
785 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
786 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
787 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
789 [OP_LOAD ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "load"),
790 [OP_STORE ] = OP( 0, 2, 0, 0, PURE | BLOCK , "store"),
792 [OP_UEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
793 [OP_SEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
794 [OP_DEPOSIT ] = OP( 0, 2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
796 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
798 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
799 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE , "blobconst"),
800 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
801 [OP_UNKNOWNVAL ] = OP( 0, 0, 0, 0, PURE | DEF, "unknown"),
803 #warning "FIXME is it correct for OP_WRITE to be a def? I currently use it as one..."
804 [OP_WRITE ] = OP( 0, 1, 1, 0, PURE | DEF | BLOCK, "write"),
805 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
806 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
807 [OP_CONVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "convert"),
808 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
809 [OP_ASM ] = OP(-1, -1, 0, 0, PURE, "asm"),
810 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
811 [OP_DOT ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "dot"),
812 [OP_INDEX ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "index"),
814 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
815 [OP_TUPLE ] = OP(-1, 0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
816 [OP_BITREF ] = OP( 0, 1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
817 /* Call is special most it can stand in for anything so it depends on context */
818 [OP_FCALL ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
819 [OP_PROG ] = OP( 0, 1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
820 /* The sizes of OP_FCALL depends upon context */
822 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
823 [OP_BRANCH ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
824 [OP_CBRANCH ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
825 [OP_CALL ] = OP( 0, 0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
826 [OP_RET ] = OP( 0, 1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
827 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
828 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
829 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
830 /* The number of RHS elements of OP_PHI depend upon context */
831 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
834 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH, "cps_branch"),
835 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH, "cps_cbranch"),
836 [OP_CPS_CALL ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH, "cps_call"),
837 [OP_CPS_RET ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH, "cps_ret"),
838 [OP_CPS_END ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
839 [OP_CPS_START ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "cps_start"),
842 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
843 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
844 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
845 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
846 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
847 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
848 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
849 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
850 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
851 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
852 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
853 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
854 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
855 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
856 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
857 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
858 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
859 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
860 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
861 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
862 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
863 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
864 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
866 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
867 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
868 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
869 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
870 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
871 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
872 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
873 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
874 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
875 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
876 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
879 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
881 static const char *tops(int index)
883 static const char unknown[] = "unknown op";
887 if (index > OP_MAX) {
890 return table_ops[index].name;
897 struct triple_set *next;
898 struct triple *member;
908 const char *filename;
909 const char *function;
912 struct occurance *parent;
919 struct triple *next, *prev;
920 struct triple_set *use;
923 unsigned int template_id : 7;
924 unsigned int lhs : 6;
925 unsigned int rhs : 7;
926 unsigned int misc : 2;
927 unsigned int targ : 1;
928 #define TRIPLE_SIZE(TRIPLE) \
929 ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
930 #define TRIPLE_LHS_OFF(PTR) (0)
931 #define TRIPLE_RHS_OFF(PTR) (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
932 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
933 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
934 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
935 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
936 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
937 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
938 unsigned id; /* A scratch value and finally the register */
939 #define TRIPLE_FLAG_FLATTENED (1 << 31)
940 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
941 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
942 #define TRIPLE_FLAG_VOLATILE (1 << 28)
943 #define TRIPLE_FLAG_INLINE (1 << 27) /* ???? */
944 #define TRIPLE_FLAG_LOCAL (1 << 26)
946 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
947 struct occurance *occurance;
950 struct bitfield bitfield;
953 struct hash_entry *field;
954 struct asm_info *ainfo;
956 struct symbol *symbol;
958 struct triple *param[2];
965 struct ins_template {
966 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
970 struct ins_template tmpl;
975 struct block_set *next;
976 struct block *member;
979 struct block *work_next;
980 struct triple *first, *last;
982 struct block_set *edges;
984 struct block_set *use;
985 struct block_set *idominates;
986 struct block_set *domfrontier;
988 struct block_set *ipdominates;
989 struct block_set *ipdomfrontier;
997 struct hash_entry *ident;
1004 struct macro_arg *next;
1005 struct hash_entry *ident;
1008 struct hash_entry *ident;
1011 struct macro_arg *args;
1016 struct hash_entry *next;
1020 struct macro *sym_define;
1021 struct symbol *sym_label;
1022 struct symbol *sym_tag;
1023 struct symbol *sym_ident;
1026 #define HASH_TABLE_SIZE 2048
1028 struct compiler_state {
1029 const char *label_prefix;
1030 const char *ofilename;
1031 unsigned long flags;
1032 unsigned long debug;
1033 unsigned long max_allocation_passes;
1035 size_t include_path_count;
1036 const char **include_paths;
1038 size_t define_count;
1039 const char **defines;
1042 const char **undefs;
1045 unsigned long features;
1047 struct basic_blocks {
1048 struct triple *func;
1049 struct triple *first;
1050 struct block *first_block, *last_block;
1053 #define MAX_PP_IF_DEPTH 63
1054 struct compile_state {
1055 struct compiler_state *compiler;
1056 struct arch_state *arch;
1060 struct file_state *file;
1061 struct occurance *last_occurance;
1062 const char *function;
1064 struct token token[6];
1065 struct hash_entry *hash_table[HASH_TABLE_SIZE];
1066 struct hash_entry *i_switch;
1067 struct hash_entry *i_case;
1068 struct hash_entry *i_continue;
1069 struct hash_entry *i_break;
1070 struct hash_entry *i_default;
1071 struct hash_entry *i_return;
1072 /* Additional hash entries for predefined macros */
1073 struct hash_entry *i_defined;
1074 struct hash_entry *i___VA_ARGS__;
1075 struct hash_entry *i___FILE__;
1076 struct hash_entry *i___LINE__;
1077 /* Additional hash entries for predefined identifiers */
1078 struct hash_entry *i___func__;
1079 /* Additional hash entries for attributes */
1080 struct hash_entry *i_noinline;
1081 struct hash_entry *i_always_inline;
1083 unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1085 int eat_depth, eat_targ;
1086 struct file_state *macro_file;
1087 struct triple *functions;
1088 struct triple *main_function;
1089 struct triple *first;
1090 struct triple *global_pool;
1091 struct basic_blocks bb;
1092 int functions_joined;
1095 /* visibility global/local */
1096 /* static/auto duration */
1097 /* typedef, register, inline */
1098 #define STOR_SHIFT 0
1099 #define STOR_MASK 0x001f
1101 #define STOR_GLOBAL 0x0001
1103 #define STOR_PERM 0x0002
1104 /* Definition locality */
1105 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1106 /* Storage specifiers */
1107 #define STOR_AUTO 0x0000
1108 #define STOR_STATIC 0x0002
1109 #define STOR_LOCAL 0x0003
1110 #define STOR_EXTERN 0x0007
1111 #define STOR_INLINE 0x0008
1112 #define STOR_REGISTER 0x0010
1113 #define STOR_TYPEDEF 0x0018
1115 #define QUAL_SHIFT 5
1116 #define QUAL_MASK 0x00e0
1117 #define QUAL_NONE 0x0000
1118 #define QUAL_CONST 0x0020
1119 #define QUAL_VOLATILE 0x0040
1120 #define QUAL_RESTRICT 0x0080
1122 #define TYPE_SHIFT 8
1123 #define TYPE_MASK 0x1f00
1124 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1125 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1126 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1127 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1128 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1129 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1130 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1131 #define TYPE_DEFAULT 0x0000
1132 #define TYPE_VOID 0x0100
1133 #define TYPE_CHAR 0x0200
1134 #define TYPE_UCHAR 0x0300
1135 #define TYPE_SHORT 0x0400
1136 #define TYPE_USHORT 0x0500
1137 #define TYPE_INT 0x0600
1138 #define TYPE_UINT 0x0700
1139 #define TYPE_LONG 0x0800
1140 #define TYPE_ULONG 0x0900
1141 #define TYPE_LLONG 0x0a00 /* long long */
1142 #define TYPE_ULLONG 0x0b00
1143 #define TYPE_FLOAT 0x0c00
1144 #define TYPE_DOUBLE 0x0d00
1145 #define TYPE_LDOUBLE 0x0e00 /* long double */
1147 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1148 #define TYPE_ENUM 0x1600
1149 #define TYPE_LIST 0x1700
1150 /* TYPE_LIST is a basic building block when defining enumerations
1151 * type->field_ident holds the name of this enumeration entry.
1152 * type->right holds the entry in the list.
1155 #define TYPE_STRUCT 0x1000
1157 * type->left holds the link list of TYPE_PRODUCT entries that
1158 * make up the structure.
1159 * type->elements hold the length of the linked list
1161 #define TYPE_UNION 0x1100
1163 * type->left holds the link list of TYPE_OVERLAP entries that
1164 * make up the union.
1165 * type->elements hold the length of the linked list
1167 #define TYPE_POINTER 0x1200
1168 /* For TYPE_POINTER:
1169 * type->left holds the type pointed to.
1171 #define TYPE_FUNCTION 0x1300
1172 /* For TYPE_FUNCTION:
1173 * type->left holds the return type.
1174 * type->right holds the type of the arguments
1175 * type->elements holds the count of the arguments
1177 #define TYPE_PRODUCT 0x1400
1178 /* TYPE_PRODUCT is a basic building block when defining structures
1179 * type->left holds the type that appears first in memory.
1180 * type->right holds the type that appears next in memory.
1182 #define TYPE_OVERLAP 0x1500
1183 /* TYPE_OVERLAP is a basic building block when defining unions
1184 * type->left and type->right holds to types that overlap
1185 * each other in memory.
1187 #define TYPE_ARRAY 0x1800
1188 /* TYPE_ARRAY is a basic building block when definitng arrays.
1189 * type->left holds the type we are an array of.
1190 * type->elements holds the number of elements.
1192 #define TYPE_TUPLE 0x1900
1193 /* TYPE_TUPLE is a basic building block when defining
1194 * positionally reference type conglomerations. (i.e. closures)
1195 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1196 * except it has no field names.
1197 * type->left holds the liked list of TYPE_PRODUCT entries that
1198 * make up the closure type.
1199 * type->elements hold the number of elements in the closure.
1201 #define TYPE_JOIN 0x1a00
1202 /* TYPE_JOIN is a basic building block when defining
1203 * positionally reference type conglomerations. (i.e. closures)
1204 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1205 * except it has no field names.
1206 * type->left holds the liked list of TYPE_OVERLAP entries that
1207 * make up the closure type.
1208 * type->elements hold the number of elements in the closure.
1210 #define TYPE_BITFIELD 0x1b00
1211 /* TYPE_BITFIED is the type of a bitfield.
1212 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1213 * type->elements holds the number of bits in the bitfield.
1215 #define TYPE_UNKNOWN 0x1c00
1216 /* TYPE_UNKNOWN is the type of an unknown value.
1217 * Used on unknown consts and other places where I don't know the type.
1220 #define ATTRIB_SHIFT 16
1221 #define ATTRIB_MASK 0xffff0000
1222 #define ATTRIB_NOINLINE 0x00010000
1223 #define ATTRIB_ALWAYS_INLINE 0x00020000
1225 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1229 struct type *left, *right;
1231 struct hash_entry *field_ident;
1232 struct hash_entry *type_ident;
1235 #define TEMPLATE_BITS 7
1236 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1237 #define MAX_REG_EQUIVS 16
1239 #define MAX_REGISTERS 75
1240 #define REGISTER_BITS 7
1241 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1244 #define REG_UNNEEDED 2
1245 #define REG_VIRT0 (MAX_REGISTERS + 0)
1246 #define REG_VIRT1 (MAX_REGISTERS + 1)
1247 #define REG_VIRT2 (MAX_REGISTERS + 2)
1248 #define REG_VIRT3 (MAX_REGISTERS + 3)
1249 #define REG_VIRT4 (MAX_REGISTERS + 4)
1250 #define REG_VIRT5 (MAX_REGISTERS + 5)
1251 #define REG_VIRT6 (MAX_REGISTERS + 6)
1252 #define REG_VIRT7 (MAX_REGISTERS + 7)
1253 #define REG_VIRT8 (MAX_REGISTERS + 8)
1254 #define REG_VIRT9 (MAX_REGISTERS + 9)
1256 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1257 #error "MAX_VIRT_REGISTERS to small"
1259 #if (MAX_REGC + REGISTER_BITS) >= 26
1260 #error "Too many id bits used"
1263 /* Provision for 8 register classes */
1265 #define REGC_SHIFT REGISTER_BITS
1266 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1267 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1268 #define ID_REG(ID) ((ID) & REG_MASK)
1269 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1270 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1271 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1272 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1273 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1275 #define ARCH_INPUT_REGS 4
1276 #define ARCH_OUTPUT_REGS 4
1278 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1279 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1280 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1281 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1282 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1283 static void arch_reg_equivs(
1284 struct compile_state *state, unsigned *equiv, int reg);
1285 static int arch_select_free_register(
1286 struct compile_state *state, char *used, int classes);
1287 static unsigned arch_regc_size(struct compile_state *state, int class);
1288 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1289 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1290 static const char *arch_reg_str(int reg);
1291 static struct reg_info arch_reg_constraint(
1292 struct compile_state *state, struct type *type, const char *constraint);
1293 static struct reg_info arch_reg_clobber(
1294 struct compile_state *state, const char *clobber);
1295 static struct reg_info arch_reg_lhs(struct compile_state *state,
1296 struct triple *ins, int index);
1297 static struct reg_info arch_reg_rhs(struct compile_state *state,
1298 struct triple *ins, int index);
1299 static int arch_reg_size(int reg);
1300 static struct triple *transform_to_arch_instruction(
1301 struct compile_state *state, struct triple *ins);
1302 static struct triple *flatten(
1303 struct compile_state *state, struct triple *first, struct triple *ptr);
1304 static void print_dominators(struct compile_state *state,
1305 FILE *fp, struct basic_blocks *bb);
1306 static void print_dominance_frontiers(struct compile_state *state,
1307 FILE *fp, struct basic_blocks *bb);
1311 #define DEBUG_ABORT_ON_ERROR 0x00000001
1312 #define DEBUG_BASIC_BLOCKS 0x00000002
1313 #define DEBUG_FDOMINATORS 0x00000004
1314 #define DEBUG_RDOMINATORS 0x00000008
1315 #define DEBUG_TRIPLES 0x00000010
1316 #define DEBUG_INTERFERENCE 0x00000020
1317 #define DEBUG_SCC_TRANSFORM 0x00000040
1318 #define DEBUG_SCC_TRANSFORM2 0x00000080
1319 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1320 #define DEBUG_INLINE 0x00000200
1321 #define DEBUG_RANGE_CONFLICTS 0x00000400
1322 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1323 #define DEBUG_COLOR_GRAPH 0x00001000
1324 #define DEBUG_COLOR_GRAPH2 0x00002000
1325 #define DEBUG_COALESCING 0x00004000
1326 #define DEBUG_COALESCING2 0x00008000
1327 #define DEBUG_VERIFICATION 0x00010000
1328 #define DEBUG_CALLS 0x00020000
1329 #define DEBUG_CALLS2 0x00040000
1330 #define DEBUG_TOKENS 0x80000000
1332 #define DEBUG_DEFAULT ( \
1333 DEBUG_ABORT_ON_ERROR | \
1334 DEBUG_BASIC_BLOCKS | \
1335 DEBUG_FDOMINATORS | \
1336 DEBUG_RDOMINATORS | \
1340 #define DEBUG_ALL ( \
1341 DEBUG_ABORT_ON_ERROR | \
1342 DEBUG_BASIC_BLOCKS | \
1343 DEBUG_FDOMINATORS | \
1344 DEBUG_RDOMINATORS | \
1346 DEBUG_INTERFERENCE | \
1347 DEBUG_SCC_TRANSFORM | \
1348 DEBUG_SCC_TRANSFORM2 | \
1349 DEBUG_REBUILD_SSA_FORM | \
1351 DEBUG_RANGE_CONFLICTS | \
1352 DEBUG_RANGE_CONFLICTS2 | \
1353 DEBUG_COLOR_GRAPH | \
1354 DEBUG_COLOR_GRAPH2 | \
1355 DEBUG_COALESCING | \
1356 DEBUG_COALESCING2 | \
1357 DEBUG_VERIFICATION | \
1363 #define COMPILER_INLINE_MASK 0x00000007
1364 #define COMPILER_INLINE_ALWAYS 0x00000000
1365 #define COMPILER_INLINE_NEVER 0x00000001
1366 #define COMPILER_INLINE_DEFAULTON 0x00000002
1367 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1368 #define COMPILER_INLINE_NOPENALTY 0x00000004
1369 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1370 #define COMPILER_SIMPLIFY 0x00000010
1371 #define COMPILER_SCC_TRANSFORM 0x00000020
1372 #define COMPILER_SIMPLIFY_OP 0x00000040
1373 #define COMPILER_SIMPLIFY_PHI 0x00000080
1374 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1375 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1376 #define COMPILER_SIMPLIFY_COPY 0x00000400
1377 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1378 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1379 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1380 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1381 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1383 #define COMPILER_TRIGRAPHS 0x40000000
1384 #define COMPILER_PP_ONLY 0x80000000
1386 #define COMPILER_DEFAULT_FLAGS ( \
1387 COMPILER_TRIGRAPHS | \
1388 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1389 COMPILER_INLINE_DEFAULTON | \
1390 COMPILER_SIMPLIFY_OP | \
1391 COMPILER_SIMPLIFY_PHI | \
1392 COMPILER_SIMPLIFY_LABEL | \
1393 COMPILER_SIMPLIFY_BRANCH | \
1394 COMPILER_SIMPLIFY_COPY | \
1395 COMPILER_SIMPLIFY_ARITH | \
1396 COMPILER_SIMPLIFY_SHIFT | \
1397 COMPILER_SIMPLIFY_BITWISE | \
1398 COMPILER_SIMPLIFY_LOGICAL | \
1399 COMPILER_SIMPLIFY_BITFIELD | \
1402 #define GLOBAL_SCOPE_DEPTH 1
1403 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1405 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1409 static void init_compiler_state(struct compiler_state *compiler)
1411 memset(compiler, 0, sizeof(*compiler));
1412 compiler->label_prefix = "";
1413 compiler->ofilename = "auto.inc";
1414 compiler->flags = COMPILER_DEFAULT_FLAGS;
1415 compiler->debug = 0;
1416 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1417 compiler->include_path_count = 1;
1418 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1419 compiler->define_count = 1;
1420 compiler->defines = xcmalloc(sizeof(char *), "defines");
1421 compiler->undef_count = 1;
1422 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1425 struct compiler_flag {
1430 struct compiler_arg {
1433 struct compiler_flag flags[16];
1436 static int set_flag(
1437 const struct compiler_flag *ptr, unsigned long *flags,
1438 int act, const char *flag)
1441 for(; ptr->name; ptr++) {
1442 if (strcmp(ptr->name, flag) == 0) {
1448 *flags &= ~(ptr->flag);
1450 *flags |= ptr->flag;
1457 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1462 val = strchr(arg, '=');
1466 for(; ptr->name; ptr++) {
1467 if (strncmp(ptr->name, arg, len) == 0) {
1472 *flags &= ~ptr->mask;
1473 result = set_flag(&ptr->flags[0], flags, 1, val);
1480 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1481 const char *prefix, const char *invert_prefix)
1483 for(;ptr->name; ptr++) {
1484 fprintf(fp, "%s%s\n", prefix, ptr->name);
1485 if (invert_prefix) {
1486 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1491 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1494 for(;ptr->name; ptr++) {
1495 const struct compiler_flag *flag;
1496 for(flag = &ptr->flags[0]; flag->name; flag++) {
1497 fprintf(fp, "%s%s=%s\n",
1498 prefix, ptr->name, flag->name);
1503 static int append_string(size_t *max, const char ***vec, const char *str,
1508 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1509 (*vec)[count -1] = 0;
1510 (*vec)[count -2] = str;
1514 static void arg_error(char *fmt, ...);
1515 static const char *identifier(const char *str, const char *end);
1517 static int append_include_path(struct compiler_state *compiler, const char *str)
1520 if (!exists(str, ".")) {
1521 arg_error("Nonexistent include path: `%s'\n",
1524 result = append_string(&compiler->include_path_count,
1525 &compiler->include_paths, str, "include_paths");
1529 static int append_define(struct compiler_state *compiler, const char *str)
1531 const char *end, *rest;
1534 end = strchr(str, '=');
1536 end = str + strlen(str);
1538 rest = identifier(str, end);
1540 int len = end - str - 1;
1541 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1544 result = append_string(&compiler->define_count,
1545 &compiler->defines, str, "defines");
1549 static int append_undef(struct compiler_state *compiler, const char *str)
1551 const char *end, *rest;
1554 end = str + strlen(str);
1555 rest = identifier(str, end);
1557 int len = end - str - 1;
1558 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1561 result = append_string(&compiler->undef_count,
1562 &compiler->undefs, str, "undefs");
1566 static const struct compiler_flag romcc_flags[] = {
1567 { "trigraphs", COMPILER_TRIGRAPHS },
1568 { "pp-only", COMPILER_PP_ONLY },
1569 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1570 { "simplify", COMPILER_SIMPLIFY },
1571 { "scc-transform", COMPILER_SCC_TRANSFORM },
1572 { "simplify-op", COMPILER_SIMPLIFY_OP },
1573 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1574 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1575 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1576 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1577 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1578 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1579 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1580 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1581 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1584 static const struct compiler_arg romcc_args[] = {
1585 { "inline-policy", COMPILER_INLINE_MASK,
1587 { "always", COMPILER_INLINE_ALWAYS, },
1588 { "never", COMPILER_INLINE_NEVER, },
1589 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1590 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1591 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1597 static const struct compiler_flag romcc_opt_flags[] = {
1598 { "-O", COMPILER_SIMPLIFY },
1599 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1600 { "-E", COMPILER_PP_ONLY },
1603 static const struct compiler_flag romcc_debug_flags[] = {
1604 { "all", DEBUG_ALL },
1605 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1606 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1607 { "fdominators", DEBUG_FDOMINATORS },
1608 { "rdominators", DEBUG_RDOMINATORS },
1609 { "triples", DEBUG_TRIPLES },
1610 { "interference", DEBUG_INTERFERENCE },
1611 { "scc-transform", DEBUG_SCC_TRANSFORM },
1612 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1613 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1614 { "inline", DEBUG_INLINE },
1615 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1616 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1617 { "color-graph", DEBUG_COLOR_GRAPH },
1618 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1619 { "coalescing", DEBUG_COALESCING },
1620 { "coalescing2", DEBUG_COALESCING2 },
1621 { "verification", DEBUG_VERIFICATION },
1622 { "calls", DEBUG_CALLS },
1623 { "calls2", DEBUG_CALLS2 },
1624 { "tokens", DEBUG_TOKENS },
1628 static int compiler_encode_flag(
1629 struct compiler_state *compiler, const char *flag)
1636 if (strncmp(flag, "no-", 3) == 0) {
1640 if (strncmp(flag, "-O", 2) == 0) {
1641 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1643 else if (strncmp(flag, "-E", 2) == 0) {
1644 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1646 else if (strncmp(flag, "-I", 2) == 0) {
1647 result = append_include_path(compiler, flag + 2);
1649 else if (strncmp(flag, "-D", 2) == 0) {
1650 result = append_define(compiler, flag + 2);
1652 else if (strncmp(flag, "-U", 2) == 0) {
1653 result = append_undef(compiler, flag + 2);
1655 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1657 compiler->label_prefix = flag + 13;
1659 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1660 unsigned long max_passes;
1662 max_passes = strtoul(flag + 22, &end, 10);
1663 if (end[0] == '\0') {
1665 compiler->max_allocation_passes = max_passes;
1668 else if (act && strcmp(flag, "debug") == 0) {
1670 compiler->debug |= DEBUG_DEFAULT;
1672 else if (strncmp(flag, "debug-", 6) == 0) {
1674 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1677 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1679 result = set_arg(romcc_args, &compiler->flags, flag);
1685 static void compiler_usage(FILE *fp)
1687 flag_usage(fp, romcc_opt_flags, "", 0);
1688 flag_usage(fp, romcc_flags, "-f", "-fno-");
1689 arg_usage(fp, romcc_args, "-f");
1690 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1691 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1692 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1693 fprintf(fp, "-I<include path>\n");
1694 fprintf(fp, "-D<macro>[=defn]\n");
1695 fprintf(fp, "-U<macro>\n");
1698 static void do_cleanup(struct compile_state *state)
1700 if (state->output) {
1701 fclose(state->output);
1702 unlink(state->compiler->ofilename);
1705 if (state->dbgout) {
1706 fflush(state->dbgout);
1708 if (state->errout) {
1709 fflush(state->errout);
1713 static struct compile_state *exit_state;
1714 static void exit_cleanup(void)
1717 do_cleanup(exit_state);
1721 static int get_col(struct file_state *file)
1724 const char *ptr, *end;
1725 ptr = file->line_start;
1727 for(col = 0; ptr < end; ptr++) {
1732 col = (col & ~7) + 8;
1738 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1741 if (triple && triple->occurance) {
1742 struct occurance *spot;
1743 for(spot = triple->occurance; spot; spot = spot->parent) {
1744 fprintf(fp, "%s:%d.%d: ",
1745 spot->filename, spot->line, spot->col);
1752 col = get_col(state->file);
1753 fprintf(fp, "%s:%d.%d: ",
1754 state->file->report_name, state->file->report_line, col);
1757 static void internal_error(struct compile_state *state, struct triple *ptr,
1758 const char *fmt, ...)
1760 FILE *fp = state->errout;
1762 va_start(args, fmt);
1763 loc(fp, state, ptr);
1766 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1768 fprintf(fp, "Internal compiler error: ");
1769 vfprintf(fp, fmt, args);
1777 static void internal_warning(struct compile_state *state, struct triple *ptr,
1778 const char *fmt, ...)
1780 FILE *fp = state->errout;
1782 va_start(args, fmt);
1783 loc(fp, state, ptr);
1785 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1787 fprintf(fp, "Internal compiler warning: ");
1788 vfprintf(fp, fmt, args);
1795 static void error(struct compile_state *state, struct triple *ptr,
1796 const char *fmt, ...)
1798 FILE *fp = state->errout;
1800 va_start(args, fmt);
1801 loc(fp, state, ptr);
1803 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1804 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1806 vfprintf(fp, fmt, args);
1810 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1816 static void warning(struct compile_state *state, struct triple *ptr,
1817 const char *fmt, ...)
1819 FILE *fp = state->errout;
1821 va_start(args, fmt);
1822 loc(fp, state, ptr);
1823 fprintf(fp, "warning: ");
1824 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1825 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1827 vfprintf(fp, fmt, args);
1832 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1834 static void valid_op(struct compile_state *state, int op)
1836 char *fmt = "invalid op: %d";
1838 internal_error(state, 0, fmt, op);
1841 internal_error(state, 0, fmt, op);
1845 static void valid_ins(struct compile_state *state, struct triple *ptr)
1847 valid_op(state, ptr->op);
1850 static void valid_param_count(struct compile_state *state, struct triple *ins)
1852 int lhs, rhs, misc, targ;
1853 valid_ins(state, ins);
1854 lhs = table_ops[ins->op].lhs;
1855 rhs = table_ops[ins->op].rhs;
1856 misc = table_ops[ins->op].misc;
1857 targ = table_ops[ins->op].targ;
1859 if ((lhs >= 0) && (ins->lhs != lhs)) {
1860 internal_error(state, ins, "Bad lhs count");
1862 if ((rhs >= 0) && (ins->rhs != rhs)) {
1863 internal_error(state, ins, "Bad rhs count");
1865 if ((misc >= 0) && (ins->misc != misc)) {
1866 internal_error(state, ins, "Bad misc count");
1868 if ((targ >= 0) && (ins->targ != targ)) {
1869 internal_error(state, ins, "Bad targ count");
1873 static struct type void_type;
1874 static struct type unknown_type;
1875 static void use_triple(struct triple *used, struct triple *user)
1877 struct triple_set **ptr, *new;
1884 if ((*ptr)->member == user) {
1887 ptr = &(*ptr)->next;
1889 /* Append new to the head of the list,
1890 * copy_func and rename_block_variables
1893 new = xcmalloc(sizeof(*new), "triple_set");
1895 new->next = used->use;
1899 static void unuse_triple(struct triple *used, struct triple *unuser)
1901 struct triple_set *use, **ptr;
1908 if (use->member == unuser) {
1918 static void put_occurance(struct occurance *occurance)
1921 occurance->count -= 1;
1922 if (occurance->count <= 0) {
1923 if (occurance->parent) {
1924 put_occurance(occurance->parent);
1931 static void get_occurance(struct occurance *occurance)
1934 occurance->count += 1;
1939 static struct occurance *new_occurance(struct compile_state *state)
1941 struct occurance *result, *last;
1942 const char *filename;
1943 const char *function;
1951 filename = state->file->report_name;
1952 line = state->file->report_line;
1953 col = get_col(state->file);
1955 if (state->function) {
1956 function = state->function;
1958 last = state->last_occurance;
1960 (last->col == col) &&
1961 (last->line == line) &&
1962 (last->function == function) &&
1963 ((last->filename == filename) ||
1964 (strcmp(last->filename, filename) == 0)))
1966 get_occurance(last);
1970 state->last_occurance = 0;
1971 put_occurance(last);
1973 result = xmalloc(sizeof(*result), "occurance");
1975 result->filename = filename;
1976 result->function = function;
1977 result->line = line;
1980 state->last_occurance = result;
1984 static struct occurance *inline_occurance(struct compile_state *state,
1985 struct occurance *base, struct occurance *top)
1987 struct occurance *result, *last;
1989 internal_error(state, 0, "inlining an already inlined function?");
1991 /* If I have a null base treat it that way */
1992 if ((base->parent == 0) &&
1994 (base->line == 0) &&
1995 (base->function[0] == '\0') &&
1996 (base->filename[0] == '\0')) {
1999 /* See if I can reuse the last occurance I had */
2000 last = state->last_occurance;
2002 (last->parent == base) &&
2003 (last->col == top->col) &&
2004 (last->line == top->line) &&
2005 (last->function == top->function) &&
2006 (last->filename == top->filename)) {
2007 get_occurance(last);
2010 /* I can't reuse the last occurance so free it */
2012 state->last_occurance = 0;
2013 put_occurance(last);
2015 /* Generate a new occurance structure */
2016 get_occurance(base);
2017 result = xmalloc(sizeof(*result), "occurance");
2019 result->filename = top->filename;
2020 result->function = top->function;
2021 result->line = top->line;
2022 result->col = top->col;
2023 result->parent = base;
2024 state->last_occurance = result;
2028 static struct occurance dummy_occurance = {
2030 .filename = __FILE__,
2037 /* The undef triple is used as a place holder when we are removing pointers
2038 * from a triple. Having allows certain sanity checks to pass even
2039 * when the original triple that was pointed to is gone.
2041 static struct triple unknown_triple = {
2042 .next = &unknown_triple,
2043 .prev = &unknown_triple,
2045 .op = OP_UNKNOWNVAL,
2050 .type = &unknown_type,
2051 .id = -1, /* An invalid id */
2052 .u = { .cval = 0, },
2053 .occurance = &dummy_occurance,
2054 .param = { [0] = 0, [1] = 0, },
2058 static size_t registers_of(struct compile_state *state, struct type *type);
2060 static struct triple *alloc_triple(struct compile_state *state,
2061 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2062 struct occurance *occurance)
2064 size_t size, extra_count, min_count;
2065 int lhs, rhs, misc, targ;
2066 struct triple *ret, dummy;
2068 dummy.occurance = occurance;
2069 valid_op(state, op);
2070 lhs = table_ops[op].lhs;
2071 rhs = table_ops[op].rhs;
2072 misc = table_ops[op].misc;
2073 targ = table_ops[op].targ;
2083 lhs = registers_of(state, type);
2086 lhs = registers_of(state, type);
2093 if ((rhs < 0) || (rhs > MAX_RHS)) {
2094 internal_error(state, &dummy, "bad rhs count %d", rhs);
2096 if ((lhs < 0) || (lhs > MAX_LHS)) {
2097 internal_error(state, &dummy, "bad lhs count %d", lhs);
2099 if ((misc < 0) || (misc > MAX_MISC)) {
2100 internal_error(state, &dummy, "bad misc count %d", misc);
2102 if ((targ < 0) || (targ > MAX_TARG)) {
2103 internal_error(state, &dummy, "bad targs count %d", targ);
2106 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2107 extra_count = lhs + rhs + misc + targ;
2108 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2110 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2111 ret = xcmalloc(size, "tripple");
2120 ret->occurance = occurance;
2121 /* A simple sanity check */
2122 if ((ret->op != op) ||
2123 (ret->lhs != lhs) ||
2124 (ret->rhs != rhs) ||
2125 (ret->misc != misc) ||
2126 (ret->targ != targ) ||
2127 (ret->type != type) ||
2128 (ret->next != ret) ||
2129 (ret->prev != ret) ||
2130 (ret->occurance != occurance)) {
2131 internal_error(state, ret, "huh?");
2136 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2139 int src_lhs, src_rhs, src_size;
2142 src_size = TRIPLE_SIZE(src);
2143 get_occurance(src->occurance);
2144 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2146 memcpy(dup, src, sizeof(*src));
2147 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2151 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2153 struct triple *copy;
2154 copy = dup_triple(state, src);
2156 copy->next = copy->prev = copy;
2160 static struct triple *new_triple(struct compile_state *state,
2161 int op, struct type *type, int lhs, int rhs)
2164 struct occurance *occurance;
2165 occurance = new_occurance(state);
2166 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2170 static struct triple *build_triple(struct compile_state *state,
2171 int op, struct type *type, struct triple *left, struct triple *right,
2172 struct occurance *occurance)
2176 ret = alloc_triple(state, op, type, -1, -1, occurance);
2177 count = TRIPLE_SIZE(ret);
2179 ret->param[0] = left;
2182 ret->param[1] = right;
2187 static struct triple *triple(struct compile_state *state,
2188 int op, struct type *type, struct triple *left, struct triple *right)
2192 ret = new_triple(state, op, type, -1, -1);
2193 count = TRIPLE_SIZE(ret);
2195 ret->param[0] = left;
2198 ret->param[1] = right;
2203 static struct triple *branch(struct compile_state *state,
2204 struct triple *targ, struct triple *test)
2208 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2211 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2213 TARG(ret, 0) = targ;
2214 /* record the branch target was used */
2215 if (!targ || (targ->op != OP_LABEL)) {
2216 internal_error(state, 0, "branch not to label");
2221 static int triple_is_label(struct compile_state *state, struct triple *ins);
2222 static int triple_is_call(struct compile_state *state, struct triple *ins);
2223 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2224 static void insert_triple(struct compile_state *state,
2225 struct triple *first, struct triple *ptr)
2228 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2229 internal_error(state, ptr, "expression already used");
2232 ptr->prev = first->prev;
2233 ptr->prev->next = ptr;
2234 ptr->next->prev = ptr;
2236 if (triple_is_cbranch(state, ptr->prev) ||
2237 triple_is_call(state, ptr->prev)) {
2238 unuse_triple(first, ptr->prev);
2239 use_triple(ptr, ptr->prev);
2244 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2246 /* This function is used to determine if u.block
2247 * is utilized to store the current block number.
2250 valid_ins(state, ins);
2251 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2252 return stores_block;
2255 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2256 static struct block *block_of_triple(struct compile_state *state,
2259 struct triple *first;
2260 if (!ins || ins == &unknown_triple) {
2263 first = state->first;
2264 while(ins != first && !triple_is_branch(state, ins->prev) &&
2265 !triple_stores_block(state, ins))
2267 if (ins == ins->prev) {
2268 internal_error(state, ins, "ins == ins->prev?");
2272 return triple_stores_block(state, ins)? ins->u.block: 0;
2275 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2276 static struct triple *pre_triple(struct compile_state *state,
2277 struct triple *base,
2278 int op, struct type *type, struct triple *left, struct triple *right)
2280 struct block *block;
2283 /* If I am an OP_PIECE jump to the real instruction */
2284 if (base->op == OP_PIECE) {
2285 base = MISC(base, 0);
2287 block = block_of_triple(state, base);
2288 get_occurance(base->occurance);
2289 ret = build_triple(state, op, type, left, right, base->occurance);
2290 generate_lhs_pieces(state, ret);
2291 if (triple_stores_block(state, ret)) {
2292 ret->u.block = block;
2294 insert_triple(state, base, ret);
2295 for(i = 0; i < ret->lhs; i++) {
2296 struct triple *piece;
2297 piece = LHS(ret, i);
2298 insert_triple(state, base, piece);
2299 use_triple(ret, piece);
2300 use_triple(piece, ret);
2302 if (block && (block->first == base)) {
2308 static struct triple *post_triple(struct compile_state *state,
2309 struct triple *base,
2310 int op, struct type *type, struct triple *left, struct triple *right)
2312 struct block *block;
2313 struct triple *ret, *next;
2315 /* If I am an OP_PIECE jump to the real instruction */
2316 if (base->op == OP_PIECE) {
2317 base = MISC(base, 0);
2319 /* If I have a left hand side skip over it */
2322 base = LHS(base, zlhs - 1);
2325 block = block_of_triple(state, base);
2326 get_occurance(base->occurance);
2327 ret = build_triple(state, op, type, left, right, base->occurance);
2328 generate_lhs_pieces(state, ret);
2329 if (triple_stores_block(state, ret)) {
2330 ret->u.block = block;
2333 insert_triple(state, next, ret);
2335 for(i = 0; i < zlhs; i++) {
2336 struct triple *piece;
2337 piece = LHS(ret, i);
2338 insert_triple(state, next, piece);
2339 use_triple(ret, piece);
2340 use_triple(piece, ret);
2342 if (block && (block->last == base)) {
2345 block->last = LHS(ret, zlhs - 1);
2351 static struct type *reg_type(
2352 struct compile_state *state, struct type *type, int reg);
2354 static void generate_lhs_piece(
2355 struct compile_state *state, struct triple *ins, int index)
2357 struct type *piece_type;
2358 struct triple *piece;
2359 get_occurance(ins->occurance);
2360 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2362 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2363 piece_type = piece_type->left;
2367 static void name_of(FILE *fp, struct type *type);
2368 FILE * fp = state->errout;
2369 fprintf(fp, "piece_type(%d): ", index);
2370 name_of(fp, piece_type);
2374 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2375 piece->u.cval = index;
2376 LHS(ins, piece->u.cval) = piece;
2377 MISC(piece, 0) = ins;
2380 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2384 for(i = 0; i < zlhs; i++) {
2385 generate_lhs_piece(state, ins, i);
2389 static struct triple *label(struct compile_state *state)
2391 /* Labels don't get a type */
2392 struct triple *result;
2393 result = triple(state, OP_LABEL, &void_type, 0, 0);
2397 static struct triple *mkprog(struct compile_state *state, ...)
2399 struct triple *prog, *head, *arg;
2403 head = label(state);
2404 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2405 RHS(prog, 0) = head;
2406 va_start(args, state);
2408 while((arg = va_arg(args, struct triple *)) != 0) {
2410 internal_error(state, 0, "too many arguments to mkprog");
2412 flatten(state, head, arg);
2415 prog->type = head->prev->type;
2418 static void name_of(FILE *fp, struct type *type);
2419 static void display_triple(FILE *fp, struct triple *ins)
2421 struct occurance *ptr;
2423 char pre, post, vol;
2424 pre = post = vol = ' ';
2426 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2429 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2432 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2435 reg = arch_reg_str(ID_REG(ins->id));
2438 fprintf(fp, "(%p) <nothing> ", ins);
2440 else if (ins->op == OP_INTCONST) {
2441 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2442 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2443 (unsigned long)(ins->u.cval));
2445 else if (ins->op == OP_ADDRCONST) {
2446 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2447 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2448 MISC(ins, 0), (unsigned long)(ins->u.cval));
2450 else if (ins->op == OP_INDEX) {
2451 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2452 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2453 RHS(ins, 0), (unsigned long)(ins->u.cval));
2455 else if (ins->op == OP_PIECE) {
2456 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2457 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2458 MISC(ins, 0), (unsigned long)(ins->u.cval));
2462 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2463 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2464 if (table_ops[ins->op].flags & BITFIELD) {
2465 fprintf(fp, " <%2d-%2d:%2d>",
2466 ins->u.bitfield.offset,
2467 ins->u.bitfield.offset + ins->u.bitfield.size,
2468 ins->u.bitfield.size);
2470 count = TRIPLE_SIZE(ins);
2471 for(i = 0; i < count; i++) {
2472 fprintf(fp, " %-10p", ins->param[i]);
2479 struct triple_set *user;
2480 #if DEBUG_DISPLAY_TYPES
2482 name_of(fp, ins->type);
2485 #if DEBUG_DISPLAY_USES
2487 for(user = ins->use; user; user = user->next) {
2488 fprintf(fp, " %-10p", user->member);
2493 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2494 fprintf(fp, " %s,%s:%d.%d",
2500 if (ins->op == OP_ASM) {
2501 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2508 static int equiv_types(struct type *left, struct type *right);
2509 static void display_triple_changes(
2510 FILE *fp, const struct triple *new, const struct triple *orig)
2513 int new_count, orig_count;
2514 new_count = TRIPLE_SIZE(new);
2515 orig_count = TRIPLE_SIZE(orig);
2516 if ((new->op != orig->op) ||
2517 (new_count != orig_count) ||
2518 (memcmp(orig->param, new->param,
2519 orig_count * sizeof(orig->param[0])) != 0) ||
2520 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2522 struct occurance *ptr;
2523 int i, min_count, indent;
2524 fprintf(fp, "(%p %p)", new, orig);
2525 if (orig->op == new->op) {
2526 fprintf(fp, " %-11s", tops(orig->op));
2528 fprintf(fp, " [%-10s %-10s]",
2529 tops(new->op), tops(orig->op));
2531 min_count = new_count;
2532 if (min_count > orig_count) {
2533 min_count = orig_count;
2535 for(indent = i = 0; i < min_count; i++) {
2536 if (orig->param[i] == new->param[i]) {
2537 fprintf(fp, " %-11p",
2541 fprintf(fp, " [%-10p %-10p]",
2547 for(; i < orig_count; i++) {
2548 fprintf(fp, " [%-9p]", orig->param[i]);
2551 for(; i < new_count; i++) {
2552 fprintf(fp, " [%-9p]", new->param[i]);
2555 if ((new->op == OP_INTCONST)||
2556 (new->op == OP_ADDRCONST)) {
2557 fprintf(fp, " <0x%08lx>",
2558 (unsigned long)(new->u.cval));
2561 for(;indent < 36; indent++) {
2565 #if DEBUG_DISPLAY_TYPES
2567 name_of(fp, new->type);
2568 if (!equiv_types(new->type, orig->type)) {
2569 fprintf(fp, " -- ");
2570 name_of(fp, orig->type);
2576 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2577 fprintf(fp, " %s,%s:%d.%d",
2589 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2591 /* Does the triple have no side effects.
2592 * I.e. Rexecuting the triple with the same arguments
2593 * gives the same value.
2596 valid_ins(state, ins);
2597 pure = PURE_BITS(table_ops[ins->op].flags);
2598 if ((pure != PURE) && (pure != IMPURE)) {
2599 internal_error(state, 0, "Purity of %s not known",
2602 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2605 static int triple_is_branch_type(struct compile_state *state,
2606 struct triple *ins, unsigned type)
2608 /* Is this one of the passed branch types? */
2609 valid_ins(state, ins);
2610 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2613 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2615 /* Is this triple a branch instruction? */
2616 valid_ins(state, ins);
2617 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2620 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2622 /* Is this triple a conditional branch instruction? */
2623 return triple_is_branch_type(state, ins, CBRANCH);
2626 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2628 /* Is this triple a unconditional branch instruction? */
2630 valid_ins(state, ins);
2631 type = BRANCH_BITS(table_ops[ins->op].flags);
2632 return (type != 0) && (type != CBRANCH);
2635 static int triple_is_call(struct compile_state *state, struct triple *ins)
2637 /* Is this triple a call instruction? */
2638 return triple_is_branch_type(state, ins, CALLBRANCH);
2641 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2643 /* Is this triple a return instruction? */
2644 return triple_is_branch_type(state, ins, RETBRANCH);
2647 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2649 /* Is this triple an unconditional branch and not a call or a
2651 return triple_is_branch_type(state, ins, UBRANCH);
2654 static int triple_is_end(struct compile_state *state, struct triple *ins)
2656 return triple_is_branch_type(state, ins, ENDBRANCH);
2659 static int triple_is_label(struct compile_state *state, struct triple *ins)
2661 valid_ins(state, ins);
2662 return (ins->op == OP_LABEL);
2665 static struct triple *triple_to_block_start(
2666 struct compile_state *state, struct triple *start)
2668 while(!triple_is_branch(state, start->prev) &&
2669 (!triple_is_label(state, start) || !start->use)) {
2670 start = start->prev;
2675 static int triple_is_def(struct compile_state *state, struct triple *ins)
2677 /* This function is used to determine which triples need
2681 valid_ins(state, ins);
2682 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2683 if (ins->lhs >= 1) {
2689 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2692 valid_ins(state, ins);
2693 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2694 return is_structural;
2697 static int triple_is_part(struct compile_state *state, struct triple *ins)
2700 valid_ins(state, ins);
2701 is_part = (table_ops[ins->op].flags & PART) == PART;
2705 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2707 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2710 static struct triple **triple_iter(struct compile_state *state,
2711 size_t count, struct triple **vector,
2712 struct triple *ins, struct triple **last)
2714 struct triple **ret;
2720 else if ((last >= vector) && (last < (vector + count - 1))) {
2728 static struct triple **triple_lhs(struct compile_state *state,
2729 struct triple *ins, struct triple **last)
2731 return triple_iter(state, ins->lhs, &LHS(ins,0),
2735 static struct triple **triple_rhs(struct compile_state *state,
2736 struct triple *ins, struct triple **last)
2738 return triple_iter(state, ins->rhs, &RHS(ins,0),
2742 static struct triple **triple_misc(struct compile_state *state,
2743 struct triple *ins, struct triple **last)
2745 return triple_iter(state, ins->misc, &MISC(ins,0),
2749 static struct triple **do_triple_targ(struct compile_state *state,
2750 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2753 struct triple **ret, **vector;
2758 if (triple_is_cbranch(state, ins)) {
2761 if (!call_edges && triple_is_call(state, ins)) {
2764 if (next_edges && triple_is_call(state, ins)) {
2767 vector = &TARG(ins, 0);
2768 if (!ret && next_is_targ) {
2771 } else if (last == &ins->next) {
2775 if (!ret && count) {
2779 else if ((last >= vector) && (last < (vector + count - 1))) {
2782 else if (last == vector + count - 1) {
2786 if (!ret && triple_is_ret(state, ins) && call_edges) {
2787 struct triple_set *use;
2788 for(use = ins->use; use; use = use->next) {
2789 if (!triple_is_call(state, use->member)) {
2793 ret = &use->member->next;
2796 else if (last == &use->member->next) {
2804 static struct triple **triple_targ(struct compile_state *state,
2805 struct triple *ins, struct triple **last)
2807 return do_triple_targ(state, ins, last, 1, 1);
2810 static struct triple **triple_edge_targ(struct compile_state *state,
2811 struct triple *ins, struct triple **last)
2813 return do_triple_targ(state, ins, last,
2814 state->functions_joined, !state->functions_joined);
2817 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2819 struct triple *next;
2823 for(i = 0; i < lhs; i++) {
2824 struct triple *piece;
2825 piece = LHS(ins, i);
2826 if (next != piece) {
2827 internal_error(state, ins, "malformed lhs on %s",
2830 if (next->op != OP_PIECE) {
2831 internal_error(state, ins, "bad lhs op %s at %d on %s",
2832 tops(next->op), i, tops(ins->op));
2834 if (next->u.cval != i) {
2835 internal_error(state, ins, "bad u.cval of %d %d expected",
2843 /* Function piece accessor functions */
2844 static struct triple *do_farg(struct compile_state *state,
2845 struct triple *func, unsigned index)
2848 struct triple *first, *arg;
2852 if((index < 0) || (index >= (ftype->elements + 2))) {
2853 internal_error(state, func, "bad argument index: %d", index);
2855 first = RHS(func, 0);
2857 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2860 if (arg->op != OP_ADECL) {
2861 internal_error(state, 0, "arg not adecl?");
2865 static struct triple *fresult(struct compile_state *state, struct triple *func)
2867 return do_farg(state, func, 0);
2869 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2871 return do_farg(state, func, 1);
2873 static struct triple *farg(struct compile_state *state,
2874 struct triple *func, unsigned index)
2876 return do_farg(state, func, index + 2);
2880 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2882 struct triple *first, *ins;
2883 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2884 first = ins = RHS(func, 0);
2886 if (triple_is_label(state, ins) && ins->use) {
2887 fprintf(fp, "%p:\n", ins);
2889 display_triple(fp, ins);
2891 if (triple_is_branch(state, ins)) {
2894 if (ins->next->prev != ins) {
2895 internal_error(state, ins->next, "bad prev");
2898 } while(ins != first);
2901 static void verify_use(struct compile_state *state,
2902 struct triple *user, struct triple *used)
2905 size = TRIPLE_SIZE(user);
2906 for(i = 0; i < size; i++) {
2907 if (user->param[i] == used) {
2911 if (triple_is_branch(state, user)) {
2912 if (user->next == used) {
2917 internal_error(state, user, "%s(%p) does not use %s(%p)",
2918 tops(user->op), user, tops(used->op), used);
2922 static int find_rhs_use(struct compile_state *state,
2923 struct triple *user, struct triple *used)
2925 struct triple **param;
2927 verify_use(state, user, used);
2928 #warning "AUDIT ME ->rhs"
2930 param = &RHS(user, 0);
2931 for(i = 0; i < size; i++) {
2932 if (param[i] == used) {
2939 static void free_triple(struct compile_state *state, struct triple *ptr)
2942 size = sizeof(*ptr) - sizeof(ptr->param) +
2943 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2944 ptr->prev->next = ptr->next;
2945 ptr->next->prev = ptr->prev;
2947 internal_error(state, ptr, "ptr->use != 0");
2949 put_occurance(ptr->occurance);
2950 memset(ptr, -1, size);
2954 static void release_triple(struct compile_state *state, struct triple *ptr)
2956 struct triple_set *set, *next;
2957 struct triple **expr;
2958 struct block *block;
2959 if (ptr == &unknown_triple) {
2962 valid_ins(state, ptr);
2963 /* Make certain the we are not the first or last element of a block */
2964 block = block_of_triple(state, ptr);
2966 if ((block->last == ptr) && (block->first == ptr)) {
2967 block->last = block->first = 0;
2969 else if (block->last == ptr) {
2970 block->last = ptr->prev;
2972 else if (block->first == ptr) {
2973 block->first = ptr->next;
2976 /* Remove ptr from use chains where it is the user */
2977 expr = triple_rhs(state, ptr, 0);
2978 for(; expr; expr = triple_rhs(state, ptr, expr)) {
2980 unuse_triple(*expr, ptr);
2983 expr = triple_lhs(state, ptr, 0);
2984 for(; expr; expr = triple_lhs(state, ptr, expr)) {
2986 unuse_triple(*expr, ptr);
2989 expr = triple_misc(state, ptr, 0);
2990 for(; expr; expr = triple_misc(state, ptr, expr)) {
2992 unuse_triple(*expr, ptr);
2995 expr = triple_targ(state, ptr, 0);
2996 for(; expr; expr = triple_targ(state, ptr, expr)) {
2998 unuse_triple(*expr, ptr);
3001 /* Reomve ptr from use chains where it is used */
3002 for(set = ptr->use; set; set = next) {
3004 valid_ins(state, set->member);
3005 expr = triple_rhs(state, set->member, 0);
3006 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3008 *expr = &unknown_triple;
3011 expr = triple_lhs(state, set->member, 0);
3012 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3014 *expr = &unknown_triple;
3017 expr = triple_misc(state, set->member, 0);
3018 for(; expr; expr = triple_misc(state, set->member, expr)) {
3020 *expr = &unknown_triple;
3023 expr = triple_targ(state, set->member, 0);
3024 for(; expr; expr = triple_targ(state, set->member, expr)) {
3026 *expr = &unknown_triple;
3029 unuse_triple(ptr, set->member);
3031 free_triple(state, ptr);
3034 static void print_triples(struct compile_state *state);
3035 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3037 #define TOK_UNKNOWN 0
3040 #define TOK_LBRACE 3
3041 #define TOK_RBRACE 4
3045 #define TOK_LBRACKET 8
3046 #define TOK_RBRACKET 9
3047 #define TOK_LPAREN 10
3048 #define TOK_RPAREN 11
3053 #define TOK_TIMESEQ 16
3054 #define TOK_DIVEQ 17
3055 #define TOK_MODEQ 18
3056 #define TOK_PLUSEQ 19
3057 #define TOK_MINUSEQ 20
3060 #define TOK_ANDEQ 23
3061 #define TOK_XOREQ 24
3064 #define TOK_NOTEQ 27
3065 #define TOK_QUEST 28
3066 #define TOK_LOGOR 29
3067 #define TOK_LOGAND 30
3071 #define TOK_LESSEQ 34
3072 #define TOK_MOREEQ 35
3076 #define TOK_MINUS 39
3079 #define TOK_PLUSPLUS 42
3080 #define TOK_MINUSMINUS 43
3082 #define TOK_ARROW 45
3084 #define TOK_TILDE 47
3085 #define TOK_LIT_STRING 48
3086 #define TOK_LIT_CHAR 49
3087 #define TOK_LIT_INT 50
3088 #define TOK_LIT_FLOAT 51
3089 #define TOK_MACRO 52
3090 #define TOK_CONCATENATE 53
3092 #define TOK_IDENT 54
3093 #define TOK_STRUCT_NAME 55
3094 #define TOK_ENUM_CONST 56
3095 #define TOK_TYPE_NAME 57
3098 #define TOK_BREAK 59
3101 #define TOK_CONST 62
3102 #define TOK_CONTINUE 63
3103 #define TOK_DEFAULT 64
3105 #define TOK_DOUBLE 66
3108 #define TOK_EXTERN 69
3109 #define TOK_FLOAT 70
3113 #define TOK_INLINE 74
3116 #define TOK_REGISTER 77
3117 #define TOK_RESTRICT 78
3118 #define TOK_RETURN 79
3119 #define TOK_SHORT 80
3120 #define TOK_SIGNED 81
3121 #define TOK_SIZEOF 82
3122 #define TOK_STATIC 83
3123 #define TOK_STRUCT 84
3124 #define TOK_SWITCH 85
3125 #define TOK_TYPEDEF 86
3126 #define TOK_UNION 87
3127 #define TOK_UNSIGNED 88
3129 #define TOK_VOLATILE 90
3130 #define TOK_WHILE 91
3132 #define TOK_ATTRIBUTE 93
3133 #define TOK_ALIGNOF 94
3134 #define TOK_FIRST_KEYWORD TOK_AUTO
3135 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3137 #define TOK_MDEFINE 100
3138 #define TOK_MDEFINED 101
3139 #define TOK_MUNDEF 102
3140 #define TOK_MINCLUDE 103
3141 #define TOK_MLINE 104
3142 #define TOK_MERROR 105
3143 #define TOK_MWARNING 106
3144 #define TOK_MPRAGMA 107
3145 #define TOK_MIFDEF 108
3146 #define TOK_MIFNDEF 109
3147 #define TOK_MELIF 110
3148 #define TOK_MENDIF 111
3150 #define TOK_FIRST_MACRO TOK_MDEFINE
3151 #define TOK_LAST_MACRO TOK_MENDIF
3154 #define TOK_MELSE 113
3155 #define TOK_MIDENT 114
3160 static const char *tokens[] = {
3161 [TOK_UNKNOWN ] = ":unknown:",
3162 [TOK_SPACE ] = ":space:",
3164 [TOK_LBRACE ] = "{",
3165 [TOK_RBRACE ] = "}",
3169 [TOK_LBRACKET ] = "[",
3170 [TOK_RBRACKET ] = "]",
3171 [TOK_LPAREN ] = "(",
3172 [TOK_RPAREN ] = ")",
3174 [TOK_DOTS ] = "...",
3177 [TOK_TIMESEQ ] = "*=",
3178 [TOK_DIVEQ ] = "/=",
3179 [TOK_MODEQ ] = "%=",
3180 [TOK_PLUSEQ ] = "+=",
3181 [TOK_MINUSEQ ] = "-=",
3182 [TOK_SLEQ ] = "<<=",
3183 [TOK_SREQ ] = ">>=",
3184 [TOK_ANDEQ ] = "&=",
3185 [TOK_XOREQ ] = "^=",
3188 [TOK_NOTEQ ] = "!=",
3190 [TOK_LOGOR ] = "||",
3191 [TOK_LOGAND ] = "&&",
3195 [TOK_LESSEQ ] = "<=",
3196 [TOK_MOREEQ ] = ">=",
3203 [TOK_PLUSPLUS ] = "++",
3204 [TOK_MINUSMINUS ] = "--",
3206 [TOK_ARROW ] = "->",
3209 [TOK_LIT_STRING ] = ":string:",
3210 [TOK_IDENT ] = ":ident:",
3211 [TOK_TYPE_NAME ] = ":typename:",
3212 [TOK_LIT_CHAR ] = ":char:",
3213 [TOK_LIT_INT ] = ":integer:",
3214 [TOK_LIT_FLOAT ] = ":float:",
3216 [TOK_CONCATENATE ] = "##",
3218 [TOK_AUTO ] = "auto",
3219 [TOK_BREAK ] = "break",
3220 [TOK_CASE ] = "case",
3221 [TOK_CHAR ] = "char",
3222 [TOK_CONST ] = "const",
3223 [TOK_CONTINUE ] = "continue",
3224 [TOK_DEFAULT ] = "default",
3226 [TOK_DOUBLE ] = "double",
3227 [TOK_ELSE ] = "else",
3228 [TOK_ENUM ] = "enum",
3229 [TOK_EXTERN ] = "extern",
3230 [TOK_FLOAT ] = "float",
3232 [TOK_GOTO ] = "goto",
3234 [TOK_INLINE ] = "inline",
3236 [TOK_LONG ] = "long",
3237 [TOK_REGISTER ] = "register",
3238 [TOK_RESTRICT ] = "restrict",
3239 [TOK_RETURN ] = "return",
3240 [TOK_SHORT ] = "short",
3241 [TOK_SIGNED ] = "signed",
3242 [TOK_SIZEOF ] = "sizeof",
3243 [TOK_STATIC ] = "static",
3244 [TOK_STRUCT ] = "struct",
3245 [TOK_SWITCH ] = "switch",
3246 [TOK_TYPEDEF ] = "typedef",
3247 [TOK_UNION ] = "union",
3248 [TOK_UNSIGNED ] = "unsigned",
3249 [TOK_VOID ] = "void",
3250 [TOK_VOLATILE ] = "volatile",
3251 [TOK_WHILE ] = "while",
3253 [TOK_ATTRIBUTE ] = "__attribute__",
3254 [TOK_ALIGNOF ] = "__alignof__",
3256 [TOK_MDEFINE ] = "#define",
3257 [TOK_MDEFINED ] = "#defined",
3258 [TOK_MUNDEF ] = "#undef",
3259 [TOK_MINCLUDE ] = "#include",
3260 [TOK_MLINE ] = "#line",
3261 [TOK_MERROR ] = "#error",
3262 [TOK_MWARNING ] = "#warning",
3263 [TOK_MPRAGMA ] = "#pragma",
3264 [TOK_MIFDEF ] = "#ifdef",
3265 [TOK_MIFNDEF ] = "#ifndef",
3266 [TOK_MELIF ] = "#elif",
3267 [TOK_MENDIF ] = "#endif",
3270 [TOK_MELSE ] = "#else",
3271 [TOK_MIDENT ] = "#:ident:",
3276 static unsigned int hash(const char *str, int str_len)
3280 end = str + str_len;
3282 for(; str < end; str++) {
3283 hash = (hash *263) + *str;
3285 hash = hash & (HASH_TABLE_SIZE -1);
3289 static struct hash_entry *lookup(
3290 struct compile_state *state, const char *name, int name_len)
3292 struct hash_entry *entry;
3294 index = hash(name, name_len);
3295 entry = state->hash_table[index];
3297 ((entry->name_len != name_len) ||
3298 (memcmp(entry->name, name, name_len) != 0))) {
3299 entry = entry->next;
3303 /* Get a private copy of the name */
3304 new_name = xmalloc(name_len + 1, "hash_name");
3305 memcpy(new_name, name, name_len);
3306 new_name[name_len] = '\0';
3308 /* Create a new hash entry */
3309 entry = xcmalloc(sizeof(*entry), "hash_entry");
3310 entry->next = state->hash_table[index];
3311 entry->name = new_name;
3312 entry->name_len = name_len;
3314 /* Place the new entry in the hash table */
3315 state->hash_table[index] = entry;
3320 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3322 struct hash_entry *entry;
3324 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3325 (entry->tok == TOK_ENUM_CONST) ||
3326 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3327 (entry->tok <= TOK_LAST_KEYWORD)))) {
3328 tk->tok = entry->tok;
3332 static void ident_to_macro(struct compile_state *state, struct token *tk)
3334 struct hash_entry *entry;
3338 if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3339 tk->tok = entry->tok;
3341 else if (entry->tok == TOK_IF) {
3344 else if (entry->tok == TOK_ELSE) {
3345 tk->tok = TOK_MELSE;
3348 tk->tok = TOK_MIDENT;
3352 static void hash_keyword(
3353 struct compile_state *state, const char *keyword, int tok)
3355 struct hash_entry *entry;
3356 entry = lookup(state, keyword, strlen(keyword));
3357 if (entry && entry->tok != TOK_UNKNOWN) {
3358 die("keyword %s already hashed", keyword);
3363 static void romcc_symbol(
3364 struct compile_state *state, struct hash_entry *ident,
3365 struct symbol **chain, struct triple *def, struct type *type, int depth)
3368 if (*chain && ((*chain)->scope_depth >= depth)) {
3369 error(state, 0, "%s already defined", ident->name);
3371 sym = xcmalloc(sizeof(*sym), "symbol");
3375 sym->scope_depth = depth;
3381 struct compile_state *state, struct hash_entry *ident,
3382 struct symbol **chain, struct triple *def, struct type *type)
3384 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3387 static void var_symbol(struct compile_state *state,
3388 struct hash_entry *ident, struct triple *def)
3390 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3391 internal_error(state, 0, "bad var type");
3393 symbol(state, ident, &ident->sym_ident, def, def->type);
3396 static void label_symbol(struct compile_state *state,
3397 struct hash_entry *ident, struct triple *label, int depth)
3399 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3402 static void start_scope(struct compile_state *state)
3404 state->scope_depth++;
3407 static void end_scope_syms(struct compile_state *state,
3408 struct symbol **chain, int depth)
3410 struct symbol *sym, *next;
3412 while(sym && (sym->scope_depth == depth)) {
3420 static void end_scope(struct compile_state *state)
3424 /* Walk through the hash table and remove all symbols
3425 * in the current scope.
3427 depth = state->scope_depth;
3428 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3429 struct hash_entry *entry;
3430 entry = state->hash_table[i];
3432 end_scope_syms(state, &entry->sym_label, depth);
3433 end_scope_syms(state, &entry->sym_tag, depth);
3434 end_scope_syms(state, &entry->sym_ident, depth);
3435 entry = entry->next;
3438 state->scope_depth = depth - 1;
3441 static void register_keywords(struct compile_state *state)
3443 hash_keyword(state, "auto", TOK_AUTO);
3444 hash_keyword(state, "break", TOK_BREAK);
3445 hash_keyword(state, "case", TOK_CASE);
3446 hash_keyword(state, "char", TOK_CHAR);
3447 hash_keyword(state, "const", TOK_CONST);
3448 hash_keyword(state, "continue", TOK_CONTINUE);
3449 hash_keyword(state, "default", TOK_DEFAULT);
3450 hash_keyword(state, "do", TOK_DO);
3451 hash_keyword(state, "double", TOK_DOUBLE);
3452 hash_keyword(state, "else", TOK_ELSE);
3453 hash_keyword(state, "enum", TOK_ENUM);
3454 hash_keyword(state, "extern", TOK_EXTERN);
3455 hash_keyword(state, "float", TOK_FLOAT);
3456 hash_keyword(state, "for", TOK_FOR);
3457 hash_keyword(state, "goto", TOK_GOTO);
3458 hash_keyword(state, "if", TOK_IF);
3459 hash_keyword(state, "inline", TOK_INLINE);
3460 hash_keyword(state, "int", TOK_INT);
3461 hash_keyword(state, "long", TOK_LONG);
3462 hash_keyword(state, "register", TOK_REGISTER);
3463 hash_keyword(state, "restrict", TOK_RESTRICT);
3464 hash_keyword(state, "return", TOK_RETURN);
3465 hash_keyword(state, "short", TOK_SHORT);
3466 hash_keyword(state, "signed", TOK_SIGNED);
3467 hash_keyword(state, "sizeof", TOK_SIZEOF);
3468 hash_keyword(state, "static", TOK_STATIC);
3469 hash_keyword(state, "struct", TOK_STRUCT);
3470 hash_keyword(state, "switch", TOK_SWITCH);
3471 hash_keyword(state, "typedef", TOK_TYPEDEF);
3472 hash_keyword(state, "union", TOK_UNION);
3473 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3474 hash_keyword(state, "void", TOK_VOID);
3475 hash_keyword(state, "volatile", TOK_VOLATILE);
3476 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3477 hash_keyword(state, "while", TOK_WHILE);
3478 hash_keyword(state, "asm", TOK_ASM);
3479 hash_keyword(state, "__asm__", TOK_ASM);
3480 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3481 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3484 static void register_macro_keywords(struct compile_state *state)
3486 hash_keyword(state, "define", TOK_MDEFINE);
3487 hash_keyword(state, "defined", TOK_MDEFINED);
3488 hash_keyword(state, "undef", TOK_MUNDEF);
3489 hash_keyword(state, "include", TOK_MINCLUDE);
3490 hash_keyword(state, "line", TOK_MLINE);
3491 hash_keyword(state, "error", TOK_MERROR);
3492 hash_keyword(state, "warning", TOK_MWARNING);
3493 hash_keyword(state, "pragma", TOK_MPRAGMA);
3494 hash_keyword(state, "ifdef", TOK_MIFDEF);
3495 hash_keyword(state, "ifndef", TOK_MIFNDEF);
3496 hash_keyword(state, "elif", TOK_MELIF);
3497 hash_keyword(state, "endif", TOK_MENDIF);
3501 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3503 if (ident->sym_define != 0) {
3504 struct macro *macro;
3505 struct macro_arg *arg, *anext;
3506 macro = ident->sym_define;
3507 ident->sym_define = 0;
3509 /* Free the macro arguments... */
3510 anext = macro->args;
3517 /* Free the macro buffer */
3520 /* Now free the macro itself */
3525 static void do_define_macro(struct compile_state *state,
3526 struct hash_entry *ident, const char *body,
3527 int argc, struct macro_arg *args)
3529 struct macro *macro;
3530 struct macro_arg *arg;
3533 /* Find the length of the body */
3534 body_len = strlen(body);
3535 macro = ident->sym_define;
3537 int identical_bodies, identical_args;
3538 struct macro_arg *oarg;
3539 /* Explicitly allow identical redfinitions of the same macro */
3541 (macro->buf_len == body_len) &&
3542 (memcmp(macro->buf, body, body_len) == 0);
3543 identical_args = macro->argc == argc;
3546 while(identical_args && arg) {
3547 identical_args = oarg->ident == arg->ident;
3551 if (identical_bodies && identical_args) {
3555 error(state, 0, "macro %s already defined\n", ident->name);
3558 fprintf(state->errout, "#define %s: `%*.*s'\n",
3559 ident->name, body_len, body_len, body);
3561 macro = xmalloc(sizeof(*macro), "macro");
3562 macro->ident = ident;
3564 macro->buf_len = body_len;
3568 ident->sym_define = macro;
3571 static void define_macro(
3572 struct compile_state *state,
3573 struct hash_entry *ident,
3574 const char *body, int body_len,
3575 int argc, struct macro_arg *args)
3578 buf = xmalloc(body_len + 1, "macro buf");
3579 memcpy(buf, body, body_len);
3580 buf[body_len] = '\0';
3581 do_define_macro(state, ident, buf, argc, args);
3584 static void register_builtin_macro(struct compile_state *state,
3585 const char *name, const char *value)
3587 struct hash_entry *ident;
3589 if (value[0] == '(') {
3590 internal_error(state, 0, "Builtin macros with arguments not supported");
3592 ident = lookup(state, name, strlen(name));
3593 define_macro(state, ident, value, strlen(value), -1, 0);
3596 static void register_builtin_macros(struct compile_state *state)
3603 tm = localtime(&now);
3605 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3606 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3607 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3608 register_builtin_macro(state, "__LINE__", "54321");
3610 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3611 sprintf(buf, "\"%s\"", scratch);
3612 register_builtin_macro(state, "__DATE__", buf);
3614 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3615 sprintf(buf, "\"%s\"", scratch);
3616 register_builtin_macro(state, "__TIME__", buf);
3618 /* I can't be a conforming implementation of C :( */
3619 register_builtin_macro(state, "__STDC__", "0");
3620 /* In particular I don't conform to C99 */
3621 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3625 static void process_cmdline_macros(struct compile_state *state)
3627 const char **macro, *name;
3628 struct hash_entry *ident;
3629 for(macro = state->compiler->defines; (name = *macro); macro++) {
3633 name_len = strlen(name);
3634 body = strchr(name, '=');
3638 name_len = body - name;
3641 ident = lookup(state, name, name_len);
3642 define_macro(state, ident, body, strlen(body), -1, 0);
3644 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3645 ident = lookup(state, name, strlen(name));
3646 undef_macro(state, ident);
3650 static int spacep(int c)
3665 static int digitp(int c)
3669 case '0': case '1': case '2': case '3': case '4':
3670 case '5': case '6': case '7': case '8': case '9':
3676 static int digval(int c)
3679 if ((c >= '0') && (c <= '9')) {
3685 static int hexdigitp(int c)
3689 case '0': case '1': case '2': case '3': case '4':
3690 case '5': case '6': case '7': case '8': case '9':
3691 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3692 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3698 static int hexdigval(int c)
3701 if ((c >= '0') && (c <= '9')) {
3704 else if ((c >= 'A') && (c <= 'F')) {
3705 val = 10 + (c - 'A');
3707 else if ((c >= 'a') && (c <= 'f')) {
3708 val = 10 + (c - 'a');
3713 static int octdigitp(int c)
3717 case '0': case '1': case '2': case '3':
3718 case '4': case '5': case '6': case '7':
3724 static int octdigval(int c)
3727 if ((c >= '0') && (c <= '7')) {
3733 static int letterp(int c)
3737 case 'a': case 'b': case 'c': case 'd': case 'e':
3738 case 'f': case 'g': case 'h': case 'i': case 'j':
3739 case 'k': case 'l': case 'm': case 'n': case 'o':
3740 case 'p': case 'q': case 'r': case 's': case 't':
3741 case 'u': case 'v': case 'w': case 'x': case 'y':
3743 case 'A': case 'B': case 'C': case 'D': case 'E':
3744 case 'F': case 'G': case 'H': case 'I': case 'J':
3745 case 'K': case 'L': case 'M': case 'N': case 'O':
3746 case 'P': case 'Q': case 'R': case 'S': case 'T':
3747 case 'U': case 'V': case 'W': case 'X': case 'Y':
3756 static const char *identifier(const char *str, const char *end)
3758 if (letterp(*str)) {
3759 for(; str < end; str++) {
3762 if (!letterp(c) && !digitp(c)) {
3770 static int char_value(struct compile_state *state,
3771 const signed char **strp, const signed char *end)
3773 const signed char *str;
3777 if ((c == '\\') && (str < end)) {
3779 case 'n': c = '\n'; str++; break;
3780 case 't': c = '\t'; str++; break;
3781 case 'v': c = '\v'; str++; break;
3782 case 'b': c = '\b'; str++; break;
3783 case 'r': c = '\r'; str++; break;
3784 case 'f': c = '\f'; str++; break;
3785 case 'a': c = '\a'; str++; break;
3786 case '\\': c = '\\'; str++; break;
3787 case '?': c = '?'; str++; break;
3788 case '\'': c = '\''; str++; break;
3789 case '"': c = '"'; str++; break;
3793 while((str < end) && hexdigitp(*str)) {
3795 c += hexdigval(*str);
3799 case '0': case '1': case '2': case '3':
3800 case '4': case '5': case '6': case '7':
3802 while((str < end) && octdigitp(*str)) {
3804 c += octdigval(*str);
3809 error(state, 0, "Invalid character constant");
3817 static const char *next_char(struct file_state *file, const char *pos, int index)
3819 const char *end = file->buf + file->size;
3821 /* Lookup the character */
3824 /* Is this a trigraph? */
3825 if (file->trigraphs &&
3826 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3829 case '=': c = '#'; break;
3830 case '/': c = '\\'; break;
3831 case '\'': c = '^'; break;
3832 case '(': c = '['; break;
3833 case ')': c = ']'; break;
3834 case '!': c = '!'; break;
3835 case '<': c = '{'; break;
3836 case '>': c = '}'; break;
3837 case '-': c = '~'; break;
3843 /* Is this an escaped newline? */
3844 if (file->join_lines &&
3845 (c == '\\') && (pos + size < end) && (pos[1] == '\n'))
3847 /* At the start of a line just eat it */
3848 if (pos == file->pos) {
3850 file->report_line++;
3851 file->line_start = pos + size + 1;
3855 /* Do I need to ga any farther? */
3856 else if (index == 0) {
3859 /* Process a normal character */
3868 static int get_char(struct file_state *file, const char *pos)
3870 const char *end = file->buf + file->size;
3873 pos = next_char(file, pos, 0);
3875 /* Lookup the character */
3877 /* If it is a trigraph get the trigraph value */
3878 if (file->trigraphs &&
3879 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3882 case '=': c = '#'; break;
3883 case '/': c = '\\'; break;
3884 case '\'': c = '^'; break;
3885 case '(': c = '['; break;
3886 case ')': c = ']'; break;
3887 case '!': c = '!'; break;
3888 case '<': c = '{'; break;
3889 case '>': c = '}'; break;
3890 case '-': c = '~'; break;
3897 static void eat_chars(struct file_state *file, const char *targ)
3899 const char *pos = file->pos;
3901 /* Do we have a newline? */
3902 if (pos[0] == '\n') {
3904 file->report_line++;
3905 file->line_start = pos + 1;
3913 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3918 src = next_char(file, src, 1);
3924 static void char_strcpy(char *dest,
3925 struct file_state *file, const char *src, const char *end)
3929 c = get_char(file, src);
3930 src = next_char(file, src, 1);
3935 static char *char_strdup(struct file_state *file,
3936 const char *start, const char *end, const char *id)
3940 str_len = char_strlen(file, start, end);
3941 str = xcmalloc(str_len + 1, id);
3942 char_strcpy(str, file, start, end);
3943 str[str_len] = '\0';
3947 static const char *after_digits(struct file_state *file, const char *ptr)
3949 while(digitp(get_char(file, ptr))) {
3950 ptr = next_char(file, ptr, 1);
3955 static const char *after_octdigits(struct file_state *file, const char *ptr)
3957 while(octdigitp(get_char(file, ptr))) {
3958 ptr = next_char(file, ptr, 1);
3963 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3965 while(hexdigitp(get_char(file, ptr))) {
3966 ptr = next_char(file, ptr, 1);
3971 static const char *after_alnums(struct file_state *file, const char *ptr)
3974 c = get_char(file, ptr);
3975 while(letterp(c) || digitp(c)) {
3976 ptr = next_char(file, ptr, 1);
3977 c = get_char(file, ptr);
3982 static void save_string(struct file_state *file,
3983 struct token *tk, const char *start, const char *end, const char *id)
3987 /* Create a private copy of the string */
3988 str = char_strdup(file, start, end, id);
3990 /* Store the copy in the token */
3992 tk->str_len = strlen(str);
3995 static void raw_next_token(struct compile_state *state,
3996 struct file_state *file, struct token *tk)
4006 token = tokp = next_char(file, file->pos, 0);
4008 c = get_char(file, tokp);
4009 tokp = next_char(file, tokp, 1);
4011 c1 = get_char(file, tokp);
4012 c2 = get_char(file, next_char(file, tokp, 1));
4013 c3 = get_char(file, next_char(file, tokp, 2));
4015 /* The end of the file */
4020 else if (spacep(c)) {
4022 while (spacep(get_char(file, tokp))) {
4023 tokp = next_char(file, tokp, 1);
4027 else if ((c == '/') && (c1 == '/')) {
4029 tokp = next_char(file, tokp, 1);
4030 while((c = get_char(file, tokp)) != -1) {
4031 tokp = next_char(file, tokp, 1);
4038 else if ((c == '/') && (c1 == '*')) {
4039 tokp = next_char(file, tokp, 2);
4041 while((c1 = get_char(file, tokp)) != -1) {
4042 tokp = next_char(file, tokp, 1);
4043 if ((c == '*') && (c1 == '/')) {
4049 if (tok == TOK_UNKNOWN) {
4050 error(state, 0, "unterminated comment");
4053 /* string constants */
4054 else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4055 int wchar, multiline;
4061 tokp = next_char(file, tokp, 1);
4063 while((c = get_char(file, tokp)) != -1) {
4064 tokp = next_char(file, tokp, 1);
4068 else if (c == '\\') {
4069 tokp = next_char(file, tokp, 1);
4071 else if (c == '"') {
4072 tok = TOK_LIT_STRING;
4076 if (tok == TOK_UNKNOWN) {
4077 error(state, 0, "unterminated string constant");
4080 warning(state, 0, "multiline string constant");
4083 /* Save the string value */
4084 save_string(file, tk, token, tokp, "literal string");
4086 /* character constants */
4087 else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4088 int wchar, multiline;
4094 tokp = next_char(file, tokp, 1);
4096 while((c = get_char(file, tokp)) != -1) {
4097 tokp = next_char(file, tokp, 1);
4101 else if (c == '\\') {
4102 tokp = next_char(file, tokp, 1);
4104 else if (c == '\'') {
4109 if (tok == TOK_UNKNOWN) {
4110 error(state, 0, "unterminated character constant");
4113 warning(state, 0, "multiline character constant");
4116 /* Save the character value */
4117 save_string(file, tk, token, tokp, "literal character");
4119 /* integer and floating constants
4125 * Floating constants
4126 * {digits}.{digits}[Ee][+-]?{digits}
4128 * {digits}[Ee][+-]?{digits}
4129 * .{digits}[Ee][+-]?{digits}
4132 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4138 next = after_digits(file, tokp);
4143 cn = get_char(file, next);
4145 next = next_char(file, next, 1);
4146 next = after_digits(file, next);
4149 cn = get_char(file, next);
4150 if ((cn == 'e') || (cn == 'E')) {
4152 next = next_char(file, next, 1);
4153 cn = get_char(file, next);
4154 if ((cn == '+') || (cn == '-')) {
4155 next = next_char(file, next, 1);
4157 new = after_digits(file, next);
4158 is_float |= (new != next);
4162 tok = TOK_LIT_FLOAT;
4163 cn = get_char(file, next);
4164 if ((cn == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4165 next = next_char(file, next, 1);
4168 if (!is_float && digitp(c)) {
4170 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4171 next = next_char(file, tokp, 1);
4172 next = after_hexdigits(file, next);
4174 else if (c == '0') {
4175 next = after_octdigits(file, tokp);
4178 next = after_digits(file, tokp);
4180 /* crazy integer suffixes */
4181 cn = get_char(file, next);
4182 if ((cn == 'u') || (cn == 'U')) {
4183 next = next_char(file, next, 1);
4184 cn = get_char(file, next);
4185 if ((cn == 'l') || (cn == 'L')) {
4186 next = next_char(file, next, 1);
4187 cn = get_char(file, next);
4189 if ((cn == 'l') || (cn == 'L')) {
4190 next = next_char(file, next, 1);
4193 else if ((cn == 'l') || (cn == 'L')) {
4194 next = next_char(file, next, 1);
4195 cn = get_char(file, next);
4196 if ((cn == 'l') || (cn == 'L')) {
4197 next = next_char(file, next, 1);
4198 cn = get_char(file, next);
4200 if ((cn == 'u') || (cn == 'U')) {
4201 next = next_char(file, next, 1);
4207 /* Save the integer/floating point value */
4208 save_string(file, tk, token, tokp, "literal number");
4211 else if (letterp(c)) {
4214 /* Find and save the identifier string */
4215 tokp = after_alnums(file, tokp);
4216 save_string(file, tk, token, tokp, "identifier");
4218 /* Look up to see which identifier it is */
4219 tk->ident = lookup(state, tk->val.str, tk->str_len);
4221 /* Free the identifier string */
4225 /* See if this identifier can be macro expanded */
4226 tk->val.notmacro = 0;
4227 c = get_char(file, tokp);
4229 tokp = next_char(file, tokp, 1);
4230 tk->val.notmacro = 1;
4233 /* C99 alternate macro characters */
4234 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4236 tok = TOK_CONCATENATE;
4238 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4239 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4240 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4241 else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4242 else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4243 else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4244 else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4245 else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4246 else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4247 else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4248 else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4249 else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4250 else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4251 else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4252 else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4253 else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4254 else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4255 else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4256 else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4257 else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4258 else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4259 else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4260 else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4261 else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4262 else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4263 else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4264 else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4265 else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4266 else if (c == ';') { tok = TOK_SEMI; }
4267 else if (c == '{') { tok = TOK_LBRACE; }
4268 else if (c == '}') { tok = TOK_RBRACE; }
4269 else if (c == ',') { tok = TOK_COMMA; }
4270 else if (c == '=') { tok = TOK_EQ; }
4271 else if (c == ':') { tok = TOK_COLON; }
4272 else if (c == '[') { tok = TOK_LBRACKET; }
4273 else if (c == ']') { tok = TOK_RBRACKET; }
4274 else if (c == '(') { tok = TOK_LPAREN; }
4275 else if (c == ')') { tok = TOK_RPAREN; }
4276 else if (c == '*') { tok = TOK_STAR; }
4277 else if (c == '>') { tok = TOK_MORE; }
4278 else if (c == '<') { tok = TOK_LESS; }
4279 else if (c == '?') { tok = TOK_QUEST; }
4280 else if (c == '|') { tok = TOK_OR; }
4281 else if (c == '&') { tok = TOK_AND; }
4282 else if (c == '^') { tok = TOK_XOR; }
4283 else if (c == '+') { tok = TOK_PLUS; }
4284 else if (c == '-') { tok = TOK_MINUS; }
4285 else if (c == '/') { tok = TOK_DIV; }
4286 else if (c == '%') { tok = TOK_MOD; }
4287 else if (c == '!') { tok = TOK_BANG; }
4288 else if (c == '.') { tok = TOK_DOT; }
4289 else if (c == '~') { tok = TOK_TILDE; }
4290 else if (c == '#') { tok = TOK_MACRO; }
4291 else if (c == '\n') { tok = TOK_EOL; }
4293 tokp = next_char(file, tokp, eat);
4294 eat_chars(file, tokp);
4299 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4301 if (tk->tok != tok) {
4302 const char *name1, *name2;
4303 name1 = tokens[tk->tok];
4305 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4306 name2 = tk->ident->name;
4308 error(state, 0, "\tfound %s %s expected %s",
4309 name1, name2, tokens[tok]);
4313 struct macro_arg_value {
4314 struct hash_entry *ident;
4315 unsigned char *value;
4318 static struct macro_arg_value *read_macro_args(
4319 struct compile_state *state, struct macro *macro,
4320 struct file_state *file, struct token *tk)
4322 struct macro_arg_value *argv;
4323 struct macro_arg *arg;
4327 if (macro->argc == 0) {
4329 raw_next_token(state, file, tk);
4330 } while(tk->tok == TOK_SPACE);
4333 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4334 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4337 argv[i].ident = arg->ident;
4346 raw_next_token(state, file, tk);
4348 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4349 (argv[i].ident != state->i___VA_ARGS__))
4352 if (i >= macro->argc) {
4353 error(state, 0, "too many args to %s\n",
4354 macro->ident->name);
4359 if (tk->tok == TOK_LPAREN) {
4363 if (tk->tok == TOK_RPAREN) {
4364 if (paren_depth == 0) {
4369 if (tk->tok == TOK_EOF) {
4370 error(state, 0, "End of file encountered while parsing macro arguments");
4373 len = char_strlen(file, start, file->pos);
4374 argv[i].value = xrealloc(
4375 argv[i].value, argv[i].len + len, "macro args");
4376 char_strcpy(argv[i].value + argv[i].len, file, start, file->pos);
4379 if (i != macro->argc -1) {
4380 error(state, 0, "missing %s arg %d\n",
4381 macro->ident->name, i +2);
4387 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4390 for(i = 0; i < macro->argc; i++) {
4391 xfree(argv[i].value);
4401 static void grow_macro_buf(struct compile_state *state,
4402 const char *id, struct macro_buf *buf,
4405 if ((buf->pos + grow) >= buf->len) {
4406 buf->str = xrealloc(buf->str, buf->len + grow, id);
4411 static void append_macro_text(struct compile_state *state,
4412 const char *id, struct macro_buf *buf,
4413 const char *fstart, size_t flen)
4415 grow_macro_buf(state, id, buf, flen);
4416 memcpy(buf->str + buf->pos, fstart, flen);
4418 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4419 buf->pos, buf->pos, buf->str,
4420 flen, flen, buf->str + buf->pos);
4426 static void append_macro_chars(struct compile_state *state,
4427 const char *id, struct macro_buf *buf,
4428 struct file_state *file, const char *start, const char *end)
4431 flen = char_strlen(file, start, end);
4432 grow_macro_buf(state, id, buf, flen);
4433 char_strcpy(buf->str + buf->pos, file, start, end);
4435 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4436 buf->pos, buf->pos, buf->str,
4437 flen, flen, buf->str + buf->pos);
4442 static int compile_macro(struct compile_state *state,
4443 struct file_state **filep, struct token *tk);
4445 static void macro_expand_args(struct compile_state *state,
4446 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4450 for(i = 0; i < macro->argc; i++) {
4451 struct file_state fmacro, *file;
4452 struct macro_buf buf;
4455 fmacro.basename = argv[i].ident->name;
4456 fmacro.dirname = "";
4457 fmacro.buf = argv[i].value;
4458 fmacro.size = argv[i].len;
4459 fmacro.pos = fmacro.buf;
4461 fmacro.line_start = fmacro.buf;
4462 fmacro.report_line = 1;
4463 fmacro.report_name = fmacro.basename;
4464 fmacro.report_dir = fmacro.dirname;
4466 fmacro.trigraphs = 0;
4467 fmacro.join_lines = 0;
4469 buf.len = argv[i].len;
4470 buf.str = xmalloc(buf.len, argv[i].ident->name);
4475 raw_next_token(state, file, tk);
4477 /* If we have recursed into another macro body
4480 if (tk->tok == TOK_EOF) {
4481 struct file_state *old;
4487 /* old->basename is used keep it */
4488 xfree(old->dirname);
4493 else if (tk->ident && tk->ident->sym_define) {
4494 if (compile_macro(state, &file, tk)) {
4499 append_macro_chars(state, macro->ident->name, &buf,
4500 file, tk->pos, file->pos);
4503 xfree(argv[i].value);
4504 argv[i].value = buf.str;
4505 argv[i].len = buf.pos;
4510 static void expand_macro(struct compile_state *state,
4511 struct macro *macro, struct macro_buf *buf,
4512 struct macro_arg_value *argv, struct token *tk)
4514 struct file_state fmacro;
4515 const char space[] = " ";
4520 /* Place the macro body in a dummy file */
4522 fmacro.basename = macro->ident->name;
4523 fmacro.dirname = "";
4524 fmacro.buf = macro->buf;
4525 fmacro.size = macro->buf_len;
4526 fmacro.pos = fmacro.buf;
4528 fmacro.line_start = fmacro.buf;
4529 fmacro.report_line = 1;
4530 fmacro.report_name = fmacro.basename;
4531 fmacro.report_dir = fmacro.dirname;
4533 fmacro.trigraphs = 0;
4534 fmacro.join_lines = 0;
4536 /* Allocate a buffer to hold the macro expansion */
4537 buf->len = macro->buf_len + 3;
4538 buf->str = xmalloc(buf->len, macro->ident->name);
4541 fstart = fmacro.pos;
4542 raw_next_token(state, &fmacro, tk);
4543 while(tk->tok != TOK_EOF) {
4544 flen = fmacro.pos - fstart;
4547 for(i = 0; i < macro->argc; i++) {
4548 if (argv[i].ident == tk->ident) {
4552 if (i >= macro->argc) {
4555 /* Substitute macro parameter */
4556 fstart = argv[i].value;
4560 if (macro->argc < 0) {
4564 raw_next_token(state, &fmacro, tk);
4565 } while(tk->tok == TOK_SPACE);
4566 check_tok(state, tk, TOK_IDENT);
4567 for(i = 0; i < macro->argc; i++) {
4568 if (argv[i].ident == tk->ident) {
4572 if (i >= macro->argc) {
4573 error(state, 0, "parameter `%s' not found",
4576 /* Stringize token */
4577 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4578 for(j = 0; j < argv[i].len; j++) {
4579 char *str = argv[i].value + j;
4585 else if (*str == '"') {
4589 append_macro_text(state, macro->ident->name, buf, str, len);
4591 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4595 case TOK_CONCATENATE:
4596 /* Concatenate tokens */
4597 /* Delete the previous whitespace token */
4598 if (buf->str[buf->pos - 1] == ' ') {
4601 /* Skip the next sequence of whitspace tokens */
4603 fstart = fmacro.pos;
4604 raw_next_token(state, &fmacro, tk);
4605 } while(tk->tok == TOK_SPACE);
4606 /* Restart at the top of the loop.
4607 * I need to process the non white space token.
4612 /* Collapse multiple spaces into one */
4613 if (buf->str[buf->pos - 1] != ' ') {
4625 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4627 fstart = fmacro.pos;
4628 raw_next_token(state, &fmacro, tk);
4632 static void tag_macro_name(struct compile_state *state,
4633 struct macro *macro, struct macro_buf *buf,
4636 /* Guard all instances of the macro name in the replacement
4637 * text from further macro expansion.
4639 struct file_state fmacro;
4643 /* Put the old macro expansion buffer in a file */
4645 fmacro.basename = macro->ident->name;
4646 fmacro.dirname = "";
4647 fmacro.buf = buf->str;
4648 fmacro.size = buf->pos;
4649 fmacro.pos = fmacro.buf;
4651 fmacro.line_start = fmacro.buf;
4652 fmacro.report_line = 1;
4653 fmacro.report_name = fmacro.basename;
4654 fmacro.report_dir = fmacro.dirname;
4656 fmacro.trigraphs = 0;
4657 fmacro.join_lines = 0;
4659 /* Allocate a new macro expansion buffer */
4660 buf->len = macro->buf_len + 3;
4661 buf->str = xmalloc(buf->len, macro->ident->name);
4664 fstart = fmacro.pos;
4665 raw_next_token(state, &fmacro, tk);
4666 while(tk->tok != TOK_EOF) {
4667 flen = fmacro.pos - fstart;
4668 if ((tk->tok == TOK_IDENT) &&
4669 (tk->ident == macro->ident) &&
4670 (tk->val.notmacro == 0))
4672 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4677 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4679 fstart = fmacro.pos;
4680 raw_next_token(state, &fmacro, tk);
4685 static int compile_macro(struct compile_state *state,
4686 struct file_state **filep, struct token *tk)
4688 struct file_state *file;
4689 struct hash_entry *ident;
4690 struct macro *macro;
4691 struct macro_arg_value *argv;
4692 struct macro_buf buf;
4695 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4698 macro = ident->sym_define;
4700 /* If this token comes from a macro expansion ignore it */
4701 if (tk->val.notmacro) {
4704 /* If I am a function like macro and the identifier is not followed
4705 * by a left parenthesis, do nothing.
4707 if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4711 /* Read in the macro arguments */
4713 if (macro->argc >= 0) {
4714 raw_next_token(state, *filep, tk);
4715 check_tok(state, tk, TOK_LPAREN);
4717 argv = read_macro_args(state, macro, *filep, tk);
4719 check_tok(state, tk, TOK_RPAREN);
4721 /* Macro expand the macro arguments */
4722 macro_expand_args(state, macro, argv, tk);
4727 if (ident == state->i___FILE__) {
4728 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4729 buf.str = xmalloc(buf.len, ident->name);
4730 sprintf(buf.str, "\"%s\"", state->file->basename);
4731 buf.pos = strlen(buf.str);
4733 else if (ident == state->i___LINE__) {
4735 buf.str = xmalloc(buf.len, ident->name);
4736 sprintf(buf.str, "%d", state->file->line);
4737 buf.pos = strlen(buf.str);
4740 expand_macro(state, macro, &buf, argv, tk);
4742 /* Tag the macro name with a $ so it will no longer
4743 * be regonized as a canidate for macro expansion.
4745 tag_macro_name(state, macro, &buf, tk);
4748 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4749 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4752 free_macro_args(macro, argv);
4754 file = xmalloc(sizeof(*file), "file_state");
4755 file->prev = *filep;
4756 file->basename = xstrdup(ident->name);
4757 file->dirname = xstrdup("");
4758 file->buf = buf.str;
4759 file->size = buf.pos;
4760 file->pos = file->buf;
4762 file->line_start = file->pos;
4763 file->report_line = 1;
4764 file->report_name = file->basename;
4765 file->report_dir = file->dirname;
4767 file->trigraphs = 0;
4768 file->join_lines = 0;
4773 static void eat_tokens(struct compile_state *state, int targ_tok)
4775 if (state->eat_depth > 0) {
4776 internal_error(state, 0, "Already eating...");
4778 state->eat_depth = state->if_depth;
4779 state->eat_targ = targ_tok;
4781 static int if_eat(struct compile_state *state)
4783 return state->eat_depth > 0;
4785 static int if_value(struct compile_state *state)
4788 index = state->if_depth / CHAR_BIT;
4789 offset = state->if_depth % CHAR_BIT;
4790 return !!(state->if_bytes[index] & (1 << (offset)));
4792 static void set_if_value(struct compile_state *state, int value)
4795 index = state->if_depth / CHAR_BIT;
4796 offset = state->if_depth % CHAR_BIT;
4798 state->if_bytes[index] &= ~(1 << offset);
4800 state->if_bytes[index] |= (1 << offset);
4803 static void in_if(struct compile_state *state, const char *name)
4805 if (state->if_depth <= 0) {
4806 error(state, 0, "%s without #if", name);
4809 static void enter_if(struct compile_state *state)
4811 state->if_depth += 1;
4812 if (state->if_depth > MAX_PP_IF_DEPTH) {
4813 error(state, 0, "#if depth too great");
4816 static void reenter_if(struct compile_state *state, const char *name)
4819 if ((state->eat_depth == state->if_depth) &&
4820 (state->eat_targ == TOK_MELSE)) {
4821 state->eat_depth = 0;
4822 state->eat_targ = 0;
4825 static void enter_else(struct compile_state *state, const char *name)
4828 if ((state->eat_depth == state->if_depth) &&
4829 (state->eat_targ == TOK_MELSE)) {
4830 state->eat_depth = 0;
4831 state->eat_targ = 0;
4834 static void exit_if(struct compile_state *state, const char *name)
4837 if (state->eat_depth == state->if_depth) {
4838 state->eat_depth = 0;
4839 state->eat_targ = 0;
4841 state->if_depth -= 1;
4844 static void raw_token(struct compile_state *state, struct token *tk)
4846 struct file_state *file;
4850 raw_next_token(state, file, tk);
4854 /* Exit out of an include directive or macro call */
4855 if ((tk->tok == TOK_EOF) &&
4856 (file != state->macro_file) && file->prev)
4858 state->file = file->prev;
4859 /* file->basename is used keep it */
4860 xfree(file->dirname);
4864 raw_next_token(state, state->file, tk);
4870 static void pp_token(struct compile_state *state, struct token *tk)
4872 struct file_state *file;
4875 raw_token(state, tk);
4879 if (tk->tok == TOK_SPACE) {
4880 raw_token(state, tk);
4883 else if (tk->tok == TOK_IDENT) {
4884 if (state->token_base == 0) {
4885 ident_to_keyword(state, tk);
4887 ident_to_macro(state, tk);
4893 static void preprocess(struct compile_state *state, struct token *tk);
4895 static void token(struct compile_state *state, struct token *tk)
4898 pp_token(state, tk);
4901 /* Process a macro directive */
4902 if (tk->tok == TOK_MACRO) {
4903 /* Only match preprocessor directives at the start of a line */
4905 ptr = state->file->line_start;
4906 while((ptr < tk->pos)
4907 && spacep(get_char(state->file, ptr)))
4909 ptr = next_char(state->file, ptr, 1);
4911 if (ptr == tk->pos) {
4912 preprocess(state, tk);
4916 /* Expand a macro call */
4917 else if (tk->ident && tk->ident->sym_define) {
4918 rescan = compile_macro(state, &state->file, tk);
4920 pp_token(state, tk);
4923 /* Eat tokens disabled by the preprocessor
4924 * (Unless we are parsing a preprocessor directive
4926 else if (if_eat(state) && (state->token_base == 0)) {
4927 pp_token(state, tk);
4930 /* Make certain EOL only shows up in preprocessor directives */
4931 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4932 pp_token(state, tk);
4935 /* Error on unknown tokens */
4936 else if (tk->tok == TOK_UNKNOWN) {
4937 error(state, 0, "unknown token");
4943 static inline struct token *get_token(struct compile_state *state, int offset)
4946 index = state->token_base + offset;
4947 if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4948 internal_error(state, 0, "token array to small");
4950 return &state->token[index];
4953 static struct token *do_eat_token(struct compile_state *state, int tok)
4957 check_tok(state, get_token(state, 1), tok);
4959 /* Free the old token value */
4960 tk = get_token(state, 0);
4962 memset((void *)tk->val.str, -1, tk->str_len);
4965 /* Overwrite the old token with newer tokens */
4966 for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4967 state->token[i] = state->token[i + 1];
4969 /* Clear the last token */
4970 memset(&state->token[i], 0, sizeof(state->token[i]));
4971 state->token[i].tok = -1;
4973 /* Return the token */
4977 static int raw_peek(struct compile_state *state)
4980 tk1 = get_token(state, 1);
4981 if (tk1->tok == -1) {
4982 raw_token(state, tk1);
4987 static struct token *raw_eat(struct compile_state *state, int tok)
4990 return do_eat_token(state, tok);
4993 static int pp_peek(struct compile_state *state)
4996 tk1 = get_token(state, 1);
4997 if (tk1->tok == -1) {
4998 pp_token(state, tk1);
5003 static struct token *pp_eat(struct compile_state *state, int tok)
5006 return do_eat_token(state, tok);
5009 static int peek(struct compile_state *state)
5012 tk1 = get_token(state, 1);
5013 if (tk1->tok == -1) {
5019 static int peek2(struct compile_state *state)
5021 struct token *tk1, *tk2;
5022 tk1 = get_token(state, 1);
5023 tk2 = get_token(state, 2);
5024 if (tk1->tok == -1) {
5027 if (tk2->tok == -1) {
5033 static struct token *eat(struct compile_state *state, int tok)
5036 return do_eat_token(state, tok);
5039 static void compile_file(struct compile_state *state, const char *filename, int local)
5041 char cwd[MAX_CWD_SIZE];
5042 const char *subdir, *base;
5044 struct file_state *file;
5046 file = xmalloc(sizeof(*file), "file_state");
5048 base = strrchr(filename, '/');
5051 subdir_len = base - filename;
5058 basename = xmalloc(strlen(base) +1, "basename");
5059 strcpy(basename, base);
5060 file->basename = basename;
5062 if (getcwd(cwd, sizeof(cwd)) == 0) {
5063 die("cwd buffer to small");
5065 if (subdir[0] == '/') {
5066 file->dirname = xmalloc(subdir_len + 1, "dirname");
5067 memcpy(file->dirname, subdir, subdir_len);
5068 file->dirname[subdir_len] = '\0';
5074 /* Find the appropriate directory... */
5076 if (!state->file && exists(cwd, filename)) {
5079 if (local && state->file && exists(state->file->dirname, filename)) {
5080 dir = state->file->dirname;
5082 for(path = state->compiler->include_paths; !dir && *path; path++) {
5083 if (exists(*path, filename)) {
5088 error(state, 0, "Cannot open `%s'\n", filename);
5090 dirlen = strlen(dir);
5091 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5092 memcpy(file->dirname, dir, dirlen);
5093 file->dirname[dirlen] = '/';
5094 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5095 file->dirname[dirlen + 1 + subdir_len] = '\0';
5097 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5099 file->pos = file->buf;
5100 file->line_start = file->pos;
5103 file->report_line = 1;
5104 file->report_name = file->basename;
5105 file->report_dir = file->dirname;
5107 file->trigraphs = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5108 file->join_lines = 1;
5110 file->prev = state->file;
5114 static struct triple *constant_expr(struct compile_state *state);
5115 static void integral(struct compile_state *state, struct triple *def);
5117 static int mcexpr(struct compile_state *state)
5119 struct triple *cvalue;
5120 cvalue = constant_expr(state);
5121 integral(state, cvalue);
5122 if (cvalue->op != OP_INTCONST) {
5123 error(state, 0, "integer constant expected");
5125 return cvalue->u.cval != 0;
5128 static void preprocess(struct compile_state *state, struct token *current_token)
5130 /* Doing much more with the preprocessor would require
5131 * a parser and a major restructuring.
5132 * Postpone that for later.
5137 state->macro_file = state->file;
5139 old_token_base = state->token_base;
5140 state->token_base = current_token - state->token;
5142 tok = pp_peek(state);
5148 tk = pp_eat(state, TOK_LIT_INT);
5149 override_line = strtoul(tk->val.str, 0, 10);
5150 /* I have a preprocessor line marker parse it */
5151 if (pp_peek(state) == TOK_LIT_STRING) {
5152 const char *token, *base;
5154 int name_len, dir_len;
5155 tk = pp_eat(state, TOK_LIT_STRING);
5156 name = xmalloc(tk->str_len, "report_name");
5157 token = tk->val.str + 1;
5158 base = strrchr(token, '/');
5159 name_len = tk->str_len -2;
5161 dir_len = base - token;
5163 name_len -= base - token;
5168 memcpy(name, base, name_len);
5169 name[name_len] = '\0';
5170 dir = xmalloc(dir_len + 1, "report_dir");
5171 memcpy(dir, token, dir_len);
5172 dir[dir_len] = '\0';
5173 state->file->report_line = override_line - 1;
5174 state->file->report_name = name;
5175 state->file->report_dir = dir;
5176 state->file->macro = 0;
5183 pp_eat(state, TOK_MLINE);
5184 tk = eat(state, TOK_LIT_INT);
5185 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5186 if (pp_peek(state) == TOK_LIT_STRING) {
5187 const char *token, *base;
5189 int name_len, dir_len;
5190 tk = pp_eat(state, TOK_LIT_STRING);
5191 name = xmalloc(tk->str_len, "report_name");
5192 token = tk->val.str + 1;
5193 base = strrchr(token, '/');
5194 name_len = tk->str_len - 2;
5196 dir_len = base - token;
5198 name_len -= base - token;
5203 memcpy(name, base, name_len);
5204 name[name_len] = '\0';
5205 dir = xmalloc(dir_len + 1, "report_dir");
5206 memcpy(dir, token, dir_len);
5207 dir[dir_len] = '\0';
5208 state->file->report_name = name;
5209 state->file->report_dir = dir;
5210 state->file->macro = 0;
5216 struct hash_entry *ident;
5217 pp_eat(state, TOK_MUNDEF);
5218 if (if_eat(state)) /* quit early when #if'd out */
5221 ident = pp_eat(state, TOK_MIDENT)->ident;
5223 undef_macro(state, ident);
5227 pp_eat(state, TOK_MPRAGMA);
5228 if (if_eat(state)) /* quit early when #if'd out */
5230 warning(state, 0, "Ignoring pragma");
5233 pp_eat(state, TOK_MELIF);
5234 reenter_if(state, "#elif");
5235 if (if_eat(state)) /* quit early when #if'd out */
5237 /* If the #if was taken the #elif just disables the following code */
5238 if (if_value(state)) {
5239 eat_tokens(state, TOK_MENDIF);
5241 /* If the previous #if was not taken see if the #elif enables the
5245 set_if_value(state, mcexpr(state));
5246 if (!if_value(state)) {
5247 eat_tokens(state, TOK_MELSE);
5252 pp_eat(state, TOK_MIF);
5254 if (if_eat(state)) /* quit early when #if'd out */
5256 set_if_value(state, mcexpr(state));
5257 if (!if_value(state)) {
5258 eat_tokens(state, TOK_MELSE);
5263 struct hash_entry *ident;
5265 pp_eat(state, TOK_MIFNDEF);
5267 if (if_eat(state)) /* quit early when #if'd out */
5269 ident = pp_eat(state, TOK_MIDENT)->ident;
5270 set_if_value(state, ident->sym_define == 0);
5271 if (!if_value(state)) {
5272 eat_tokens(state, TOK_MELSE);
5278 struct hash_entry *ident;
5279 pp_eat(state, TOK_MIFDEF);
5281 if (if_eat(state)) /* quit early when #if'd out */
5283 ident = pp_eat(state, TOK_MIDENT)->ident;
5284 set_if_value(state, ident->sym_define != 0);
5285 if (!if_value(state)) {
5286 eat_tokens(state, TOK_MELSE);
5291 pp_eat(state, TOK_MELSE);
5292 enter_else(state, "#else");
5293 if (!if_eat(state) && if_value(state)) {
5294 eat_tokens(state, TOK_MENDIF);
5298 pp_eat(state, TOK_MENDIF);
5299 exit_if(state, "#endif");
5303 struct hash_entry *ident;
5304 struct macro_arg *args, **larg;
5305 const char *mstart, *mend;
5308 pp_eat(state, TOK_MDEFINE);
5309 if (if_eat(state)) /* quit early when #if'd out */
5311 ident = pp_eat(state, TOK_MIDENT)->ident;
5316 /* Parse macro parameters */
5317 if (raw_peek(state) == TOK_LPAREN) {
5318 raw_eat(state, TOK_LPAREN);
5322 struct macro_arg *narg, *arg;
5323 struct hash_entry *aident;
5326 tok = pp_peek(state);
5327 if (!args && (tok == TOK_RPAREN)) {
5330 else if (tok == TOK_DOTS) {
5331 pp_eat(state, TOK_DOTS);
5332 aident = state->i___VA_ARGS__;
5335 aident = pp_eat(state, TOK_MIDENT)->ident;
5338 narg = xcmalloc(sizeof(*arg), "macro arg");
5339 narg->ident = aident;
5341 /* Verify I don't have a duplicate identifier */
5342 for(arg = args; arg; arg = arg->next) {
5343 if (arg->ident == narg->ident) {
5344 error(state, 0, "Duplicate macro arg `%s'",
5348 /* Add the new argument to the end of the list */
5353 if ((aident == state->i___VA_ARGS__) ||
5354 (pp_peek(state) != TOK_COMMA)) {
5357 pp_eat(state, TOK_COMMA);
5359 pp_eat(state, TOK_RPAREN);
5361 /* Remove leading whitespace */
5362 while(raw_peek(state) == TOK_SPACE) {
5363 raw_eat(state, TOK_SPACE);
5366 /* Remember the start of the macro body */
5367 tok = raw_peek(state);
5368 mend = mstart = get_token(state, 1)->pos;
5370 /* Find the end of the macro */
5371 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5372 raw_eat(state, tok);
5373 /* Remember the end of the last non space token */
5375 if (tok != TOK_SPACE) {
5376 mend = get_token(state, 1)->pos;
5380 /* Now that I have found the body defined the token */
5381 do_define_macro(state, ident,
5382 char_strdup(state->file, mstart, mend, "macro buf"),
5388 const char *start, *end;
5391 pp_eat(state, TOK_MERROR);
5392 /* Find the start of the line */
5394 start = get_token(state, 1)->pos;
5396 /* Find the end of the line */
5397 while((tok = raw_peek(state)) != TOK_EOL) {
5398 raw_eat(state, tok);
5400 end = get_token(state, 1)->pos;
5402 if (!if_eat(state)) {
5403 error(state, 0, "%*.*s", len, len, start);
5409 const char *start, *end;
5412 pp_eat(state, TOK_MWARNING);
5414 /* Find the start of the line */
5416 start = get_token(state, 1)->pos;
5418 /* Find the end of the line */
5419 while((tok = raw_peek(state)) != TOK_EOL) {
5420 raw_eat(state, tok);
5422 end = get_token(state, 1)->pos;
5424 if (!if_eat(state)) {
5425 warning(state, 0, "%*.*s", len, len, start);
5436 pp_eat(state, TOK_MINCLUDE);
5438 if (tok == TOK_LIT_STRING) {
5442 tk = eat(state, TOK_LIT_STRING);
5443 name = xmalloc(tk->str_len, "include");
5444 token = tk->val.str +1;
5445 name_len = tk->str_len -2;
5446 if (*token == '"') {
5450 memcpy(name, token, name_len);
5451 name[name_len] = '\0';
5454 else if (tok == TOK_LESS) {
5455 struct macro_buf buf;
5456 eat(state, TOK_LESS);
5459 buf.str = xmalloc(buf.len, "include");
5463 while((tok != TOK_MORE) &&
5464 (tok != TOK_EOL) && (tok != TOK_EOF))
5467 tk = eat(state, tok);
5468 append_macro_chars(state, "include", &buf,
5469 state->file, tk->pos, state->file->pos);
5472 append_macro_text(state, "include", &buf, "\0", 1);
5473 if (peek(state) != TOK_MORE) {
5474 error(state, 0, "Unterminated include directive");
5476 eat(state, TOK_MORE);
5481 error(state, 0, "Invalid include directive");
5483 /* Error if there are any tokens after the include */
5484 if (pp_peek(state) != TOK_EOL) {
5485 error(state, 0, "garbage after include directive");
5487 if (!if_eat(state)) {
5488 compile_file(state, name, local);
5494 /* Ignore # without a follwing ident */
5498 const char *name1, *name2;
5499 name1 = tokens[tok];
5501 if (tok == TOK_MIDENT) {
5502 name2 = get_token(state, 1)->ident->name;
5504 error(state, 0, "Invalid preprocessor directive: %s %s",
5509 /* Consume the rest of the macro line */
5511 tok = pp_peek(state);
5513 } while((tok != TOK_EOF) && (tok != TOK_EOL));
5514 state->token_base = old_token_base;
5515 state->macro_file = NULL;
5519 /* Type helper functions */
5521 static struct type *new_type(
5522 unsigned int type, struct type *left, struct type *right)
5524 struct type *result;
5525 result = xmalloc(sizeof(*result), "type");
5526 result->type = type;
5527 result->left = left;
5528 result->right = right;
5529 result->field_ident = 0;
5530 result->type_ident = 0;
5531 result->elements = 0;
5535 static struct type *clone_type(unsigned int specifiers, struct type *old)
5537 struct type *result;
5538 result = xmalloc(sizeof(*result), "type");
5539 memcpy(result, old, sizeof(*result));
5540 result->type &= TYPE_MASK;
5541 result->type |= specifiers;
5545 static struct type *dup_type(struct compile_state *state, struct type *orig)
5548 new = xcmalloc(sizeof(*new), "type");
5549 new->type = orig->type;
5550 new->field_ident = orig->field_ident;
5551 new->type_ident = orig->type_ident;
5552 new->elements = orig->elements;
5554 new->left = dup_type(state, orig->left);
5557 new->right = dup_type(state, orig->right);
5563 static struct type *invalid_type(struct compile_state *state, struct type *type)
5565 struct type *invalid, *member;
5568 internal_error(state, 0, "type missing?");
5570 switch(type->type & TYPE_MASK) {
5572 case TYPE_CHAR: case TYPE_UCHAR:
5573 case TYPE_SHORT: case TYPE_USHORT:
5574 case TYPE_INT: case TYPE_UINT:
5575 case TYPE_LONG: case TYPE_ULONG:
5576 case TYPE_LLONG: case TYPE_ULLONG:
5581 invalid = invalid_type(state, type->left);
5584 invalid = invalid_type(state, type->left);
5588 member = type->left;
5589 while(member && (invalid == 0) &&
5590 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5591 invalid = invalid_type(state, member->left);
5592 member = member->right;
5595 invalid = invalid_type(state, member);
5600 member = type->left;
5601 while(member && (invalid == 0) &&
5602 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5603 invalid = invalid_type(state, member->left);
5604 member = member->right;
5607 invalid = invalid_type(state, member);
5618 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5619 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5620 static inline ulong_t mask_uint(ulong_t x)
5622 if (SIZEOF_INT < SIZEOF_LONG) {
5623 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT))) -1;
5628 #define MASK_UINT(X) (mask_uint(X))
5629 #define MASK_ULONG(X) (X)
5631 static struct type void_type = { .type = TYPE_VOID };
5632 static struct type char_type = { .type = TYPE_CHAR };
5633 static struct type uchar_type = { .type = TYPE_UCHAR };
5634 static struct type short_type = { .type = TYPE_SHORT };
5635 static struct type ushort_type = { .type = TYPE_USHORT };
5636 static struct type int_type = { .type = TYPE_INT };
5637 static struct type uint_type = { .type = TYPE_UINT };
5638 static struct type long_type = { .type = TYPE_LONG };
5639 static struct type ulong_type = { .type = TYPE_ULONG };
5640 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5642 static struct type void_ptr_type = {
5643 .type = TYPE_POINTER,
5647 static struct type void_func_type = {
5648 .type = TYPE_FUNCTION,
5650 .right = &void_type,
5653 static size_t bits_to_bytes(size_t size)
5655 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5658 static struct triple *variable(struct compile_state *state, struct type *type)
5660 struct triple *result;
5661 if ((type->type & STOR_MASK) != STOR_PERM) {
5662 result = triple(state, OP_ADECL, type, 0, 0);
5663 generate_lhs_pieces(state, result);
5666 result = triple(state, OP_SDECL, type, 0, 0);
5671 static void stor_of(FILE *fp, struct type *type)
5673 switch(type->type & STOR_MASK) {
5675 fprintf(fp, "auto ");
5678 fprintf(fp, "static ");
5681 fprintf(fp, "local ");
5684 fprintf(fp, "extern ");
5687 fprintf(fp, "register ");
5690 fprintf(fp, "typedef ");
5692 case STOR_INLINE | STOR_LOCAL:
5693 fprintf(fp, "inline ");
5695 case STOR_INLINE | STOR_STATIC:
5696 fprintf(fp, "static inline");
5698 case STOR_INLINE | STOR_EXTERN:
5699 fprintf(fp, "extern inline");
5702 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5706 static void qual_of(FILE *fp, struct type *type)
5708 if (type->type & QUAL_CONST) {
5709 fprintf(fp, " const");
5711 if (type->type & QUAL_VOLATILE) {
5712 fprintf(fp, " volatile");
5714 if (type->type & QUAL_RESTRICT) {
5715 fprintf(fp, " restrict");
5719 static void name_of(FILE *fp, struct type *type)
5721 unsigned int base_type;
5722 base_type = type->type & TYPE_MASK;
5723 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5728 fprintf(fp, "void");
5732 fprintf(fp, "signed char");
5736 fprintf(fp, "unsigned char");
5740 fprintf(fp, "signed short");
5744 fprintf(fp, "unsigned short");
5748 fprintf(fp, "signed int");
5752 fprintf(fp, "unsigned int");
5756 fprintf(fp, "signed long");
5760 fprintf(fp, "unsigned long");
5764 name_of(fp, type->left);
5769 name_of(fp, type->left);
5771 name_of(fp, type->right);
5774 name_of(fp, type->left);
5776 name_of(fp, type->right);
5779 fprintf(fp, "enum %s",
5780 (type->type_ident)? type->type_ident->name : "");
5784 fprintf(fp, "struct %s { ",
5785 (type->type_ident)? type->type_ident->name : "");
5786 name_of(fp, type->left);
5791 fprintf(fp, "union %s { ",
5792 (type->type_ident)? type->type_ident->name : "");
5793 name_of(fp, type->left);
5798 name_of(fp, type->left);
5799 fprintf(fp, " (*)(");
5800 name_of(fp, type->right);
5804 name_of(fp, type->left);
5805 fprintf(fp, " [%ld]", (long)(type->elements));
5808 fprintf(fp, "tuple { ");
5809 name_of(fp, type->left);
5814 fprintf(fp, "join { ");
5815 name_of(fp, type->left);
5820 name_of(fp, type->left);
5821 fprintf(fp, " : %d ", type->elements);
5825 fprintf(fp, "unknown_t");
5828 fprintf(fp, "????: %x", base_type);
5831 if (type->field_ident && type->field_ident->name) {
5832 fprintf(fp, " .%s", type->field_ident->name);
5836 static size_t align_of(struct compile_state *state, struct type *type)
5840 switch(type->type & TYPE_MASK) {
5849 align = ALIGNOF_CHAR;
5853 align = ALIGNOF_SHORT;
5858 align = ALIGNOF_INT;
5862 align = ALIGNOF_LONG;
5865 align = ALIGNOF_POINTER;
5870 size_t left_align, right_align;
5871 left_align = align_of(state, type->left);
5872 right_align = align_of(state, type->right);
5873 align = (left_align >= right_align) ? left_align : right_align;
5877 align = align_of(state, type->left);
5883 align = align_of(state, type->left);
5886 error(state, 0, "alignof not yet defined for type\n");
5892 static size_t reg_align_of(struct compile_state *state, struct type *type)
5896 switch(type->type & TYPE_MASK) {
5905 align = REG_ALIGNOF_CHAR;
5909 align = REG_ALIGNOF_SHORT;
5914 align = REG_ALIGNOF_INT;
5918 align = REG_ALIGNOF_LONG;
5921 align = REG_ALIGNOF_POINTER;
5926 size_t left_align, right_align;
5927 left_align = reg_align_of(state, type->left);
5928 right_align = reg_align_of(state, type->right);
5929 align = (left_align >= right_align) ? left_align : right_align;
5933 align = reg_align_of(state, type->left);
5939 align = reg_align_of(state, type->left);
5942 error(state, 0, "alignof not yet defined for type\n");
5948 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5950 return bits_to_bytes(align_of(state, type));
5952 static size_t size_of(struct compile_state *state, struct type *type);
5953 static size_t reg_size_of(struct compile_state *state, struct type *type);
5955 static size_t needed_padding(struct compile_state *state,
5956 struct type *type, size_t offset)
5958 size_t padding, align;
5959 align = align_of(state, type);
5960 /* Align to the next machine word if the bitfield does completely
5961 * fit into the current word.
5963 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
5965 size = size_of(state, type);
5966 if ((offset + type->elements)/size != offset/size) {
5971 if (offset % align) {
5972 padding = align - (offset % align);
5977 static size_t reg_needed_padding(struct compile_state *state,
5978 struct type *type, size_t offset)
5980 size_t padding, align;
5981 align = reg_align_of(state, type);
5982 /* Align to the next register word if the bitfield does completely
5983 * fit into the current register.
5985 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
5986 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
5988 align = REG_SIZEOF_REG;
5991 if (offset % align) {
5992 padding = align - (offset % align);
5997 static size_t size_of(struct compile_state *state, struct type *type)
6001 switch(type->type & TYPE_MASK) {
6006 size = type->elements;
6014 size = SIZEOF_SHORT;
6026 size = SIZEOF_POINTER;
6032 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6033 pad = needed_padding(state, type->left, size);
6034 size = size + pad + size_of(state, type->left);
6037 pad = needed_padding(state, type, size);
6038 size = size + pad + size_of(state, type);
6043 size_t size_left, size_right;
6044 size_left = size_of(state, type->left);
6045 size_right = size_of(state, type->right);
6046 size = (size_left >= size_right)? size_left : size_right;
6050 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6051 internal_error(state, 0, "Invalid array type");
6053 size = size_of(state, type->left) * type->elements;
6060 size = size_of(state, type->left);
6061 /* Pad structures so their size is a multiples of their alignment */
6062 pad = needed_padding(state, type, size);
6070 size = size_of(state, type->left);
6071 /* Pad unions so their size is a multiple of their alignment */
6072 pad = needed_padding(state, type, size);
6077 internal_error(state, 0, "sizeof not yet defined for type");
6083 static size_t reg_size_of(struct compile_state *state, struct type *type)
6087 switch(type->type & TYPE_MASK) {
6092 size = type->elements;
6096 size = REG_SIZEOF_CHAR;
6100 size = REG_SIZEOF_SHORT;
6105 size = REG_SIZEOF_INT;
6109 size = REG_SIZEOF_LONG;
6112 size = REG_SIZEOF_POINTER;
6118 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6119 pad = reg_needed_padding(state, type->left, size);
6120 size = size + pad + reg_size_of(state, type->left);
6123 pad = reg_needed_padding(state, type, size);
6124 size = size + pad + reg_size_of(state, type);
6129 size_t size_left, size_right;
6130 size_left = reg_size_of(state, type->left);
6131 size_right = reg_size_of(state, type->right);
6132 size = (size_left >= size_right)? size_left : size_right;
6136 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6137 internal_error(state, 0, "Invalid array type");
6139 size = reg_size_of(state, type->left) * type->elements;
6146 size = reg_size_of(state, type->left);
6147 /* Pad structures so their size is a multiples of their alignment */
6148 pad = reg_needed_padding(state, type, size);
6156 size = reg_size_of(state, type->left);
6157 /* Pad unions so their size is a multiple of their alignment */
6158 pad = reg_needed_padding(state, type, size);
6163 internal_error(state, 0, "sizeof not yet defined for type");
6169 static size_t registers_of(struct compile_state *state, struct type *type)
6172 registers = reg_size_of(state, type);
6173 registers += REG_SIZEOF_REG - 1;
6174 registers /= REG_SIZEOF_REG;
6178 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6180 return bits_to_bytes(size_of(state, type));
6183 static size_t field_offset(struct compile_state *state,
6184 struct type *type, struct hash_entry *field)
6186 struct type *member;
6191 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6192 member = type->left;
6193 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6194 size += needed_padding(state, member->left, size);
6195 if (member->left->field_ident == field) {
6196 member = member->left;
6199 size += size_of(state, member->left);
6200 member = member->right;
6202 size += needed_padding(state, member, size);
6204 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6205 member = type->left;
6206 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6207 if (member->left->field_ident == field) {
6208 member = member->left;
6211 member = member->right;
6215 internal_error(state, 0, "field_offset only works on structures and unions");
6218 if (!member || (member->field_ident != field)) {
6219 error(state, 0, "member %s not present", field->name);
6224 static size_t field_reg_offset(struct compile_state *state,
6225 struct type *type, struct hash_entry *field)
6227 struct type *member;
6232 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6233 member = type->left;
6234 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6235 size += reg_needed_padding(state, member->left, size);
6236 if (member->left->field_ident == field) {
6237 member = member->left;
6240 size += reg_size_of(state, member->left);
6241 member = member->right;
6244 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6245 member = type->left;
6246 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6247 if (member->left->field_ident == field) {
6248 member = member->left;
6251 member = member->right;
6255 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6258 size += reg_needed_padding(state, member, size);
6259 if (!member || (member->field_ident != field)) {
6260 error(state, 0, "member %s not present", field->name);
6265 static struct type *field_type(struct compile_state *state,
6266 struct type *type, struct hash_entry *field)
6268 struct type *member;
6271 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6272 member = type->left;
6273 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6274 if (member->left->field_ident == field) {
6275 member = member->left;
6278 member = member->right;
6281 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6282 member = type->left;
6283 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6284 if (member->left->field_ident == field) {
6285 member = member->left;
6288 member = member->right;
6292 internal_error(state, 0, "field_type only works on structures and unions");
6295 if (!member || (member->field_ident != field)) {
6296 error(state, 0, "member %s not present", field->name);
6301 static size_t index_offset(struct compile_state *state,
6302 struct type *type, ulong_t index)
6304 struct type *member;
6307 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6308 size = size_of(state, type->left) * index;
6310 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6312 member = type->left;
6314 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6315 size += needed_padding(state, member->left, size);
6317 member = member->left;
6320 size += size_of(state, member->left);
6322 member = member->right;
6324 size += needed_padding(state, member, size);
6326 internal_error(state, 0, "Missing member index: %u", index);
6329 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6332 member = type->left;
6334 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6336 member = member->left;
6340 member = member->right;
6343 internal_error(state, 0, "Missing member index: %u", index);
6347 internal_error(state, 0,
6348 "request for index %u in something not an array, tuple or join",
6354 static size_t index_reg_offset(struct compile_state *state,
6355 struct type *type, ulong_t index)
6357 struct type *member;
6360 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6361 size = reg_size_of(state, type->left) * index;
6363 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6365 member = type->left;
6367 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6368 size += reg_needed_padding(state, member->left, size);
6370 member = member->left;
6373 size += reg_size_of(state, member->left);
6375 member = member->right;
6377 size += reg_needed_padding(state, member, size);
6379 internal_error(state, 0, "Missing member index: %u", index);
6383 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6386 member = type->left;
6388 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6390 member = member->left;
6394 member = member->right;
6397 internal_error(state, 0, "Missing member index: %u", index);
6401 internal_error(state, 0,
6402 "request for index %u in something not an array, tuple or join",
6408 static struct type *index_type(struct compile_state *state,
6409 struct type *type, ulong_t index)
6411 struct type *member;
6412 if (index >= type->elements) {
6413 internal_error(state, 0, "Invalid element %u requested", index);
6415 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6416 member = type->left;
6418 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6420 member = type->left;
6422 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6424 member = member->left;
6428 member = member->right;
6431 internal_error(state, 0, "Missing member index: %u", index);
6434 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6436 member = type->left;
6438 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6440 member = member->left;
6444 member = member->right;
6447 internal_error(state, 0, "Missing member index: %u", index);
6452 internal_error(state, 0,
6453 "request for index %u in something not an array, tuple or join",
6459 static struct type *unpack_type(struct compile_state *state, struct type *type)
6461 /* If I have a single register compound type not a bit-field
6462 * find the real type.
6464 struct type *start_type;
6466 /* Get out early if I need multiple registers for this type */
6467 size = reg_size_of(state, type);
6468 if (size > REG_SIZEOF_REG) {
6471 /* Get out early if I don't need any registers for this type */
6475 /* Loop until I have no more layers I can remove */
6478 switch(type->type & TYPE_MASK) {
6480 /* If I have a single element the unpacked type
6483 if (type->elements == 1) {
6489 /* If I have a single element the unpacked type
6492 if (type->elements == 1) {
6495 /* If I have multiple elements the unpacked
6496 * type is the non-void element.
6499 struct type *next, *member;
6500 struct type *sub_type;
6506 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6507 next = member->right;
6508 member = member->left;
6510 if (reg_size_of(state, member) > 0) {
6512 internal_error(state, 0, "true compound type in a register");
6525 /* If I have a single element the unpacked type
6528 if (type->elements == 1) {
6531 /* I can't in general unpack union types */
6534 /* If I'm not a compound type I can't unpack it */
6537 } while(start_type != type);
6538 switch(type->type & TYPE_MASK) {
6542 internal_error(state, 0, "irredicible type?");
6548 static int equiv_types(struct type *left, struct type *right);
6549 static int is_compound_type(struct type *type);
6551 static struct type *reg_type(
6552 struct compile_state *state, struct type *type, int reg_offset)
6554 struct type *member;
6557 struct type *invalid;
6558 invalid = invalid_type(state, type);
6560 fprintf(state->errout, "type: ");
6561 name_of(state->errout, type);
6562 fprintf(state->errout, "\n");
6563 fprintf(state->errout, "invalid: ");
6564 name_of(state->errout, invalid);
6565 fprintf(state->errout, "\n");
6566 internal_error(state, 0, "bad input type?");
6570 size = reg_size_of(state, type);
6571 if (reg_offset > size) {
6573 fprintf(state->errout, "type: ");
6574 name_of(state->errout, type);
6575 fprintf(state->errout, "\n");
6576 internal_error(state, 0, "offset outside of type");
6579 switch(type->type & TYPE_MASK) {
6580 /* Don't do anything with the basic types */
6582 case TYPE_CHAR: case TYPE_UCHAR:
6583 case TYPE_SHORT: case TYPE_USHORT:
6584 case TYPE_INT: case TYPE_UINT:
6585 case TYPE_LONG: case TYPE_ULONG:
6586 case TYPE_LLONG: case TYPE_ULLONG:
6587 case TYPE_FLOAT: case TYPE_DOUBLE:
6595 member = type->left;
6596 size = reg_size_of(state, member);
6597 if (size > REG_SIZEOF_REG) {
6598 member = reg_type(state, member, reg_offset % size);
6606 member = type->left;
6607 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6608 size = reg_size_of(state, member->left);
6609 offset += reg_needed_padding(state, member->left, offset);
6610 if ((offset + size) > reg_offset) {
6611 member = member->left;
6615 member = member->right;
6617 offset += reg_needed_padding(state, member, offset);
6618 member = reg_type(state, member, reg_offset - offset);
6624 struct type *join, **jnext, *mnext;
6625 join = new_type(TYPE_JOIN, 0, 0);
6626 jnext = &join->left;
6632 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6633 mnext = member->right;
6634 member = member->left;
6636 size = reg_size_of(state, member);
6637 if (size > reg_offset) {
6638 struct type *part, *hunt;
6639 part = reg_type(state, member, reg_offset);
6640 /* See if this type is already in the union */
6643 struct type *test = hunt;
6645 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6649 if (equiv_types(part, test)) {
6657 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6658 jnext = &(*jnext)->right;
6665 if (join->elements == 0) {
6666 internal_error(state, 0, "No elements?");
6673 fprintf(state->errout, "type: ");
6674 name_of(state->errout, type);
6675 fprintf(state->errout, "\n");
6676 internal_error(state, 0, "reg_type not yet defined for type");
6680 /* If I have a single register compound type not a bit-field
6681 * find the real type.
6683 member = unpack_type(state, member);
6685 size = reg_size_of(state, member);
6686 if (size > REG_SIZEOF_REG) {
6687 internal_error(state, 0, "Cannot find type of single register");
6690 invalid = invalid_type(state, member);
6692 fprintf(state->errout, "type: ");
6693 name_of(state->errout, member);
6694 fprintf(state->errout, "\n");
6695 fprintf(state->errout, "invalid: ");
6696 name_of(state->errout, invalid);
6697 fprintf(state->errout, "\n");
6698 internal_error(state, 0, "returning bad type?");
6704 static struct type *next_field(struct compile_state *state,
6705 struct type *type, struct type *prev_member)
6707 struct type *member;
6708 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6709 internal_error(state, 0, "next_field only works on structures");
6711 member = type->left;
6712 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6714 member = member->left;
6717 if (member->left == prev_member) {
6720 member = member->right;
6722 if (member == prev_member) {
6726 internal_error(state, 0, "prev_member %s not present",
6727 prev_member->field_ident->name);
6732 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6733 size_t ret_offset, size_t mem_offset, void *arg);
6735 static void walk_type_fields(struct compile_state *state,
6736 struct type *type, size_t reg_offset, size_t mem_offset,
6737 walk_type_fields_cb_t cb, void *arg);
6739 static void walk_struct_fields(struct compile_state *state,
6740 struct type *type, size_t reg_offset, size_t mem_offset,
6741 walk_type_fields_cb_t cb, void *arg)
6745 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6746 internal_error(state, 0, "walk_struct_fields only works on structures");
6749 for(i = 0; i < type->elements; i++) {
6752 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6753 mtype = mtype->left;
6755 walk_type_fields(state, mtype,
6757 field_reg_offset(state, type, mtype->field_ident),
6759 field_offset(state, type, mtype->field_ident),
6766 static void walk_type_fields(struct compile_state *state,
6767 struct type *type, size_t reg_offset, size_t mem_offset,
6768 walk_type_fields_cb_t cb, void *arg)
6770 switch(type->type & TYPE_MASK) {
6772 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6782 cb(state, type, reg_offset, mem_offset, arg);
6787 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6791 static void arrays_complete(struct compile_state *state, struct type *type)
6793 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6794 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6795 error(state, 0, "array size not specified");
6797 arrays_complete(state, type->left);
6801 static unsigned int get_basic_type(struct type *type)
6804 basic = type->type & TYPE_MASK;
6805 /* Convert enums to ints */
6806 if (basic == TYPE_ENUM) {
6809 /* Convert bitfields to standard types */
6810 else if (basic == TYPE_BITFIELD) {
6811 if (type->elements <= SIZEOF_CHAR) {
6814 else if (type->elements <= SIZEOF_SHORT) {
6817 else if (type->elements <= SIZEOF_INT) {
6820 else if (type->elements <= SIZEOF_LONG) {
6823 if (!TYPE_SIGNED(type->left->type)) {
6830 static unsigned int do_integral_promotion(unsigned int type)
6832 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6838 static unsigned int do_arithmetic_conversion(
6839 unsigned int left, unsigned int right)
6841 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6842 return TYPE_LDOUBLE;
6844 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6847 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6850 left = do_integral_promotion(left);
6851 right = do_integral_promotion(right);
6852 /* If both operands have the same size done */
6853 if (left == right) {
6856 /* If both operands have the same signedness pick the larger */
6857 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6858 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6860 /* If the signed type can hold everything use it */
6861 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6864 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6867 /* Convert to the unsigned type with the same rank as the signed type */
6868 else if (TYPE_SIGNED(left)) {
6869 return TYPE_MKUNSIGNED(left);
6872 return TYPE_MKUNSIGNED(right);
6876 /* see if two types are the same except for qualifiers */
6877 static int equiv_types(struct type *left, struct type *right)
6880 /* Error if the basic types do not match */
6881 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6884 type = left->type & TYPE_MASK;
6885 /* If the basic types match and it is a void type we are done */
6886 if (type == TYPE_VOID) {
6889 /* For bitfields we need to compare the sizes */
6890 else if (type == TYPE_BITFIELD) {
6891 return (left->elements == right->elements) &&
6892 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6894 /* if the basic types match and it is an arithmetic type we are done */
6895 else if (TYPE_ARITHMETIC(type)) {
6898 /* If it is a pointer type recurse and keep testing */
6899 else if (type == TYPE_POINTER) {
6900 return equiv_types(left->left, right->left);
6902 else if (type == TYPE_ARRAY) {
6903 return (left->elements == right->elements) &&
6904 equiv_types(left->left, right->left);
6906 /* test for struct equality */
6907 else if (type == TYPE_STRUCT) {
6908 return left->type_ident == right->type_ident;
6910 /* test for union equality */
6911 else if (type == TYPE_UNION) {
6912 return left->type_ident == right->type_ident;
6914 /* Test for equivalent functions */
6915 else if (type == TYPE_FUNCTION) {
6916 return equiv_types(left->left, right->left) &&
6917 equiv_types(left->right, right->right);
6919 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6920 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6921 else if (type == TYPE_PRODUCT) {
6922 return equiv_types(left->left, right->left) &&
6923 equiv_types(left->right, right->right);
6925 /* We should see TYPE_OVERLAP when comparing joins */
6926 else if (type == TYPE_OVERLAP) {
6927 return equiv_types(left->left, right->left) &&
6928 equiv_types(left->right, right->right);
6930 /* Test for equivalence of tuples */
6931 else if (type == TYPE_TUPLE) {
6932 return (left->elements == right->elements) &&
6933 equiv_types(left->left, right->left);
6935 /* Test for equivalence of joins */
6936 else if (type == TYPE_JOIN) {
6937 return (left->elements == right->elements) &&
6938 equiv_types(left->left, right->left);
6945 static int equiv_ptrs(struct type *left, struct type *right)
6947 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6948 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6951 return equiv_types(left->left, right->left);
6954 static struct type *compatible_types(struct type *left, struct type *right)
6956 struct type *result;
6957 unsigned int type, qual_type;
6958 /* Error if the basic types do not match */
6959 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6962 type = left->type & TYPE_MASK;
6963 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
6965 /* if the basic types match and it is an arithmetic type we are done */
6966 if (TYPE_ARITHMETIC(type)) {
6967 result = new_type(qual_type, 0, 0);
6969 /* If it is a pointer type recurse and keep testing */
6970 else if (type == TYPE_POINTER) {
6971 result = compatible_types(left->left, right->left);
6973 result = new_type(qual_type, result, 0);
6976 /* test for struct equality */
6977 else if (type == TYPE_STRUCT) {
6978 if (left->type_ident == right->type_ident) {
6982 /* test for union equality */
6983 else if (type == TYPE_UNION) {
6984 if (left->type_ident == right->type_ident) {
6988 /* Test for equivalent functions */
6989 else if (type == TYPE_FUNCTION) {
6990 struct type *lf, *rf;
6991 lf = compatible_types(left->left, right->left);
6992 rf = compatible_types(left->right, right->right);
6994 result = new_type(qual_type, lf, rf);
6997 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6998 else if (type == TYPE_PRODUCT) {
6999 struct type *lf, *rf;
7000 lf = compatible_types(left->left, right->left);
7001 rf = compatible_types(left->right, right->right);
7003 result = new_type(qual_type, lf, rf);
7007 /* Nothing else is compatible */
7012 /* See if left is a equivalent to right or right is a union member of left */
7013 static int is_subset_type(struct type *left, struct type *right)
7015 if (equiv_types(left, right)) {
7018 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7019 struct type *member, *mnext;
7024 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7025 mnext = member->right;
7026 member = member->left;
7028 if (is_subset_type( member, right)) {
7036 static struct type *compatible_ptrs(struct type *left, struct type *right)
7038 struct type *result;
7039 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7040 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7043 result = compatible_types(left->left, right->left);
7045 unsigned int qual_type;
7046 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7047 result = new_type(qual_type, result, 0);
7052 static struct triple *integral_promotion(
7053 struct compile_state *state, struct triple *def)
7057 /* As all operations are carried out in registers
7058 * the values are converted on load I just convert
7059 * logical type of the operand.
7061 if (TYPE_INTEGER(type->type)) {
7062 unsigned int int_type;
7063 int_type = type->type & ~TYPE_MASK;
7064 int_type |= do_integral_promotion(get_basic_type(type));
7065 if (int_type != type->type) {
7066 if (def->op != OP_LOAD) {
7067 def->type = new_type(int_type, 0, 0);
7070 def = triple(state, OP_CONVERT,
7071 new_type(int_type, 0, 0), def, 0);
7079 static void arithmetic(struct compile_state *state, struct triple *def)
7081 if (!TYPE_ARITHMETIC(def->type->type)) {
7082 error(state, 0, "arithmetic type expexted");
7086 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7088 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7089 error(state, def, "pointer or arithmetic type expected");
7093 static int is_integral(struct triple *ins)
7095 return TYPE_INTEGER(ins->type->type);
7098 static void integral(struct compile_state *state, struct triple *def)
7100 if (!is_integral(def)) {
7101 error(state, 0, "integral type expected");
7106 static void bool(struct compile_state *state, struct triple *def)
7108 if (!TYPE_ARITHMETIC(def->type->type) &&
7109 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7110 error(state, 0, "arithmetic or pointer type expected");
7114 static int is_signed(struct type *type)
7116 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7119 return !!TYPE_SIGNED(type->type);
7121 static int is_compound_type(struct type *type)
7124 switch((type->type & TYPE_MASK)) {
7139 /* Is this value located in a register otherwise it must be in memory */
7140 static int is_in_reg(struct compile_state *state, struct triple *def)
7143 if (def->op == OP_ADECL) {
7146 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7149 else if (triple_is_part(state, def)) {
7150 in_reg = is_in_reg(state, MISC(def, 0));
7153 internal_error(state, def, "unknown expr storage location");
7159 /* Is this an auto or static variable location? Something that can
7160 * be assigned to. Otherwise it must must be a pure value, a temporary.
7162 static int is_lvalue(struct compile_state *state, struct triple *def)
7169 if ((def->op == OP_ADECL) ||
7170 (def->op == OP_SDECL) ||
7171 (def->op == OP_DEREF) ||
7172 (def->op == OP_BLOBCONST) ||
7173 (def->op == OP_LIST)) {
7176 else if (triple_is_part(state, def)) {
7177 ret = is_lvalue(state, MISC(def, 0));
7182 static void clvalue(struct compile_state *state, struct triple *def)
7185 internal_error(state, def, "nothing where lvalue expected?");
7187 if (!is_lvalue(state, def)) {
7188 error(state, def, "lvalue expected");
7191 static void lvalue(struct compile_state *state, struct triple *def)
7193 clvalue(state, def);
7194 if (def->type->type & QUAL_CONST) {
7195 error(state, def, "modifable lvalue expected");
7199 static int is_pointer(struct triple *def)
7201 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7204 static void pointer(struct compile_state *state, struct triple *def)
7206 if (!is_pointer(def)) {
7207 error(state, def, "pointer expected");
7211 static struct triple *int_const(
7212 struct compile_state *state, struct type *type, ulong_t value)
7214 struct triple *result;
7215 switch(type->type & TYPE_MASK) {
7217 case TYPE_INT: case TYPE_UINT:
7218 case TYPE_LONG: case TYPE_ULONG:
7221 internal_error(state, 0, "constant for unknown type");
7223 result = triple(state, OP_INTCONST, type, 0, 0);
7224 result->u.cval = value;
7229 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7231 static struct triple *do_mk_addr_expr(struct compile_state *state,
7232 struct triple *expr, struct type *type, ulong_t offset)
7234 struct triple *result;
7235 struct type *ptr_type;
7236 clvalue(state, expr);
7238 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7242 if (expr->op == OP_ADECL) {
7243 error(state, expr, "address of auto variables not supported");
7245 else if (expr->op == OP_SDECL) {
7246 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7247 MISC(result, 0) = expr;
7248 result->u.cval = offset;
7250 else if (expr->op == OP_DEREF) {
7251 result = triple(state, OP_ADD, ptr_type,
7253 int_const(state, &ulong_type, offset));
7255 else if (expr->op == OP_BLOBCONST) {
7257 internal_error(state, expr, "not yet implemented");
7259 else if (expr->op == OP_LIST) {
7260 error(state, 0, "Function addresses not supported");
7262 else if (triple_is_part(state, expr)) {
7263 struct triple *part;
7265 expr = MISC(expr, 0);
7266 if (part->op == OP_DOT) {
7267 offset += bits_to_bytes(
7268 field_offset(state, expr->type, part->u.field));
7270 else if (part->op == OP_INDEX) {
7271 offset += bits_to_bytes(
7272 index_offset(state, expr->type, part->u.cval));
7275 internal_error(state, part, "unhandled part type");
7277 result = do_mk_addr_expr(state, expr, type, offset);
7280 internal_error(state, expr, "cannot take address of expression");
7285 static struct triple *mk_addr_expr(
7286 struct compile_state *state, struct triple *expr, ulong_t offset)
7288 return do_mk_addr_expr(state, expr, expr->type, offset);
7291 static struct triple *mk_deref_expr(
7292 struct compile_state *state, struct triple *expr)
7294 struct type *base_type;
7295 pointer(state, expr);
7296 base_type = expr->type->left;
7297 return triple(state, OP_DEREF, base_type, expr, 0);
7300 /* lvalue conversions always apply except when certain operators
7301 * are applied. So I apply apply it when I know no more
7302 * operators will be applied.
7304 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7306 /* Tranform an array to a pointer to the first element */
7307 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7310 TYPE_POINTER | (def->type->type & QUAL_MASK),
7311 def->type->left, 0);
7312 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7313 struct triple *addrconst;
7314 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7315 internal_error(state, def, "bad array constant");
7317 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7318 MISC(addrconst, 0) = def;
7322 def = triple(state, OP_CONVERT, type, def, 0);
7325 /* Transform a function to a pointer to it */
7326 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7327 def = mk_addr_expr(state, def, 0);
7332 static struct triple *deref_field(
7333 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7335 struct triple *result;
7336 struct type *type, *member;
7339 internal_error(state, 0, "No field passed to deref_field");
7343 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7344 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7345 error(state, 0, "request for member %s in something not a struct or union",
7348 member = field_type(state, type, field);
7349 if ((type->type & STOR_MASK) == STOR_PERM) {
7350 /* Do the pointer arithmetic to get a deref the field */
7351 offset = bits_to_bytes(field_offset(state, type, field));
7352 result = do_mk_addr_expr(state, expr, member, offset);
7353 result = mk_deref_expr(state, result);
7356 /* Find the variable for the field I want. */
7357 result = triple(state, OP_DOT, member, expr, 0);
7358 result->u.field = field;
7363 static struct triple *deref_index(
7364 struct compile_state *state, struct triple *expr, size_t index)
7366 struct triple *result;
7367 struct type *type, *member;
7372 member = index_type(state, type, index);
7374 if ((type->type & STOR_MASK) == STOR_PERM) {
7375 offset = bits_to_bytes(index_offset(state, type, index));
7376 result = do_mk_addr_expr(state, expr, member, offset);
7377 result = mk_deref_expr(state, result);
7380 result = triple(state, OP_INDEX, member, expr, 0);
7381 result->u.cval = index;
7386 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7392 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7393 /* Transform lvalues into something we can read */
7394 def = lvalue_conversion(state, def);
7395 if (!is_lvalue(state, def)) {
7398 if (is_in_reg(state, def)) {
7401 if (def->op == OP_SDECL) {
7402 def = mk_addr_expr(state, def, 0);
7403 def = mk_deref_expr(state, def);
7407 def = triple(state, op, def->type, def, 0);
7408 if (def->type->type & QUAL_VOLATILE) {
7409 def->id |= TRIPLE_FLAG_VOLATILE;
7414 int is_write_compatible(struct compile_state *state,
7415 struct type *dest, struct type *rval)
7418 /* Both operands have arithmetic type */
7419 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7422 /* One operand is a pointer and the other is a pointer to void */
7423 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7424 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7425 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7426 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7429 /* If both types are the same without qualifiers we are good */
7430 else if (equiv_ptrs(dest, rval)) {
7433 /* test for struct/union equality */
7434 else if (equiv_types(dest, rval)) {
7440 static void write_compatible(struct compile_state *state,
7441 struct type *dest, struct type *rval)
7443 if (!is_write_compatible(state, dest, rval)) {
7444 FILE *fp = state->errout;
7445 fprintf(fp, "dest: ");
7447 fprintf(fp,"\nrval: ");
7450 error(state, 0, "Incompatible types in assignment");
7454 static int is_init_compatible(struct compile_state *state,
7455 struct type *dest, struct type *rval)
7458 if (is_write_compatible(state, dest, rval)) {
7461 else if (equiv_types(dest, rval)) {
7467 static struct triple *write_expr(
7468 struct compile_state *state, struct triple *dest, struct triple *rval)
7475 internal_error(state, 0, "missing rval");
7478 if (rval->op == OP_LIST) {
7479 internal_error(state, 0, "expression of type OP_LIST?");
7481 if (!is_lvalue(state, dest)) {
7482 internal_error(state, 0, "writing to a non lvalue?");
7484 if (dest->type->type & QUAL_CONST) {
7485 internal_error(state, 0, "modifable lvalue expexted");
7488 write_compatible(state, dest->type, rval->type);
7489 if (!equiv_types(dest->type, rval->type)) {
7490 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7493 /* Now figure out which assignment operator to use */
7495 if (is_in_reg(state, dest)) {
7496 def = triple(state, OP_WRITE, dest->type, rval, dest);
7497 if (MISC(def, 0) != dest) {
7498 internal_error(state, def, "huh?");
7500 if (RHS(def, 0) != rval) {
7501 internal_error(state, def, "huh?");
7504 def = triple(state, OP_STORE, dest->type, dest, rval);
7506 if (def->type->type & QUAL_VOLATILE) {
7507 def->id |= TRIPLE_FLAG_VOLATILE;
7512 static struct triple *init_expr(
7513 struct compile_state *state, struct triple *dest, struct triple *rval)
7519 internal_error(state, 0, "missing rval");
7521 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7522 rval = read_expr(state, rval);
7523 def = write_expr(state, dest, rval);
7526 /* Fill in the array size if necessary */
7527 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7528 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7529 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7530 dest->type->elements = rval->type->elements;
7533 if (!equiv_types(dest->type, rval->type)) {
7534 error(state, 0, "Incompatible types in inializer");
7536 MISC(dest, 0) = rval;
7537 insert_triple(state, dest, rval);
7538 rval->id |= TRIPLE_FLAG_FLATTENED;
7539 use_triple(MISC(dest, 0), dest);
7544 struct type *arithmetic_result(
7545 struct compile_state *state, struct triple *left, struct triple *right)
7548 /* Sanity checks to ensure I am working with arithmetic types */
7549 arithmetic(state, left);
7550 arithmetic(state, right);
7552 do_arithmetic_conversion(
7553 get_basic_type(left->type),
7554 get_basic_type(right->type)),
7559 struct type *ptr_arithmetic_result(
7560 struct compile_state *state, struct triple *left, struct triple *right)
7563 /* Sanity checks to ensure I am working with the proper types */
7564 ptr_arithmetic(state, left);
7565 arithmetic(state, right);
7566 if (TYPE_ARITHMETIC(left->type->type) &&
7567 TYPE_ARITHMETIC(right->type->type)) {
7568 type = arithmetic_result(state, left, right);
7570 else if (TYPE_PTR(left->type->type)) {
7574 internal_error(state, 0, "huh?");
7580 /* boolean helper function */
7582 static struct triple *ltrue_expr(struct compile_state *state,
7583 struct triple *expr)
7586 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7587 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7588 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7589 /* If the expression is already boolean do nothing */
7592 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7598 static struct triple *lfalse_expr(struct compile_state *state,
7599 struct triple *expr)
7601 return triple(state, OP_LFALSE, &int_type, expr, 0);
7604 static struct triple *mkland_expr(
7605 struct compile_state *state,
7606 struct triple *left, struct triple *right)
7608 struct triple *def, *val, *var, *jmp, *mid, *end;
7609 struct triple *lstore, *rstore;
7611 /* Generate some intermediate triples */
7613 var = variable(state, &int_type);
7615 /* Store the left hand side value */
7616 lstore = write_expr(state, var, left);
7618 /* Jump if the value is false */
7619 jmp = branch(state, end,
7620 lfalse_expr(state, read_expr(state, var)));
7623 /* Store the right hand side value */
7624 rstore = write_expr(state, var, right);
7626 /* An expression for the computed value */
7627 val = read_expr(state, var);
7629 /* Generate the prog for a logical and */
7630 def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0);
7635 static struct triple *mklor_expr(
7636 struct compile_state *state,
7637 struct triple *left, struct triple *right)
7639 struct triple *def, *val, *var, *jmp, *mid, *end;
7641 /* Generate some intermediate triples */
7643 var = variable(state, &int_type);
7645 /* Store the left hand side value */
7646 left = write_expr(state, var, left);
7648 /* Jump if the value is true */
7649 jmp = branch(state, end, read_expr(state, var));
7652 /* Store the right hand side value */
7653 right = write_expr(state, var, right);
7655 /* An expression for the computed value*/
7656 val = read_expr(state, var);
7658 /* Generate the prog for a logical or */
7659 def = mkprog(state, var, left, jmp, mid, right, end, val, 0);
7664 static struct triple *mkcond_expr(
7665 struct compile_state *state,
7666 struct triple *test, struct triple *left, struct triple *right)
7668 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7669 struct type *result_type;
7670 unsigned int left_type, right_type;
7672 left_type = left->type->type;
7673 right_type = right->type->type;
7675 /* Both operands have arithmetic type */
7676 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7677 result_type = arithmetic_result(state, left, right);
7679 /* Both operands have void type */
7680 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7681 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7682 result_type = &void_type;
7684 /* pointers to the same type... */
7685 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7688 /* Both operands are pointers and left is a pointer to void */
7689 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7690 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7691 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7692 result_type = right->type;
7694 /* Both operands are pointers and right is a pointer to void */
7695 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7696 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7697 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7698 result_type = left->type;
7701 error(state, 0, "Incompatible types in conditional expression");
7703 /* Generate some intermediate triples */
7706 var = variable(state, result_type);
7708 /* Branch if the test is false */
7709 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7712 /* Store the left hand side value */
7713 left = write_expr(state, var, left);
7715 /* Branch to the end */
7716 jmp2 = branch(state, end, 0);
7718 /* Store the right hand side value */
7719 right = write_expr(state, var, right);
7721 /* An expression for the computed value */
7722 val = read_expr(state, var);
7724 /* Generate the prog for a conditional expression */
7725 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0);
7731 static int expr_depth(struct compile_state *state, struct triple *ins)
7733 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7736 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7739 else if (ins->op == OP_DEREF) {
7740 count = expr_depth(state, RHS(ins, 0)) - 1;
7742 else if (ins->op == OP_VAL) {
7743 count = expr_depth(state, RHS(ins, 0)) - 1;
7745 else if (ins->op == OP_FCALL) {
7746 /* Don't figure the depth of a call just guess it is huge */
7750 struct triple **expr;
7751 expr = triple_rhs(state, ins, 0);
7752 for(;expr; expr = triple_rhs(state, ins, expr)) {
7755 depth = expr_depth(state, *expr);
7756 if (depth > count) {
7765 static struct triple *flatten_generic(
7766 struct compile_state *state, struct triple *first, struct triple *ptr,
7771 struct triple **ins;
7774 /* Only operations with just a rhs and a lhs should come here */
7777 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7778 internal_error(state, ptr, "unexpected args for: %d %s",
7779 ptr->op, tops(ptr->op));
7781 /* Find the depth of the rhs elements */
7782 for(i = 0; i < rhs; i++) {
7783 vector[i].ins = &RHS(ptr, i);
7784 vector[i].depth = expr_depth(state, *vector[i].ins);
7786 /* Selection sort the rhs */
7787 for(i = 0; i < rhs; i++) {
7789 for(j = i + 1; j < rhs; j++ ) {
7790 if (vector[j].depth > vector[max].depth) {
7795 struct rhs_vector tmp;
7797 vector[i] = vector[max];
7801 /* Now flatten the rhs elements */
7802 for(i = 0; i < rhs; i++) {
7803 *vector[i].ins = flatten(state, first, *vector[i].ins);
7804 use_triple(*vector[i].ins, ptr);
7807 insert_triple(state, first, ptr);
7808 ptr->id |= TRIPLE_FLAG_FLATTENED;
7809 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7811 /* Now flatten the lhs elements */
7812 for(i = 0; i < lhs; i++) {
7813 struct triple **ins = &LHS(ptr, i);
7814 *ins = flatten(state, first, *ins);
7815 use_triple(*ins, ptr);
7821 static struct triple *flatten_prog(
7822 struct compile_state *state, struct triple *first, struct triple *ptr)
7824 struct triple *head, *body, *val;
7829 release_triple(state, head);
7830 release_triple(state, ptr);
7832 body->prev = first->prev;
7833 body->prev->next = body;
7834 val->next->prev = val;
7836 if (triple_is_cbranch(state, body->prev) ||
7837 triple_is_call(state, body->prev)) {
7838 unuse_triple(first, body->prev);
7839 use_triple(body, body->prev);
7842 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7843 internal_error(state, val, "val not flattened?");
7850 static struct triple *flatten_part(
7851 struct compile_state *state, struct triple *first, struct triple *ptr)
7853 if (!triple_is_part(state, ptr)) {
7854 internal_error(state, ptr, "not a part");
7856 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7857 internal_error(state, ptr, "unexpected args for: %d %s",
7858 ptr->op, tops(ptr->op));
7860 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7861 use_triple(MISC(ptr, 0), ptr);
7862 return flatten_generic(state, first, ptr, 1);
7865 static struct triple *flatten(
7866 struct compile_state *state, struct triple *first, struct triple *ptr)
7868 struct triple *orig_ptr;
7873 /* Only flatten triples once */
7874 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7879 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7880 return MISC(ptr, 0);
7883 ptr = flatten_prog(state, first, ptr);
7886 ptr = flatten_generic(state, first, ptr, 1);
7887 insert_triple(state, first, ptr);
7888 ptr->id |= TRIPLE_FLAG_FLATTENED;
7889 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7890 if (ptr->next != ptr) {
7891 use_triple(ptr->next, ptr);
7896 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7897 use_triple(RHS(ptr, 0), ptr);
7900 ptr = flatten_generic(state, first, ptr, 1);
7901 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7902 use_triple(MISC(ptr, 0), ptr);
7905 use_triple(TARG(ptr, 0), ptr);
7908 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7909 use_triple(RHS(ptr, 0), ptr);
7910 use_triple(TARG(ptr, 0), ptr);
7911 insert_triple(state, first, ptr);
7912 ptr->id |= TRIPLE_FLAG_FLATTENED;
7913 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7914 if (ptr->next != ptr) {
7915 use_triple(ptr->next, ptr);
7919 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7920 use_triple(MISC(ptr, 0), ptr);
7921 use_triple(TARG(ptr, 0), ptr);
7922 insert_triple(state, first, ptr);
7923 ptr->id |= TRIPLE_FLAG_FLATTENED;
7924 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7925 if (ptr->next != ptr) {
7926 use_triple(ptr->next, ptr);
7930 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7931 use_triple(RHS(ptr, 0), ptr);
7934 insert_triple(state, state->global_pool, ptr);
7935 ptr->id |= TRIPLE_FLAG_FLATTENED;
7936 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7937 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7938 use_triple(MISC(ptr, 0), ptr);
7941 /* Since OP_DEREF is just a marker delete it when I flatten it */
7943 RHS(orig_ptr, 0) = 0;
7944 free_triple(state, orig_ptr);
7947 if (RHS(ptr, 0)->op == OP_DEREF) {
7948 struct triple *base, *left;
7950 base = MISC(ptr, 0);
7951 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7952 left = RHS(base, 0);
7953 ptr = triple(state, OP_ADD, left->type,
7954 read_expr(state, left),
7955 int_const(state, &ulong_type, offset));
7956 free_triple(state, base);
7959 ptr = flatten_part(state, first, ptr);
7963 if (RHS(ptr, 0)->op == OP_DEREF) {
7964 struct triple *base, *left;
7966 base = MISC(ptr, 0);
7967 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
7968 left = RHS(base, 0);
7969 ptr = triple(state, OP_ADD, left->type,
7970 read_expr(state, left),
7971 int_const(state, &long_type, offset));
7972 free_triple(state, base);
7975 ptr = flatten_part(state, first, ptr);
7979 ptr = flatten_part(state, first, ptr);
7980 use_triple(ptr, MISC(ptr, 0));
7983 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7984 use_triple(MISC(ptr, 0), ptr);
7987 first = state->global_pool;
7988 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7989 use_triple(MISC(ptr, 0), ptr);
7990 insert_triple(state, first, ptr);
7991 ptr->id |= TRIPLE_FLAG_FLATTENED;
7992 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7995 ptr = flatten_generic(state, first, ptr, 0);
7998 /* Flatten the easy cases we don't override */
7999 ptr = flatten_generic(state, first, ptr, 0);
8002 } while(ptr && (ptr != orig_ptr));
8003 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8004 insert_triple(state, first, ptr);
8005 ptr->id |= TRIPLE_FLAG_FLATTENED;
8006 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8011 static void release_expr(struct compile_state *state, struct triple *expr)
8013 struct triple *head;
8014 head = label(state);
8015 flatten(state, head, expr);
8016 while(head->next != head) {
8017 release_triple(state, head->next);
8019 free_triple(state, head);
8022 static int replace_rhs_use(struct compile_state *state,
8023 struct triple *orig, struct triple *new, struct triple *use)
8025 struct triple **expr;
8028 expr = triple_rhs(state, use, 0);
8029 for(;expr; expr = triple_rhs(state, use, expr)) {
8030 if (*expr == orig) {
8036 unuse_triple(orig, use);
8037 use_triple(new, use);
8042 static int replace_lhs_use(struct compile_state *state,
8043 struct triple *orig, struct triple *new, struct triple *use)
8045 struct triple **expr;
8048 expr = triple_lhs(state, use, 0);
8049 for(;expr; expr = triple_lhs(state, use, expr)) {
8050 if (*expr == orig) {
8056 unuse_triple(orig, use);
8057 use_triple(new, use);
8062 static int replace_misc_use(struct compile_state *state,
8063 struct triple *orig, struct triple *new, struct triple *use)
8065 struct triple **expr;
8068 expr = triple_misc(state, use, 0);
8069 for(;expr; expr = triple_misc(state, use, expr)) {
8070 if (*expr == orig) {
8076 unuse_triple(orig, use);
8077 use_triple(new, use);
8082 static int replace_targ_use(struct compile_state *state,
8083 struct triple *orig, struct triple *new, struct triple *use)
8085 struct triple **expr;
8088 expr = triple_targ(state, use, 0);
8089 for(;expr; expr = triple_targ(state, use, expr)) {
8090 if (*expr == orig) {
8096 unuse_triple(orig, use);
8097 use_triple(new, use);
8102 static void replace_use(struct compile_state *state,
8103 struct triple *orig, struct triple *new, struct triple *use)
8107 found |= replace_rhs_use(state, orig, new, use);
8108 found |= replace_lhs_use(state, orig, new, use);
8109 found |= replace_misc_use(state, orig, new, use);
8110 found |= replace_targ_use(state, orig, new, use);
8112 internal_error(state, use, "use without use");
8116 static void propogate_use(struct compile_state *state,
8117 struct triple *orig, struct triple *new)
8119 struct triple_set *user, *next;
8120 for(user = orig->use; user; user = next) {
8121 /* Careful replace_use modifies the use chain and
8122 * removes use. So we must get a copy of the next
8126 replace_use(state, orig, new, user->member);
8129 internal_error(state, orig, "used after propogate_use");
8135 * ===========================
8138 static struct triple *mk_cast_expr(
8139 struct compile_state *state, struct type *type, struct triple *expr)
8142 def = read_expr(state, expr);
8143 def = triple(state, OP_CONVERT, type, def, 0);
8147 static struct triple *mk_add_expr(
8148 struct compile_state *state, struct triple *left, struct triple *right)
8150 struct type *result_type;
8151 /* Put pointer operands on the left */
8152 if (is_pointer(right)) {
8158 left = read_expr(state, left);
8159 right = read_expr(state, right);
8160 result_type = ptr_arithmetic_result(state, left, right);
8161 if (is_pointer(left)) {
8162 struct type *ptr_math;
8164 if (is_signed(right->type)) {
8165 ptr_math = &long_type;
8168 ptr_math = &ulong_type;
8171 if (!equiv_types(right->type, ptr_math)) {
8172 right = mk_cast_expr(state, ptr_math, right);
8174 right = triple(state, op, ptr_math, right,
8175 int_const(state, ptr_math,
8176 size_of_in_bytes(state, left->type->left)));
8178 return triple(state, OP_ADD, result_type, left, right);
8181 static struct triple *mk_sub_expr(
8182 struct compile_state *state, struct triple *left, struct triple *right)
8184 struct type *result_type;
8185 result_type = ptr_arithmetic_result(state, left, right);
8186 left = read_expr(state, left);
8187 right = read_expr(state, right);
8188 if (is_pointer(left)) {
8189 struct type *ptr_math;
8191 if (is_signed(right->type)) {
8192 ptr_math = &long_type;
8195 ptr_math = &ulong_type;
8198 if (!equiv_types(right->type, ptr_math)) {
8199 right = mk_cast_expr(state, ptr_math, right);
8201 right = triple(state, op, ptr_math, right,
8202 int_const(state, ptr_math,
8203 size_of_in_bytes(state, left->type->left)));
8205 return triple(state, OP_SUB, result_type, left, right);
8208 static struct triple *mk_pre_inc_expr(
8209 struct compile_state *state, struct triple *def)
8213 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8214 return triple(state, OP_VAL, def->type,
8215 write_expr(state, def, val),
8219 static struct triple *mk_pre_dec_expr(
8220 struct compile_state *state, struct triple *def)
8224 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8225 return triple(state, OP_VAL, def->type,
8226 write_expr(state, def, val),
8230 static struct triple *mk_post_inc_expr(
8231 struct compile_state *state, struct triple *def)
8235 val = read_expr(state, def);
8236 return triple(state, OP_VAL, def->type,
8237 write_expr(state, def,
8238 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8242 static struct triple *mk_post_dec_expr(
8243 struct compile_state *state, struct triple *def)
8247 val = read_expr(state, def);
8248 return triple(state, OP_VAL, def->type,
8249 write_expr(state, def,
8250 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8254 static struct triple *mk_subscript_expr(
8255 struct compile_state *state, struct triple *left, struct triple *right)
8257 left = read_expr(state, left);
8258 right = read_expr(state, right);
8259 if (!is_pointer(left) && !is_pointer(right)) {
8260 error(state, left, "subscripted value is not a pointer");
8262 return mk_deref_expr(state, mk_add_expr(state, left, right));
8267 * Compile time evaluation
8268 * ===========================
8270 static int is_const(struct triple *ins)
8272 return IS_CONST_OP(ins->op);
8275 static int is_simple_const(struct triple *ins)
8277 /* Is this a constant that u.cval has the value.
8278 * Or equivalently is this a constant that read_const
8280 * So far only OP_INTCONST qualifies.
8282 return (ins->op == OP_INTCONST);
8285 static int constants_equal(struct compile_state *state,
8286 struct triple *left, struct triple *right)
8289 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8292 else if (!is_const(left) || !is_const(right)) {
8295 else if (left->op != right->op) {
8298 else if (!equiv_types(left->type, right->type)) {
8305 if (left->u.cval == right->u.cval) {
8311 size_t lsize, rsize, bytes;
8312 lsize = size_of(state, left->type);
8313 rsize = size_of(state, right->type);
8314 if (lsize != rsize) {
8317 bytes = bits_to_bytes(lsize);
8318 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8324 if ((MISC(left, 0) == MISC(right, 0)) &&
8325 (left->u.cval == right->u.cval)) {
8330 internal_error(state, left, "uknown constant type");
8337 static int is_zero(struct triple *ins)
8339 return is_simple_const(ins) && (ins->u.cval == 0);
8342 static int is_one(struct triple *ins)
8344 return is_simple_const(ins) && (ins->u.cval == 1);
8347 static long_t bit_count(ulong_t value)
8352 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8363 static long_t bsr(ulong_t value)
8366 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8377 static long_t bsf(ulong_t value)
8380 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8391 static long_t ilog2(ulong_t value)
8396 static long_t tlog2(struct triple *ins)
8398 return ilog2(ins->u.cval);
8401 static int is_pow2(struct triple *ins)
8403 ulong_t value, mask;
8405 if (!is_const(ins)) {
8408 value = ins->u.cval;
8415 return ((value & mask) == value);
8418 static ulong_t read_const(struct compile_state *state,
8419 struct triple *ins, struct triple *rhs)
8421 switch(rhs->type->type &TYPE_MASK) {
8434 fprintf(state->errout, "type: ");
8435 name_of(state->errout, rhs->type);
8436 fprintf(state->errout, "\n");
8437 internal_warning(state, rhs, "bad type to read_const");
8440 if (!is_simple_const(rhs)) {
8441 internal_error(state, rhs, "bad op to read_const");
8446 static long_t read_sconst(struct compile_state *state,
8447 struct triple *ins, struct triple *rhs)
8449 return (long_t)(rhs->u.cval);
8452 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8454 if (!is_const(rhs)) {
8455 internal_error(state, 0, "non const passed to const_true");
8457 return !is_zero(rhs);
8460 int const_eq(struct compile_state *state, struct triple *ins,
8461 struct triple *left, struct triple *right)
8464 if (!is_const(left) || !is_const(right)) {
8465 internal_warning(state, ins, "non const passed to const_eq");
8468 else if (left == right) {
8471 else if (is_simple_const(left) && is_simple_const(right)) {
8473 lval = read_const(state, ins, left);
8474 rval = read_const(state, ins, right);
8475 result = (lval == rval);
8477 else if ((left->op == OP_ADDRCONST) &&
8478 (right->op == OP_ADDRCONST)) {
8479 result = (MISC(left, 0) == MISC(right, 0)) &&
8480 (left->u.cval == right->u.cval);
8483 internal_warning(state, ins, "incomparable constants passed to const_eq");
8490 int const_ucmp(struct compile_state *state, struct triple *ins,
8491 struct triple *left, struct triple *right)
8494 if (!is_const(left) || !is_const(right)) {
8495 internal_warning(state, ins, "non const past to const_ucmp");
8498 else if (left == right) {
8501 else if (is_simple_const(left) && is_simple_const(right)) {
8503 lval = read_const(state, ins, left);
8504 rval = read_const(state, ins, right);
8508 } else if (rval > lval) {
8512 else if ((left->op == OP_ADDRCONST) &&
8513 (right->op == OP_ADDRCONST) &&
8514 (MISC(left, 0) == MISC(right, 0))) {
8516 if (left->u.cval > right->u.cval) {
8518 } else if (left->u.cval < right->u.cval) {
8523 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8529 int const_scmp(struct compile_state *state, struct triple *ins,
8530 struct triple *left, struct triple *right)
8533 if (!is_const(left) || !is_const(right)) {
8534 internal_warning(state, ins, "non const past to ucmp_const");
8537 else if (left == right) {
8540 else if (is_simple_const(left) && is_simple_const(right)) {
8542 lval = read_sconst(state, ins, left);
8543 rval = read_sconst(state, ins, right);
8547 } else if (rval > lval) {
8552 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8558 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8560 struct triple **expr;
8561 expr = triple_rhs(state, ins, 0);
8562 for(;expr;expr = triple_rhs(state, ins, expr)) {
8564 unuse_triple(*expr, ins);
8570 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8572 struct triple **expr;
8573 expr = triple_lhs(state, ins, 0);
8574 for(;expr;expr = triple_lhs(state, ins, expr)) {
8575 unuse_triple(*expr, ins);
8580 static void unuse_misc(struct compile_state *state, struct triple *ins)
8582 struct triple **expr;
8583 expr = triple_misc(state, ins, 0);
8584 for(;expr;expr = triple_misc(state, ins, expr)) {
8585 unuse_triple(*expr, ins);
8590 static void unuse_targ(struct compile_state *state, struct triple *ins)
8593 struct triple **slot;
8594 slot = &TARG(ins, 0);
8595 for(i = 0; i < ins->targ; i++) {
8596 unuse_triple(slot[i], ins);
8601 static void check_lhs(struct compile_state *state, struct triple *ins)
8603 struct triple **expr;
8604 expr = triple_lhs(state, ins, 0);
8605 for(;expr;expr = triple_lhs(state, ins, expr)) {
8606 internal_error(state, ins, "unexpected lhs");
8611 static void check_misc(struct compile_state *state, struct triple *ins)
8613 struct triple **expr;
8614 expr = triple_misc(state, ins, 0);
8615 for(;expr;expr = triple_misc(state, ins, expr)) {
8617 internal_error(state, ins, "unexpected misc");
8622 static void check_targ(struct compile_state *state, struct triple *ins)
8624 struct triple **expr;
8625 expr = triple_targ(state, ins, 0);
8626 for(;expr;expr = triple_targ(state, ins, expr)) {
8627 internal_error(state, ins, "unexpected targ");
8631 static void wipe_ins(struct compile_state *state, struct triple *ins)
8633 /* Becareful which instructions you replace the wiped
8634 * instruction with, as there are not enough slots
8635 * in all instructions to hold all others.
8637 check_targ(state, ins);
8638 check_misc(state, ins);
8639 unuse_rhs(state, ins);
8640 unuse_lhs(state, ins);
8647 static void wipe_branch(struct compile_state *state, struct triple *ins)
8649 /* Becareful which instructions you replace the wiped
8650 * instruction with, as there are not enough slots
8651 * in all instructions to hold all others.
8653 unuse_rhs(state, ins);
8654 unuse_lhs(state, ins);
8655 unuse_misc(state, ins);
8656 unuse_targ(state, ins);
8663 static void mkcopy(struct compile_state *state,
8664 struct triple *ins, struct triple *rhs)
8666 struct block *block;
8667 if (!equiv_types(ins->type, rhs->type)) {
8668 FILE *fp = state->errout;
8669 fprintf(fp, "src type: ");
8670 name_of(fp, rhs->type);
8671 fprintf(fp, "\ndst type: ");
8672 name_of(fp, ins->type);
8674 internal_error(state, ins, "mkcopy type mismatch");
8676 block = block_of_triple(state, ins);
8677 wipe_ins(state, ins);
8680 ins->u.block = block;
8682 use_triple(RHS(ins, 0), ins);
8685 static void mkconst(struct compile_state *state,
8686 struct triple *ins, ulong_t value)
8688 if (!is_integral(ins) && !is_pointer(ins)) {
8689 fprintf(state->errout, "type: ");
8690 name_of(state->errout, ins->type);
8691 fprintf(state->errout, "\n");
8692 internal_error(state, ins, "unknown type to make constant value: %ld",
8695 wipe_ins(state, ins);
8696 ins->op = OP_INTCONST;
8697 ins->u.cval = value;
8700 static void mkaddr_const(struct compile_state *state,
8701 struct triple *ins, struct triple *sdecl, ulong_t value)
8703 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8704 internal_error(state, ins, "bad base for addrconst");
8706 wipe_ins(state, ins);
8707 ins->op = OP_ADDRCONST;
8709 MISC(ins, 0) = sdecl;
8710 ins->u.cval = value;
8711 use_triple(sdecl, ins);
8714 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8715 static void print_tuple(struct compile_state *state,
8716 struct triple *ins, struct triple *tuple)
8718 FILE *fp = state->dbgout;
8719 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8720 name_of(fp, tuple->type);
8721 if (tuple->lhs > 0) {
8722 fprintf(fp, " lhs: ");
8723 name_of(fp, LHS(tuple, 0)->type);
8730 static struct triple *decompose_with_tuple(struct compile_state *state,
8731 struct triple *ins, struct triple *tuple)
8733 struct triple *next;
8735 flatten(state, next, tuple);
8736 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8737 print_tuple(state, ins, tuple);
8740 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8742 if (tuple->lhs != 1) {
8743 internal_error(state, tuple, "plain type in multiple registers?");
8745 tmp = LHS(tuple, 0);
8746 release_triple(state, tuple);
8750 propogate_use(state, ins, tuple);
8751 release_triple(state, ins);
8756 static struct triple *decompose_unknownval(struct compile_state *state,
8759 struct triple *tuple;
8762 #if DEBUG_DECOMPOSE_HIRES
8763 FILE *fp = state->dbgout;
8764 fprintf(fp, "unknown type: ");
8765 name_of(fp, ins->type);
8769 get_occurance(ins->occurance);
8770 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8773 for(i = 0; i < tuple->lhs; i++) {
8774 struct type *piece_type;
8775 struct triple *unknown;
8777 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8778 get_occurance(tuple->occurance);
8779 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8781 LHS(tuple, i) = unknown;
8783 return decompose_with_tuple(state, ins, tuple);
8787 static struct triple *decompose_read(struct compile_state *state,
8790 struct triple *tuple, *lval;
8795 if (lval->op == OP_PIECE) {
8798 get_occurance(ins->occurance);
8799 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8802 if ((tuple->lhs != lval->lhs) &&
8803 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8805 internal_error(state, ins, "lhs size inconsistency?");
8807 for(i = 0; i < tuple->lhs; i++) {
8808 struct triple *piece, *read, *bitref;
8809 if ((i != 0) || !triple_is_def(state, lval)) {
8810 piece = LHS(lval, i);
8815 /* See if the piece is really a bitref */
8817 if (piece->op == OP_BITREF) {
8819 piece = RHS(bitref, 0);
8822 get_occurance(tuple->occurance);
8823 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8825 RHS(read, 0) = piece;
8828 struct triple *extract;
8830 if (is_signed(bitref->type->left)) {
8835 get_occurance(tuple->occurance);
8836 extract = alloc_triple(state, op, bitref->type, -1, -1,
8838 RHS(extract, 0) = read;
8839 extract->u.bitfield.size = bitref->u.bitfield.size;
8840 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8845 LHS(tuple, i) = read;
8847 return decompose_with_tuple(state, ins, tuple);
8850 static struct triple *decompose_write(struct compile_state *state,
8853 struct triple *tuple, *lval, *val;
8856 lval = MISC(ins, 0);
8858 get_occurance(ins->occurance);
8859 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8862 if ((tuple->lhs != lval->lhs) &&
8863 (!triple_is_def(state, lval) || tuple->lhs != 1))
8865 internal_error(state, ins, "lhs size inconsistency?");
8867 for(i = 0; i < tuple->lhs; i++) {
8868 struct triple *piece, *write, *pval, *bitref;
8869 if ((i != 0) || !triple_is_def(state, lval)) {
8870 piece = LHS(lval, i);
8874 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8879 internal_error(state, ins, "lhs size inconsistency?");
8884 /* See if the piece is really a bitref */
8886 if (piece->op == OP_BITREF) {
8887 struct triple *read, *deposit;
8889 piece = RHS(bitref, 0);
8891 /* Read the destination register */
8892 get_occurance(tuple->occurance);
8893 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8895 RHS(read, 0) = piece;
8897 /* Deposit the new bitfield value */
8898 get_occurance(tuple->occurance);
8899 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8901 RHS(deposit, 0) = read;
8902 RHS(deposit, 1) = pval;
8903 deposit->u.bitfield.size = bitref->u.bitfield.size;
8904 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8906 /* Now write the newly generated value */
8910 get_occurance(tuple->occurance);
8911 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
8913 MISC(write, 0) = piece;
8914 RHS(write, 0) = pval;
8915 LHS(tuple, i) = write;
8917 return decompose_with_tuple(state, ins, tuple);
8920 struct decompose_load_info {
8921 struct occurance *occurance;
8922 struct triple *lval;
8923 struct triple *tuple;
8925 static void decompose_load_cb(struct compile_state *state,
8926 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8928 struct decompose_load_info *info = arg;
8929 struct triple *load;
8931 if (reg_offset > info->tuple->lhs) {
8932 internal_error(state, info->tuple, "lhs to small?");
8934 get_occurance(info->occurance);
8935 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8936 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8937 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8940 static struct triple *decompose_load(struct compile_state *state,
8943 struct triple *tuple;
8944 struct decompose_load_info info;
8946 if (!is_compound_type(ins->type)) {
8949 get_occurance(ins->occurance);
8950 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8953 info.occurance = ins->occurance;
8954 info.lval = RHS(ins, 0);
8956 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
8958 return decompose_with_tuple(state, ins, tuple);
8962 struct decompose_store_info {
8963 struct occurance *occurance;
8964 struct triple *lval;
8966 struct triple *tuple;
8968 static void decompose_store_cb(struct compile_state *state,
8969 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8971 struct decompose_store_info *info = arg;
8972 struct triple *store;
8974 if (reg_offset > info->tuple->lhs) {
8975 internal_error(state, info->tuple, "lhs to small?");
8977 get_occurance(info->occurance);
8978 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
8979 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
8980 RHS(store, 1) = LHS(info->val, reg_offset);
8981 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
8984 static struct triple *decompose_store(struct compile_state *state,
8987 struct triple *tuple;
8988 struct decompose_store_info info;
8990 if (!is_compound_type(ins->type)) {
8993 get_occurance(ins->occurance);
8994 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8997 info.occurance = ins->occurance;
8998 info.lval = RHS(ins, 0);
8999 info.val = RHS(ins, 1);
9001 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9003 return decompose_with_tuple(state, ins, tuple);
9006 static struct triple *decompose_dot(struct compile_state *state,
9009 struct triple *tuple, *lval;
9014 lval = MISC(ins, 0);
9015 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9016 idx = reg_offset/REG_SIZEOF_REG;
9017 type = field_type(state, lval->type, ins->u.field);
9018 #if DEBUG_DECOMPOSE_HIRES
9020 FILE *fp = state->dbgout;
9021 fprintf(fp, "field type: ");
9027 get_occurance(ins->occurance);
9028 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9031 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9034 internal_error(state, ins, "multi register bitfield?");
9037 for(i = 0; i < tuple->lhs; i++, idx++) {
9038 struct triple *piece;
9039 if (!triple_is_def(state, lval)) {
9040 if (idx > lval->lhs) {
9041 internal_error(state, ins, "inconsistent lhs count");
9043 piece = LHS(lval, idx);
9046 internal_error(state, ins, "bad reg_offset into def");
9049 internal_error(state, ins, "bad reg count from def");
9054 /* Remember the offset of the bitfield */
9055 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9056 get_occurance(ins->occurance);
9057 piece = build_triple(state, OP_BITREF, type, piece, 0,
9059 piece->u.bitfield.size = size_of(state, type);
9060 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9062 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9063 internal_error(state, ins,
9064 "request for a nonbitfield sub register?");
9067 LHS(tuple, i) = piece;
9070 return decompose_with_tuple(state, ins, tuple);
9073 static struct triple *decompose_index(struct compile_state *state,
9076 struct triple *tuple, *lval;
9080 lval = MISC(ins, 0);
9081 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9082 type = index_type(state, lval->type, ins->u.cval);
9083 #if DEBUG_DECOMPOSE_HIRES
9085 FILE *fp = state->dbgout;
9086 fprintf(fp, "index type: ");
9092 get_occurance(ins->occurance);
9093 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9096 for(i = 0; i < tuple->lhs; i++, idx++) {
9097 struct triple *piece;
9098 if (!triple_is_def(state, lval)) {
9099 if (idx > lval->lhs) {
9100 internal_error(state, ins, "inconsistent lhs count");
9102 piece = LHS(lval, idx);
9105 internal_error(state, ins, "bad reg_offset into def");
9108 internal_error(state, ins, "bad reg count from def");
9112 LHS(tuple, i) = piece;
9115 return decompose_with_tuple(state, ins, tuple);
9118 static void decompose_compound_types(struct compile_state *state)
9120 struct triple *ins, *next, *first;
9123 first = state->first;
9126 /* Pass one expand compound values into pseudo registers.
9134 next = decompose_unknownval(state, ins);
9138 next = decompose_read(state, ins);
9142 next = decompose_write(state, ins);
9146 /* Be very careful with the load/store logic. These
9147 * operations must convert from the in register layout
9148 * to the in memory layout, which is nontrivial.
9151 next = decompose_load(state, ins);
9154 next = decompose_store(state, ins);
9158 next = decompose_dot(state, ins);
9161 next = decompose_index(state, ins);
9165 #if DEBUG_DECOMPOSE_HIRES
9166 fprintf(fp, "decompose next: %p \n", next);
9168 fprintf(fp, "next->op: %d %s\n",
9169 next->op, tops(next->op));
9170 /* High resolution debugging mode */
9171 print_triples(state);
9173 } while (next != first);
9175 /* Pass two remove the tuples.
9180 if (ins->op == OP_TUPLE) {
9182 internal_error(state, ins, "tuple used");
9185 release_triple(state, ins);
9189 } while(ins != first);
9193 if (ins->op == OP_BITREF) {
9195 internal_error(state, ins, "bitref used");
9198 release_triple(state, ins);
9202 } while(ins != first);
9204 /* Pass three verify the state and set ->id to 0.
9210 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9211 if (triple_stores_block(state, ins)) {
9214 if (triple_is_def(state, ins)) {
9215 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9216 internal_error(state, ins, "multi register value remains?");
9219 if (ins->op == OP_DOT) {
9220 internal_error(state, ins, "OP_DOT remains?");
9222 if (ins->op == OP_INDEX) {
9223 internal_error(state, ins, "OP_INDEX remains?");
9225 if (ins->op == OP_BITREF) {
9226 internal_error(state, ins, "OP_BITREF remains?");
9228 if (ins->op == OP_TUPLE) {
9229 internal_error(state, ins, "OP_TUPLE remains?");
9231 } while(next != first);
9234 /* For those operations that cannot be simplified */
9235 static void simplify_noop(struct compile_state *state, struct triple *ins)
9240 static void simplify_smul(struct compile_state *state, struct triple *ins)
9242 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9245 RHS(ins, 0) = RHS(ins, 1);
9248 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9250 left = read_sconst(state, ins, RHS(ins, 0));
9251 right = read_sconst(state, ins, RHS(ins, 1));
9252 mkconst(state, ins, left * right);
9254 else if (is_zero(RHS(ins, 1))) {
9255 mkconst(state, ins, 0);
9257 else if (is_one(RHS(ins, 1))) {
9258 mkcopy(state, ins, RHS(ins, 0));
9260 else if (is_pow2(RHS(ins, 1))) {
9262 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9264 insert_triple(state, state->global_pool, val);
9265 unuse_triple(RHS(ins, 1), ins);
9266 use_triple(val, ins);
9271 static void simplify_umul(struct compile_state *state, struct triple *ins)
9273 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9276 RHS(ins, 0) = RHS(ins, 1);
9279 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9280 ulong_t left, right;
9281 left = read_const(state, ins, RHS(ins, 0));
9282 right = read_const(state, ins, RHS(ins, 1));
9283 mkconst(state, ins, left * right);
9285 else if (is_zero(RHS(ins, 1))) {
9286 mkconst(state, ins, 0);
9288 else if (is_one(RHS(ins, 1))) {
9289 mkcopy(state, ins, RHS(ins, 0));
9291 else if (is_pow2(RHS(ins, 1))) {
9293 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9295 insert_triple(state, state->global_pool, val);
9296 unuse_triple(RHS(ins, 1), ins);
9297 use_triple(val, ins);
9302 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9304 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9306 left = read_sconst(state, ins, RHS(ins, 0));
9307 right = read_sconst(state, ins, RHS(ins, 1));
9308 mkconst(state, ins, left / right);
9310 else if (is_zero(RHS(ins, 0))) {
9311 mkconst(state, ins, 0);
9313 else if (is_zero(RHS(ins, 1))) {
9314 error(state, ins, "division by zero");
9316 else if (is_one(RHS(ins, 1))) {
9317 mkcopy(state, ins, RHS(ins, 0));
9319 else if (is_pow2(RHS(ins, 1))) {
9321 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9323 insert_triple(state, state->global_pool, val);
9324 unuse_triple(RHS(ins, 1), ins);
9325 use_triple(val, ins);
9330 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9332 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9333 ulong_t left, right;
9334 left = read_const(state, ins, RHS(ins, 0));
9335 right = read_const(state, ins, RHS(ins, 1));
9336 mkconst(state, ins, left / right);
9338 else if (is_zero(RHS(ins, 0))) {
9339 mkconst(state, ins, 0);
9341 else if (is_zero(RHS(ins, 1))) {
9342 error(state, ins, "division by zero");
9344 else if (is_one(RHS(ins, 1))) {
9345 mkcopy(state, ins, RHS(ins, 0));
9347 else if (is_pow2(RHS(ins, 1))) {
9349 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9351 insert_triple(state, state->global_pool, val);
9352 unuse_triple(RHS(ins, 1), ins);
9353 use_triple(val, ins);
9358 static void simplify_smod(struct compile_state *state, struct triple *ins)
9360 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9362 left = read_const(state, ins, RHS(ins, 0));
9363 right = read_const(state, ins, RHS(ins, 1));
9364 mkconst(state, ins, left % right);
9366 else if (is_zero(RHS(ins, 0))) {
9367 mkconst(state, ins, 0);
9369 else if (is_zero(RHS(ins, 1))) {
9370 error(state, ins, "division by zero");
9372 else if (is_one(RHS(ins, 1))) {
9373 mkconst(state, ins, 0);
9375 else if (is_pow2(RHS(ins, 1))) {
9377 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9379 insert_triple(state, state->global_pool, val);
9380 unuse_triple(RHS(ins, 1), ins);
9381 use_triple(val, ins);
9386 static void simplify_umod(struct compile_state *state, struct triple *ins)
9388 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9389 ulong_t left, right;
9390 left = read_const(state, ins, RHS(ins, 0));
9391 right = read_const(state, ins, RHS(ins, 1));
9392 mkconst(state, ins, left % right);
9394 else if (is_zero(RHS(ins, 0))) {
9395 mkconst(state, ins, 0);
9397 else if (is_zero(RHS(ins, 1))) {
9398 error(state, ins, "division by zero");
9400 else if (is_one(RHS(ins, 1))) {
9401 mkconst(state, ins, 0);
9403 else if (is_pow2(RHS(ins, 1))) {
9405 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9407 insert_triple(state, state->global_pool, val);
9408 unuse_triple(RHS(ins, 1), ins);
9409 use_triple(val, ins);
9414 static void simplify_add(struct compile_state *state, struct triple *ins)
9416 /* start with the pointer on the left */
9417 if (is_pointer(RHS(ins, 1))) {
9420 RHS(ins, 0) = RHS(ins, 1);
9423 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9424 if (RHS(ins, 0)->op == OP_INTCONST) {
9425 ulong_t left, right;
9426 left = read_const(state, ins, RHS(ins, 0));
9427 right = read_const(state, ins, RHS(ins, 1));
9428 mkconst(state, ins, left + right);
9430 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9431 struct triple *sdecl;
9432 ulong_t left, right;
9433 sdecl = MISC(RHS(ins, 0), 0);
9434 left = RHS(ins, 0)->u.cval;
9435 right = RHS(ins, 1)->u.cval;
9436 mkaddr_const(state, ins, sdecl, left + right);
9439 internal_warning(state, ins, "Optimize me!");
9442 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9445 RHS(ins, 1) = RHS(ins, 0);
9450 static void simplify_sub(struct compile_state *state, struct triple *ins)
9452 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9453 if (RHS(ins, 0)->op == OP_INTCONST) {
9454 ulong_t left, right;
9455 left = read_const(state, ins, RHS(ins, 0));
9456 right = read_const(state, ins, RHS(ins, 1));
9457 mkconst(state, ins, left - right);
9459 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9460 struct triple *sdecl;
9461 ulong_t left, right;
9462 sdecl = MISC(RHS(ins, 0), 0);
9463 left = RHS(ins, 0)->u.cval;
9464 right = RHS(ins, 1)->u.cval;
9465 mkaddr_const(state, ins, sdecl, left - right);
9468 internal_warning(state, ins, "Optimize me!");
9473 static void simplify_sl(struct compile_state *state, struct triple *ins)
9475 if (is_simple_const(RHS(ins, 1))) {
9477 right = read_const(state, ins, RHS(ins, 1));
9478 if (right >= (size_of(state, ins->type))) {
9479 warning(state, ins, "left shift count >= width of type");
9482 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9483 ulong_t left, right;
9484 left = read_const(state, ins, RHS(ins, 0));
9485 right = read_const(state, ins, RHS(ins, 1));
9486 mkconst(state, ins, left << right);
9490 static void simplify_usr(struct compile_state *state, struct triple *ins)
9492 if (is_simple_const(RHS(ins, 1))) {
9494 right = read_const(state, ins, RHS(ins, 1));
9495 if (right >= (size_of(state, ins->type))) {
9496 warning(state, ins, "right shift count >= width of type");
9499 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9500 ulong_t left, right;
9501 left = read_const(state, ins, RHS(ins, 0));
9502 right = read_const(state, ins, RHS(ins, 1));
9503 mkconst(state, ins, left >> right);
9507 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9509 if (is_simple_const(RHS(ins, 1))) {
9511 right = read_const(state, ins, RHS(ins, 1));
9512 if (right >= (size_of(state, ins->type))) {
9513 warning(state, ins, "right shift count >= width of type");
9516 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9518 left = read_sconst(state, ins, RHS(ins, 0));
9519 right = read_sconst(state, ins, RHS(ins, 1));
9520 mkconst(state, ins, left >> right);
9524 static void simplify_and(struct compile_state *state, struct triple *ins)
9526 struct triple *left, *right;
9528 right = RHS(ins, 1);
9530 if (is_simple_const(left) && is_simple_const(right)) {
9532 lval = read_const(state, ins, left);
9533 rval = read_const(state, ins, right);
9534 mkconst(state, ins, lval & rval);
9536 else if (is_zero(right) || is_zero(left)) {
9537 mkconst(state, ins, 0);
9541 static void simplify_or(struct compile_state *state, struct triple *ins)
9543 struct triple *left, *right;
9545 right = RHS(ins, 1);
9547 if (is_simple_const(left) && is_simple_const(right)) {
9549 lval = read_const(state, ins, left);
9550 rval = read_const(state, ins, right);
9551 mkconst(state, ins, lval | rval);
9553 #if 0 /* I need to handle type mismatches here... */
9554 else if (is_zero(right)) {
9555 mkcopy(state, ins, left);
9557 else if (is_zero(left)) {
9558 mkcopy(state, ins, right);
9563 static void simplify_xor(struct compile_state *state, struct triple *ins)
9565 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9566 ulong_t left, right;
9567 left = read_const(state, ins, RHS(ins, 0));
9568 right = read_const(state, ins, RHS(ins, 1));
9569 mkconst(state, ins, left ^ right);
9573 static void simplify_pos(struct compile_state *state, struct triple *ins)
9575 if (is_const(RHS(ins, 0))) {
9576 mkconst(state, ins, RHS(ins, 0)->u.cval);
9579 mkcopy(state, ins, RHS(ins, 0));
9583 static void simplify_neg(struct compile_state *state, struct triple *ins)
9585 if (is_simple_const(RHS(ins, 0))) {
9587 left = read_const(state, ins, RHS(ins, 0));
9588 mkconst(state, ins, -left);
9590 else if (RHS(ins, 0)->op == OP_NEG) {
9591 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9595 static void simplify_invert(struct compile_state *state, struct triple *ins)
9597 if (is_simple_const(RHS(ins, 0))) {
9599 left = read_const(state, ins, RHS(ins, 0));
9600 mkconst(state, ins, ~left);
9604 static void simplify_eq(struct compile_state *state, struct triple *ins)
9606 struct triple *left, *right;
9608 right = RHS(ins, 1);
9610 if (is_const(left) && is_const(right)) {
9612 val = const_eq(state, ins, left, right);
9614 mkconst(state, ins, val == 1);
9617 else if (left == right) {
9618 mkconst(state, ins, 1);
9622 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9624 struct triple *left, *right;
9626 right = RHS(ins, 1);
9628 if (is_const(left) && is_const(right)) {
9630 val = const_eq(state, ins, left, right);
9632 mkconst(state, ins, val != 1);
9635 if (left == right) {
9636 mkconst(state, ins, 0);
9640 static void simplify_sless(struct compile_state *state, struct triple *ins)
9642 struct triple *left, *right;
9644 right = RHS(ins, 1);
9646 if (is_const(left) && is_const(right)) {
9648 val = const_scmp(state, ins, left, right);
9649 if ((val >= -1) && (val <= 1)) {
9650 mkconst(state, ins, val < 0);
9653 else if (left == right) {
9654 mkconst(state, ins, 0);
9658 static void simplify_uless(struct compile_state *state, struct triple *ins)
9660 struct triple *left, *right;
9662 right = RHS(ins, 1);
9664 if (is_const(left) && is_const(right)) {
9666 val = const_ucmp(state, ins, left, right);
9667 if ((val >= -1) && (val <= 1)) {
9668 mkconst(state, ins, val < 0);
9671 else if (is_zero(right)) {
9672 mkconst(state, ins, 0);
9674 else if (left == right) {
9675 mkconst(state, ins, 0);
9679 static void simplify_smore(struct compile_state *state, struct triple *ins)
9681 struct triple *left, *right;
9683 right = RHS(ins, 1);
9685 if (is_const(left) && is_const(right)) {
9687 val = const_scmp(state, ins, left, right);
9688 if ((val >= -1) && (val <= 1)) {
9689 mkconst(state, ins, val > 0);
9692 else if (left == right) {
9693 mkconst(state, ins, 0);
9697 static void simplify_umore(struct compile_state *state, struct triple *ins)
9699 struct triple *left, *right;
9701 right = RHS(ins, 1);
9703 if (is_const(left) && is_const(right)) {
9705 val = const_ucmp(state, ins, left, right);
9706 if ((val >= -1) && (val <= 1)) {
9707 mkconst(state, ins, val > 0);
9710 else if (is_zero(left)) {
9711 mkconst(state, ins, 0);
9713 else if (left == right) {
9714 mkconst(state, ins, 0);
9719 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9721 struct triple *left, *right;
9723 right = RHS(ins, 1);
9725 if (is_const(left) && is_const(right)) {
9727 val = const_scmp(state, ins, left, right);
9728 if ((val >= -1) && (val <= 1)) {
9729 mkconst(state, ins, val <= 0);
9732 else if (left == right) {
9733 mkconst(state, ins, 1);
9737 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9739 struct triple *left, *right;
9741 right = RHS(ins, 1);
9743 if (is_const(left) && is_const(right)) {
9745 val = const_ucmp(state, ins, left, right);
9746 if ((val >= -1) && (val <= 1)) {
9747 mkconst(state, ins, val <= 0);
9750 else if (is_zero(left)) {
9751 mkconst(state, ins, 1);
9753 else if (left == right) {
9754 mkconst(state, ins, 1);
9758 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9760 struct triple *left, *right;
9762 right = RHS(ins, 1);
9764 if (is_const(left) && is_const(right)) {
9766 val = const_scmp(state, ins, left, right);
9767 if ((val >= -1) && (val <= 1)) {
9768 mkconst(state, ins, val >= 0);
9771 else if (left == right) {
9772 mkconst(state, ins, 1);
9776 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9778 struct triple *left, *right;
9780 right = RHS(ins, 1);
9782 if (is_const(left) && is_const(right)) {
9784 val = const_ucmp(state, ins, left, right);
9785 if ((val >= -1) && (val <= 1)) {
9786 mkconst(state, ins, val >= 0);
9789 else if (is_zero(right)) {
9790 mkconst(state, ins, 1);
9792 else if (left == right) {
9793 mkconst(state, ins, 1);
9797 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9802 if (is_const(rhs)) {
9803 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9805 /* Otherwise if I am the only user... */
9806 else if ((rhs->use) &&
9807 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9809 /* Invert a boolean operation */
9811 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9812 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9813 case OP_EQ: rhs->op = OP_NOTEQ; break;
9814 case OP_NOTEQ: rhs->op = OP_EQ; break;
9815 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9816 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9817 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9818 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9819 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9820 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9821 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9822 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9828 mkcopy(state, ins, rhs);
9833 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9838 if (is_const(rhs)) {
9839 mkconst(state, ins, const_ltrue(state, ins, rhs));
9841 else switch(rhs->op) {
9842 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9843 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9844 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9845 mkcopy(state, ins, rhs);
9850 static void simplify_load(struct compile_state *state, struct triple *ins)
9852 struct triple *addr, *sdecl, *blob;
9854 /* If I am doing a load with a constant pointer from a constant
9855 * table get the value.
9858 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9859 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9860 (blob->op == OP_BLOBCONST)) {
9861 unsigned char buffer[SIZEOF_WORD];
9862 size_t reg_size, mem_size;
9863 const char *src, *end;
9865 reg_size = reg_size_of(state, ins->type);
9866 if (reg_size > REG_SIZEOF_REG) {
9867 internal_error(state, ins, "load size greater than register");
9869 mem_size = size_of(state, ins->type);
9871 end += bits_to_bytes(size_of(state, sdecl->type));
9873 src += addr->u.cval;
9876 error(state, ins, "Load address out of bounds");
9879 memset(buffer, 0, sizeof(buffer));
9880 memcpy(buffer, src, bits_to_bytes(mem_size));
9883 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
9884 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9885 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9886 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9888 internal_error(state, ins, "mem_size: %d not handled",
9893 mkconst(state, ins, val);
9897 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9899 if (is_simple_const(RHS(ins, 0))) {
9902 val = read_const(state, ins, RHS(ins, 0));
9904 mask <<= ins->u.bitfield.size;
9906 val >>= ins->u.bitfield.offset;
9908 mkconst(state, ins, val);
9912 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9914 if (is_simple_const(RHS(ins, 0))) {
9918 val = read_const(state, ins, RHS(ins, 0));
9920 mask <<= ins->u.bitfield.size;
9922 val >>= ins->u.bitfield.offset;
9924 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9926 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9927 mkconst(state, ins, sval);
9931 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9933 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9936 targ = read_const(state, ins, RHS(ins, 0));
9937 val = read_const(state, ins, RHS(ins, 1));
9939 mask <<= ins->u.bitfield.size;
9941 mask <<= ins->u.bitfield.offset;
9943 val <<= ins->u.bitfield.offset;
9946 mkconst(state, ins, targ);
9950 static void simplify_copy(struct compile_state *state, struct triple *ins)
9952 struct triple *right;
9953 right = RHS(ins, 0);
9954 if (is_subset_type(ins->type, right->type)) {
9955 ins->type = right->type;
9957 if (equiv_types(ins->type, right->type)) {
9958 ins->op = OP_COPY;/* I don't need to convert if the types match */
9960 if (ins->op == OP_COPY) {
9961 internal_error(state, ins, "type mismatch on copy");
9964 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
9965 struct triple *sdecl;
9967 sdecl = MISC(right, 0);
9968 offset = right->u.cval;
9969 mkaddr_const(state, ins, sdecl, offset);
9971 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
9976 left = read_const(state, ins, right);
9977 /* Ensure I have not overflowed the destination. */
9978 if (size_of(state, right->type) > size_of(state, ins->type)) {
9981 mask <<= size_of(state, ins->type);
9985 /* Ensure I am properly sign extended */
9986 if (size_of(state, right->type) < size_of(state, ins->type) &&
9987 is_signed(right->type)) {
9990 shift = SIZEOF_LONG - size_of(state, right->type);
9996 mkconst(state, ins, left);
10000 internal_error(state, ins, "uknown constant");
10006 static int phi_present(struct block *block)
10008 struct triple *ptr;
10012 ptr = block->first;
10014 if (ptr->op == OP_PHI) {
10018 } while(ptr != block->last);
10022 static int phi_dependency(struct block *block)
10024 /* A block has a phi dependency if a phi function
10025 * depends on that block to exist, and makes a block
10026 * that is otherwise useless unsafe to remove.
10029 struct block_set *edge;
10030 for(edge = block->edges; edge; edge = edge->next) {
10031 if (phi_present(edge->member)) {
10039 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10041 struct triple *targ;
10042 targ = TARG(ins, 0);
10043 /* During scc_transform temporary triples are allocated that
10044 * loop back onto themselves. If I see one don't advance the
10047 while(triple_is_structural(state, targ) &&
10048 (targ->next != targ) && (targ->next != state->first)) {
10055 static void simplify_branch(struct compile_state *state, struct triple *ins)
10057 int simplified, loops;
10058 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10059 internal_error(state, ins, "not branch");
10061 if (ins->use != 0) {
10062 internal_error(state, ins, "branch use");
10064 /* The challenge here with simplify branch is that I need to
10065 * make modifications to the control flow graph as well
10066 * as to the branch instruction itself. That is handled
10067 * by rebuilding the basic blocks after simplify all is called.
10070 /* If we have a branch to an unconditional branch update
10071 * our target. But watch out for dependencies from phi
10073 * Also only do this a limited number of times so
10074 * we don't get into an infinite loop.
10078 struct triple *targ;
10080 targ = branch_target(state, ins);
10081 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10082 !phi_dependency(targ->u.block))
10084 unuse_triple(TARG(ins, 0), ins);
10085 TARG(ins, 0) = TARG(targ, 0);
10086 use_triple(TARG(ins, 0), ins);
10089 } while(simplified && (++loops < 20));
10091 /* If we have a conditional branch with a constant condition
10092 * make it an unconditional branch.
10094 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10095 struct triple *targ;
10097 value = read_const(state, ins, RHS(ins, 0));
10098 unuse_triple(RHS(ins, 0), ins);
10099 targ = TARG(ins, 0);
10102 ins->op = OP_BRANCH;
10104 unuse_triple(ins->next, ins);
10105 TARG(ins, 0) = targ;
10108 unuse_triple(targ, ins);
10109 TARG(ins, 0) = ins->next;
10113 /* If we have a branch to the next instruction,
10116 if (TARG(ins, 0) == ins->next) {
10117 unuse_triple(TARG(ins, 0), ins);
10118 if (ins->op == OP_CBRANCH) {
10119 unuse_triple(RHS(ins, 0), ins);
10120 unuse_triple(ins->next, ins);
10128 internal_error(state, ins, "noop use != 0");
10133 static void simplify_label(struct compile_state *state, struct triple *ins)
10135 /* Ignore volatile labels */
10136 if (!triple_is_pure(state, ins, ins->id)) {
10139 if (ins->use == 0) {
10142 else if (ins->prev->op == OP_LABEL) {
10143 /* In general it is not safe to merge one label that
10144 * imediately follows another. The problem is that the empty
10145 * looking block may have phi functions that depend on it.
10147 if (!phi_dependency(ins->prev->u.block)) {
10148 struct triple_set *user, *next;
10150 for(user = ins->use; user; user = next) {
10151 struct triple *use, **expr;
10153 use = user->member;
10154 expr = triple_targ(state, use, 0);
10155 for(;expr; expr = triple_targ(state, use, expr)) {
10156 if (*expr == ins) {
10158 unuse_triple(ins, use);
10159 use_triple(ins->prev, use);
10165 internal_error(state, ins, "noop use != 0");
10171 static void simplify_phi(struct compile_state *state, struct triple *ins)
10173 struct triple **slot;
10174 struct triple *value;
10177 slot = &RHS(ins, 0);
10182 /* See if all of the rhs members of a phi have the same value */
10183 if (slot[0] && is_simple_const(slot[0])) {
10184 cvalue = read_const(state, ins, slot[0]);
10185 for(i = 1; i < zrhs; i++) {
10187 !is_simple_const(slot[i]) ||
10188 !equiv_types(slot[0]->type, slot[i]->type) ||
10189 (cvalue != read_const(state, ins, slot[i]))) {
10194 mkconst(state, ins, cvalue);
10199 /* See if all of rhs members of a phi are the same */
10201 for(i = 1; i < zrhs; i++) {
10202 if (slot[i] != value) {
10207 /* If the phi has a single value just copy it */
10208 if (!is_subset_type(ins->type, value->type)) {
10209 internal_error(state, ins, "bad input type to phi");
10211 /* Make the types match */
10212 if (!equiv_types(ins->type, value->type)) {
10213 ins->type = value->type;
10215 /* Now make the actual copy */
10216 mkcopy(state, ins, value);
10222 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10224 if (is_simple_const(RHS(ins, 0))) {
10226 left = read_const(state, ins, RHS(ins, 0));
10227 mkconst(state, ins, bsf(left));
10231 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10233 if (is_simple_const(RHS(ins, 0))) {
10235 left = read_const(state, ins, RHS(ins, 0));
10236 mkconst(state, ins, bsr(left));
10241 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10242 static const struct simplify_table {
10244 unsigned long flag;
10245 } table_simplify[] = {
10246 #define simplify_sdivt simplify_noop
10247 #define simplify_udivt simplify_noop
10248 #define simplify_piece simplify_noop
10250 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10251 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10252 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10253 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10254 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10255 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10256 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10257 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10258 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10259 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10260 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10261 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10262 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10263 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10264 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10265 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10266 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10267 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10268 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10270 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10271 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10272 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10273 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10274 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10275 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10276 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10277 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10278 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10279 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10280 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10281 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10283 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10284 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10286 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10287 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10288 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10290 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10292 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10293 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10294 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10295 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10297 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10298 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10299 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10300 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10301 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10302 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10304 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10305 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10307 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10308 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10309 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10310 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10311 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10312 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10313 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10314 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10315 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10317 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10318 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10319 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10320 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10321 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10322 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10323 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10324 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10325 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10326 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10327 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10330 static inline void debug_simplify(struct compile_state *state,
10331 simplify_t do_simplify, struct triple *ins)
10333 #if DEBUG_SIMPLIFY_HIRES
10334 if (state->functions_joined && (do_simplify != simplify_noop)) {
10335 /* High resolution debugging mode */
10336 fprintf(state->dbgout, "simplifing: ");
10337 display_triple(state->dbgout, ins);
10340 do_simplify(state, ins);
10341 #if DEBUG_SIMPLIFY_HIRES
10342 if (state->functions_joined && (do_simplify != simplify_noop)) {
10343 /* High resolution debugging mode */
10344 fprintf(state->dbgout, "simplified: ");
10345 display_triple(state->dbgout, ins);
10349 static void simplify(struct compile_state *state, struct triple *ins)
10352 simplify_t do_simplify;
10353 if (ins == &unknown_triple) {
10354 internal_error(state, ins, "simplifying the unknown triple?");
10359 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10363 do_simplify = table_simplify[op].func;
10366 !(state->compiler->flags & table_simplify[op].flag)) {
10367 do_simplify = simplify_noop;
10369 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10370 do_simplify = simplify_noop;
10373 if (!do_simplify) {
10374 internal_error(state, ins, "cannot simplify op: %d %s",
10378 debug_simplify(state, do_simplify, ins);
10379 } while(ins->op != op);
10382 static void rebuild_ssa_form(struct compile_state *state);
10384 static void simplify_all(struct compile_state *state)
10386 struct triple *ins, *first;
10387 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10390 first = state->first;
10393 simplify(state, ins);
10395 } while(ins != first->prev);
10398 simplify(state, ins);
10400 }while(ins != first);
10401 rebuild_ssa_form(state);
10403 print_blocks(state, __func__, state->dbgout);
10408 * ============================
10411 static void register_builtin_function(struct compile_state *state,
10412 const char *name, int op, struct type *rtype, ...)
10414 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10415 struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10416 struct hash_entry *ident;
10417 struct file_state file;
10423 /* Dummy file state to get debug handling right */
10424 memset(&file, 0, sizeof(file));
10425 file.basename = "<built-in>";
10427 file.report_line = 1;
10428 file.report_name = file.basename;
10429 file.prev = state->file;
10430 state->file = &file;
10431 state->function = name;
10433 /* Find the Parameter count */
10434 valid_op(state, op);
10435 parameters = table_ops[op].rhs;
10436 if (parameters < 0 ) {
10437 internal_error(state, 0, "Invalid builtin parameter count");
10440 /* Find the function type */
10441 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10442 ftype->elements = parameters;
10443 next = &ftype->right;
10444 va_start(args, rtype);
10445 for(i = 0; i < parameters; i++) {
10446 atype = va_arg(args, struct type *);
10450 *next = new_type(TYPE_PRODUCT, *next, atype);
10451 next = &((*next)->right);
10455 *next = &void_type;
10459 /* Get the initial closure type */
10460 ctype = new_type(TYPE_JOIN, &void_type, 0);
10461 ctype->elements = 1;
10463 /* Get the return type */
10464 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10465 crtype->elements = 2;
10467 /* Generate the needed triples */
10468 def = triple(state, OP_LIST, ftype, 0, 0);
10469 first = label(state);
10470 RHS(def, 0) = first;
10471 result = flatten(state, first, variable(state, crtype));
10472 retvar = flatten(state, first, variable(state, &void_ptr_type));
10473 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10475 /* Now string them together */
10476 param = ftype->right;
10477 for(i = 0; i < parameters; i++) {
10478 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10479 atype = param->left;
10483 arg = flatten(state, first, variable(state, atype));
10484 param = param->right;
10486 work = new_triple(state, op, rtype, -1, parameters);
10487 generate_lhs_pieces(state, work);
10488 for(i = 0; i < parameters; i++) {
10489 RHS(work, i) = read_expr(state, farg(state, def, i));
10491 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10492 work = write_expr(state, deref_index(state, result, 1), work);
10494 work = flatten(state, first, work);
10495 last = flatten(state, first, label(state));
10496 ret = flatten(state, first, ret);
10497 name_len = strlen(name);
10498 ident = lookup(state, name, name_len);
10499 ftype->type_ident = ident;
10500 symbol(state, ident, &ident->sym_ident, def, ftype);
10502 state->file = file.prev;
10503 state->function = 0;
10504 state->main_function = 0;
10506 if (!state->functions) {
10507 state->functions = def;
10509 insert_triple(state, state->functions, def);
10511 if (state->compiler->debug & DEBUG_INLINE) {
10512 FILE *fp = state->dbgout;
10515 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10516 display_func(state, fp, def);
10517 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10521 static struct type *partial_struct(struct compile_state *state,
10522 const char *field_name, struct type *type, struct type *rest)
10524 struct hash_entry *field_ident;
10525 struct type *result;
10526 int field_name_len;
10528 field_name_len = strlen(field_name);
10529 field_ident = lookup(state, field_name, field_name_len);
10531 result = clone_type(0, type);
10532 result->field_ident = field_ident;
10535 result = new_type(TYPE_PRODUCT, result, rest);
10540 static struct type *register_builtin_type(struct compile_state *state,
10541 const char *name, struct type *type)
10543 struct hash_entry *ident;
10546 name_len = strlen(name);
10547 ident = lookup(state, name, name_len);
10549 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10550 ulong_t elements = 0;
10551 struct type *field;
10552 type = new_type(TYPE_STRUCT, type, 0);
10553 field = type->left;
10554 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10556 field = field->right;
10559 symbol(state, ident, &ident->sym_tag, 0, type);
10560 type->type_ident = ident;
10561 type->elements = elements;
10563 symbol(state, ident, &ident->sym_ident, 0, type);
10564 ident->tok = TOK_TYPE_NAME;
10569 static void register_builtins(struct compile_state *state)
10571 struct type *div_type, *ldiv_type;
10572 struct type *udiv_type, *uldiv_type;
10573 struct type *msr_type;
10575 div_type = register_builtin_type(state, "__builtin_div_t",
10576 partial_struct(state, "quot", &int_type,
10577 partial_struct(state, "rem", &int_type, 0)));
10578 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10579 partial_struct(state, "quot", &long_type,
10580 partial_struct(state, "rem", &long_type, 0)));
10581 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10582 partial_struct(state, "quot", &uint_type,
10583 partial_struct(state, "rem", &uint_type, 0)));
10584 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10585 partial_struct(state, "quot", &ulong_type,
10586 partial_struct(state, "rem", &ulong_type, 0)));
10588 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10589 &int_type, &int_type);
10590 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10591 &long_type, &long_type);
10592 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10593 &uint_type, &uint_type);
10594 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10595 &ulong_type, &ulong_type);
10597 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10599 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10601 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10604 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10605 &uchar_type, &ushort_type);
10606 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10607 &ushort_type, &ushort_type);
10608 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10609 &uint_type, &ushort_type);
10611 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10613 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10616 msr_type = register_builtin_type(state, "__builtin_msr_t",
10617 partial_struct(state, "lo", &ulong_type,
10618 partial_struct(state, "hi", &ulong_type, 0)));
10620 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10622 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10623 &ulong_type, &ulong_type, &ulong_type);
10625 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10629 static struct type *declarator(
10630 struct compile_state *state, struct type *type,
10631 struct hash_entry **ident, int need_ident);
10632 static void decl(struct compile_state *state, struct triple *first);
10633 static struct type *specifier_qualifier_list(struct compile_state *state);
10634 static int isdecl_specifier(int tok);
10635 static struct type *decl_specifiers(struct compile_state *state);
10636 static int istype(int tok);
10637 static struct triple *expr(struct compile_state *state);
10638 static struct triple *assignment_expr(struct compile_state *state);
10639 static struct type *type_name(struct compile_state *state);
10640 static void statement(struct compile_state *state, struct triple *first);
10642 static struct triple *call_expr(
10643 struct compile_state *state, struct triple *func)
10645 struct triple *def;
10646 struct type *param, *type;
10647 ulong_t pvals, index;
10649 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10650 error(state, 0, "Called object is not a function");
10652 if (func->op != OP_LIST) {
10653 internal_error(state, 0, "improper function");
10655 eat(state, TOK_LPAREN);
10656 /* Find the return type without any specifiers */
10657 type = clone_type(0, func->type->left);
10658 /* Count the number of rhs entries for OP_FCALL */
10659 param = func->type->right;
10661 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10663 param = param->right;
10665 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10668 def = new_triple(state, OP_FCALL, type, -1, pvals);
10669 MISC(def, 0) = func;
10671 param = func->type->right;
10672 for(index = 0; index < pvals; index++) {
10673 struct triple *val;
10674 struct type *arg_type;
10675 val = read_expr(state, assignment_expr(state));
10677 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10678 arg_type = param->left;
10680 write_compatible(state, arg_type, val->type);
10681 RHS(def, index) = val;
10682 if (index != (pvals - 1)) {
10683 eat(state, TOK_COMMA);
10684 param = param->right;
10687 eat(state, TOK_RPAREN);
10692 static struct triple *character_constant(struct compile_state *state)
10694 struct triple *def;
10696 const signed char *str, *end;
10699 tk = eat(state, TOK_LIT_CHAR);
10700 str = tk->val.str + 1;
10701 str_len = tk->str_len - 2;
10702 if (str_len <= 0) {
10703 error(state, 0, "empty character constant");
10705 end = str + str_len;
10706 c = char_value(state, &str, end);
10708 error(state, 0, "multibyte character constant not supported");
10710 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10714 static struct triple *string_constant(struct compile_state *state)
10716 struct triple *def;
10719 const signed char *str, *end;
10720 signed char *buf, *ptr;
10724 type = new_type(TYPE_ARRAY, &char_type, 0);
10725 type->elements = 0;
10726 /* The while loop handles string concatenation */
10728 tk = eat(state, TOK_LIT_STRING);
10729 str = tk->val.str + 1;
10730 str_len = tk->str_len - 2;
10732 error(state, 0, "negative string constant length");
10734 end = str + str_len;
10736 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10737 memcpy(buf, ptr, type->elements);
10738 ptr = buf + type->elements;
10740 *ptr++ = char_value(state, &str, end);
10741 } while(str < end);
10742 type->elements = ptr - buf;
10743 } while(peek(state) == TOK_LIT_STRING);
10745 type->elements += 1;
10746 def = triple(state, OP_BLOBCONST, type, 0, 0);
10753 static struct triple *integer_constant(struct compile_state *state)
10755 struct triple *def;
10762 tk = eat(state, TOK_LIT_INT);
10764 decimal = (tk->val.str[0] != '0');
10765 val = strtoul(tk->val.str, &end, 0);
10766 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10767 error(state, 0, "Integer constant to large");
10770 if ((*end == 'u') || (*end == 'U')) {
10774 if ((*end == 'l') || (*end == 'L')) {
10778 if ((*end == 'u') || (*end == 'U')) {
10783 error(state, 0, "Junk at end of integer constant");
10786 type = &ulong_type;
10790 if (!decimal && (val > LONG_T_MAX)) {
10791 type = &ulong_type;
10796 if (val > UINT_T_MAX) {
10797 type = &ulong_type;
10802 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10805 else if (!decimal && (val > LONG_T_MAX)) {
10806 type = &ulong_type;
10808 else if (val > INT_T_MAX) {
10812 def = int_const(state, type, val);
10816 static struct triple *primary_expr(struct compile_state *state)
10818 struct triple *def;
10824 struct hash_entry *ident;
10825 /* Here ident is either:
10829 ident = eat(state, TOK_IDENT)->ident;
10830 if (!ident->sym_ident) {
10831 error(state, 0, "%s undeclared", ident->name);
10833 def = ident->sym_ident->def;
10836 case TOK_ENUM_CONST:
10838 struct hash_entry *ident;
10839 /* Here ident is an enumeration constant */
10840 ident = eat(state, TOK_ENUM_CONST)->ident;
10841 if (!ident->sym_ident) {
10842 error(state, 0, "%s undeclared", ident->name);
10844 def = ident->sym_ident->def;
10849 struct hash_entry *ident;
10850 ident = eat(state, TOK_MIDENT)->ident;
10851 warning(state, 0, "Replacing undefined macro: %s with 0",
10853 def = int_const(state, &int_type, 0);
10857 eat(state, TOK_LPAREN);
10859 eat(state, TOK_RPAREN);
10862 def = integer_constant(state);
10864 case TOK_LIT_FLOAT:
10865 eat(state, TOK_LIT_FLOAT);
10866 error(state, 0, "Floating point constants not supported");
10871 def = character_constant(state);
10873 case TOK_LIT_STRING:
10874 def = string_constant(state);
10878 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10883 static struct triple *postfix_expr(struct compile_state *state)
10885 struct triple *def;
10887 def = primary_expr(state);
10889 struct triple *left;
10893 switch((tok = peek(state))) {
10895 eat(state, TOK_LBRACKET);
10896 def = mk_subscript_expr(state, left, expr(state));
10897 eat(state, TOK_RBRACKET);
10900 def = call_expr(state, def);
10904 struct hash_entry *field;
10905 eat(state, TOK_DOT);
10906 field = eat(state, TOK_IDENT)->ident;
10907 def = deref_field(state, def, field);
10912 struct hash_entry *field;
10913 eat(state, TOK_ARROW);
10914 field = eat(state, TOK_IDENT)->ident;
10915 def = mk_deref_expr(state, read_expr(state, def));
10916 def = deref_field(state, def, field);
10920 eat(state, TOK_PLUSPLUS);
10921 def = mk_post_inc_expr(state, left);
10923 case TOK_MINUSMINUS:
10924 eat(state, TOK_MINUSMINUS);
10925 def = mk_post_dec_expr(state, left);
10935 static struct triple *cast_expr(struct compile_state *state);
10937 static struct triple *unary_expr(struct compile_state *state)
10939 struct triple *def, *right;
10941 switch((tok = peek(state))) {
10943 eat(state, TOK_PLUSPLUS);
10944 def = mk_pre_inc_expr(state, unary_expr(state));
10946 case TOK_MINUSMINUS:
10947 eat(state, TOK_MINUSMINUS);
10948 def = mk_pre_dec_expr(state, unary_expr(state));
10951 eat(state, TOK_AND);
10952 def = mk_addr_expr(state, cast_expr(state), 0);
10955 eat(state, TOK_STAR);
10956 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
10959 eat(state, TOK_PLUS);
10960 right = read_expr(state, cast_expr(state));
10961 arithmetic(state, right);
10962 def = integral_promotion(state, right);
10965 eat(state, TOK_MINUS);
10966 right = read_expr(state, cast_expr(state));
10967 arithmetic(state, right);
10968 def = integral_promotion(state, right);
10969 def = triple(state, OP_NEG, def->type, def, 0);
10972 eat(state, TOK_TILDE);
10973 right = read_expr(state, cast_expr(state));
10974 integral(state, right);
10975 def = integral_promotion(state, right);
10976 def = triple(state, OP_INVERT, def->type, def, 0);
10979 eat(state, TOK_BANG);
10980 right = read_expr(state, cast_expr(state));
10981 bool(state, right);
10982 def = lfalse_expr(state, right);
10988 eat(state, TOK_SIZEOF);
10989 tok1 = peek(state);
10990 tok2 = peek2(state);
10991 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
10992 eat(state, TOK_LPAREN);
10993 type = type_name(state);
10994 eat(state, TOK_RPAREN);
10997 struct triple *expr;
10998 expr = unary_expr(state);
11000 release_expr(state, expr);
11002 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11009 eat(state, TOK_ALIGNOF);
11010 tok1 = peek(state);
11011 tok2 = peek2(state);
11012 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11013 eat(state, TOK_LPAREN);
11014 type = type_name(state);
11015 eat(state, TOK_RPAREN);
11018 struct triple *expr;
11019 expr = unary_expr(state);
11021 release_expr(state, expr);
11023 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11028 /* We only come here if we are called from the preprocessor */
11029 struct hash_entry *ident;
11031 eat(state, TOK_MDEFINED);
11033 if (pp_peek(state) == TOK_LPAREN) {
11034 pp_eat(state, TOK_LPAREN);
11037 ident = pp_eat(state, TOK_MIDENT)->ident;
11039 eat(state, TOK_RPAREN);
11041 def = int_const(state, &int_type, ident->sym_define != 0);
11045 def = postfix_expr(state);
11051 static struct triple *cast_expr(struct compile_state *state)
11053 struct triple *def;
11055 tok1 = peek(state);
11056 tok2 = peek2(state);
11057 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11059 eat(state, TOK_LPAREN);
11060 type = type_name(state);
11061 eat(state, TOK_RPAREN);
11062 def = mk_cast_expr(state, type, cast_expr(state));
11065 def = unary_expr(state);
11070 static struct triple *mult_expr(struct compile_state *state)
11072 struct triple *def;
11074 def = cast_expr(state);
11076 struct triple *left, *right;
11077 struct type *result_type;
11085 left = read_expr(state, def);
11086 arithmetic(state, left);
11090 right = read_expr(state, cast_expr(state));
11091 arithmetic(state, right);
11093 result_type = arithmetic_result(state, left, right);
11094 sign = is_signed(result_type);
11097 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11098 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11099 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11101 def = triple(state, op, result_type, left, right);
11111 static struct triple *add_expr(struct compile_state *state)
11113 struct triple *def;
11115 def = mult_expr(state);
11118 switch( peek(state)) {
11120 eat(state, TOK_PLUS);
11121 def = mk_add_expr(state, def, mult_expr(state));
11124 eat(state, TOK_MINUS);
11125 def = mk_sub_expr(state, def, mult_expr(state));
11135 static struct triple *shift_expr(struct compile_state *state)
11137 struct triple *def;
11139 def = add_expr(state);
11141 struct triple *left, *right;
11144 switch((tok = peek(state))) {
11147 left = read_expr(state, def);
11148 integral(state, left);
11149 left = integral_promotion(state, left);
11153 right = read_expr(state, add_expr(state));
11154 integral(state, right);
11155 right = integral_promotion(state, right);
11157 op = (tok == TOK_SL)? OP_SL :
11158 is_signed(left->type)? OP_SSR: OP_USR;
11160 def = triple(state, op, left->type, left, right);
11170 static struct triple *relational_expr(struct compile_state *state)
11172 #warning "Extend relational exprs to work on more than arithmetic types"
11173 struct triple *def;
11175 def = shift_expr(state);
11177 struct triple *left, *right;
11178 struct type *arg_type;
11181 switch((tok = peek(state))) {
11186 left = read_expr(state, def);
11187 arithmetic(state, left);
11191 right = read_expr(state, shift_expr(state));
11192 arithmetic(state, right);
11194 arg_type = arithmetic_result(state, left, right);
11195 sign = is_signed(arg_type);
11198 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11199 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11200 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11201 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11203 def = triple(state, op, &int_type, left, right);
11213 static struct triple *equality_expr(struct compile_state *state)
11215 #warning "Extend equality exprs to work on more than arithmetic types"
11216 struct triple *def;
11218 def = relational_expr(state);
11220 struct triple *left, *right;
11223 switch((tok = peek(state))) {
11226 left = read_expr(state, def);
11227 arithmetic(state, left);
11229 right = read_expr(state, relational_expr(state));
11230 arithmetic(state, right);
11231 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11232 def = triple(state, op, &int_type, left, right);
11242 static struct triple *and_expr(struct compile_state *state)
11244 struct triple *def;
11245 def = equality_expr(state);
11246 while(peek(state) == TOK_AND) {
11247 struct triple *left, *right;
11248 struct type *result_type;
11249 left = read_expr(state, def);
11250 integral(state, left);
11251 eat(state, TOK_AND);
11252 right = read_expr(state, equality_expr(state));
11253 integral(state, right);
11254 result_type = arithmetic_result(state, left, right);
11255 def = triple(state, OP_AND, result_type, left, right);
11260 static struct triple *xor_expr(struct compile_state *state)
11262 struct triple *def;
11263 def = and_expr(state);
11264 while(peek(state) == TOK_XOR) {
11265 struct triple *left, *right;
11266 struct type *result_type;
11267 left = read_expr(state, def);
11268 integral(state, left);
11269 eat(state, TOK_XOR);
11270 right = read_expr(state, and_expr(state));
11271 integral(state, right);
11272 result_type = arithmetic_result(state, left, right);
11273 def = triple(state, OP_XOR, result_type, left, right);
11278 static struct triple *or_expr(struct compile_state *state)
11280 struct triple *def;
11281 def = xor_expr(state);
11282 while(peek(state) == TOK_OR) {
11283 struct triple *left, *right;
11284 struct type *result_type;
11285 left = read_expr(state, def);
11286 integral(state, left);
11287 eat(state, TOK_OR);
11288 right = read_expr(state, xor_expr(state));
11289 integral(state, right);
11290 result_type = arithmetic_result(state, left, right);
11291 def = triple(state, OP_OR, result_type, left, right);
11296 static struct triple *land_expr(struct compile_state *state)
11298 struct triple *def;
11299 def = or_expr(state);
11300 while(peek(state) == TOK_LOGAND) {
11301 struct triple *left, *right;
11302 left = read_expr(state, def);
11304 eat(state, TOK_LOGAND);
11305 right = read_expr(state, or_expr(state));
11306 bool(state, right);
11308 def = mkland_expr(state,
11309 ltrue_expr(state, left),
11310 ltrue_expr(state, right));
11315 static struct triple *lor_expr(struct compile_state *state)
11317 struct triple *def;
11318 def = land_expr(state);
11319 while(peek(state) == TOK_LOGOR) {
11320 struct triple *left, *right;
11321 left = read_expr(state, def);
11323 eat(state, TOK_LOGOR);
11324 right = read_expr(state, land_expr(state));
11325 bool(state, right);
11327 def = mklor_expr(state,
11328 ltrue_expr(state, left),
11329 ltrue_expr(state, right));
11334 static struct triple *conditional_expr(struct compile_state *state)
11336 struct triple *def;
11337 def = lor_expr(state);
11338 if (peek(state) == TOK_QUEST) {
11339 struct triple *test, *left, *right;
11341 test = ltrue_expr(state, read_expr(state, def));
11342 eat(state, TOK_QUEST);
11343 left = read_expr(state, expr(state));
11344 eat(state, TOK_COLON);
11345 right = read_expr(state, conditional_expr(state));
11347 def = mkcond_expr(state, test, left, right);
11353 struct triple *val;
11357 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11358 struct triple *dest, struct triple *val)
11360 if (cv[dest->id].val) {
11361 free_triple(state, cv[dest->id].val);
11363 cv[dest->id].val = val;
11365 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11366 struct triple *src)
11368 return cv[src->id].val;
11371 static struct triple *eval_const_expr(
11372 struct compile_state *state, struct triple *expr)
11374 struct triple *def;
11375 if (is_const(expr)) {
11379 /* If we don't start out as a constant simplify into one */
11380 struct triple *head, *ptr;
11381 struct cv_triple *cv;
11383 head = label(state); /* dummy initial triple */
11384 flatten(state, head, expr);
11386 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11389 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11391 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11393 cv[i].id = ptr->id;
11399 valid_ins(state, ptr);
11400 if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11401 internal_error(state, ptr,
11402 "unexpected %s in constant expression",
11405 else if (ptr->op == OP_LIST) {
11407 else if (triple_is_structural(state, ptr)) {
11410 else if (triple_is_ubranch(state, ptr)) {
11411 ptr = TARG(ptr, 0);
11413 else if (triple_is_cbranch(state, ptr)) {
11414 struct triple *cond_val;
11415 cond_val = get_cv(state, cv, RHS(ptr, 0));
11416 if (!cond_val || !is_const(cond_val) ||
11417 (cond_val->op != OP_INTCONST))
11419 internal_error(state, ptr, "bad branch condition");
11421 if (cond_val->u.cval == 0) {
11424 ptr = TARG(ptr, 0);
11427 else if (triple_is_branch(state, ptr)) {
11428 error(state, ptr, "bad branch type in constant expression");
11430 else if (ptr->op == OP_WRITE) {
11431 struct triple *val;
11432 val = get_cv(state, cv, RHS(ptr, 0));
11434 set_cv(state, cv, MISC(ptr, 0),
11435 copy_triple(state, val));
11436 set_cv(state, cv, ptr,
11437 copy_triple(state, val));
11440 else if (ptr->op == OP_READ) {
11441 set_cv(state, cv, ptr,
11443 get_cv(state, cv, RHS(ptr, 0))));
11446 else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11447 struct triple *val, **rhs;
11448 val = copy_triple(state, ptr);
11449 rhs = triple_rhs(state, val, 0);
11450 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11452 internal_error(state, ptr, "Missing rhs");
11454 *rhs = get_cv(state, cv, *rhs);
11456 simplify(state, val);
11457 set_cv(state, cv, ptr, val);
11461 error(state, ptr, "impure operation in constant expression");
11464 } while(ptr != head);
11466 /* Get the result value */
11467 def = get_cv(state, cv, head->prev);
11468 cv[head->prev->id].val = 0;
11470 /* Free the temporary values */
11471 for(i = 0; i < count; i++) {
11473 free_triple(state, cv[i].val);
11478 /* Free the intermediate expressions */
11479 while(head->next != head) {
11480 release_triple(state, head->next);
11482 free_triple(state, head);
11484 if (!is_const(def)) {
11485 error(state, expr, "Not a constant expression");
11490 static struct triple *constant_expr(struct compile_state *state)
11492 return eval_const_expr(state, conditional_expr(state));
11495 static struct triple *assignment_expr(struct compile_state *state)
11497 struct triple *def, *left, *right;
11499 /* The C grammer in K&R shows assignment expressions
11500 * only taking unary expressions as input on their
11501 * left hand side. But specifies the precedence of
11502 * assignemnt as the lowest operator except for comma.
11504 * Allowing conditional expressions on the left hand side
11505 * of an assignement results in a grammar that accepts
11506 * a larger set of statements than standard C. As long
11507 * as the subset of the grammar that is standard C behaves
11508 * correctly this should cause no problems.
11510 * For the extra token strings accepted by the grammar
11511 * none of them should produce a valid lvalue, so they
11512 * should not produce functioning programs.
11514 * GCC has this bug as well, so surprises should be minimal.
11516 def = conditional_expr(state);
11518 switch((tok = peek(state))) {
11520 lvalue(state, left);
11521 eat(state, TOK_EQ);
11522 def = write_expr(state, left,
11523 read_expr(state, assignment_expr(state)));
11528 lvalue(state, left);
11529 arithmetic(state, left);
11531 right = read_expr(state, assignment_expr(state));
11532 arithmetic(state, right);
11534 sign = is_signed(left->type);
11537 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11538 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11539 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11541 def = write_expr(state, left,
11542 triple(state, op, left->type,
11543 read_expr(state, left), right));
11546 lvalue(state, left);
11547 eat(state, TOK_PLUSEQ);
11548 def = write_expr(state, left,
11549 mk_add_expr(state, left, assignment_expr(state)));
11552 lvalue(state, left);
11553 eat(state, TOK_MINUSEQ);
11554 def = write_expr(state, left,
11555 mk_sub_expr(state, left, assignment_expr(state)));
11562 lvalue(state, left);
11563 integral(state, left);
11565 right = read_expr(state, assignment_expr(state));
11566 integral(state, right);
11567 right = integral_promotion(state, right);
11568 sign = is_signed(left->type);
11571 case TOK_SLEQ: op = OP_SL; break;
11572 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11573 case TOK_ANDEQ: op = OP_AND; break;
11574 case TOK_XOREQ: op = OP_XOR; break;
11575 case TOK_OREQ: op = OP_OR; break;
11577 def = write_expr(state, left,
11578 triple(state, op, left->type,
11579 read_expr(state, left), right));
11585 static struct triple *expr(struct compile_state *state)
11587 struct triple *def;
11588 def = assignment_expr(state);
11589 while(peek(state) == TOK_COMMA) {
11590 eat(state, TOK_COMMA);
11591 def = mkprog(state, def, assignment_expr(state), 0);
11596 static void expr_statement(struct compile_state *state, struct triple *first)
11598 if (peek(state) != TOK_SEMI) {
11599 /* lvalue conversions always apply except when certian operators
11600 * are applied. I apply the lvalue conversions here
11601 * as I know no more operators will be applied.
11603 flatten(state, first, lvalue_conversion(state, expr(state)));
11605 eat(state, TOK_SEMI);
11608 static void if_statement(struct compile_state *state, struct triple *first)
11610 struct triple *test, *jmp1, *jmp2, *middle, *end;
11612 jmp1 = jmp2 = middle = 0;
11613 eat(state, TOK_IF);
11614 eat(state, TOK_LPAREN);
11615 test = expr(state);
11617 /* Cleanup and invert the test */
11618 test = lfalse_expr(state, read_expr(state, test));
11619 eat(state, TOK_RPAREN);
11620 /* Generate the needed pieces */
11621 middle = label(state);
11622 jmp1 = branch(state, middle, test);
11623 /* Thread the pieces together */
11624 flatten(state, first, test);
11625 flatten(state, first, jmp1);
11626 flatten(state, first, label(state));
11627 statement(state, first);
11628 if (peek(state) == TOK_ELSE) {
11629 eat(state, TOK_ELSE);
11630 /* Generate the rest of the pieces */
11631 end = label(state);
11632 jmp2 = branch(state, end, 0);
11633 /* Thread them together */
11634 flatten(state, first, jmp2);
11635 flatten(state, first, middle);
11636 statement(state, first);
11637 flatten(state, first, end);
11640 flatten(state, first, middle);
11644 static void for_statement(struct compile_state *state, struct triple *first)
11646 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11647 struct triple *label1, *label2, *label3;
11648 struct hash_entry *ident;
11650 eat(state, TOK_FOR);
11651 eat(state, TOK_LPAREN);
11652 head = test = tail = jmp1 = jmp2 = 0;
11653 if (peek(state) != TOK_SEMI) {
11654 head = expr(state);
11656 eat(state, TOK_SEMI);
11657 if (peek(state) != TOK_SEMI) {
11658 test = expr(state);
11660 test = ltrue_expr(state, read_expr(state, test));
11662 eat(state, TOK_SEMI);
11663 if (peek(state) != TOK_RPAREN) {
11664 tail = expr(state);
11666 eat(state, TOK_RPAREN);
11667 /* Generate the needed pieces */
11668 label1 = label(state);
11669 label2 = label(state);
11670 label3 = label(state);
11672 jmp1 = branch(state, label3, 0);
11673 jmp2 = branch(state, label1, test);
11676 jmp2 = branch(state, label1, 0);
11678 end = label(state);
11679 /* Remember where break and continue go */
11680 start_scope(state);
11681 ident = state->i_break;
11682 symbol(state, ident, &ident->sym_ident, end, end->type);
11683 ident = state->i_continue;
11684 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11685 /* Now include the body */
11686 flatten(state, first, head);
11687 flatten(state, first, jmp1);
11688 flatten(state, first, label1);
11689 statement(state, first);
11690 flatten(state, first, label2);
11691 flatten(state, first, tail);
11692 flatten(state, first, label3);
11693 flatten(state, first, test);
11694 flatten(state, first, jmp2);
11695 flatten(state, first, end);
11696 /* Cleanup the break/continue scope */
11700 static void while_statement(struct compile_state *state, struct triple *first)
11702 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11703 struct hash_entry *ident;
11704 eat(state, TOK_WHILE);
11705 eat(state, TOK_LPAREN);
11706 test = expr(state);
11708 test = ltrue_expr(state, read_expr(state, test));
11709 eat(state, TOK_RPAREN);
11710 /* Generate the needed pieces */
11711 label1 = label(state);
11712 label2 = label(state);
11713 jmp1 = branch(state, label2, 0);
11714 jmp2 = branch(state, label1, test);
11715 end = label(state);
11716 /* Remember where break and continue go */
11717 start_scope(state);
11718 ident = state->i_break;
11719 symbol(state, ident, &ident->sym_ident, end, end->type);
11720 ident = state->i_continue;
11721 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11722 /* Thread them together */
11723 flatten(state, first, jmp1);
11724 flatten(state, first, label1);
11725 statement(state, first);
11726 flatten(state, first, label2);
11727 flatten(state, first, test);
11728 flatten(state, first, jmp2);
11729 flatten(state, first, end);
11730 /* Cleanup the break/continue scope */
11734 static void do_statement(struct compile_state *state, struct triple *first)
11736 struct triple *label1, *label2, *test, *end;
11737 struct hash_entry *ident;
11738 eat(state, TOK_DO);
11739 /* Generate the needed pieces */
11740 label1 = label(state);
11741 label2 = label(state);
11742 end = label(state);
11743 /* Remember where break and continue go */
11744 start_scope(state);
11745 ident = state->i_break;
11746 symbol(state, ident, &ident->sym_ident, end, end->type);
11747 ident = state->i_continue;
11748 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11749 /* Now include the body */
11750 flatten(state, first, label1);
11751 statement(state, first);
11752 /* Cleanup the break/continue scope */
11754 /* Eat the rest of the loop */
11755 eat(state, TOK_WHILE);
11756 eat(state, TOK_LPAREN);
11757 test = read_expr(state, expr(state));
11759 eat(state, TOK_RPAREN);
11760 eat(state, TOK_SEMI);
11761 /* Thread the pieces together */
11762 test = ltrue_expr(state, test);
11763 flatten(state, first, label2);
11764 flatten(state, first, test);
11765 flatten(state, first, branch(state, label1, test));
11766 flatten(state, first, end);
11770 static void return_statement(struct compile_state *state, struct triple *first)
11772 struct triple *jmp, *mv, *dest, *var, *val;
11774 eat(state, TOK_RETURN);
11776 #warning "FIXME implement a more general excess branch elimination"
11778 /* If we have a return value do some more work */
11779 if (peek(state) != TOK_SEMI) {
11780 val = read_expr(state, expr(state));
11782 eat(state, TOK_SEMI);
11784 /* See if this last statement in a function */
11785 last = ((peek(state) == TOK_RBRACE) &&
11786 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11788 /* Find the return variable */
11789 var = fresult(state, state->main_function);
11791 /* Find the return destination */
11792 dest = state->i_return->sym_ident->def;
11794 /* If needed generate a jump instruction */
11796 jmp = branch(state, dest, 0);
11798 /* If needed generate an assignment instruction */
11800 mv = write_expr(state, deref_index(state, var, 1), val);
11802 /* Now put the code together */
11804 flatten(state, first, mv);
11805 flatten(state, first, jmp);
11808 flatten(state, first, jmp);
11812 static void break_statement(struct compile_state *state, struct triple *first)
11814 struct triple *dest;
11815 eat(state, TOK_BREAK);
11816 eat(state, TOK_SEMI);
11817 if (!state->i_break->sym_ident) {
11818 error(state, 0, "break statement not within loop or switch");
11820 dest = state->i_break->sym_ident->def;
11821 flatten(state, first, branch(state, dest, 0));
11824 static void continue_statement(struct compile_state *state, struct triple *first)
11826 struct triple *dest;
11827 eat(state, TOK_CONTINUE);
11828 eat(state, TOK_SEMI);
11829 if (!state->i_continue->sym_ident) {
11830 error(state, 0, "continue statement outside of a loop");
11832 dest = state->i_continue->sym_ident->def;
11833 flatten(state, first, branch(state, dest, 0));
11836 static void goto_statement(struct compile_state *state, struct triple *first)
11838 struct hash_entry *ident;
11839 eat(state, TOK_GOTO);
11840 ident = eat(state, TOK_IDENT)->ident;
11841 if (!ident->sym_label) {
11842 /* If this is a forward branch allocate the label now,
11843 * it will be flattend in the appropriate location later.
11845 struct triple *ins;
11846 ins = label(state);
11847 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11849 eat(state, TOK_SEMI);
11851 flatten(state, first, branch(state, ident->sym_label->def, 0));
11854 static void labeled_statement(struct compile_state *state, struct triple *first)
11856 struct triple *ins;
11857 struct hash_entry *ident;
11859 ident = eat(state, TOK_IDENT)->ident;
11860 if (ident->sym_label && ident->sym_label->def) {
11861 ins = ident->sym_label->def;
11862 put_occurance(ins->occurance);
11863 ins->occurance = new_occurance(state);
11866 ins = label(state);
11867 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11869 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11870 error(state, 0, "label %s already defined", ident->name);
11872 flatten(state, first, ins);
11874 eat(state, TOK_COLON);
11875 statement(state, first);
11878 static void switch_statement(struct compile_state *state, struct triple *first)
11880 struct triple *value, *top, *end, *dbranch;
11881 struct hash_entry *ident;
11883 /* See if we have a valid switch statement */
11884 eat(state, TOK_SWITCH);
11885 eat(state, TOK_LPAREN);
11886 value = expr(state);
11887 integral(state, value);
11888 value = read_expr(state, value);
11889 eat(state, TOK_RPAREN);
11890 /* Generate the needed pieces */
11891 top = label(state);
11892 end = label(state);
11893 dbranch = branch(state, end, 0);
11894 /* Remember where case branches and break goes */
11895 start_scope(state);
11896 ident = state->i_switch;
11897 symbol(state, ident, &ident->sym_ident, value, value->type);
11898 ident = state->i_case;
11899 symbol(state, ident, &ident->sym_ident, top, top->type);
11900 ident = state->i_break;
11901 symbol(state, ident, &ident->sym_ident, end, end->type);
11902 ident = state->i_default;
11903 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11904 /* Thread them together */
11905 flatten(state, first, value);
11906 flatten(state, first, top);
11907 flatten(state, first, dbranch);
11908 statement(state, first);
11909 flatten(state, first, end);
11910 /* Cleanup the switch scope */
11914 static void case_statement(struct compile_state *state, struct triple *first)
11916 struct triple *cvalue, *dest, *test, *jmp;
11917 struct triple *ptr, *value, *top, *dbranch;
11919 /* See if w have a valid case statement */
11920 eat(state, TOK_CASE);
11921 cvalue = constant_expr(state);
11922 integral(state, cvalue);
11923 if (cvalue->op != OP_INTCONST) {
11924 error(state, 0, "integer constant expected");
11926 eat(state, TOK_COLON);
11927 if (!state->i_case->sym_ident) {
11928 error(state, 0, "case statement not within a switch");
11931 /* Lookup the interesting pieces */
11932 top = state->i_case->sym_ident->def;
11933 value = state->i_switch->sym_ident->def;
11934 dbranch = state->i_default->sym_ident->def;
11936 /* See if this case label has already been used */
11937 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11938 if (ptr->op != OP_EQ) {
11941 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11942 error(state, 0, "duplicate case %d statement",
11946 /* Generate the needed pieces */
11947 dest = label(state);
11948 test = triple(state, OP_EQ, &int_type, value, cvalue);
11949 jmp = branch(state, dest, test);
11950 /* Thread the pieces together */
11951 flatten(state, dbranch, test);
11952 flatten(state, dbranch, jmp);
11953 flatten(state, dbranch, label(state));
11954 flatten(state, first, dest);
11955 statement(state, first);
11958 static void default_statement(struct compile_state *state, struct triple *first)
11960 struct triple *dest;
11961 struct triple *dbranch, *end;
11963 /* See if we have a valid default statement */
11964 eat(state, TOK_DEFAULT);
11965 eat(state, TOK_COLON);
11967 if (!state->i_case->sym_ident) {
11968 error(state, 0, "default statement not within a switch");
11971 /* Lookup the interesting pieces */
11972 dbranch = state->i_default->sym_ident->def;
11973 end = state->i_break->sym_ident->def;
11975 /* See if a default statement has already happened */
11976 if (TARG(dbranch, 0) != end) {
11977 error(state, 0, "duplicate default statement");
11980 /* Generate the needed pieces */
11981 dest = label(state);
11983 /* Blame the branch on the default statement */
11984 put_occurance(dbranch->occurance);
11985 dbranch->occurance = new_occurance(state);
11987 /* Thread the pieces together */
11988 TARG(dbranch, 0) = dest;
11989 use_triple(dest, dbranch);
11990 flatten(state, first, dest);
11991 statement(state, first);
11994 static void asm_statement(struct compile_state *state, struct triple *first)
11996 struct asm_info *info;
11998 struct triple *constraint;
11999 struct triple *expr;
12000 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12001 struct triple *def, *asm_str;
12002 int out, in, clobbers, more, colons, i;
12006 eat(state, TOK_ASM);
12007 /* For now ignore the qualifiers */
12008 switch(peek(state)) {
12010 eat(state, TOK_CONST);
12013 eat(state, TOK_VOLATILE);
12014 flags |= TRIPLE_FLAG_VOLATILE;
12017 eat(state, TOK_LPAREN);
12018 asm_str = string_constant(state);
12021 out = in = clobbers = 0;
12023 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12024 eat(state, TOK_COLON);
12026 more = (peek(state) == TOK_LIT_STRING);
12028 struct triple *var;
12029 struct triple *constraint;
12032 if (out > MAX_LHS) {
12033 error(state, 0, "Maximum output count exceeded.");
12035 constraint = string_constant(state);
12036 str = constraint->u.blob;
12037 if (str[0] != '=') {
12038 error(state, 0, "Output constraint does not start with =");
12040 constraint->u.blob = str + 1;
12041 eat(state, TOK_LPAREN);
12042 var = conditional_expr(state);
12043 eat(state, TOK_RPAREN);
12045 lvalue(state, var);
12046 out_param[out].constraint = constraint;
12047 out_param[out].expr = var;
12048 if (peek(state) == TOK_COMMA) {
12049 eat(state, TOK_COMMA);
12056 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12057 eat(state, TOK_COLON);
12059 more = (peek(state) == TOK_LIT_STRING);
12061 struct triple *val;
12062 struct triple *constraint;
12065 if (in > MAX_RHS) {
12066 error(state, 0, "Maximum input count exceeded.");
12068 constraint = string_constant(state);
12069 str = constraint->u.blob;
12070 if (digitp(str[0] && str[1] == '\0')) {
12072 val = digval(str[0]);
12073 if ((val < 0) || (val >= out)) {
12074 error(state, 0, "Invalid input constraint %d", val);
12077 eat(state, TOK_LPAREN);
12078 val = conditional_expr(state);
12079 eat(state, TOK_RPAREN);
12081 in_param[in].constraint = constraint;
12082 in_param[in].expr = val;
12083 if (peek(state) == TOK_COMMA) {
12084 eat(state, TOK_COMMA);
12092 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12093 eat(state, TOK_COLON);
12095 more = (peek(state) == TOK_LIT_STRING);
12097 struct triple *clobber;
12099 if ((clobbers + out) > MAX_LHS) {
12100 error(state, 0, "Maximum clobber limit exceeded.");
12102 clobber = string_constant(state);
12104 clob_param[clobbers].constraint = clobber;
12105 if (peek(state) == TOK_COMMA) {
12106 eat(state, TOK_COMMA);
12112 eat(state, TOK_RPAREN);
12113 eat(state, TOK_SEMI);
12116 info = xcmalloc(sizeof(*info), "asm_info");
12117 info->str = asm_str->u.blob;
12118 free_triple(state, asm_str);
12120 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12121 def->u.ainfo = info;
12124 /* Find the register constraints */
12125 for(i = 0; i < out; i++) {
12126 struct triple *constraint;
12127 constraint = out_param[i].constraint;
12128 info->tmpl.lhs[i] = arch_reg_constraint(state,
12129 out_param[i].expr->type, constraint->u.blob);
12130 free_triple(state, constraint);
12132 for(; i - out < clobbers; i++) {
12133 struct triple *constraint;
12134 constraint = clob_param[i - out].constraint;
12135 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12136 free_triple(state, constraint);
12138 for(i = 0; i < in; i++) {
12139 struct triple *constraint;
12141 constraint = in_param[i].constraint;
12142 str = constraint->u.blob;
12143 if (digitp(str[0]) && str[1] == '\0') {
12144 struct reg_info cinfo;
12146 val = digval(str[0]);
12147 cinfo.reg = info->tmpl.lhs[val].reg;
12148 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12149 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12150 if (cinfo.reg == REG_UNSET) {
12151 cinfo.reg = REG_VIRT0 + val;
12153 if (cinfo.regcm == 0) {
12154 error(state, 0, "No registers for %d", val);
12156 info->tmpl.lhs[val] = cinfo;
12157 info->tmpl.rhs[i] = cinfo;
12160 info->tmpl.rhs[i] = arch_reg_constraint(state,
12161 in_param[i].expr->type, str);
12163 free_triple(state, constraint);
12166 /* Now build the helper expressions */
12167 for(i = 0; i < in; i++) {
12168 RHS(def, i) = read_expr(state, in_param[i].expr);
12170 flatten(state, first, def);
12171 for(i = 0; i < (out + clobbers); i++) {
12173 struct triple *piece;
12175 type = out_param[i].expr->type;
12177 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12178 if (size >= SIZEOF_LONG) {
12179 type = &ulong_type;
12181 else if (size >= SIZEOF_INT) {
12184 else if (size >= SIZEOF_SHORT) {
12185 type = &ushort_type;
12188 type = &uchar_type;
12191 piece = triple(state, OP_PIECE, type, def, 0);
12193 LHS(def, i) = piece;
12194 flatten(state, first, piece);
12196 /* And write the helpers to their destinations */
12197 for(i = 0; i < out; i++) {
12198 struct triple *piece;
12199 piece = LHS(def, i);
12200 flatten(state, first,
12201 write_expr(state, out_param[i].expr, piece));
12206 static int isdecl(int tok)
12229 case TOK_TYPE_NAME: /* typedef name */
12236 static void compound_statement(struct compile_state *state, struct triple *first)
12238 eat(state, TOK_LBRACE);
12239 start_scope(state);
12241 /* statement-list opt */
12242 while (peek(state) != TOK_RBRACE) {
12243 statement(state, first);
12246 eat(state, TOK_RBRACE);
12249 static void statement(struct compile_state *state, struct triple *first)
12253 if (tok == TOK_LBRACE) {
12254 compound_statement(state, first);
12256 else if (tok == TOK_IF) {
12257 if_statement(state, first);
12259 else if (tok == TOK_FOR) {
12260 for_statement(state, first);
12262 else if (tok == TOK_WHILE) {
12263 while_statement(state, first);
12265 else if (tok == TOK_DO) {
12266 do_statement(state, first);
12268 else if (tok == TOK_RETURN) {
12269 return_statement(state, first);
12271 else if (tok == TOK_BREAK) {
12272 break_statement(state, first);
12274 else if (tok == TOK_CONTINUE) {
12275 continue_statement(state, first);
12277 else if (tok == TOK_GOTO) {
12278 goto_statement(state, first);
12280 else if (tok == TOK_SWITCH) {
12281 switch_statement(state, first);
12283 else if (tok == TOK_ASM) {
12284 asm_statement(state, first);
12286 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12287 labeled_statement(state, first);
12289 else if (tok == TOK_CASE) {
12290 case_statement(state, first);
12292 else if (tok == TOK_DEFAULT) {
12293 default_statement(state, first);
12295 else if (isdecl(tok)) {
12296 /* This handles C99 intermixing of statements and decls */
12297 decl(state, first);
12300 expr_statement(state, first);
12304 static struct type *param_decl(struct compile_state *state)
12307 struct hash_entry *ident;
12308 /* Cheat so the declarator will know we are not global */
12309 start_scope(state);
12311 type = decl_specifiers(state);
12312 type = declarator(state, type, &ident, 0);
12313 type->field_ident = ident;
12318 static struct type *param_type_list(struct compile_state *state, struct type *type)
12320 struct type *ftype, **next;
12321 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12322 next = &ftype->right;
12323 ftype->elements = 1;
12324 while(peek(state) == TOK_COMMA) {
12325 eat(state, TOK_COMMA);
12326 if (peek(state) == TOK_DOTS) {
12327 eat(state, TOK_DOTS);
12328 error(state, 0, "variadic functions not supported");
12331 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12332 next = &((*next)->right);
12339 static struct type *type_name(struct compile_state *state)
12342 type = specifier_qualifier_list(state);
12343 /* abstract-declarator (may consume no tokens) */
12344 type = declarator(state, type, 0, 0);
12348 static struct type *direct_declarator(
12349 struct compile_state *state, struct type *type,
12350 struct hash_entry **pident, int need_ident)
12352 struct hash_entry *ident;
12353 struct type *outer;
12356 arrays_complete(state, type);
12357 switch(peek(state)) {
12359 ident = eat(state, TOK_IDENT)->ident;
12361 error(state, 0, "Unexpected identifier found");
12363 /* The name of what we are declaring */
12367 eat(state, TOK_LPAREN);
12368 outer = declarator(state, type, pident, need_ident);
12369 eat(state, TOK_RPAREN);
12373 error(state, 0, "Identifier expected");
12379 arrays_complete(state, type);
12380 switch(peek(state)) {
12382 eat(state, TOK_LPAREN);
12383 type = param_type_list(state, type);
12384 eat(state, TOK_RPAREN);
12388 unsigned int qualifiers;
12389 struct triple *value;
12391 eat(state, TOK_LBRACKET);
12392 if (peek(state) != TOK_RBRACKET) {
12393 value = constant_expr(state);
12394 integral(state, value);
12396 eat(state, TOK_RBRACKET);
12398 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12399 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12401 type->elements = value->u.cval;
12402 free_triple(state, value);
12404 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12415 struct type *inner;
12416 arrays_complete(state, type);
12418 for(inner = outer; inner->left; inner = inner->left)
12420 inner->left = type;
12426 static struct type *declarator(
12427 struct compile_state *state, struct type *type,
12428 struct hash_entry **pident, int need_ident)
12430 while(peek(state) == TOK_STAR) {
12431 eat(state, TOK_STAR);
12432 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12434 type = direct_declarator(state, type, pident, need_ident);
12438 static struct type *typedef_name(
12439 struct compile_state *state, unsigned int specifiers)
12441 struct hash_entry *ident;
12443 ident = eat(state, TOK_TYPE_NAME)->ident;
12444 type = ident->sym_ident->type;
12445 specifiers |= type->type & QUAL_MASK;
12446 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12447 (type->type & (STOR_MASK | QUAL_MASK))) {
12448 type = clone_type(specifiers, type);
12453 static struct type *enum_specifier(
12454 struct compile_state *state, unsigned int spec)
12456 struct hash_entry *ident;
12459 struct type *enum_type;
12462 eat(state, TOK_ENUM);
12464 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12465 ident = eat(state, tok)->ident;
12468 if (!ident || (peek(state) == TOK_LBRACE)) {
12469 struct type **next;
12470 eat(state, TOK_LBRACE);
12471 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12472 enum_type->type_ident = ident;
12473 next = &enum_type->right;
12475 struct hash_entry *eident;
12476 struct triple *value;
12477 struct type *entry;
12478 eident = eat(state, TOK_IDENT)->ident;
12479 if (eident->sym_ident) {
12480 error(state, 0, "%s already declared",
12483 eident->tok = TOK_ENUM_CONST;
12484 if (peek(state) == TOK_EQ) {
12485 struct triple *val;
12486 eat(state, TOK_EQ);
12487 val = constant_expr(state);
12488 integral(state, val);
12489 base = val->u.cval;
12491 value = int_const(state, &int_type, base);
12492 symbol(state, eident, &eident->sym_ident, value, &int_type);
12493 entry = new_type(TYPE_LIST, 0, 0);
12494 entry->field_ident = eident;
12496 next = &entry->right;
12498 if (peek(state) == TOK_COMMA) {
12499 eat(state, TOK_COMMA);
12501 } while(peek(state) != TOK_RBRACE);
12502 eat(state, TOK_RBRACE);
12504 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12507 if (ident && ident->sym_tag &&
12508 ident->sym_tag->type &&
12509 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12510 enum_type = clone_type(spec, ident->sym_tag->type);
12512 else if (ident && !enum_type) {
12513 error(state, 0, "enum %s undeclared", ident->name);
12518 static struct type *struct_declarator(
12519 struct compile_state *state, struct type *type, struct hash_entry **ident)
12521 if (peek(state) != TOK_COLON) {
12522 type = declarator(state, type, ident, 1);
12524 if (peek(state) == TOK_COLON) {
12525 struct triple *value;
12526 eat(state, TOK_COLON);
12527 value = constant_expr(state);
12528 if (value->op != OP_INTCONST) {
12529 error(state, 0, "Invalid constant expression");
12531 if (value->u.cval > size_of(state, type)) {
12532 error(state, 0, "bitfield larger than base type");
12534 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12535 error(state, 0, "bitfield base not an integer type");
12537 type = new_type(TYPE_BITFIELD, type, 0);
12538 type->elements = value->u.cval;
12543 static struct type *struct_or_union_specifier(
12544 struct compile_state *state, unsigned int spec)
12546 struct type *struct_type;
12547 struct hash_entry *ident;
12548 unsigned int type_main;
12549 unsigned int type_join;
12553 switch(peek(state)) {
12555 eat(state, TOK_STRUCT);
12556 type_main = TYPE_STRUCT;
12557 type_join = TYPE_PRODUCT;
12560 eat(state, TOK_UNION);
12561 type_main = TYPE_UNION;
12562 type_join = TYPE_OVERLAP;
12565 eat(state, TOK_STRUCT);
12566 type_main = TYPE_STRUCT;
12567 type_join = TYPE_PRODUCT;
12571 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12572 ident = eat(state, tok)->ident;
12574 if (!ident || (peek(state) == TOK_LBRACE)) {
12576 struct type **next;
12578 eat(state, TOK_LBRACE);
12579 next = &struct_type;
12581 struct type *base_type;
12583 base_type = specifier_qualifier_list(state);
12586 struct hash_entry *fident;
12588 type = struct_declarator(state, base_type, &fident);
12590 if (peek(state) == TOK_COMMA) {
12592 eat(state, TOK_COMMA);
12594 type = clone_type(0, type);
12595 type->field_ident = fident;
12597 *next = new_type(type_join, *next, type);
12598 next = &((*next)->right);
12603 eat(state, TOK_SEMI);
12604 } while(peek(state) != TOK_RBRACE);
12605 eat(state, TOK_RBRACE);
12606 struct_type = new_type(type_main | spec, struct_type, 0);
12607 struct_type->type_ident = ident;
12608 struct_type->elements = elements;
12610 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12613 if (ident && ident->sym_tag &&
12614 ident->sym_tag->type &&
12615 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12616 struct_type = clone_type(spec, ident->sym_tag->type);
12618 else if (ident && !struct_type) {
12619 error(state, 0, "%s %s undeclared",
12620 (type_main == TYPE_STRUCT)?"struct" : "union",
12623 return struct_type;
12626 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12628 unsigned int specifiers;
12629 switch(peek(state)) {
12631 eat(state, TOK_AUTO);
12632 specifiers = STOR_AUTO;
12635 eat(state, TOK_REGISTER);
12636 specifiers = STOR_REGISTER;
12639 eat(state, TOK_STATIC);
12640 specifiers = STOR_STATIC;
12643 eat(state, TOK_EXTERN);
12644 specifiers = STOR_EXTERN;
12647 eat(state, TOK_TYPEDEF);
12648 specifiers = STOR_TYPEDEF;
12651 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12652 specifiers = STOR_LOCAL;
12655 specifiers = STOR_AUTO;
12661 static unsigned int function_specifier_opt(struct compile_state *state)
12663 /* Ignore the inline keyword */
12664 unsigned int specifiers;
12666 switch(peek(state)) {
12668 eat(state, TOK_INLINE);
12669 specifiers = STOR_INLINE;
12674 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12676 int tok = peek(state);
12680 /* The empty attribute ignore it */
12683 case TOK_ENUM_CONST:
12684 case TOK_TYPE_NAME:
12686 struct hash_entry *ident;
12687 ident = eat(state, TOK_IDENT)->ident;
12689 if (ident == state->i_noinline) {
12690 if (attributes & ATTRIB_ALWAYS_INLINE) {
12691 error(state, 0, "both always_inline and noinline attribtes");
12693 attributes |= ATTRIB_NOINLINE;
12695 else if (ident == state->i_always_inline) {
12696 if (attributes & ATTRIB_NOINLINE) {
12697 error(state, 0, "both noinline and always_inline attribtes");
12699 attributes |= ATTRIB_ALWAYS_INLINE;
12702 error(state, 0, "Unknown attribute:%s", ident->name);
12707 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12713 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12715 type = attrib(state, type);
12716 while(peek(state) == TOK_COMMA) {
12717 eat(state, TOK_COMMA);
12718 type = attrib(state, type);
12723 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12725 if (peek(state) == TOK_ATTRIBUTE) {
12726 eat(state, TOK_ATTRIBUTE);
12727 eat(state, TOK_LPAREN);
12728 eat(state, TOK_LPAREN);
12729 type = attribute_list(state, type);
12730 eat(state, TOK_RPAREN);
12731 eat(state, TOK_RPAREN);
12736 static unsigned int type_qualifiers(struct compile_state *state)
12738 unsigned int specifiers;
12741 specifiers = QUAL_NONE;
12743 switch(peek(state)) {
12745 eat(state, TOK_CONST);
12746 specifiers |= QUAL_CONST;
12749 eat(state, TOK_VOLATILE);
12750 specifiers |= QUAL_VOLATILE;
12753 eat(state, TOK_RESTRICT);
12754 specifiers |= QUAL_RESTRICT;
12764 static struct type *type_specifier(
12765 struct compile_state *state, unsigned int spec)
12770 switch((tok = peek(state))) {
12772 eat(state, TOK_VOID);
12773 type = new_type(TYPE_VOID | spec, 0, 0);
12776 eat(state, TOK_CHAR);
12777 type = new_type(TYPE_CHAR | spec, 0, 0);
12780 eat(state, TOK_SHORT);
12781 if (peek(state) == TOK_INT) {
12782 eat(state, TOK_INT);
12784 type = new_type(TYPE_SHORT | spec, 0, 0);
12787 eat(state, TOK_INT);
12788 type = new_type(TYPE_INT | spec, 0, 0);
12791 eat(state, TOK_LONG);
12792 switch(peek(state)) {
12794 eat(state, TOK_LONG);
12795 error(state, 0, "long long not supported");
12798 eat(state, TOK_DOUBLE);
12799 error(state, 0, "long double not supported");
12802 eat(state, TOK_INT);
12803 type = new_type(TYPE_LONG | spec, 0, 0);
12806 type = new_type(TYPE_LONG | spec, 0, 0);
12811 eat(state, TOK_FLOAT);
12812 error(state, 0, "type float not supported");
12815 eat(state, TOK_DOUBLE);
12816 error(state, 0, "type double not supported");
12819 eat(state, TOK_SIGNED);
12820 switch(peek(state)) {
12822 eat(state, TOK_LONG);
12823 switch(peek(state)) {
12825 eat(state, TOK_LONG);
12826 error(state, 0, "type long long not supported");
12829 eat(state, TOK_INT);
12830 type = new_type(TYPE_LONG | spec, 0, 0);
12833 type = new_type(TYPE_LONG | spec, 0, 0);
12838 eat(state, TOK_INT);
12839 type = new_type(TYPE_INT | spec, 0, 0);
12842 eat(state, TOK_SHORT);
12843 type = new_type(TYPE_SHORT | spec, 0, 0);
12846 eat(state, TOK_CHAR);
12847 type = new_type(TYPE_CHAR | spec, 0, 0);
12850 type = new_type(TYPE_INT | spec, 0, 0);
12855 eat(state, TOK_UNSIGNED);
12856 switch(peek(state)) {
12858 eat(state, TOK_LONG);
12859 switch(peek(state)) {
12861 eat(state, TOK_LONG);
12862 error(state, 0, "unsigned long long not supported");
12865 eat(state, TOK_INT);
12866 type = new_type(TYPE_ULONG | spec, 0, 0);
12869 type = new_type(TYPE_ULONG | spec, 0, 0);
12874 eat(state, TOK_INT);
12875 type = new_type(TYPE_UINT | spec, 0, 0);
12878 eat(state, TOK_SHORT);
12879 type = new_type(TYPE_USHORT | spec, 0, 0);
12882 eat(state, TOK_CHAR);
12883 type = new_type(TYPE_UCHAR | spec, 0, 0);
12886 type = new_type(TYPE_UINT | spec, 0, 0);
12890 /* struct or union specifier */
12893 type = struct_or_union_specifier(state, spec);
12895 /* enum-spefifier */
12897 type = enum_specifier(state, spec);
12900 case TOK_TYPE_NAME:
12901 type = typedef_name(state, spec);
12904 error(state, 0, "bad type specifier %s",
12911 static int istype(int tok)
12929 case TOK_TYPE_NAME:
12937 static struct type *specifier_qualifier_list(struct compile_state *state)
12940 unsigned int specifiers = 0;
12942 /* type qualifiers */
12943 specifiers |= type_qualifiers(state);
12945 /* type specifier */
12946 type = type_specifier(state, specifiers);
12951 static int isdecl_specifier(int tok)
12954 /* storage class specifier */
12960 /* type qualifier */
12964 /* type specifiers */
12974 /* struct or union specifier */
12977 /* enum-spefifier */
12980 case TOK_TYPE_NAME:
12981 /* function specifiers */
12989 static struct type *decl_specifiers(struct compile_state *state)
12992 unsigned int specifiers;
12993 /* I am overly restrictive in the arragement of specifiers supported.
12994 * C is overly flexible in this department it makes interpreting
12995 * the parse tree difficult.
12999 /* storage class specifier */
13000 specifiers |= storage_class_specifier_opt(state);
13002 /* function-specifier */
13003 specifiers |= function_specifier_opt(state);
13006 specifiers |= attributes_opt(state, 0);
13008 /* type qualifier */
13009 specifiers |= type_qualifiers(state);
13011 /* type specifier */
13012 type = type_specifier(state, specifiers);
13016 struct field_info {
13021 static struct field_info designator(struct compile_state *state, struct type *type)
13024 struct field_info info;
13028 switch(peek(state)) {
13031 struct triple *value;
13032 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13033 error(state, 0, "Array designator not in array initializer");
13035 eat(state, TOK_LBRACKET);
13036 value = constant_expr(state);
13037 eat(state, TOK_RBRACKET);
13039 info.type = type->left;
13040 info.offset = value->u.cval * size_of(state, info.type);
13045 struct hash_entry *field;
13046 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13047 ((type->type & TYPE_MASK) != TYPE_UNION))
13049 error(state, 0, "Struct designator not in struct initializer");
13051 eat(state, TOK_DOT);
13052 field = eat(state, TOK_IDENT)->ident;
13053 info.offset = field_offset(state, type, field);
13054 info.type = field_type(state, type, field);
13058 error(state, 0, "Invalid designator");
13061 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13062 eat(state, TOK_EQ);
13066 static struct triple *initializer(
13067 struct compile_state *state, struct type *type)
13069 struct triple *result;
13070 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13071 if (peek(state) != TOK_LBRACE) {
13072 result = assignment_expr(state);
13073 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13074 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13075 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13076 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13077 (equiv_types(type->left, result->type->left))) {
13078 type->elements = result->type->elements;
13080 if (is_lvalue(state, result) &&
13081 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13082 (type->type & TYPE_MASK) != TYPE_ARRAY)
13084 result = lvalue_conversion(state, result);
13086 if (!is_init_compatible(state, type, result->type)) {
13087 error(state, 0, "Incompatible types in initializer");
13089 if (!equiv_types(type, result->type)) {
13090 result = mk_cast_expr(state, type, result);
13096 struct field_info info;
13098 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13099 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13100 internal_error(state, 0, "unknown initializer type");
13103 info.type = type->left;
13104 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13105 info.type = next_field(state, type, 0);
13107 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13110 max_offset = size_of(state, type);
13112 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13113 eat(state, TOK_LBRACE);
13115 struct triple *value;
13116 struct type *value_type;
13122 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13123 info = designator(state, type);
13125 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13126 (info.offset >= max_offset)) {
13127 error(state, 0, "element beyond bounds");
13129 value_type = info.type;
13130 value = eval_const_expr(state, initializer(state, value_type));
13131 value_size = size_of(state, value_type);
13132 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13133 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13134 (max_offset <= info.offset)) {
13138 old_size = max_offset;
13139 max_offset = info.offset + value_size;
13140 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13141 memcpy(buf, old_buf, bits_to_bytes(old_size));
13144 dest = ((char *)buf) + bits_to_bytes(info.offset);
13145 #if DEBUG_INITIALIZER
13146 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13148 bits_to_bytes(max_offset),
13149 bits_to_bytes(value_size),
13152 if (value->op == OP_BLOBCONST) {
13153 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13155 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13156 #if DEBUG_INITIALIZER
13157 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13159 *((uint8_t *)dest) = value->u.cval & 0xff;
13161 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13162 *((uint16_t *)dest) = value->u.cval & 0xffff;
13164 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13165 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13168 internal_error(state, 0, "unhandled constant initializer");
13170 free_triple(state, value);
13171 if (peek(state) == TOK_COMMA) {
13172 eat(state, TOK_COMMA);
13175 info.offset += value_size;
13176 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13177 info.type = next_field(state, type, info.type);
13178 info.offset = field_offset(state, type,
13179 info.type->field_ident);
13181 } while(comma && (peek(state) != TOK_RBRACE));
13182 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13183 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13184 type->elements = max_offset / size_of(state, type->left);
13186 eat(state, TOK_RBRACE);
13187 result = triple(state, OP_BLOBCONST, type, 0, 0);
13188 result->u.blob = buf;
13193 static void resolve_branches(struct compile_state *state, struct triple *first)
13195 /* Make a second pass and finish anything outstanding
13196 * with respect to branches. The only outstanding item
13197 * is to see if there are goto to labels that have not
13198 * been defined and to error about them.
13201 struct triple *ins;
13202 /* Also error on branches that do not use their targets */
13205 if (!triple_is_ret(state, ins)) {
13206 struct triple **expr ;
13207 struct triple_set *set;
13208 expr = triple_targ(state, ins, 0);
13209 for(; expr; expr = triple_targ(state, ins, expr)) {
13210 struct triple *targ;
13212 for(set = targ?targ->use:0; set; set = set->next) {
13213 if (set->member == ins) {
13218 internal_error(state, ins, "targ not used");
13223 } while(ins != first);
13224 /* See if there are goto to labels that have not been defined */
13225 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13226 struct hash_entry *entry;
13227 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13228 struct triple *ins;
13229 if (!entry->sym_label) {
13232 ins = entry->sym_label->def;
13233 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13234 error(state, ins, "label `%s' used but not defined",
13241 static struct triple *function_definition(
13242 struct compile_state *state, struct type *type)
13244 struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13245 struct triple *fname;
13246 struct type *fname_type;
13247 struct hash_entry *ident;
13248 struct type *param, *crtype, *ctype;
13250 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13251 error(state, 0, "Invalid function header");
13254 /* Verify the function type */
13255 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13256 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13257 (type->right->field_ident == 0)) {
13258 error(state, 0, "Invalid function parameters");
13260 param = type->right;
13262 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13264 if (!param->left->field_ident) {
13265 error(state, 0, "No identifier for parameter %d\n", i);
13267 param = param->right;
13270 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13271 error(state, 0, "No identifier for paramter %d\n", i);
13274 /* Get a list of statements for this function. */
13275 def = triple(state, OP_LIST, type, 0, 0);
13277 /* Start a new scope for the passed parameters */
13278 start_scope(state);
13280 /* Put a label at the very start of a function */
13281 first = label(state);
13282 RHS(def, 0) = first;
13284 /* Put a label at the very end of a function */
13285 end = label(state);
13286 flatten(state, first, end);
13287 /* Remember where return goes */
13288 ident = state->i_return;
13289 symbol(state, ident, &ident->sym_ident, end, end->type);
13291 /* Get the initial closure type */
13292 ctype = new_type(TYPE_JOIN, &void_type, 0);
13293 ctype->elements = 1;
13295 /* Add a variable for the return value */
13296 crtype = new_type(TYPE_TUPLE,
13297 /* Remove all type qualifiers from the return type */
13298 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13299 crtype->elements = 2;
13300 result = flatten(state, end, variable(state, crtype));
13302 /* Allocate a variable for the return address */
13303 retvar = flatten(state, end, variable(state, &void_ptr_type));
13305 /* Add in the return instruction */
13306 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13307 ret = flatten(state, first, ret);
13309 /* Walk through the parameters and create symbol table entries
13312 param = type->right;
13313 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13314 ident = param->left->field_ident;
13315 tmp = variable(state, param->left);
13316 var_symbol(state, ident, tmp);
13317 flatten(state, end, tmp);
13318 param = param->right;
13320 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13321 /* And don't forget the last parameter */
13322 ident = param->field_ident;
13323 tmp = variable(state, param);
13324 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13325 flatten(state, end, tmp);
13328 /* Add the declaration static const char __func__ [] = "func-name" */
13329 fname_type = new_type(TYPE_ARRAY,
13330 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13331 fname_type->type |= QUAL_CONST | STOR_STATIC;
13332 fname_type->elements = strlen(state->function) + 1;
13334 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13335 fname->u.blob = (void *)state->function;
13336 fname = flatten(state, end, fname);
13338 ident = state->i___func__;
13339 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13341 /* Remember which function I am compiling.
13342 * Also assume the last defined function is the main function.
13344 state->main_function = def;
13346 /* Now get the actual function definition */
13347 compound_statement(state, end);
13349 /* Finish anything unfinished with branches */
13350 resolve_branches(state, first);
13352 /* Remove the parameter scope */
13356 /* Remember I have defined a function */
13357 if (!state->functions) {
13358 state->functions = def;
13360 insert_triple(state, state->functions, def);
13362 if (state->compiler->debug & DEBUG_INLINE) {
13363 FILE *fp = state->dbgout;
13366 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13367 display_func(state, fp, def);
13368 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13374 static struct triple *do_decl(struct compile_state *state,
13375 struct type *type, struct hash_entry *ident)
13377 struct triple *def;
13379 /* Clean up the storage types used */
13380 switch (type->type & STOR_MASK) {
13383 /* These are the good types I am aiming for */
13385 case STOR_REGISTER:
13386 type->type &= ~STOR_MASK;
13387 type->type |= STOR_AUTO;
13391 type->type &= ~STOR_MASK;
13392 type->type |= STOR_STATIC;
13396 error(state, 0, "typedef without name");
13398 symbol(state, ident, &ident->sym_ident, 0, type);
13399 ident->tok = TOK_TYPE_NAME;
13403 internal_error(state, 0, "Undefined storage class");
13405 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13406 error(state, 0, "Function prototypes not supported");
13409 ((type->type & STOR_MASK) == STOR_STATIC) &&
13410 ((type->type & QUAL_CONST) == 0)) {
13411 error(state, 0, "non const static variables not supported");
13414 def = variable(state, type);
13415 var_symbol(state, ident, def);
13420 static void decl(struct compile_state *state, struct triple *first)
13422 struct type *base_type, *type;
13423 struct hash_entry *ident;
13424 struct triple *def;
13426 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13427 base_type = decl_specifiers(state);
13429 type = declarator(state, base_type, &ident, 0);
13430 type->type = attributes_opt(state, type->type);
13431 if (global && ident && (peek(state) == TOK_LBRACE)) {
13433 type->type_ident = ident;
13434 state->function = ident->name;
13435 def = function_definition(state, type);
13436 symbol(state, ident, &ident->sym_ident, def, type);
13437 state->function = 0;
13441 flatten(state, first, do_decl(state, type, ident));
13442 /* type or variable definition */
13445 if (peek(state) == TOK_EQ) {
13447 error(state, 0, "cannot assign to a type");
13449 eat(state, TOK_EQ);
13450 flatten(state, first,
13452 ident->sym_ident->def,
13453 initializer(state, type)));
13455 arrays_complete(state, type);
13456 if (peek(state) == TOK_COMMA) {
13457 eat(state, TOK_COMMA);
13459 type = declarator(state, base_type, &ident, 0);
13460 flatten(state, first, do_decl(state, type, ident));
13464 eat(state, TOK_SEMI);
13468 static void decls(struct compile_state *state)
13470 struct triple *list;
13472 list = label(state);
13475 if (tok == TOK_EOF) {
13478 if (tok == TOK_SPACE) {
13479 eat(state, TOK_SPACE);
13482 if (list->next != list) {
13483 error(state, 0, "global variables not supported");
13489 * Function inlining
13491 struct triple_reg_set {
13492 struct triple_reg_set *next;
13493 struct triple *member;
13494 struct triple *new;
13497 struct block *block;
13498 struct triple_reg_set *in;
13499 struct triple_reg_set *out;
13502 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13503 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13504 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13505 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13506 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13507 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13509 static void print_block(
13510 struct compile_state *state, struct block *block, void *arg);
13511 static int do_triple_set(struct triple_reg_set **head,
13512 struct triple *member, struct triple *new_member);
13513 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13514 static struct reg_block *compute_variable_lifetimes(
13515 struct compile_state *state, struct basic_blocks *bb);
13516 static void free_variable_lifetimes(struct compile_state *state,
13517 struct basic_blocks *bb, struct reg_block *blocks);
13518 static void print_live_variables(struct compile_state *state,
13519 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13522 static struct triple *call(struct compile_state *state,
13523 struct triple *retvar, struct triple *ret_addr,
13524 struct triple *targ, struct triple *ret)
13526 struct triple *call;
13528 if (!retvar || !is_lvalue(state, retvar)) {
13529 internal_error(state, 0, "writing to a non lvalue?");
13531 write_compatible(state, retvar->type, &void_ptr_type);
13533 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13534 TARG(call, 0) = targ;
13535 MISC(call, 0) = ret;
13536 if (!targ || (targ->op != OP_LABEL)) {
13537 internal_error(state, 0, "call not to a label");
13539 if (!ret || (ret->op != OP_RET)) {
13540 internal_error(state, 0, "call not matched with return");
13545 static void walk_functions(struct compile_state *state,
13546 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13549 struct triple *func, *first;
13550 func = first = state->functions;
13552 cb(state, func, arg);
13554 } while(func != first);
13557 static void reverse_walk_functions(struct compile_state *state,
13558 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13561 struct triple *func, *first;
13562 func = first = state->functions;
13565 cb(state, func, arg);
13566 } while(func != first);
13570 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13572 struct triple *ptr, *first;
13573 if (func->u.cval == 0) {
13576 ptr = first = RHS(func, 0);
13578 if (ptr->op == OP_FCALL) {
13579 struct triple *called_func;
13580 called_func = MISC(ptr, 0);
13581 /* Mark the called function as used */
13582 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13583 called_func->u.cval++;
13585 /* Remove the called function from the list */
13586 called_func->prev->next = called_func->next;
13587 called_func->next->prev = called_func->prev;
13589 /* Place the called function before me on the list */
13590 called_func->next = func;
13591 called_func->prev = func->prev;
13592 called_func->prev->next = called_func;
13593 called_func->next->prev = called_func;
13596 } while(ptr != first);
13597 func->id |= TRIPLE_FLAG_FLATTENED;
13600 static void mark_live_functions(struct compile_state *state)
13602 /* Ensure state->main_function is the last function in
13603 * the list of functions.
13605 if ((state->main_function->next != state->functions) ||
13606 (state->functions->prev != state->main_function)) {
13607 internal_error(state, 0,
13608 "state->main_function is not at the end of the function list ");
13610 state->main_function->u.cval = 1;
13611 reverse_walk_functions(state, mark_live, 0);
13614 static int local_triple(struct compile_state *state,
13615 struct triple *func, struct triple *ins)
13617 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13620 FILE *fp = state->errout;
13621 fprintf(fp, "global: ");
13622 display_triple(fp, ins);
13628 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13629 struct occurance *base_occurance)
13631 struct triple *nfunc;
13632 struct triple *nfirst, *ofirst;
13633 struct triple *new, *old;
13635 if (state->compiler->debug & DEBUG_INLINE) {
13636 FILE *fp = state->dbgout;
13639 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13640 display_func(state, fp, ofunc);
13641 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13644 /* Make a new copy of the old function */
13645 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13647 ofirst = old = RHS(ofunc, 0);
13649 struct triple *new;
13650 struct occurance *occurance;
13651 int old_lhs, old_rhs;
13652 old_lhs = old->lhs;
13653 old_rhs = old->rhs;
13654 occurance = inline_occurance(state, base_occurance, old->occurance);
13655 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13656 MISC(old, 0)->u.cval += 1;
13658 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13660 if (!triple_stores_block(state, new)) {
13661 memcpy(&new->u, &old->u, sizeof(new->u));
13664 RHS(nfunc, 0) = nfirst = new;
13667 insert_triple(state, nfirst, new);
13669 new->id |= TRIPLE_FLAG_FLATTENED;
13670 new->id |= old->id & TRIPLE_FLAG_COPY;
13672 /* During the copy remember new as user of old */
13673 use_triple(old, new);
13675 /* Remember which instructions are local */
13676 old->id |= TRIPLE_FLAG_LOCAL;
13678 } while(old != ofirst);
13680 /* Make a second pass to fix up any unresolved references */
13684 struct triple **oexpr, **nexpr;
13686 /* Lookup where the copy is, to join pointers */
13687 count = TRIPLE_SIZE(old);
13688 for(i = 0; i < count; i++) {
13689 oexpr = &old->param[i];
13690 nexpr = &new->param[i];
13691 if (*oexpr && !*nexpr) {
13692 if (!local_triple(state, ofunc, *oexpr)) {
13695 else if ((*oexpr)->use) {
13696 *nexpr = (*oexpr)->use->member;
13698 if (*nexpr == old) {
13699 internal_error(state, 0, "new == old?");
13701 use_triple(*nexpr, new);
13703 if (!*nexpr && *oexpr) {
13704 internal_error(state, 0, "Could not copy %d", i);
13709 } while((old != ofirst) && (new != nfirst));
13711 /* Make a third pass to cleanup the extra useses */
13715 unuse_triple(old, new);
13716 /* Forget which instructions are local */
13717 old->id &= ~TRIPLE_FLAG_LOCAL;
13720 } while ((old != ofirst) && (new != nfirst));
13724 static void expand_inline_call(
13725 struct compile_state *state, struct triple *me, struct triple *fcall)
13727 /* Inline the function call */
13728 struct type *ptype;
13729 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13730 struct triple *end, *nend;
13733 /* Find the triples */
13734 ofunc = MISC(fcall, 0);
13735 if (ofunc->op != OP_LIST) {
13736 internal_error(state, 0, "improper function");
13738 nfunc = copy_func(state, ofunc, fcall->occurance);
13739 /* Prepend the parameter reading into the new function list */
13740 ptype = nfunc->type->right;
13741 pvals = fcall->rhs;
13742 for(i = 0; i < pvals; i++) {
13743 struct type *atype;
13744 struct triple *arg, *param;
13746 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13747 atype = ptype->left;
13749 param = farg(state, nfunc, i);
13750 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13751 internal_error(state, fcall, "param %d type mismatch", i);
13753 arg = RHS(fcall, i);
13754 flatten(state, fcall, write_expr(state, param, arg));
13755 ptype = ptype->right;
13758 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13759 result = read_expr(state,
13760 deref_index(state, fresult(state, nfunc), 1));
13762 if (state->compiler->debug & DEBUG_INLINE) {
13763 FILE *fp = state->dbgout;
13766 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13767 display_func(state, fp, nfunc);
13768 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13772 * Get rid of the extra triples
13774 /* Remove the read of the return address */
13775 ins = RHS(nfunc, 0)->prev->prev;
13776 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13777 internal_error(state, ins, "Not return addres read?");
13779 release_triple(state, ins);
13780 /* Remove the return instruction */
13781 ins = RHS(nfunc, 0)->prev;
13782 if (ins->op != OP_RET) {
13783 internal_error(state, ins, "Not return?");
13785 release_triple(state, ins);
13786 /* Remove the retaddres variable */
13787 retvar = fretaddr(state, nfunc);
13788 if ((retvar->lhs != 1) ||
13789 (retvar->op != OP_ADECL) ||
13790 (retvar->next->op != OP_PIECE) ||
13791 (MISC(retvar->next, 0) != retvar)) {
13792 internal_error(state, retvar, "Not the return address?");
13794 release_triple(state, retvar->next);
13795 release_triple(state, retvar);
13797 /* Remove the label at the start of the function */
13798 ins = RHS(nfunc, 0);
13799 if (ins->op != OP_LABEL) {
13800 internal_error(state, ins, "Not label?");
13802 nfirst = ins->next;
13803 free_triple(state, ins);
13804 /* Release the new function header */
13806 free_triple(state, nfunc);
13808 /* Append the new function list onto the return list */
13810 nend = nfirst->prev;
13811 end->next = nfirst;
13812 nfirst->prev = end;
13813 nend->next = fcall;
13814 fcall->prev = nend;
13816 /* Now the result reading code */
13818 result = flatten(state, fcall, result);
13819 propogate_use(state, fcall, result);
13822 /* Release the original fcall instruction */
13823 release_triple(state, fcall);
13830 * Type of the result variable.
13834 * +----------+------------+
13836 * union of closures result_type
13838 * +------------------+---------------+
13840 * closure1 ... closuerN
13842 * +----+--+-+--------+-----+ +----+----+---+-----+
13843 * | | | | | | | | |
13844 * var1 var2 var3 ... varN result var1 var2 ... varN result
13846 * +--------+---------+
13848 * union of closures result_type
13850 * +-----+-------------------+
13852 * closure1 ... closureN
13854 * +-----+---+----+----+ +----+---+----+-----+
13856 * var1 var2 ... varN result var1 var2 ... varN result
13859 static int add_closure_type(struct compile_state *state,
13860 struct triple *func, struct type *closure_type)
13862 struct type *type, *ctype, **next;
13863 struct triple *var, *new_var;
13867 FILE *fp = state->errout;
13868 fprintf(fp, "original_type: ");
13869 name_of(fp, fresult(state, func)->type);
13872 /* find the original type */
13873 var = fresult(state, func);
13875 if (type->elements != 2) {
13876 internal_error(state, var, "bad return type");
13879 /* Find the complete closure type and update it */
13880 ctype = type->left->left;
13881 next = &ctype->left;
13882 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13883 next = &(*next)->right;
13885 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13886 ctype->elements += 1;
13889 fprintf(fp, "new_type: ");
13892 fprintf(fp, "ctype: %p %d bits: %d ",
13893 ctype, ctype->elements, reg_size_of(state, ctype));
13894 name_of(fp, ctype);
13898 /* Regenerate the variable with the new type definition */
13899 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13900 new_var->id |= TRIPLE_FLAG_FLATTENED;
13901 for(i = 0; i < new_var->lhs; i++) {
13902 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13905 /* Point everyone at the new variable */
13906 propogate_use(state, var, new_var);
13908 /* Release the original variable */
13909 for(i = 0; i < var->lhs; i++) {
13910 release_triple(state, LHS(var, i));
13912 release_triple(state, var);
13914 /* Return the index of the added closure type */
13915 return ctype->elements - 1;
13918 static struct triple *closure_expr(struct compile_state *state,
13919 struct triple *func, int closure_idx, int var_idx)
13921 return deref_index(state,
13923 deref_index(state, fresult(state, func), 0),
13929 static void insert_triple_set(
13930 struct triple_reg_set **head, struct triple *member)
13932 struct triple_reg_set *new;
13933 new = xcmalloc(sizeof(*new), "triple_set");
13934 new->member = member;
13940 static int ordered_triple_set(
13941 struct triple_reg_set **head, struct triple *member)
13943 struct triple_reg_set **ptr;
13948 if (member == (*ptr)->member) {
13951 /* keep the list ordered */
13952 if (member->id < (*ptr)->member->id) {
13955 ptr = &(*ptr)->next;
13957 insert_triple_set(ptr, member);
13962 static void free_closure_variables(struct compile_state *state,
13963 struct triple_reg_set **enclose)
13965 struct triple_reg_set *entry, *next;
13966 for(entry = *enclose; entry; entry = next) {
13967 next = entry->next;
13968 do_triple_unset(enclose, entry->member);
13972 static int lookup_closure_index(struct compile_state *state,
13973 struct triple *me, struct triple *val)
13975 struct triple *first, *ins, *next;
13976 first = RHS(me, 0);
13977 ins = next = first;
13979 struct triple *result;
13980 struct triple *index0, *index1, *index2, *read, *write;
13983 if (ins->op != OP_CALL) {
13986 /* I am at a previous call point examine it closely */
13987 if (ins->next->op != OP_LABEL) {
13988 internal_error(state, ins, "call not followed by label");
13990 /* Does this call does not enclose any variables? */
13991 if ((ins->next->next->op != OP_INDEX) ||
13992 (ins->next->next->u.cval != 0) ||
13993 (result = MISC(ins->next->next, 0)) ||
13994 (result->id & TRIPLE_FLAG_LOCAL)) {
13997 index0 = ins->next->next;
13999 * 0 index result < 0 >
14005 for(index0 = ins->next->next;
14006 (index0->op == OP_INDEX) &&
14007 (MISC(index0, 0) == result) &&
14008 (index0->u.cval == 0) ;
14009 index0 = write->next)
14011 index1 = index0->next;
14012 index2 = index1->next;
14013 read = index2->next;
14014 write = read->next;
14015 if ((index0->op != OP_INDEX) ||
14016 (index1->op != OP_INDEX) ||
14017 (index2->op != OP_INDEX) ||
14018 (read->op != OP_READ) ||
14019 (write->op != OP_WRITE) ||
14020 (MISC(index1, 0) != index0) ||
14021 (MISC(index2, 0) != index1) ||
14022 (RHS(read, 0) != index2) ||
14023 (RHS(write, 0) != read)) {
14024 internal_error(state, index0, "bad var read");
14026 if (MISC(write, 0) == val) {
14027 return index2->u.cval;
14030 } while(next != first);
14034 static inline int enclose_triple(struct triple *ins)
14036 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14039 static void compute_closure_variables(struct compile_state *state,
14040 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14042 struct triple_reg_set *set, *vars, **last_var;
14043 struct basic_blocks bb;
14044 struct reg_block *rb;
14045 struct block *block;
14046 struct triple *old_result, *first, *ins;
14048 unsigned long used_indicies;
14050 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14051 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14058 /* Find the basic blocks of this function */
14060 bb.first = RHS(me, 0);
14062 if (!triple_is_ret(state, bb.first->prev)) {
14065 old_result = fresult(state, me);
14067 analyze_basic_blocks(state, &bb);
14069 /* Find which variables are currently alive in a given block */
14070 rb = compute_variable_lifetimes(state, &bb);
14072 /* Find the variables that are currently alive */
14073 block = block_of_triple(state, fcall);
14074 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14075 internal_error(state, fcall, "No reg block? block: %p", block);
14078 #if DEBUG_EXPLICIT_CLOSURES
14079 print_live_variables(state, &bb, rb, state->dbgout);
14080 fflush(state->dbgout);
14083 /* Count the number of triples in the function */
14084 first = RHS(me, 0);
14090 } while(ins != first);
14092 /* Allocate some memory to temorary hold the id info */
14093 info = xcmalloc(sizeof(*info) * (count +1), "info");
14095 /* Mark the local function */
14096 first = RHS(me, 0);
14100 info[idx].id = ins->id;
14101 ins->id = TRIPLE_FLAG_LOCAL | idx;
14104 } while(ins != first);
14107 * Build the list of variables to enclose.
14109 * A target it to put the same variable in the
14110 * same slot for ever call of a given function.
14111 * After coloring this removes all of the variable
14112 * manipulation code.
14114 * The list of variables to enclose is built ordered
14115 * program order because except in corner cases this
14116 * gives me the stability of assignment I need.
14118 * To gurantee that stability I lookup the variables
14119 * to see where they have been used before and
14120 * I build my final list with the assigned indicies.
14123 if (enclose_triple(old_result)) {
14124 ordered_triple_set(&vars, old_result);
14126 for(set = rb[block->vertex].out; set; set = set->next) {
14127 if (!enclose_triple(set->member)) {
14130 if ((set->member == fcall) || (set->member == old_result)) {
14133 if (!local_triple(state, me, set->member)) {
14134 internal_error(state, set->member, "not local?");
14136 ordered_triple_set(&vars, set->member);
14139 /* Lookup the current indicies of the live varialbe */
14142 for(set = vars; set ; set = set->next) {
14143 struct triple *ins;
14146 index = lookup_closure_index(state, me, ins);
14147 info[ID_BITS(ins->id)].index = index;
14151 if (index >= MAX_INDICIES) {
14152 internal_error(state, ins, "index unexpectedly large");
14154 if (used_indicies & (1 << index)) {
14155 internal_error(state, ins, "index previously used?");
14157 /* Remember which indicies have been used */
14158 used_indicies |= (1 << index);
14159 if (index > max_index) {
14164 /* Walk through the live variables and make certain
14165 * everything is assigned an index.
14167 for(set = vars; set; set = set->next) {
14168 struct triple *ins;
14171 index = info[ID_BITS(ins->id)].index;
14175 /* Find the lowest unused index value */
14176 for(index = 0; index < MAX_INDICIES; index++) {
14177 if (!(used_indicies & (1 << index))) {
14181 if (index == MAX_INDICIES) {
14182 internal_error(state, ins, "no free indicies?");
14184 info[ID_BITS(ins->id)].index = index;
14185 /* Remember which indicies have been used */
14186 used_indicies |= (1 << index);
14187 if (index > max_index) {
14192 /* Build the return list of variables with positions matching
14196 last_var = enclose;
14197 for(i = 0; i <= max_index; i++) {
14198 struct triple *var;
14200 if (used_indicies & (1 << i)) {
14201 for(set = vars; set; set = set->next) {
14203 index = info[ID_BITS(set->member->id)].index;
14210 internal_error(state, me, "missing variable");
14213 insert_triple_set(last_var, var);
14214 last_var = &(*last_var)->next;
14217 #if DEBUG_EXPLICIT_CLOSURES
14218 /* Print out the variables to be enclosed */
14219 loc(state->dbgout, state, fcall);
14220 fprintf(state->dbgout, "Alive: \n");
14221 for(set = *enclose; set; set = set->next) {
14222 display_triple(state->dbgout, set->member);
14224 fflush(state->dbgout);
14227 /* Clear the marks */
14230 ins->id = info[ID_BITS(ins->id)].id;
14232 } while(ins != first);
14234 /* Release the ordered list of live variables */
14235 free_closure_variables(state, &vars);
14237 /* Release the storage of the old ids */
14240 /* Release the variable lifetime information */
14241 free_variable_lifetimes(state, &bb, rb);
14243 /* Release the basic blocks of this function */
14244 free_basic_blocks(state, &bb);
14247 static void expand_function_call(
14248 struct compile_state *state, struct triple *me, struct triple *fcall)
14250 /* Generate an ordinary function call */
14251 struct type *closure_type, **closure_next;
14252 struct triple *func, *func_first, *func_last, *retvar;
14253 struct triple *first;
14254 struct type *ptype, *rtype;
14255 struct triple *jmp;
14256 struct triple *ret_addr, *ret_loc, *ret_set;
14257 struct triple_reg_set *enclose, *set;
14258 int closure_idx, pvals, i;
14260 #if DEBUG_EXPLICIT_CLOSURES
14261 FILE *fp = state->dbgout;
14262 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14263 display_func(state, fp, MISC(fcall, 0));
14264 display_func(state, fp, me);
14265 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14268 /* Find the triples */
14269 func = MISC(fcall, 0);
14270 func_first = RHS(func, 0);
14271 retvar = fretaddr(state, func);
14272 func_last = func_first->prev;
14273 first = fcall->next;
14275 /* Find what I need to enclose */
14276 compute_closure_variables(state, me, fcall, &enclose);
14278 /* Compute the closure type */
14279 closure_type = new_type(TYPE_TUPLE, 0, 0);
14280 closure_type->elements = 0;
14281 closure_next = &closure_type->left;
14282 for(set = enclose; set ; set = set->next) {
14286 type = set->member->type;
14288 if (!*closure_next) {
14289 *closure_next = type;
14291 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14293 closure_next = &(*closure_next)->right;
14295 closure_type->elements += 1;
14297 if (closure_type->elements == 0) {
14298 closure_type->type = TYPE_VOID;
14302 #if DEBUG_EXPLICIT_CLOSURES
14303 fprintf(state->dbgout, "closure type: ");
14304 name_of(state->dbgout, closure_type);
14305 fprintf(state->dbgout, "\n");
14308 /* Update the called functions closure variable */
14309 closure_idx = add_closure_type(state, func, closure_type);
14311 /* Generate some needed triples */
14312 ret_loc = label(state);
14313 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14315 /* Pass the parameters to the new function */
14316 ptype = func->type->right;
14317 pvals = fcall->rhs;
14318 for(i = 0; i < pvals; i++) {
14319 struct type *atype;
14320 struct triple *arg, *param;
14322 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14323 atype = ptype->left;
14325 param = farg(state, func, i);
14326 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14327 internal_error(state, fcall, "param type mismatch");
14329 arg = RHS(fcall, i);
14330 flatten(state, first, write_expr(state, param, arg));
14331 ptype = ptype->right;
14333 rtype = func->type->left;
14335 /* Thread the triples together */
14336 ret_loc = flatten(state, first, ret_loc);
14338 /* Save the active variables in the result variable */
14339 for(i = 0, set = enclose; set ; set = set->next, i++) {
14340 if (!set->member) {
14343 flatten(state, ret_loc,
14345 closure_expr(state, func, closure_idx, i),
14346 read_expr(state, set->member)));
14349 /* Initialize the return value */
14350 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14351 flatten(state, ret_loc,
14353 deref_index(state, fresult(state, func), 1),
14354 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14357 ret_addr = flatten(state, ret_loc, ret_addr);
14358 ret_set = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14359 jmp = flatten(state, ret_loc,
14360 call(state, retvar, ret_addr, func_first, func_last));
14362 /* Find the result */
14363 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14364 struct triple * result;
14365 result = flatten(state, first,
14367 deref_index(state, fresult(state, func), 1)));
14369 propogate_use(state, fcall, result);
14372 /* Release the original fcall instruction */
14373 release_triple(state, fcall);
14375 /* Restore the active variables from the result variable */
14376 for(i = 0, set = enclose; set ; set = set->next, i++) {
14377 struct triple_set *use, *next;
14378 struct triple *new;
14379 struct basic_blocks bb;
14380 if (!set->member || (set->member == fcall)) {
14383 /* Generate an expression for the value */
14384 new = flatten(state, first,
14386 closure_expr(state, func, closure_idx, i)));
14389 /* If the original is an lvalue restore the preserved value */
14390 if (is_lvalue(state, set->member)) {
14391 flatten(state, first,
14392 write_expr(state, set->member, new));
14396 * If the original is a value update the dominated uses.
14399 /* Analyze the basic blocks so I can see who dominates whom */
14401 bb.first = RHS(me, 0);
14402 if (!triple_is_ret(state, bb.first->prev)) {
14405 analyze_basic_blocks(state, &bb);
14408 #if DEBUG_EXPLICIT_CLOSURES
14409 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14412 /* If fcall dominates the use update the expression */
14413 for(use = set->member->use; use; use = next) {
14414 /* Replace use modifies the use chain and
14415 * removes use, so I must take a copy of the
14416 * next entry early.
14419 if (!tdominates(state, fcall, use->member)) {
14422 replace_use(state, set->member, new, use->member);
14425 /* Release the basic blocks, the instructions will be
14426 * different next time, and flatten/insert_triple does
14427 * not update the block values so I can't cache the analysis.
14429 free_basic_blocks(state, &bb);
14432 /* Release the closure variable list */
14433 free_closure_variables(state, &enclose);
14435 if (state->compiler->debug & DEBUG_INLINE) {
14436 FILE *fp = state->dbgout;
14439 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14440 display_func(state, fp, func);
14441 display_func(state, fp, me);
14442 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14448 static int do_inline(struct compile_state *state, struct triple *func)
14453 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14455 case COMPILER_INLINE_ALWAYS:
14457 if (func->type->type & ATTRIB_NOINLINE) {
14458 error(state, func, "noinline with always_inline compiler option");
14461 case COMPILER_INLINE_NEVER:
14463 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14464 error(state, func, "always_inline with noinline compiler option");
14467 case COMPILER_INLINE_DEFAULTON:
14468 switch(func->type->type & STOR_MASK) {
14469 case STOR_STATIC | STOR_INLINE:
14470 case STOR_LOCAL | STOR_INLINE:
14471 case STOR_EXTERN | STOR_INLINE:
14479 case COMPILER_INLINE_DEFAULTOFF:
14480 switch(func->type->type & STOR_MASK) {
14481 case STOR_STATIC | STOR_INLINE:
14482 case STOR_LOCAL | STOR_INLINE:
14483 case STOR_EXTERN | STOR_INLINE:
14491 case COMPILER_INLINE_NOPENALTY:
14492 switch(func->type->type & STOR_MASK) {
14493 case STOR_STATIC | STOR_INLINE:
14494 case STOR_LOCAL | STOR_INLINE:
14495 case STOR_EXTERN | STOR_INLINE:
14499 do_inline = (func->u.cval == 1);
14505 internal_error(state, 0, "Unimplemented inline policy");
14508 /* Force inlining */
14509 if (func->type->type & ATTRIB_NOINLINE) {
14512 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14518 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14520 struct triple *first, *ptr, *next;
14521 /* If the function is not used don't bother */
14522 if (me->u.cval <= 0) {
14525 if (state->compiler->debug & DEBUG_CALLS2) {
14526 FILE *fp = state->dbgout;
14527 fprintf(fp, "in: %s\n",
14528 me->type->type_ident->name);
14531 first = RHS(me, 0);
14532 ptr = next = first;
14534 struct triple *func, *prev;
14538 if (ptr->op != OP_FCALL) {
14541 func = MISC(ptr, 0);
14542 /* See if the function should be inlined */
14543 if (!do_inline(state, func)) {
14544 /* Put a label after the fcall */
14545 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14548 if (state->compiler->debug & DEBUG_CALLS) {
14549 FILE *fp = state->dbgout;
14550 if (state->compiler->debug & DEBUG_CALLS2) {
14551 loc(fp, state, ptr);
14553 fprintf(fp, "inlining %s\n",
14554 func->type->type_ident->name);
14558 /* Update the function use counts */
14561 /* Replace the fcall with the called function */
14562 expand_inline_call(state, me, ptr);
14565 } while (next != first);
14567 ptr = next = first;
14569 struct triple *prev, *func;
14573 if (ptr->op != OP_FCALL) {
14576 func = MISC(ptr, 0);
14577 if (state->compiler->debug & DEBUG_CALLS) {
14578 FILE *fp = state->dbgout;
14579 if (state->compiler->debug & DEBUG_CALLS2) {
14580 loc(fp, state, ptr);
14582 fprintf(fp, "calling %s\n",
14583 func->type->type_ident->name);
14586 /* Replace the fcall with the instruction sequence
14587 * needed to make the call.
14589 expand_function_call(state, me, ptr);
14591 } while(next != first);
14594 static void inline_functions(struct compile_state *state, struct triple *func)
14596 inline_function(state, func, 0);
14597 reverse_walk_functions(state, inline_function, 0);
14600 static void insert_function(struct compile_state *state,
14601 struct triple *func, void *arg)
14603 struct triple *first, *end, *ffirst, *fend;
14605 if (state->compiler->debug & DEBUG_INLINE) {
14606 FILE *fp = state->errout;
14607 fprintf(fp, "%s func count: %d\n",
14608 func->type->type_ident->name, func->u.cval);
14610 if (func->u.cval == 0) {
14614 /* Find the end points of the lists */
14617 ffirst = RHS(func, 0);
14618 fend = ffirst->prev;
14620 /* splice the lists together */
14621 end->next = ffirst;
14622 ffirst->prev = end;
14623 fend->next = first;
14624 first->prev = fend;
14627 struct triple *input_asm(struct compile_state *state)
14629 struct asm_info *info;
14630 struct triple *def;
14633 info = xcmalloc(sizeof(*info), "asm_info");
14636 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14637 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14639 def = new_triple(state, OP_ASM, &void_type, out, 0);
14640 def->u.ainfo = info;
14641 def->id |= TRIPLE_FLAG_VOLATILE;
14643 for(i = 0; i < out; i++) {
14644 struct triple *piece;
14645 piece = triple(state, OP_PIECE, &int_type, def, 0);
14647 LHS(def, i) = piece;
14653 struct triple *output_asm(struct compile_state *state)
14655 struct asm_info *info;
14656 struct triple *def;
14659 info = xcmalloc(sizeof(*info), "asm_info");
14662 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14663 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14665 def = new_triple(state, OP_ASM, &void_type, 0, in);
14666 def->u.ainfo = info;
14667 def->id |= TRIPLE_FLAG_VOLATILE;
14672 static void join_functions(struct compile_state *state)
14674 struct triple *jmp, *start, *end, *call, *in, *out, *func;
14675 struct file_state file;
14676 struct type *pnext, *param;
14677 struct type *result_type, *args_type;
14680 /* Be clear the functions have not been joined yet */
14681 state->functions_joined = 0;
14683 /* Dummy file state to get debug handing right */
14684 memset(&file, 0, sizeof(file));
14685 file.basename = "";
14687 file.report_line = 0;
14688 file.report_name = file.basename;
14689 file.prev = state->file;
14690 state->file = &file;
14691 state->function = "";
14693 if (!state->main_function) {
14694 error(state, 0, "No functions to compile\n");
14697 /* The type of arguments */
14698 args_type = state->main_function->type->right;
14699 /* The return type without any specifiers */
14700 result_type = clone_type(0, state->main_function->type->left);
14703 /* Verify the external arguments */
14704 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14705 error(state, state->main_function,
14706 "Too many external input arguments");
14708 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14709 error(state, state->main_function,
14710 "Too many external output arguments");
14713 /* Lay down the basic program structure */
14714 end = label(state);
14715 start = label(state);
14716 start = flatten(state, state->first, start);
14717 end = flatten(state, state->first, end);
14718 in = input_asm(state);
14719 out = output_asm(state);
14720 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14721 MISC(call, 0) = state->main_function;
14722 in = flatten(state, state->first, in);
14723 call = flatten(state, state->first, call);
14724 out = flatten(state, state->first, out);
14727 /* Read the external input arguments */
14730 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14731 struct triple *expr;
14734 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14735 pnext = param->right;
14736 param = param->left;
14738 if (registers_of(state, param) != 1) {
14739 error(state, state->main_function,
14740 "Arg: %d %s requires multiple registers",
14741 idx + 1, param->field_ident->name);
14743 expr = read_expr(state, LHS(in, idx));
14744 RHS(call, idx) = expr;
14745 expr = flatten(state, call, expr);
14746 use_triple(expr, call);
14752 /* Write the external output arguments */
14753 pnext = result_type;
14754 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14755 pnext = result_type->left;
14757 for(idx = 0; idx < out->rhs; idx++) {
14758 struct triple *expr;
14761 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14762 pnext = param->right;
14763 param = param->left;
14765 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14769 if (registers_of(state, param) != 1) {
14770 error(state, state->main_function,
14771 "Result: %d %s requires multiple registers",
14772 idx, param->field_ident->name);
14774 expr = read_expr(state, call);
14775 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14776 expr = deref_field(state, expr, param->field_ident);
14779 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14781 flatten(state, out, expr);
14782 RHS(out, idx) = expr;
14783 use_triple(expr, out);
14786 /* Allocate a dummy containing function */
14787 func = triple(state, OP_LIST,
14788 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14789 func->type->type_ident = lookup(state, "", 0);
14790 RHS(func, 0) = state->first;
14793 /* See which functions are called, and how often */
14794 mark_live_functions(state);
14795 inline_functions(state, func);
14796 walk_functions(state, insert_function, end);
14798 if (start->next != end) {
14799 jmp = flatten(state, start, branch(state, end, 0));
14802 /* OK now the functions have been joined. */
14803 state->functions_joined = 1;
14805 /* Done now cleanup */
14806 state->file = file.prev;
14807 state->function = 0;
14811 * Data structurs for optimation.
14815 static int do_use_block(
14816 struct block *used, struct block_set **head, struct block *user,
14819 struct block_set **ptr, *new;
14826 if ((*ptr)->member == user) {
14829 ptr = &(*ptr)->next;
14831 new = xcmalloc(sizeof(*new), "block_set");
14832 new->member = user;
14843 static int do_unuse_block(
14844 struct block *used, struct block_set **head, struct block *unuser)
14846 struct block_set *use, **ptr;
14852 if (use->member == unuser) {
14854 memset(use, -1, sizeof(*use));
14865 static void use_block(struct block *used, struct block *user)
14868 /* Append new to the head of the list, print_block
14871 count = do_use_block(used, &used->use, user, 1);
14872 used->users += count;
14874 static void unuse_block(struct block *used, struct block *unuser)
14877 count = do_unuse_block(used, &used->use, unuser);
14878 used->users -= count;
14881 static void add_block_edge(struct block *block, struct block *edge, int front)
14884 count = do_use_block(block, &block->edges, edge, front);
14885 block->edge_count += count;
14888 static void remove_block_edge(struct block *block, struct block *edge)
14891 count = do_unuse_block(block, &block->edges, edge);
14892 block->edge_count -= count;
14895 static void idom_block(struct block *idom, struct block *user)
14897 do_use_block(idom, &idom->idominates, user, 0);
14900 static void unidom_block(struct block *idom, struct block *unuser)
14902 do_unuse_block(idom, &idom->idominates, unuser);
14905 static void domf_block(struct block *block, struct block *domf)
14907 do_use_block(block, &block->domfrontier, domf, 0);
14910 static void undomf_block(struct block *block, struct block *undomf)
14912 do_unuse_block(block, &block->domfrontier, undomf);
14915 static void ipdom_block(struct block *ipdom, struct block *user)
14917 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14920 static void unipdom_block(struct block *ipdom, struct block *unuser)
14922 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14925 static void ipdomf_block(struct block *block, struct block *ipdomf)
14927 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14930 static void unipdomf_block(struct block *block, struct block *unipdomf)
14932 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14935 static int walk_triples(
14936 struct compile_state *state,
14937 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
14940 struct triple *ptr;
14942 ptr = state->first;
14944 result = cb(state, ptr, arg);
14945 if (ptr->next->prev != ptr) {
14946 internal_error(state, ptr->next, "bad prev");
14949 } while((result == 0) && (ptr != state->first));
14953 #define PRINT_LIST 1
14954 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
14959 if (op == OP_LIST) {
14964 if ((op == OP_LABEL) && (ins->use)) {
14965 fprintf(fp, "\n%p:\n", ins);
14967 display_triple(fp, ins);
14969 if (triple_is_branch(state, ins) && ins->use &&
14970 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
14971 internal_error(state, ins, "branch used?");
14973 if (triple_is_branch(state, ins)) {
14979 static void print_triples(struct compile_state *state)
14981 if (state->compiler->debug & DEBUG_TRIPLES) {
14982 FILE *fp = state->dbgout;
14983 fprintf(fp, "--------------- triples ---------------\n");
14984 walk_triples(state, do_print_triple, fp);
14990 struct block *block;
14992 static void find_cf_blocks(struct cf_block *cf, struct block *block)
14994 struct block_set *edge;
14995 if (!block || (cf[block->vertex].block == block)) {
14998 cf[block->vertex].block = block;
14999 for(edge = block->edges; edge; edge = edge->next) {
15000 find_cf_blocks(cf, edge->member);
15004 static void print_control_flow(struct compile_state *state,
15005 FILE *fp, struct basic_blocks *bb)
15007 struct cf_block *cf;
15009 fprintf(fp, "\ncontrol flow\n");
15010 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15011 find_cf_blocks(cf, bb->first_block);
15013 for(i = 1; i <= bb->last_vertex; i++) {
15014 struct block *block;
15015 struct block_set *edge;
15016 block = cf[i].block;
15019 fprintf(fp, "(%p) %d:", block, block->vertex);
15020 for(edge = block->edges; edge; edge = edge->next) {
15021 fprintf(fp, " %d", edge->member->vertex);
15029 static void free_basic_block(struct compile_state *state, struct block *block)
15031 struct block_set *edge, *entry;
15032 struct block *child;
15036 if (block->vertex == -1) {
15039 block->vertex = -1;
15040 for(edge = block->edges; edge; edge = edge->next) {
15041 if (edge->member) {
15042 unuse_block(edge->member, block);
15046 unidom_block(block->idom, block);
15049 if (block->ipdom) {
15050 unipdom_block(block->ipdom, block);
15053 while((entry = block->use)) {
15054 child = entry->member;
15055 unuse_block(block, child);
15056 if (child && (child->vertex != -1)) {
15057 for(edge = child->edges; edge; edge = edge->next) {
15062 while((entry = block->idominates)) {
15063 child = entry->member;
15064 unidom_block(block, child);
15065 if (child && (child->vertex != -1)) {
15069 while((entry = block->domfrontier)) {
15070 child = entry->member;
15071 undomf_block(block, child);
15073 while((entry = block->ipdominates)) {
15074 child = entry->member;
15075 unipdom_block(block, child);
15076 if (child && (child->vertex != -1)) {
15080 while((entry = block->ipdomfrontier)) {
15081 child = entry->member;
15082 unipdomf_block(block, child);
15084 if (block->users != 0) {
15085 internal_error(state, 0, "block still has users");
15087 while((edge = block->edges)) {
15088 child = edge->member;
15089 remove_block_edge(block, child);
15091 if (child && (child->vertex != -1)) {
15092 free_basic_block(state, child);
15095 memset(block, -1, sizeof(*block));
15099 static void free_basic_blocks(struct compile_state *state,
15100 struct basic_blocks *bb)
15102 struct triple *first, *ins;
15103 free_basic_block(state, bb->first_block);
15104 bb->last_vertex = 0;
15105 bb->first_block = bb->last_block = 0;
15109 if (triple_stores_block(state, ins)) {
15113 } while(ins != first);
15117 static struct block *basic_block(struct compile_state *state,
15118 struct basic_blocks *bb, struct triple *first)
15120 struct block *block;
15121 struct triple *ptr;
15122 if (!triple_is_label(state, first)) {
15123 internal_error(state, first, "block does not start with a label");
15125 /* See if this basic block has already been setup */
15126 if (first->u.block != 0) {
15127 return first->u.block;
15129 /* Allocate another basic block structure */
15130 bb->last_vertex += 1;
15131 block = xcmalloc(sizeof(*block), "block");
15132 block->first = block->last = first;
15133 block->vertex = bb->last_vertex;
15136 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15140 /* If ptr->u is not used remember where the baic block is */
15141 if (triple_stores_block(state, ptr)) {
15142 ptr->u.block = block;
15144 if (triple_is_branch(state, ptr)) {
15148 } while (ptr != bb->first);
15149 if ((ptr == bb->first) ||
15150 ((ptr->next == bb->first) && (
15151 triple_is_end(state, ptr) ||
15152 triple_is_ret(state, ptr))))
15154 /* The block has no outflowing edges */
15156 else if (triple_is_label(state, ptr)) {
15157 struct block *next;
15158 next = basic_block(state, bb, ptr);
15159 add_block_edge(block, next, 0);
15160 use_block(next, block);
15162 else if (triple_is_branch(state, ptr)) {
15163 struct triple **expr, *first;
15164 struct block *child;
15165 /* Find the branch targets.
15166 * I special case the first branch as that magically
15167 * avoids some difficult cases for the register allocator.
15169 expr = triple_edge_targ(state, ptr, 0);
15171 internal_error(state, ptr, "branch without targets");
15174 expr = triple_edge_targ(state, ptr, expr);
15175 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15176 if (!*expr) continue;
15177 child = basic_block(state, bb, *expr);
15178 use_block(child, block);
15179 add_block_edge(block, child, 0);
15182 child = basic_block(state, bb, first);
15183 use_block(child, block);
15184 add_block_edge(block, child, 1);
15186 /* Be certain the return block of a call is
15187 * in a basic block. When it is not find
15188 * start of the block, insert a label if
15189 * necessary and build the basic block.
15190 * Then add a fake edge from the start block
15191 * to the return block of the function.
15193 if (state->functions_joined && triple_is_call(state, ptr)
15194 && !block_of_triple(state, MISC(ptr, 0))) {
15195 struct block *tail;
15196 struct triple *start;
15197 start = triple_to_block_start(state, MISC(ptr, 0));
15198 if (!triple_is_label(state, start)) {
15199 start = pre_triple(state,
15200 start, OP_LABEL, &void_type, 0, 0);
15202 tail = basic_block(state, bb, start);
15203 add_block_edge(child, tail, 0);
15204 use_block(tail, child);
15209 internal_error(state, 0, "Bad basic block split");
15213 struct block_set *edge;
15214 FILE *fp = state->errout;
15215 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15216 block, block->vertex,
15217 block->first, block->last);
15218 for(edge = block->edges; edge; edge = edge->next) {
15219 fprintf(fp, " %10p [%2d]",
15220 edge->member ? edge->member->first : 0,
15221 edge->member ? edge->member->vertex : -1);
15230 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15231 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15234 struct triple *ptr, *first;
15235 struct block *last_block;
15240 if (triple_stores_block(state, ptr)) {
15241 struct block *block;
15242 block = ptr->u.block;
15243 if (block && (block != last_block)) {
15244 cb(state, block, arg);
15246 last_block = block;
15249 } while(ptr != first);
15252 static void print_block(
15253 struct compile_state *state, struct block *block, void *arg)
15255 struct block_set *user, *edge;
15256 struct triple *ptr;
15259 fprintf(fp, "\nblock: %p (%d) ",
15263 for(edge = block->edges; edge; edge = edge->next) {
15264 fprintf(fp, " %p<-%p",
15266 (edge->member && edge->member->use)?
15267 edge->member->use->member : 0);
15270 if (block->first->op == OP_LABEL) {
15271 fprintf(fp, "%p:\n", block->first);
15273 for(ptr = block->first; ; ) {
15274 display_triple(fp, ptr);
15275 if (ptr == block->last)
15278 if (ptr == block->first) {
15279 internal_error(state, 0, "missing block last?");
15282 fprintf(fp, "users %d: ", block->users);
15283 for(user = block->use; user; user = user->next) {
15284 fprintf(fp, "%p (%d) ",
15286 user->member->vertex);
15288 fprintf(fp,"\n\n");
15292 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15294 fprintf(fp, "--------------- blocks ---------------\n");
15295 walk_blocks(state, &state->bb, print_block, fp);
15297 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15299 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15300 fprintf(fp, "After %s\n", func);
15301 romcc_print_blocks(state, fp);
15302 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15303 print_dominators(state, fp, &state->bb);
15304 print_dominance_frontiers(state, fp, &state->bb);
15306 print_control_flow(state, fp, &state->bb);
15310 static void prune_nonblock_triples(struct compile_state *state,
15311 struct basic_blocks *bb)
15313 struct block *block;
15314 struct triple *first, *ins, *next;
15315 /* Delete the triples not in a basic block */
15321 if (ins->op == OP_LABEL) {
15322 block = ins->u.block;
15325 struct triple_set *use;
15326 for(use = ins->use; use; use = use->next) {
15327 struct block *block;
15328 block = block_of_triple(state, use->member);
15330 internal_error(state, ins, "pruning used ins?");
15333 release_triple(state, ins);
15335 if (block && block->last == ins) {
15339 } while(ins != first);
15342 static void setup_basic_blocks(struct compile_state *state,
15343 struct basic_blocks *bb)
15345 if (!triple_stores_block(state, bb->first)) {
15346 internal_error(state, 0, "ins will not store block?");
15348 /* Initialize the state */
15349 bb->first_block = bb->last_block = 0;
15350 bb->last_vertex = 0;
15351 free_basic_blocks(state, bb);
15353 /* Find the basic blocks */
15354 bb->first_block = basic_block(state, bb, bb->first);
15356 /* Be certain the last instruction of a function, or the
15357 * entire program is in a basic block. When it is not find
15358 * the start of the block, insert a label if necessary and build
15359 * basic block. Then add a fake edge from the start block
15360 * to the final block.
15362 if (!block_of_triple(state, bb->first->prev)) {
15363 struct triple *start;
15364 struct block *tail;
15365 start = triple_to_block_start(state, bb->first->prev);
15366 if (!triple_is_label(state, start)) {
15367 start = pre_triple(state,
15368 start, OP_LABEL, &void_type, 0, 0);
15370 tail = basic_block(state, bb, start);
15371 add_block_edge(bb->first_block, tail, 0);
15372 use_block(tail, bb->first_block);
15375 /* Find the last basic block.
15377 bb->last_block = block_of_triple(state, bb->first->prev);
15379 /* Delete the triples not in a basic block */
15380 prune_nonblock_triples(state, bb);
15383 /* If we are debugging print what I have just done */
15384 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15385 print_blocks(state, state->dbgout);
15386 print_control_flow(state, bb);
15392 struct sdom_block {
15393 struct block *block;
15394 struct sdom_block *sdominates;
15395 struct sdom_block *sdom_next;
15396 struct sdom_block *sdom;
15397 struct sdom_block *label;
15398 struct sdom_block *parent;
15399 struct sdom_block *ancestor;
15404 static void unsdom_block(struct sdom_block *block)
15406 struct sdom_block **ptr;
15407 if (!block->sdom_next) {
15410 ptr = &block->sdom->sdominates;
15412 if ((*ptr) == block) {
15413 *ptr = block->sdom_next;
15416 ptr = &(*ptr)->sdom_next;
15420 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15422 unsdom_block(block);
15423 block->sdom = sdom;
15424 block->sdom_next = sdom->sdominates;
15425 sdom->sdominates = block;
15430 static int initialize_sdblock(struct sdom_block *sd,
15431 struct block *parent, struct block *block, int vertex)
15433 struct block_set *edge;
15434 if (!block || (sd[block->vertex].block == block)) {
15438 /* Renumber the blocks in a convinient fashion */
15439 block->vertex = vertex;
15440 sd[vertex].block = block;
15441 sd[vertex].sdom = &sd[vertex];
15442 sd[vertex].label = &sd[vertex];
15443 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15444 sd[vertex].ancestor = 0;
15445 sd[vertex].vertex = vertex;
15446 for(edge = block->edges; edge; edge = edge->next) {
15447 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15452 static int initialize_spdblock(
15453 struct compile_state *state, struct sdom_block *sd,
15454 struct block *parent, struct block *block, int vertex)
15456 struct block_set *user;
15457 if (!block || (sd[block->vertex].block == block)) {
15461 /* Renumber the blocks in a convinient fashion */
15462 block->vertex = vertex;
15463 sd[vertex].block = block;
15464 sd[vertex].sdom = &sd[vertex];
15465 sd[vertex].label = &sd[vertex];
15466 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15467 sd[vertex].ancestor = 0;
15468 sd[vertex].vertex = vertex;
15469 for(user = block->use; user; user = user->next) {
15470 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15475 static int setup_spdblocks(struct compile_state *state,
15476 struct basic_blocks *bb, struct sdom_block *sd)
15478 struct block *block;
15480 /* Setup as many sdpblocks as possible without using fake edges */
15481 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15483 /* Walk through the graph and find unconnected blocks. Add a
15484 * fake edge from the unconnected blocks to the end of the
15487 block = bb->first_block->last->next->u.block;
15488 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15489 if (sd[block->vertex].block == block) {
15492 #if DEBUG_SDP_BLOCKS
15494 FILE *fp = state->errout;
15495 fprintf(fp, "Adding %d\n", vertex +1);
15498 add_block_edge(block, bb->last_block, 0);
15499 use_block(bb->last_block, block);
15501 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15506 static void compress_ancestors(struct sdom_block *v)
15508 /* This procedure assumes ancestor(v) != 0 */
15509 /* if (ancestor(ancestor(v)) != 0) {
15510 * compress(ancestor(ancestor(v)));
15511 * if (semi(label(ancestor(v))) < semi(label(v))) {
15512 * label(v) = label(ancestor(v));
15514 * ancestor(v) = ancestor(ancestor(v));
15517 if (!v->ancestor) {
15520 if (v->ancestor->ancestor) {
15521 compress_ancestors(v->ancestor->ancestor);
15522 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15523 v->label = v->ancestor->label;
15525 v->ancestor = v->ancestor->ancestor;
15529 static void compute_sdom(struct compile_state *state,
15530 struct basic_blocks *bb, struct sdom_block *sd)
15534 * for each v <= pred(w) {
15536 * if (semi[u] < semi[w] {
15537 * semi[w] = semi[u];
15540 * add w to bucket(vertex(semi[w]));
15541 * LINK(parent(w), w);
15544 * for each v <= bucket(parent(w)) {
15545 * delete v from bucket(parent(w));
15547 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15550 for(i = bb->last_vertex; i >= 2; i--) {
15551 struct sdom_block *v, *parent, *next;
15552 struct block_set *user;
15553 struct block *block;
15554 block = sd[i].block;
15555 parent = sd[i].parent;
15557 for(user = block->use; user; user = user->next) {
15558 struct sdom_block *v, *u;
15559 v = &sd[user->member->vertex];
15560 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15561 if (u->sdom->vertex < sd[i].sdom->vertex) {
15562 sd[i].sdom = u->sdom;
15565 sdom_block(sd[i].sdom, &sd[i]);
15566 sd[i].ancestor = parent;
15568 for(v = parent->sdominates; v; v = next) {
15569 struct sdom_block *u;
15570 next = v->sdom_next;
15572 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15573 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15574 u->block : parent->block;
15579 static void compute_spdom(struct compile_state *state,
15580 struct basic_blocks *bb, struct sdom_block *sd)
15584 * for each v <= pred(w) {
15586 * if (semi[u] < semi[w] {
15587 * semi[w] = semi[u];
15590 * add w to bucket(vertex(semi[w]));
15591 * LINK(parent(w), w);
15594 * for each v <= bucket(parent(w)) {
15595 * delete v from bucket(parent(w));
15597 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15600 for(i = bb->last_vertex; i >= 2; i--) {
15601 struct sdom_block *u, *v, *parent, *next;
15602 struct block_set *edge;
15603 struct block *block;
15604 block = sd[i].block;
15605 parent = sd[i].parent;
15607 for(edge = block->edges; edge; edge = edge->next) {
15608 v = &sd[edge->member->vertex];
15609 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15610 if (u->sdom->vertex < sd[i].sdom->vertex) {
15611 sd[i].sdom = u->sdom;
15614 sdom_block(sd[i].sdom, &sd[i]);
15615 sd[i].ancestor = parent;
15617 for(v = parent->sdominates; v; v = next) {
15618 struct sdom_block *u;
15619 next = v->sdom_next;
15621 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15622 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15623 u->block : parent->block;
15628 static void compute_idom(struct compile_state *state,
15629 struct basic_blocks *bb, struct sdom_block *sd)
15632 for(i = 2; i <= bb->last_vertex; i++) {
15633 struct block *block;
15634 block = sd[i].block;
15635 if (block->idom->vertex != sd[i].sdom->vertex) {
15636 block->idom = block->idom->idom;
15638 idom_block(block->idom, block);
15640 sd[1].block->idom = 0;
15643 static void compute_ipdom(struct compile_state *state,
15644 struct basic_blocks *bb, struct sdom_block *sd)
15647 for(i = 2; i <= bb->last_vertex; i++) {
15648 struct block *block;
15649 block = sd[i].block;
15650 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15651 block->ipdom = block->ipdom->ipdom;
15653 ipdom_block(block->ipdom, block);
15655 sd[1].block->ipdom = 0;
15659 * Every vertex of a flowgraph G = (V, E, r) except r has
15660 * a unique immediate dominator.
15661 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15662 * rooted at r, called the dominator tree of G, such that
15663 * v dominates w if and only if v is a proper ancestor of w in
15664 * the dominator tree.
15667 * If v and w are vertices of G such that v <= w,
15668 * than any path from v to w must contain a common ancestor
15671 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15672 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15673 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15675 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15676 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15679 * Let w != r and let u be a vertex for which sdom(u) is
15680 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15681 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15683 /* Lemma 5: Let vertices v,w satisfy v -> w.
15684 * Then v -> idom(w) or idom(w) -> idom(v)
15687 static void find_immediate_dominators(struct compile_state *state,
15688 struct basic_blocks *bb)
15690 struct sdom_block *sd;
15691 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15692 * vi > w for (1 <= i <= k - 1}
15695 * For any vertex w != r.
15697 * {v|(v,w) <= E and v < w } U
15698 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15701 * Let w != r and let u be a vertex for which sdom(u) is
15702 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15704 * { sdom(w) if sdom(w) = sdom(u),
15706 * { idom(u) otherwise
15708 /* The algorithm consists of the following 4 steps.
15709 * Step 1. Carry out a depth-first search of the problem graph.
15710 * Number the vertices from 1 to N as they are reached during
15711 * the search. Initialize the variables used in succeeding steps.
15712 * Step 2. Compute the semidominators of all vertices by applying
15713 * theorem 4. Carry out the computation vertex by vertex in
15714 * decreasing order by number.
15715 * Step 3. Implicitly define the immediate dominator of each vertex
15716 * by applying Corollary 1.
15717 * Step 4. Explicitly define the immediate dominator of each vertex,
15718 * carrying out the computation vertex by vertex in increasing order
15721 /* Step 1 initialize the basic block information */
15722 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15723 initialize_sdblock(sd, 0, bb->first_block, 0);
15729 /* Step 2 compute the semidominators */
15730 /* Step 3 implicitly define the immediate dominator of each vertex */
15731 compute_sdom(state, bb, sd);
15732 /* Step 4 explicitly define the immediate dominator of each vertex */
15733 compute_idom(state, bb, sd);
15737 static void find_post_dominators(struct compile_state *state,
15738 struct basic_blocks *bb)
15740 struct sdom_block *sd;
15742 /* Step 1 initialize the basic block information */
15743 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15745 vertex = setup_spdblocks(state, bb, sd);
15746 if (vertex != bb->last_vertex) {
15747 internal_error(state, 0, "missing %d blocks",
15748 bb->last_vertex - vertex);
15751 /* Step 2 compute the semidominators */
15752 /* Step 3 implicitly define the immediate dominator of each vertex */
15753 compute_spdom(state, bb, sd);
15754 /* Step 4 explicitly define the immediate dominator of each vertex */
15755 compute_ipdom(state, bb, sd);
15761 static void find_block_domf(struct compile_state *state, struct block *block)
15763 struct block *child;
15764 struct block_set *user, *edge;
15765 if (block->domfrontier != 0) {
15766 internal_error(state, block->first, "domfrontier present?");
15768 for(user = block->idominates; user; user = user->next) {
15769 child = user->member;
15770 if (child->idom != block) {
15771 internal_error(state, block->first, "bad idom");
15773 find_block_domf(state, child);
15775 for(edge = block->edges; edge; edge = edge->next) {
15776 if (edge->member->idom != block) {
15777 domf_block(block, edge->member);
15780 for(user = block->idominates; user; user = user->next) {
15781 struct block_set *frontier;
15782 child = user->member;
15783 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15784 if (frontier->member->idom != block) {
15785 domf_block(block, frontier->member);
15791 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15793 struct block *child;
15794 struct block_set *user;
15795 if (block->ipdomfrontier != 0) {
15796 internal_error(state, block->first, "ipdomfrontier present?");
15798 for(user = block->ipdominates; user; user = user->next) {
15799 child = user->member;
15800 if (child->ipdom != block) {
15801 internal_error(state, block->first, "bad ipdom");
15803 find_block_ipdomf(state, child);
15805 for(user = block->use; user; user = user->next) {
15806 if (user->member->ipdom != block) {
15807 ipdomf_block(block, user->member);
15810 for(user = block->ipdominates; user; user = user->next) {
15811 struct block_set *frontier;
15812 child = user->member;
15813 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15814 if (frontier->member->ipdom != block) {
15815 ipdomf_block(block, frontier->member);
15821 static void print_dominated(
15822 struct compile_state *state, struct block *block, void *arg)
15824 struct block_set *user;
15827 fprintf(fp, "%d:", block->vertex);
15828 for(user = block->idominates; user; user = user->next) {
15829 fprintf(fp, " %d", user->member->vertex);
15830 if (user->member->idom != block) {
15831 internal_error(state, user->member->first, "bad idom");
15837 static void print_dominated2(
15838 struct compile_state *state, FILE *fp, int depth, struct block *block)
15840 struct block_set *user;
15841 struct triple *ins;
15842 struct occurance *ptr, *ptr2;
15843 const char *filename1, *filename2;
15844 int equal_filenames;
15846 for(i = 0; i < depth; i++) {
15849 fprintf(fp, "%3d: %p (%p - %p) @",
15850 block->vertex, block, block->first, block->last);
15851 ins = block->first;
15852 while(ins != block->last && (ins->occurance->line == 0)) {
15855 ptr = ins->occurance;
15856 ptr2 = block->last->occurance;
15857 filename1 = ptr->filename? ptr->filename : "";
15858 filename2 = ptr2->filename? ptr2->filename : "";
15859 equal_filenames = (strcmp(filename1, filename2) == 0);
15860 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15861 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15862 } else if (equal_filenames) {
15863 fprintf(fp, " %s:(%d - %d)",
15864 ptr->filename, ptr->line, ptr2->line);
15866 fprintf(fp, " (%s:%d - %s:%d)",
15867 ptr->filename, ptr->line,
15868 ptr2->filename, ptr2->line);
15871 for(user = block->idominates; user; user = user->next) {
15872 print_dominated2(state, fp, depth + 1, user->member);
15876 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15878 fprintf(fp, "\ndominates\n");
15879 walk_blocks(state, bb, print_dominated, fp);
15880 fprintf(fp, "dominates\n");
15881 print_dominated2(state, fp, 0, bb->first_block);
15885 static int print_frontiers(
15886 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15888 struct block_set *user, *edge;
15890 if (!block || (block->vertex != vertex + 1)) {
15895 fprintf(fp, "%d:", block->vertex);
15896 for(user = block->domfrontier; user; user = user->next) {
15897 fprintf(fp, " %d", user->member->vertex);
15901 for(edge = block->edges; edge; edge = edge->next) {
15902 vertex = print_frontiers(state, fp, edge->member, vertex);
15906 static void print_dominance_frontiers(struct compile_state *state,
15907 FILE *fp, struct basic_blocks *bb)
15909 fprintf(fp, "\ndominance frontiers\n");
15910 print_frontiers(state, fp, bb->first_block, 0);
15914 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15916 /* Find the immediate dominators */
15917 find_immediate_dominators(state, bb);
15918 /* Find the dominance frontiers */
15919 find_block_domf(state, bb->first_block);
15920 /* If debuging print the print what I have just found */
15921 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15922 print_dominators(state, state->dbgout, bb);
15923 print_dominance_frontiers(state, state->dbgout, bb);
15924 print_control_flow(state, state->dbgout, bb);
15929 static void print_ipdominated(
15930 struct compile_state *state, struct block *block, void *arg)
15932 struct block_set *user;
15935 fprintf(fp, "%d:", block->vertex);
15936 for(user = block->ipdominates; user; user = user->next) {
15937 fprintf(fp, " %d", user->member->vertex);
15938 if (user->member->ipdom != block) {
15939 internal_error(state, user->member->first, "bad ipdom");
15945 static void print_ipdominators(struct compile_state *state, FILE *fp,
15946 struct basic_blocks *bb)
15948 fprintf(fp, "\nipdominates\n");
15949 walk_blocks(state, bb, print_ipdominated, fp);
15952 static int print_pfrontiers(
15953 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15955 struct block_set *user;
15957 if (!block || (block->vertex != vertex + 1)) {
15962 fprintf(fp, "%d:", block->vertex);
15963 for(user = block->ipdomfrontier; user; user = user->next) {
15964 fprintf(fp, " %d", user->member->vertex);
15967 for(user = block->use; user; user = user->next) {
15968 vertex = print_pfrontiers(state, fp, user->member, vertex);
15972 static void print_ipdominance_frontiers(struct compile_state *state,
15973 FILE *fp, struct basic_blocks *bb)
15975 fprintf(fp, "\nipdominance frontiers\n");
15976 print_pfrontiers(state, fp, bb->last_block, 0);
15980 static void analyze_ipdominators(struct compile_state *state,
15981 struct basic_blocks *bb)
15983 /* Find the post dominators */
15984 find_post_dominators(state, bb);
15985 /* Find the control dependencies (post dominance frontiers) */
15986 find_block_ipdomf(state, bb->last_block);
15987 /* If debuging print the print what I have just found */
15988 if (state->compiler->debug & DEBUG_RDOMINATORS) {
15989 print_ipdominators(state, state->dbgout, bb);
15990 print_ipdominance_frontiers(state, state->dbgout, bb);
15991 print_control_flow(state, state->dbgout, bb);
15995 static int bdominates(struct compile_state *state,
15996 struct block *dom, struct block *sub)
15998 while(sub && (sub != dom)) {
16004 static int tdominates(struct compile_state *state,
16005 struct triple *dom, struct triple *sub)
16007 struct block *bdom, *bsub;
16009 bdom = block_of_triple(state, dom);
16010 bsub = block_of_triple(state, sub);
16011 if (bdom != bsub) {
16012 result = bdominates(state, bdom, bsub);
16015 struct triple *ins;
16016 if (!bdom || !bsub) {
16017 internal_error(state, dom, "huh?");
16020 while((ins != bsub->first) && (ins != dom)) {
16023 result = (ins == dom);
16028 static void analyze_basic_blocks(
16029 struct compile_state *state, struct basic_blocks *bb)
16031 setup_basic_blocks(state, bb);
16032 analyze_idominators(state, bb);
16033 analyze_ipdominators(state, bb);
16036 static void insert_phi_operations(struct compile_state *state)
16039 struct triple *first;
16040 int *has_already, *work;
16041 struct block *work_list, **work_list_tail;
16043 struct triple *var, *vnext;
16045 size = sizeof(int) * (state->bb.last_vertex + 1);
16046 has_already = xcmalloc(size, "has_already");
16047 work = xcmalloc(size, "work");
16050 first = state->first;
16051 for(var = first->next; var != first ; var = vnext) {
16052 struct block *block;
16053 struct triple_set *user, *unext;
16056 if (!triple_is_auto_var(state, var) || !var->use) {
16062 work_list_tail = &work_list;
16063 for(user = var->use; user; user = unext) {
16064 unext = user->next;
16065 if (MISC(var, 0) == user->member) {
16068 if (user->member->op == OP_READ) {
16071 if (user->member->op != OP_WRITE) {
16072 internal_error(state, user->member,
16073 "bad variable access");
16075 block = user->member->u.block;
16077 warning(state, user->member, "dead code");
16078 release_triple(state, user->member);
16081 if (work[block->vertex] >= iter) {
16084 work[block->vertex] = iter;
16085 *work_list_tail = block;
16086 block->work_next = 0;
16087 work_list_tail = &block->work_next;
16089 for(block = work_list; block; block = block->work_next) {
16090 struct block_set *df;
16091 for(df = block->domfrontier; df; df = df->next) {
16092 struct triple *phi;
16093 struct block *front;
16095 front = df->member;
16097 if (has_already[front->vertex] >= iter) {
16100 /* Count how many edges flow into this block */
16101 in_edges = front->users;
16102 /* Insert a phi function for this variable */
16103 get_occurance(var->occurance);
16104 phi = alloc_triple(
16105 state, OP_PHI, var->type, -1, in_edges,
16107 phi->u.block = front;
16108 MISC(phi, 0) = var;
16109 use_triple(var, phi);
16111 if (phi->rhs != in_edges) {
16112 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16113 phi->rhs, in_edges);
16116 /* Insert the phi functions immediately after the label */
16117 insert_triple(state, front->first->next, phi);
16118 if (front->first == front->last) {
16119 front->last = front->first->next;
16121 has_already[front->vertex] = iter;
16122 transform_to_arch_instruction(state, phi);
16124 /* If necessary plan to visit the basic block */
16125 if (work[front->vertex] >= iter) {
16128 work[front->vertex] = iter;
16129 *work_list_tail = front;
16130 front->work_next = 0;
16131 work_list_tail = &front->work_next;
16135 xfree(has_already);
16141 struct triple_set *top;
16145 static int count_auto_vars(struct compile_state *state)
16147 struct triple *first, *ins;
16149 first = state->first;
16152 if (triple_is_auto_var(state, ins)) {
16156 } while(ins != first);
16160 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16162 struct triple *first, *ins;
16164 first = state->first;
16167 if (triple_is_auto_var(state, ins)) {
16169 stacks[auto_vars].orig_id = ins->id;
16170 ins->id = auto_vars;
16173 } while(ins != first);
16176 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16178 struct triple *first, *ins;
16179 first = state->first;
16182 if (triple_is_auto_var(state, ins)) {
16183 ins->id = stacks[ins->id].orig_id;
16186 } while(ins != first);
16189 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16191 struct triple_set *head;
16192 struct triple *top_val;
16194 head = stacks[var->id].top;
16196 top_val = head->member;
16201 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16203 struct triple_set *new;
16204 /* Append new to the head of the list,
16205 * it's the only sensible behavoir for a stack.
16207 new = xcmalloc(sizeof(*new), "triple_set");
16209 new->next = stacks[var->id].top;
16210 stacks[var->id].top = new;
16213 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16215 struct triple_set *set, **ptr;
16216 ptr = &stacks[var->id].top;
16219 if (set->member == oldval) {
16222 /* Only free one occurance from the stack */
16235 static void fixup_block_phi_variables(
16236 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16238 struct block_set *set;
16239 struct triple *ptr;
16241 if (!parent || !block)
16243 /* Find the edge I am coming in on */
16245 for(set = block->use; set; set = set->next, edge++) {
16246 if (set->member == parent) {
16251 internal_error(state, 0, "phi input is not on a control predecessor");
16253 for(ptr = block->first; ; ptr = ptr->next) {
16254 if (ptr->op == OP_PHI) {
16255 struct triple *var, *val, **slot;
16256 var = MISC(ptr, 0);
16258 internal_error(state, ptr, "no var???");
16260 /* Find the current value of the variable */
16261 val = peek_triple(stacks, var);
16262 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16263 internal_error(state, val, "bad value in phi");
16265 if (edge >= ptr->rhs) {
16266 internal_error(state, ptr, "edges > phi rhs");
16268 slot = &RHS(ptr, edge);
16269 if ((*slot != 0) && (*slot != val)) {
16270 internal_error(state, ptr, "phi already bound on this edge");
16273 use_triple(val, ptr);
16275 if (ptr == block->last) {
16282 static void rename_block_variables(
16283 struct compile_state *state, struct stack *stacks, struct block *block)
16285 struct block_set *user, *edge;
16286 struct triple *ptr, *next, *last;
16290 last = block->first;
16292 for(ptr = block->first; !done; ptr = next) {
16294 if (ptr == block->last) {
16298 if (ptr->op == OP_READ) {
16299 struct triple *var, *val;
16301 if (!triple_is_auto_var(state, var)) {
16302 internal_error(state, ptr, "read of non auto var!");
16304 unuse_triple(var, ptr);
16305 /* Find the current value of the variable */
16306 val = peek_triple(stacks, var);
16308 /* Let the optimizer at variables that are not initially
16309 * set. But give it a bogus value so things seem to
16310 * work by accident. This is useful for bitfields because
16311 * setting them always involves a read-modify-write.
16313 if (TYPE_ARITHMETIC(ptr->type->type)) {
16314 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16315 val->u.cval = 0xdeadbeaf;
16317 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16321 error(state, ptr, "variable used without being set");
16323 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16324 internal_error(state, val, "bad value in read");
16326 propogate_use(state, ptr, val);
16327 release_triple(state, ptr);
16331 if (ptr->op == OP_WRITE) {
16332 struct triple *var, *val, *tval;
16333 var = MISC(ptr, 0);
16334 if (!triple_is_auto_var(state, var)) {
16335 internal_error(state, ptr, "write to non auto var!");
16337 tval = val = RHS(ptr, 0);
16338 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16339 triple_is_auto_var(state, val)) {
16340 internal_error(state, ptr, "bad value in write");
16342 /* Insert a cast if the types differ */
16343 if (!is_subset_type(ptr->type, val->type)) {
16344 if (val->op == OP_INTCONST) {
16345 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16346 tval->u.cval = val->u.cval;
16349 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16350 use_triple(val, tval);
16352 transform_to_arch_instruction(state, tval);
16353 unuse_triple(val, ptr);
16354 RHS(ptr, 0) = tval;
16355 use_triple(tval, ptr);
16357 propogate_use(state, ptr, tval);
16358 unuse_triple(var, ptr);
16359 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16360 push_triple(stacks, var, tval);
16362 if (ptr->op == OP_PHI) {
16363 struct triple *var;
16364 var = MISC(ptr, 0);
16365 if (!triple_is_auto_var(state, var)) {
16366 internal_error(state, ptr, "phi references non auto var!");
16368 /* Push OP_PHI onto a stack of variable uses */
16369 push_triple(stacks, var, ptr);
16373 block->last = last;
16375 /* Fixup PHI functions in the cf successors */
16376 for(edge = block->edges; edge; edge = edge->next) {
16377 fixup_block_phi_variables(state, stacks, block, edge->member);
16379 /* rename variables in the dominated nodes */
16380 for(user = block->idominates; user; user = user->next) {
16381 rename_block_variables(state, stacks, user->member);
16383 /* pop the renamed variable stack */
16384 last = block->first;
16386 for(ptr = block->first; !done ; ptr = next) {
16388 if (ptr == block->last) {
16391 if (ptr->op == OP_WRITE) {
16392 struct triple *var;
16393 var = MISC(ptr, 0);
16394 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16395 pop_triple(stacks, var, RHS(ptr, 0));
16396 release_triple(state, ptr);
16399 if (ptr->op == OP_PHI) {
16400 struct triple *var;
16401 var = MISC(ptr, 0);
16402 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16403 pop_triple(stacks, var, ptr);
16407 block->last = last;
16410 static void rename_variables(struct compile_state *state)
16412 struct stack *stacks;
16415 /* Allocate stacks for the Variables */
16416 auto_vars = count_auto_vars(state);
16417 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16419 /* Give each auto_var a stack */
16420 number_auto_vars(state, stacks);
16422 /* Rename the variables */
16423 rename_block_variables(state, stacks, state->bb.first_block);
16425 /* Remove the stacks from the auto_vars */
16426 restore_auto_vars(state, stacks);
16430 static void prune_block_variables(struct compile_state *state,
16431 struct block *block)
16433 struct block_set *user;
16434 struct triple *next, *ptr;
16438 for(ptr = block->first; !done; ptr = next) {
16439 /* Be extremely careful I am deleting the list
16440 * as I walk trhough it.
16443 if (ptr == block->last) {
16446 if (triple_is_auto_var(state, ptr)) {
16447 struct triple_set *user, *next;
16448 for(user = ptr->use; user; user = next) {
16449 struct triple *use;
16451 use = user->member;
16452 if (MISC(ptr, 0) == user->member) {
16455 if (use->op != OP_PHI) {
16456 internal_error(state, use, "decl still used");
16458 if (MISC(use, 0) != ptr) {
16459 internal_error(state, use, "bad phi use of decl");
16461 unuse_triple(ptr, use);
16464 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16465 /* Delete the adecl */
16466 release_triple(state, MISC(ptr, 0));
16467 /* And the piece */
16468 release_triple(state, ptr);
16473 for(user = block->idominates; user; user = user->next) {
16474 prune_block_variables(state, user->member);
16478 struct phi_triple {
16479 struct triple *phi;
16484 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16486 struct triple **slot;
16488 if (live[phi->id].alive) {
16491 live[phi->id].alive = 1;
16493 slot = &RHS(phi, 0);
16494 for(i = 0; i < zrhs; i++) {
16495 struct triple *used;
16497 if (used && (used->op == OP_PHI)) {
16498 keep_phi(state, live, used);
16503 static void prune_unused_phis(struct compile_state *state)
16505 struct triple *first, *phi;
16506 struct phi_triple *live;
16509 /* Find the first instruction */
16510 first = state->first;
16512 /* Count how many phi functions I need to process */
16514 for(phi = first->next; phi != first; phi = phi->next) {
16515 if (phi->op == OP_PHI) {
16520 /* Mark them all dead */
16521 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16523 for(phi = first->next; phi != first; phi = phi->next) {
16524 if (phi->op != OP_PHI) {
16527 live[phis].alive = 0;
16528 live[phis].orig_id = phi->id;
16529 live[phis].phi = phi;
16534 /* Mark phis alive that are used by non phis */
16535 for(i = 0; i < phis; i++) {
16536 struct triple_set *set;
16537 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16538 if (set->member->op != OP_PHI) {
16539 keep_phi(state, live, live[i].phi);
16545 /* Delete the extraneous phis */
16546 for(i = 0; i < phis; i++) {
16547 struct triple **slot;
16549 if (!live[i].alive) {
16550 release_triple(state, live[i].phi);
16554 slot = &RHS(phi, 0);
16556 for(j = 0; j < zrhs; j++) {
16558 struct triple *unknown;
16559 get_occurance(phi->occurance);
16560 unknown = flatten(state, state->global_pool,
16561 alloc_triple(state, OP_UNKNOWNVAL,
16562 phi->type, 0, 0, phi->occurance));
16564 use_triple(unknown, phi);
16565 transform_to_arch_instruction(state, unknown);
16567 warning(state, phi, "variable not set at index %d on all paths to use", j);
16575 static void transform_to_ssa_form(struct compile_state *state)
16577 insert_phi_operations(state);
16578 rename_variables(state);
16580 prune_block_variables(state, state->bb.first_block);
16581 prune_unused_phis(state);
16583 print_blocks(state, __func__, state->dbgout);
16587 static void clear_vertex(
16588 struct compile_state *state, struct block *block, void *arg)
16590 /* Clear the current blocks vertex and the vertex of all
16591 * of the current blocks neighbors in case there are malformed
16592 * blocks with now instructions at this point.
16594 struct block_set *user, *edge;
16596 for(edge = block->edges; edge; edge = edge->next) {
16597 edge->member->vertex = 0;
16599 for(user = block->use; user; user = user->next) {
16600 user->member->vertex = 0;
16604 static void mark_live_block(
16605 struct compile_state *state, struct block *block, int *next_vertex)
16607 /* See if this is a block that has not been marked */
16608 if (block->vertex != 0) {
16611 block->vertex = *next_vertex;
16613 if (triple_is_branch(state, block->last)) {
16614 struct triple **targ;
16615 targ = triple_edge_targ(state, block->last, 0);
16616 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16620 if (!triple_stores_block(state, *targ)) {
16621 internal_error(state, 0, "bad targ");
16623 mark_live_block(state, (*targ)->u.block, next_vertex);
16625 /* Ensure the last block of a function remains alive */
16626 if (triple_is_call(state, block->last)) {
16627 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16630 else if (block->last->next != state->first) {
16631 struct triple *ins;
16632 ins = block->last->next;
16633 if (!triple_stores_block(state, ins)) {
16634 internal_error(state, 0, "bad block start");
16636 mark_live_block(state, ins->u.block, next_vertex);
16640 static void transform_from_ssa_form(struct compile_state *state)
16642 /* To get out of ssa form we insert moves on the incoming
16643 * edges to blocks containting phi functions.
16645 struct triple *first;
16646 struct triple *phi, *var, *next;
16649 /* Walk the control flow to see which blocks remain alive */
16650 walk_blocks(state, &state->bb, clear_vertex, 0);
16652 mark_live_block(state, state->bb.first_block, &next_vertex);
16654 /* Walk all of the operations to find the phi functions */
16655 first = state->first;
16656 for(phi = first->next; phi != first ; phi = next) {
16657 struct block_set *set;
16658 struct block *block;
16659 struct triple **slot;
16660 struct triple *var;
16661 struct triple_set *use, *use_next;
16662 int edge, writers, readers;
16664 if (phi->op != OP_PHI) {
16668 block = phi->u.block;
16669 slot = &RHS(phi, 0);
16671 /* If this phi is in a dead block just forget it */
16672 if (block->vertex == 0) {
16673 release_triple(state, phi);
16677 /* Forget uses from code in dead blocks */
16678 for(use = phi->use; use; use = use_next) {
16679 struct block *ublock;
16680 struct triple **expr;
16681 use_next = use->next;
16682 ublock = block_of_triple(state, use->member);
16683 if ((use->member == phi) || (ublock->vertex != 0)) {
16686 expr = triple_rhs(state, use->member, 0);
16687 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16688 if (*expr == phi) {
16692 unuse_triple(phi, use->member);
16694 /* A variable to replace the phi function */
16695 if (registers_of(state, phi->type) != 1) {
16696 internal_error(state, phi, "phi->type does not fit in a single register!");
16698 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16699 var = var->next; /* point at the var */
16701 /* Replaces use of phi with var */
16702 propogate_use(state, phi, var);
16704 /* Count the readers */
16706 for(use = var->use; use; use = use->next) {
16707 if (use->member != MISC(var, 0)) {
16712 /* Walk all of the incoming edges/blocks and insert moves.
16715 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16716 struct block *eblock, *vblock;
16717 struct triple *move;
16718 struct triple *val, *base;
16719 eblock = set->member;
16722 unuse_triple(val, phi);
16723 vblock = block_of_triple(state, val);
16725 /* If we don't have a value that belongs in an OP_WRITE
16728 if (!val || (val == &unknown_triple) || (val == phi)
16729 || (vblock && (vblock->vertex == 0))) {
16732 /* If the value should never occur error */
16734 internal_error(state, val, "no vblock?");
16738 /* If the value occurs in a dead block see if a replacement
16739 * block can be found.
16741 while(eblock && (eblock->vertex == 0)) {
16742 eblock = eblock->idom;
16744 /* If not continue on with the next value. */
16745 if (!eblock || (eblock->vertex == 0)) {
16749 /* If we have an empty incoming block ignore it. */
16750 if (!eblock->first) {
16751 internal_error(state, 0, "empty block?");
16754 /* Make certain the write is placed in the edge block... */
16755 /* Walk through the edge block backwards to find an
16756 * appropriate location for the OP_WRITE.
16758 for(base = eblock->last; base != eblock->first; base = base->prev) {
16759 struct triple **expr;
16760 if (base->op == OP_PIECE) {
16761 base = MISC(base, 0);
16763 if ((base == var) || (base == val)) {
16766 expr = triple_lhs(state, base, 0);
16767 for(; expr; expr = triple_lhs(state, base, expr)) {
16768 if ((*expr) == val) {
16772 expr = triple_rhs(state, base, 0);
16773 for(; expr; expr = triple_rhs(state, base, expr)) {
16774 if ((*expr) == var) {
16780 if (triple_is_branch(state, base)) {
16781 internal_error(state, base,
16782 "Could not insert write to phi");
16784 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16785 use_triple(val, move);
16786 use_triple(var, move);
16789 if (!writers && readers) {
16790 internal_error(state, var, "no value written to in use phi?");
16792 /* If var is not used free it */
16794 release_triple(state, MISC(var, 0));
16795 release_triple(state, var);
16797 /* Release the phi function */
16798 release_triple(state, phi);
16801 /* Walk all of the operations to find the adecls */
16802 for(var = first->next; var != first ; var = var->next) {
16803 struct triple_set *use, *use_next;
16804 if (!triple_is_auto_var(state, var)) {
16808 /* Walk through all of the rhs uses of var and
16809 * replace them with read of var.
16811 for(use = var->use; use; use = use_next) {
16812 struct triple *read, *user;
16813 struct triple **slot;
16815 use_next = use->next;
16816 user = use->member;
16818 /* Generate a read of var */
16819 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16820 use_triple(var, read);
16822 /* Find the rhs uses and see if they need to be replaced */
16825 slot = &RHS(user, 0);
16826 for(i = 0; i < zrhs; i++) {
16827 if (slot[i] == var) {
16832 /* If we did use it cleanup the uses */
16834 unuse_triple(var, user);
16835 use_triple(read, user);
16837 /* If we didn't use it release the extra triple */
16839 release_triple(state, read);
16845 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16846 FILE *fp = state->dbgout; \
16847 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16850 static void rebuild_ssa_form(struct compile_state *state)
16853 transform_from_ssa_form(state);
16855 state->bb.first = state->first;
16856 free_basic_blocks(state, &state->bb);
16857 analyze_basic_blocks(state, &state->bb);
16859 insert_phi_operations(state);
16861 rename_variables(state);
16864 prune_block_variables(state, state->bb.first_block);
16866 prune_unused_phis(state);
16872 * Register conflict resolution
16873 * =========================================================
16876 static struct reg_info find_def_color(
16877 struct compile_state *state, struct triple *def)
16879 struct triple_set *set;
16880 struct reg_info info;
16881 info.reg = REG_UNSET;
16883 if (!triple_is_def(state, def)) {
16886 info = arch_reg_lhs(state, def, 0);
16887 if (info.reg >= MAX_REGISTERS) {
16888 info.reg = REG_UNSET;
16890 for(set = def->use; set; set = set->next) {
16891 struct reg_info tinfo;
16893 i = find_rhs_use(state, set->member, def);
16897 tinfo = arch_reg_rhs(state, set->member, i);
16898 if (tinfo.reg >= MAX_REGISTERS) {
16899 tinfo.reg = REG_UNSET;
16901 if ((tinfo.reg != REG_UNSET) &&
16902 (info.reg != REG_UNSET) &&
16903 (tinfo.reg != info.reg)) {
16904 internal_error(state, def, "register conflict");
16906 if ((info.regcm & tinfo.regcm) == 0) {
16907 internal_error(state, def, "regcm conflict %x & %x == 0",
16908 info.regcm, tinfo.regcm);
16910 if (info.reg == REG_UNSET) {
16911 info.reg = tinfo.reg;
16913 info.regcm &= tinfo.regcm;
16915 if (info.reg >= MAX_REGISTERS) {
16916 internal_error(state, def, "register out of range");
16921 static struct reg_info find_lhs_pre_color(
16922 struct compile_state *state, struct triple *ins, int index)
16924 struct reg_info info;
16928 if (!zlhs && triple_is_def(state, ins)) {
16931 if (index >= zlhs) {
16932 internal_error(state, ins, "Bad lhs %d", index);
16934 info = arch_reg_lhs(state, ins, index);
16935 for(i = 0; i < zrhs; i++) {
16936 struct reg_info rinfo;
16937 rinfo = arch_reg_rhs(state, ins, i);
16938 if ((info.reg == rinfo.reg) &&
16939 (rinfo.reg >= MAX_REGISTERS)) {
16940 struct reg_info tinfo;
16941 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
16942 info.reg = tinfo.reg;
16943 info.regcm &= tinfo.regcm;
16947 if (info.reg >= MAX_REGISTERS) {
16948 info.reg = REG_UNSET;
16953 static struct reg_info find_rhs_post_color(
16954 struct compile_state *state, struct triple *ins, int index);
16956 static struct reg_info find_lhs_post_color(
16957 struct compile_state *state, struct triple *ins, int index)
16959 struct triple_set *set;
16960 struct reg_info info;
16961 struct triple *lhs;
16962 #if DEBUG_TRIPLE_COLOR
16963 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
16966 if ((index == 0) && triple_is_def(state, ins)) {
16969 else if (index < ins->lhs) {
16970 lhs = LHS(ins, index);
16973 internal_error(state, ins, "Bad lhs %d", index);
16976 info = arch_reg_lhs(state, ins, index);
16977 if (info.reg >= MAX_REGISTERS) {
16978 info.reg = REG_UNSET;
16980 for(set = lhs->use; set; set = set->next) {
16981 struct reg_info rinfo;
16982 struct triple *user;
16984 user = set->member;
16986 for(i = 0; i < zrhs; i++) {
16987 if (RHS(user, i) != lhs) {
16990 rinfo = find_rhs_post_color(state, user, i);
16991 if ((info.reg != REG_UNSET) &&
16992 (rinfo.reg != REG_UNSET) &&
16993 (info.reg != rinfo.reg)) {
16994 internal_error(state, ins, "register conflict");
16996 if ((info.regcm & rinfo.regcm) == 0) {
16997 internal_error(state, ins, "regcm conflict %x & %x == 0",
16998 info.regcm, rinfo.regcm);
17000 if (info.reg == REG_UNSET) {
17001 info.reg = rinfo.reg;
17003 info.regcm &= rinfo.regcm;
17006 #if DEBUG_TRIPLE_COLOR
17007 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17008 ins, index, info.reg, info.regcm);
17013 static struct reg_info find_rhs_post_color(
17014 struct compile_state *state, struct triple *ins, int index)
17016 struct reg_info info, rinfo;
17018 #if DEBUG_TRIPLE_COLOR
17019 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17022 rinfo = arch_reg_rhs(state, ins, index);
17024 if (!zlhs && triple_is_def(state, ins)) {
17028 if (info.reg >= MAX_REGISTERS) {
17029 info.reg = REG_UNSET;
17031 for(i = 0; i < zlhs; i++) {
17032 struct reg_info linfo;
17033 linfo = arch_reg_lhs(state, ins, i);
17034 if ((linfo.reg == rinfo.reg) &&
17035 (linfo.reg >= MAX_REGISTERS)) {
17036 struct reg_info tinfo;
17037 tinfo = find_lhs_post_color(state, ins, i);
17038 if (tinfo.reg >= MAX_REGISTERS) {
17039 tinfo.reg = REG_UNSET;
17041 info.regcm &= linfo.regcm;
17042 info.regcm &= tinfo.regcm;
17043 if (info.reg != REG_UNSET) {
17044 internal_error(state, ins, "register conflict");
17046 if (info.regcm == 0) {
17047 internal_error(state, ins, "regcm conflict");
17049 info.reg = tinfo.reg;
17052 #if DEBUG_TRIPLE_COLOR
17053 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17054 ins, index, info.reg, info.regcm);
17059 static struct reg_info find_lhs_color(
17060 struct compile_state *state, struct triple *ins, int index)
17062 struct reg_info pre, post, info;
17063 #if DEBUG_TRIPLE_COLOR
17064 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17067 pre = find_lhs_pre_color(state, ins, index);
17068 post = find_lhs_post_color(state, ins, index);
17069 if ((pre.reg != post.reg) &&
17070 (pre.reg != REG_UNSET) &&
17071 (post.reg != REG_UNSET)) {
17072 internal_error(state, ins, "register conflict");
17074 info.regcm = pre.regcm & post.regcm;
17075 info.reg = pre.reg;
17076 if (info.reg == REG_UNSET) {
17077 info.reg = post.reg;
17079 #if DEBUG_TRIPLE_COLOR
17080 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17081 ins, index, info.reg, info.regcm,
17082 pre.reg, pre.regcm, post.reg, post.regcm);
17087 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17089 struct triple_set *entry, *next;
17090 struct triple *out;
17091 struct reg_info info, rinfo;
17093 info = arch_reg_lhs(state, ins, 0);
17094 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17095 use_triple(RHS(out, 0), out);
17096 /* Get the users of ins to use out instead */
17097 for(entry = ins->use; entry; entry = next) {
17099 next = entry->next;
17100 if (entry->member == out) {
17103 i = find_rhs_use(state, entry->member, ins);
17107 rinfo = arch_reg_rhs(state, entry->member, i);
17108 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17111 replace_rhs_use(state, ins, out, entry->member);
17113 transform_to_arch_instruction(state, out);
17117 static struct triple *typed_pre_copy(
17118 struct compile_state *state, struct type *type, struct triple *ins, int index)
17120 /* Carefully insert enough operations so that I can
17121 * enter any operation with a GPR32.
17124 struct triple **expr;
17126 struct reg_info info;
17128 if (ins->op == OP_PHI) {
17129 internal_error(state, ins, "pre_copy on a phi?");
17131 classes = arch_type_to_regcm(state, type);
17132 info = arch_reg_rhs(state, ins, index);
17133 expr = &RHS(ins, index);
17134 if ((info.regcm & classes) == 0) {
17135 FILE *fp = state->errout;
17136 fprintf(fp, "src_type: ");
17137 name_of(fp, ins->type);
17138 fprintf(fp, "\ndst_type: ");
17141 internal_error(state, ins, "pre_copy with no register classes");
17144 if (!equiv_types(type, (*expr)->type)) {
17147 in = pre_triple(state, ins, op, type, *expr, 0);
17148 unuse_triple(*expr, ins);
17150 use_triple(RHS(in, 0), in);
17151 use_triple(in, ins);
17152 transform_to_arch_instruction(state, in);
17156 static struct triple *pre_copy(
17157 struct compile_state *state, struct triple *ins, int index)
17159 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17163 static void insert_copies_to_phi(struct compile_state *state)
17165 /* To get out of ssa form we insert moves on the incoming
17166 * edges to blocks containting phi functions.
17168 struct triple *first;
17169 struct triple *phi;
17171 /* Walk all of the operations to find the phi functions */
17172 first = state->first;
17173 for(phi = first->next; phi != first ; phi = phi->next) {
17174 struct block_set *set;
17175 struct block *block;
17176 struct triple **slot, *copy;
17178 if (phi->op != OP_PHI) {
17181 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17182 block = phi->u.block;
17183 slot = &RHS(phi, 0);
17184 /* Phi's that feed into mandatory live range joins
17185 * cause nasty complications. Insert a copy of
17186 * the phi value so I never have to deal with
17187 * that in the rest of the code.
17189 copy = post_copy(state, phi);
17190 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17191 /* Walk all of the incoming edges/blocks and insert moves.
17193 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17194 struct block *eblock;
17195 struct triple *move;
17196 struct triple *val;
17197 struct triple *ptr;
17198 eblock = set->member;
17205 get_occurance(val->occurance);
17206 move = build_triple(state, OP_COPY, val->type, val, 0,
17208 move->u.block = eblock;
17209 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17210 use_triple(val, move);
17213 unuse_triple(val, phi);
17214 use_triple(move, phi);
17216 /* Walk up the dominator tree until I have found the appropriate block */
17217 while(eblock && !tdominates(state, val, eblock->last)) {
17218 eblock = eblock->idom;
17221 internal_error(state, phi, "Cannot find block dominated by %p",
17225 /* Walk through the block backwards to find
17226 * an appropriate location for the OP_COPY.
17228 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17229 struct triple **expr;
17230 if (ptr->op == OP_PIECE) {
17231 ptr = MISC(ptr, 0);
17233 if ((ptr == phi) || (ptr == val)) {
17236 expr = triple_lhs(state, ptr, 0);
17237 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17238 if ((*expr) == val) {
17242 expr = triple_rhs(state, ptr, 0);
17243 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17244 if ((*expr) == phi) {
17250 if (triple_is_branch(state, ptr)) {
17251 internal_error(state, ptr,
17252 "Could not insert write to phi");
17254 insert_triple(state, after_lhs(state, ptr), move);
17255 if (eblock->last == after_lhs(state, ptr)->prev) {
17256 eblock->last = move;
17258 transform_to_arch_instruction(state, move);
17261 print_blocks(state, __func__, state->dbgout);
17264 struct triple_reg_set;
17268 static int do_triple_set(struct triple_reg_set **head,
17269 struct triple *member, struct triple *new_member)
17271 struct triple_reg_set **ptr, *new;
17276 if ((*ptr)->member == member) {
17279 ptr = &(*ptr)->next;
17281 new = xcmalloc(sizeof(*new), "triple_set");
17282 new->member = member;
17283 new->new = new_member;
17289 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17291 struct triple_reg_set *entry, **ptr;
17295 if (entry->member == member) {
17296 *ptr = entry->next;
17301 ptr = &entry->next;
17306 static int in_triple(struct reg_block *rb, struct triple *in)
17308 return do_triple_set(&rb->in, in, 0);
17310 static void unin_triple(struct reg_block *rb, struct triple *unin)
17312 do_triple_unset(&rb->in, unin);
17315 static int out_triple(struct reg_block *rb, struct triple *out)
17317 return do_triple_set(&rb->out, out, 0);
17319 static void unout_triple(struct reg_block *rb, struct triple *unout)
17321 do_triple_unset(&rb->out, unout);
17324 static int initialize_regblock(struct reg_block *blocks,
17325 struct block *block, int vertex)
17327 struct block_set *user;
17328 if (!block || (blocks[block->vertex].block == block)) {
17332 /* Renumber the blocks in a convinient fashion */
17333 block->vertex = vertex;
17334 blocks[vertex].block = block;
17335 blocks[vertex].vertex = vertex;
17336 for(user = block->use; user; user = user->next) {
17337 vertex = initialize_regblock(blocks, user->member, vertex);
17342 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17344 /* Part to piece is a best attempt and it cannot be correct all by
17345 * itself. If various values are read as different sizes in different
17346 * parts of the code this function cannot work. Or rather it cannot
17347 * work in conjunction with compute_variable_liftimes. As the
17348 * analysis will get confused.
17350 struct triple *base;
17352 if (!is_lvalue(state, ins)) {
17357 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17358 base = MISC(ins, 0);
17361 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17364 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17367 internal_error(state, ins, "unhandled part");
17373 if (reg > base->lhs) {
17374 internal_error(state, base, "part out of range?");
17376 ins = LHS(base, reg);
17381 static int this_def(struct compile_state *state,
17382 struct triple *ins, struct triple *other)
17384 if (ins == other) {
17387 if (ins->op == OP_WRITE) {
17388 ins = part_to_piece(state, MISC(ins, 0));
17390 return ins == other;
17393 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17394 struct reg_block *rb, struct block *suc)
17396 /* Read the conditional input set of a successor block
17397 * (i.e. the input to the phi nodes) and place it in the
17398 * current blocks output set.
17400 struct block_set *set;
17401 struct triple *ptr;
17405 /* Find the edge I am coming in on */
17406 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17407 if (set->member == rb->block) {
17412 internal_error(state, 0, "Not coming on a control edge?");
17414 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17415 struct triple **slot, *expr, *ptr2;
17416 int out_change, done2;
17417 done = (ptr == suc->last);
17418 if (ptr->op != OP_PHI) {
17421 slot = &RHS(ptr, 0);
17423 out_change = out_triple(rb, expr);
17427 /* If we don't define the variable also plast it
17428 * in the current blocks input set.
17430 ptr2 = rb->block->first;
17431 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17432 if (this_def(state, ptr2, expr)) {
17435 done2 = (ptr2 == rb->block->last);
17440 change |= in_triple(rb, expr);
17445 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17446 struct reg_block *rb, struct block *suc)
17448 struct triple_reg_set *in_set;
17451 /* Read the input set of a successor block
17452 * and place it in the current blocks output set.
17454 in_set = blocks[suc->vertex].in;
17455 for(; in_set; in_set = in_set->next) {
17456 int out_change, done;
17457 struct triple *first, *last, *ptr;
17458 out_change = out_triple(rb, in_set->member);
17462 /* If we don't define the variable also place it
17463 * in the current blocks input set.
17465 first = rb->block->first;
17466 last = rb->block->last;
17468 for(ptr = first; !done; ptr = ptr->next) {
17469 if (this_def(state, ptr, in_set->member)) {
17472 done = (ptr == last);
17477 change |= in_triple(rb, in_set->member);
17479 change |= phi_in(state, blocks, rb, suc);
17483 static int use_in(struct compile_state *state, struct reg_block *rb)
17485 /* Find the variables we use but don't define and add
17486 * it to the current blocks input set.
17488 #warning "FIXME is this O(N^2) algorithm bad?"
17489 struct block *block;
17490 struct triple *ptr;
17495 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17496 struct triple **expr;
17497 done = (ptr == block->first);
17498 /* The variable a phi function uses depends on the
17499 * control flow, and is handled in phi_in, not
17502 if (ptr->op == OP_PHI) {
17505 expr = triple_rhs(state, ptr, 0);
17506 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17507 struct triple *rhs, *test;
17509 rhs = part_to_piece(state, *expr);
17514 /* See if rhs is defined in this block.
17515 * A write counts as a definition.
17517 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17518 tdone = (test == block->first);
17519 if (this_def(state, test, rhs)) {
17524 /* If I still have a valid rhs add it to in */
17525 change |= in_triple(rb, rhs);
17531 static struct reg_block *compute_variable_lifetimes(
17532 struct compile_state *state, struct basic_blocks *bb)
17534 struct reg_block *blocks;
17537 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17538 initialize_regblock(blocks, bb->last_block, 0);
17542 for(i = 1; i <= bb->last_vertex; i++) {
17543 struct block_set *edge;
17544 struct reg_block *rb;
17546 /* Add the all successor's input set to in */
17547 for(edge = rb->block->edges; edge; edge = edge->next) {
17548 change |= reg_in(state, blocks, rb, edge->member);
17550 /* Add use to in... */
17551 change |= use_in(state, rb);
17557 static void free_variable_lifetimes(struct compile_state *state,
17558 struct basic_blocks *bb, struct reg_block *blocks)
17561 /* free in_set && out_set on each block */
17562 for(i = 1; i <= bb->last_vertex; i++) {
17563 struct triple_reg_set *entry, *next;
17564 struct reg_block *rb;
17566 for(entry = rb->in; entry ; entry = next) {
17567 next = entry->next;
17568 do_triple_unset(&rb->in, entry->member);
17570 for(entry = rb->out; entry; entry = next) {
17571 next = entry->next;
17572 do_triple_unset(&rb->out, entry->member);
17579 typedef void (*wvl_cb_t)(
17580 struct compile_state *state,
17581 struct reg_block *blocks, struct triple_reg_set *live,
17582 struct reg_block *rb, struct triple *ins, void *arg);
17584 static void walk_variable_lifetimes(struct compile_state *state,
17585 struct basic_blocks *bb, struct reg_block *blocks,
17586 wvl_cb_t cb, void *arg)
17590 for(i = 1; i <= state->bb.last_vertex; i++) {
17591 struct triple_reg_set *live;
17592 struct triple_reg_set *entry, *next;
17593 struct triple *ptr, *prev;
17594 struct reg_block *rb;
17595 struct block *block;
17598 /* Get the blocks */
17602 /* Copy out into live */
17604 for(entry = rb->out; entry; entry = next) {
17605 next = entry->next;
17606 do_triple_set(&live, entry->member, entry->new);
17608 /* Walk through the basic block calculating live */
17609 for(done = 0, ptr = block->last; !done; ptr = prev) {
17610 struct triple **expr;
17613 done = (ptr == block->first);
17615 /* Ensure the current definition is in live */
17616 if (triple_is_def(state, ptr)) {
17617 do_triple_set(&live, ptr, 0);
17620 /* Inform the callback function of what is
17623 cb(state, blocks, live, rb, ptr, arg);
17625 /* Remove the current definition from live */
17626 do_triple_unset(&live, ptr);
17628 /* Add the current uses to live.
17630 * It is safe to skip phi functions because they do
17631 * not have any block local uses, and the block
17632 * output sets already properly account for what
17633 * control flow depedent uses phi functions do have.
17635 if (ptr->op == OP_PHI) {
17638 expr = triple_rhs(state, ptr, 0);
17639 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17640 /* If the triple is not a definition skip it. */
17641 if (!*expr || !triple_is_def(state, *expr)) {
17644 do_triple_set(&live, *expr, 0);
17648 for(entry = live; entry; entry = next) {
17649 next = entry->next;
17650 do_triple_unset(&live, entry->member);
17655 struct print_live_variable_info {
17656 struct reg_block *rb;
17659 static void print_live_variables_block(
17660 struct compile_state *state, struct block *block, void *arg)
17663 struct print_live_variable_info *info = arg;
17664 struct block_set *edge;
17665 FILE *fp = info->fp;
17666 struct reg_block *rb;
17667 struct triple *ptr;
17670 rb = &info->rb[block->vertex];
17672 fprintf(fp, "\nblock: %p (%d),",
17673 block, block->vertex);
17674 for(edge = block->edges; edge; edge = edge->next) {
17675 fprintf(fp, " %p<-%p",
17677 edge->member && edge->member->use?edge->member->use->member : 0);
17681 struct triple_reg_set *in_set;
17682 fprintf(fp, " in:");
17683 for(in_set = rb->in; in_set; in_set = in_set->next) {
17684 fprintf(fp, " %-10p", in_set->member);
17689 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17690 done = (ptr == block->last);
17691 if (ptr->op == OP_PHI) {
17698 for(edge = 0; edge < block->users; edge++) {
17699 fprintf(fp, " in(%d):", edge);
17700 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17701 struct triple **slot;
17702 done = (ptr == block->last);
17703 if (ptr->op != OP_PHI) {
17706 slot = &RHS(ptr, 0);
17707 fprintf(fp, " %-10p", slot[edge]);
17712 if (block->first->op == OP_LABEL) {
17713 fprintf(fp, "%p:\n", block->first);
17715 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17716 done = (ptr == block->last);
17717 display_triple(fp, ptr);
17720 struct triple_reg_set *out_set;
17721 fprintf(fp, " out:");
17722 for(out_set = rb->out; out_set; out_set = out_set->next) {
17723 fprintf(fp, " %-10p", out_set->member);
17730 static void print_live_variables(struct compile_state *state,
17731 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17733 struct print_live_variable_info info;
17736 fprintf(fp, "\nlive variables by block\n");
17737 walk_blocks(state, bb, print_live_variables_block, &info);
17742 static int count_triples(struct compile_state *state)
17744 struct triple *first, *ins;
17746 first = state->first;
17751 } while (ins != first);
17756 struct dead_triple {
17757 struct triple *triple;
17758 struct dead_triple *work_next;
17759 struct block *block;
17762 #define TRIPLE_FLAG_ALIVE 1
17763 #define TRIPLE_FLAG_FREE 1
17766 static void print_dead_triples(struct compile_state *state,
17767 struct dead_triple *dtriple)
17769 struct triple *first, *ins;
17770 struct dead_triple *dt;
17772 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17775 fp = state->dbgout;
17776 fprintf(fp, "--------------- dtriples ---------------\n");
17777 first = state->first;
17780 dt = &dtriple[ins->id];
17781 if ((ins->op == OP_LABEL) && (ins->use)) {
17782 fprintf(fp, "\n%p:\n", ins);
17785 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17786 display_triple(fp, ins);
17787 if (triple_is_branch(state, ins)) {
17791 } while(ins != first);
17796 static void awaken(
17797 struct compile_state *state,
17798 struct dead_triple *dtriple, struct triple **expr,
17799 struct dead_triple ***work_list_tail)
17801 struct triple *triple;
17802 struct dead_triple *dt;
17810 if (triple->id <= 0) {
17811 internal_error(state, triple, "bad triple id: %d",
17814 if (triple->op == OP_NOOP) {
17815 internal_error(state, triple, "awakening noop?");
17818 dt = &dtriple[triple->id];
17819 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17820 dt->flags |= TRIPLE_FLAG_ALIVE;
17821 if (!dt->work_next) {
17822 **work_list_tail = dt;
17823 *work_list_tail = &dt->work_next;
17828 static void eliminate_inefectual_code(struct compile_state *state)
17830 struct block *block;
17831 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17833 struct triple *first, *final, *ins;
17835 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17839 /* Setup the work list */
17841 work_list_tail = &work_list;
17843 first = state->first;
17844 final = state->first->prev;
17846 /* Count how many triples I have */
17847 triples = count_triples(state);
17849 /* Now put then in an array and mark all of the triples dead */
17850 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17856 dtriple[i].triple = ins;
17857 dtriple[i].block = block_of_triple(state, ins);
17858 dtriple[i].flags = 0;
17859 dtriple[i].old_id = ins->id;
17861 /* See if it is an operation we always keep */
17862 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17863 awaken(state, dtriple, &ins, &work_list_tail);
17867 } while(ins != first);
17869 struct block *block;
17870 struct dead_triple *dt;
17871 struct block_set *user;
17872 struct triple **expr;
17874 work_list = dt->work_next;
17876 work_list_tail = &work_list;
17878 /* Make certain the block the current instruction is in lives */
17879 block = block_of_triple(state, dt->triple);
17880 awaken(state, dtriple, &block->first, &work_list_tail);
17881 if (triple_is_branch(state, block->last)) {
17882 awaken(state, dtriple, &block->last, &work_list_tail);
17884 awaken(state, dtriple, &block->last->next, &work_list_tail);
17887 /* Wake up the data depencencies of this triple */
17890 expr = triple_rhs(state, dt->triple, expr);
17891 awaken(state, dtriple, expr, &work_list_tail);
17894 expr = triple_lhs(state, dt->triple, expr);
17895 awaken(state, dtriple, expr, &work_list_tail);
17898 expr = triple_misc(state, dt->triple, expr);
17899 awaken(state, dtriple, expr, &work_list_tail);
17901 /* Wake up the forward control dependencies */
17903 expr = triple_targ(state, dt->triple, expr);
17904 awaken(state, dtriple, expr, &work_list_tail);
17906 /* Wake up the reverse control dependencies of this triple */
17907 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17908 struct triple *last;
17909 last = user->member->last;
17910 while((last->op == OP_NOOP) && (last != user->member->first)) {
17911 internal_warning(state, last, "awakening noop?");
17914 awaken(state, dtriple, &last, &work_list_tail);
17917 print_dead_triples(state, dtriple);
17918 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17919 if ((dt->triple->op == OP_NOOP) &&
17920 (dt->flags & TRIPLE_FLAG_ALIVE)) {
17921 internal_error(state, dt->triple, "noop effective?");
17923 dt->triple->id = dt->old_id; /* Restore the color */
17924 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17925 release_triple(state, dt->triple);
17930 rebuild_ssa_form(state);
17932 print_blocks(state, __func__, state->dbgout);
17936 static void insert_mandatory_copies(struct compile_state *state)
17938 struct triple *ins, *first;
17940 /* The object is with a minimum of inserted copies,
17941 * to resolve in fundamental register conflicts between
17942 * register value producers and consumers.
17943 * Theoretically we may be greater than minimal when we
17944 * are inserting copies before instructions but that
17945 * case should be rare.
17947 first = state->first;
17950 struct triple_set *entry, *next;
17951 struct triple *tmp;
17952 struct reg_info info;
17953 unsigned reg, regcm;
17954 int do_post_copy, do_pre_copy;
17956 if (!triple_is_def(state, ins)) {
17959 /* Find the architecture specific color information */
17960 info = find_lhs_pre_color(state, ins, 0);
17961 if (info.reg >= MAX_REGISTERS) {
17962 info.reg = REG_UNSET;
17966 regcm = arch_type_to_regcm(state, ins->type);
17967 do_post_copy = do_pre_copy = 0;
17969 /* Walk through the uses of ins and check for conflicts */
17970 for(entry = ins->use; entry; entry = next) {
17971 struct reg_info rinfo;
17973 next = entry->next;
17974 i = find_rhs_use(state, entry->member, ins);
17979 /* Find the users color requirements */
17980 rinfo = arch_reg_rhs(state, entry->member, i);
17981 if (rinfo.reg >= MAX_REGISTERS) {
17982 rinfo.reg = REG_UNSET;
17985 /* See if I need a pre_copy */
17986 if (rinfo.reg != REG_UNSET) {
17987 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
17992 regcm &= rinfo.regcm;
17993 regcm = arch_regcm_normalize(state, regcm);
17997 /* Always use pre_copies for constants.
17998 * They do not take up any registers until a
17999 * copy places them in one.
18001 if ((info.reg == REG_UNNEEDED) &&
18002 (rinfo.reg != REG_UNNEEDED)) {
18008 (((info.reg != REG_UNSET) &&
18009 (reg != REG_UNSET) &&
18010 (info.reg != reg)) ||
18011 ((info.regcm & regcm) == 0));
18014 regcm = info.regcm;
18015 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18016 for(entry = ins->use; entry; entry = next) {
18017 struct reg_info rinfo;
18019 next = entry->next;
18020 i = find_rhs_use(state, entry->member, ins);
18025 /* Find the users color requirements */
18026 rinfo = arch_reg_rhs(state, entry->member, i);
18027 if (rinfo.reg >= MAX_REGISTERS) {
18028 rinfo.reg = REG_UNSET;
18031 /* Now see if it is time to do the pre_copy */
18032 if (rinfo.reg != REG_UNSET) {
18033 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18034 ((regcm & rinfo.regcm) == 0) ||
18035 /* Don't let a mandatory coalesce sneak
18036 * into a operation that is marked to prevent
18039 ((reg != REG_UNNEEDED) &&
18040 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18041 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18044 struct triple *user;
18045 user = entry->member;
18046 if (RHS(user, i) != ins) {
18047 internal_error(state, user, "bad rhs");
18049 tmp = pre_copy(state, user, i);
18050 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18058 if ((regcm & rinfo.regcm) == 0) {
18060 struct triple *user;
18061 user = entry->member;
18062 if (RHS(user, i) != ins) {
18063 internal_error(state, user, "bad rhs");
18065 tmp = pre_copy(state, user, i);
18066 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18072 regcm &= rinfo.regcm;
18075 if (do_post_copy) {
18076 struct reg_info pre, post;
18077 tmp = post_copy(state, ins);
18078 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18079 pre = arch_reg_lhs(state, ins, 0);
18080 post = arch_reg_lhs(state, tmp, 0);
18081 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18082 internal_error(state, tmp, "useless copy");
18087 } while(ins != first);
18089 print_blocks(state, __func__, state->dbgout);
18093 struct live_range_edge;
18094 struct live_range_def;
18095 struct live_range {
18096 struct live_range_edge *edges;
18097 struct live_range_def *defs;
18098 /* Note. The list pointed to by defs is kept in order.
18099 * That is baring splits in the flow control
18100 * defs dominates defs->next wich dominates defs->next->next
18107 struct live_range *group_next, **group_prev;
18110 struct live_range_edge {
18111 struct live_range_edge *next;
18112 struct live_range *node;
18115 struct live_range_def {
18116 struct live_range_def *next;
18117 struct live_range_def *prev;
18118 struct live_range *lr;
18119 struct triple *def;
18123 #define LRE_HASH_SIZE 2048
18125 struct lre_hash *next;
18126 struct live_range *left;
18127 struct live_range *right;
18132 struct lre_hash *hash[LRE_HASH_SIZE];
18133 struct reg_block *blocks;
18134 struct live_range_def *lrd;
18135 struct live_range *lr;
18136 struct live_range *low, **low_tail;
18137 struct live_range *high, **high_tail;
18140 int passes, max_passes;
18144 struct print_interference_block_info {
18145 struct reg_state *rstate;
18149 static void print_interference_block(
18150 struct compile_state *state, struct block *block, void *arg)
18153 struct print_interference_block_info *info = arg;
18154 struct reg_state *rstate = info->rstate;
18155 struct block_set *edge;
18156 FILE *fp = info->fp;
18157 struct reg_block *rb;
18158 struct triple *ptr;
18161 rb = &rstate->blocks[block->vertex];
18163 fprintf(fp, "\nblock: %p (%d),",
18164 block, block->vertex);
18165 for(edge = block->edges; edge; edge = edge->next) {
18166 fprintf(fp, " %p<-%p",
18168 edge->member && edge->member->use?edge->member->use->member : 0);
18172 struct triple_reg_set *in_set;
18173 fprintf(fp, " in:");
18174 for(in_set = rb->in; in_set; in_set = in_set->next) {
18175 fprintf(fp, " %-10p", in_set->member);
18180 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18181 done = (ptr == block->last);
18182 if (ptr->op == OP_PHI) {
18189 for(edge = 0; edge < block->users; edge++) {
18190 fprintf(fp, " in(%d):", edge);
18191 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18192 struct triple **slot;
18193 done = (ptr == block->last);
18194 if (ptr->op != OP_PHI) {
18197 slot = &RHS(ptr, 0);
18198 fprintf(fp, " %-10p", slot[edge]);
18203 if (block->first->op == OP_LABEL) {
18204 fprintf(fp, "%p:\n", block->first);
18206 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18207 struct live_range *lr;
18211 done = (ptr == block->last);
18212 lr = rstate->lrd[ptr->id].lr;
18215 ptr->id = rstate->lrd[id].orig_id;
18216 SET_REG(ptr->id, lr->color);
18217 display_triple(fp, ptr);
18220 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18221 internal_error(state, ptr, "lr has no defs!");
18223 if (info->need_edges) {
18225 struct live_range_def *lrd;
18226 fprintf(fp, " range:");
18229 fprintf(fp, " %-10p", lrd->def);
18231 } while(lrd != lr->defs);
18234 if (lr->edges > 0) {
18235 struct live_range_edge *edge;
18236 fprintf(fp, " edges:");
18237 for(edge = lr->edges; edge; edge = edge->next) {
18238 struct live_range_def *lrd;
18239 lrd = edge->node->defs;
18241 fprintf(fp, " %-10p", lrd->def);
18243 } while(lrd != edge->node->defs);
18249 /* Do a bunch of sanity checks */
18250 valid_ins(state, ptr);
18251 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18252 internal_error(state, ptr, "Invalid triple id: %d",
18257 struct triple_reg_set *out_set;
18258 fprintf(fp, " out:");
18259 for(out_set = rb->out; out_set; out_set = out_set->next) {
18260 fprintf(fp, " %-10p", out_set->member);
18267 static void print_interference_blocks(
18268 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18270 struct print_interference_block_info info;
18271 info.rstate = rstate;
18273 info.need_edges = need_edges;
18274 fprintf(fp, "\nlive variables by block\n");
18275 walk_blocks(state, &state->bb, print_interference_block, &info);
18279 static unsigned regc_max_size(struct compile_state *state, int classes)
18284 for(i = 0; i < MAX_REGC; i++) {
18285 if (classes & (1 << i)) {
18287 size = arch_regc_size(state, i);
18288 if (size > max_size) {
18296 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18298 unsigned equivs[MAX_REG_EQUIVS];
18300 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18301 internal_error(state, 0, "invalid register");
18303 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18304 internal_error(state, 0, "invalid register");
18306 arch_reg_equivs(state, equivs, reg1);
18307 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18308 if (equivs[i] == reg2) {
18315 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18317 unsigned equivs[MAX_REG_EQUIVS];
18319 if (reg == REG_UNNEEDED) {
18322 arch_reg_equivs(state, equivs, reg);
18323 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18324 used[equivs[i]] = 1;
18329 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18331 unsigned equivs[MAX_REG_EQUIVS];
18333 if (reg == REG_UNNEEDED) {
18336 arch_reg_equivs(state, equivs, reg);
18337 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18338 used[equivs[i]] += 1;
18343 static unsigned int hash_live_edge(
18344 struct live_range *left, struct live_range *right)
18346 unsigned int hash, val;
18347 unsigned long lval, rval;
18348 lval = ((unsigned long)left)/sizeof(struct live_range);
18349 rval = ((unsigned long)right)/sizeof(struct live_range);
18354 hash = (hash *263) + val;
18359 hash = (hash *263) + val;
18361 hash = hash & (LRE_HASH_SIZE - 1);
18365 static struct lre_hash **lre_probe(struct reg_state *rstate,
18366 struct live_range *left, struct live_range *right)
18368 struct lre_hash **ptr;
18369 unsigned int index;
18370 /* Ensure left <= right */
18371 if (left > right) {
18372 struct live_range *tmp;
18377 index = hash_live_edge(left, right);
18379 ptr = &rstate->hash[index];
18381 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18384 ptr = &(*ptr)->next;
18389 static int interfere(struct reg_state *rstate,
18390 struct live_range *left, struct live_range *right)
18392 struct lre_hash **ptr;
18393 ptr = lre_probe(rstate, left, right);
18394 return ptr && *ptr;
18397 static void add_live_edge(struct reg_state *rstate,
18398 struct live_range *left, struct live_range *right)
18400 /* FIXME the memory allocation overhead is noticeable here... */
18401 struct lre_hash **ptr, *new_hash;
18402 struct live_range_edge *edge;
18404 if (left == right) {
18407 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18410 /* Ensure left <= right */
18411 if (left > right) {
18412 struct live_range *tmp;
18417 ptr = lre_probe(rstate, left, right);
18422 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18425 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18426 new_hash->next = *ptr;
18427 new_hash->left = left;
18428 new_hash->right = right;
18431 edge = xmalloc(sizeof(*edge), "live_range_edge");
18432 edge->next = left->edges;
18433 edge->node = right;
18434 left->edges = edge;
18437 edge = xmalloc(sizeof(*edge), "live_range_edge");
18438 edge->next = right->edges;
18440 right->edges = edge;
18441 right->degree += 1;
18444 static void remove_live_edge(struct reg_state *rstate,
18445 struct live_range *left, struct live_range *right)
18447 struct live_range_edge *edge, **ptr;
18448 struct lre_hash **hptr, *entry;
18449 hptr = lre_probe(rstate, left, right);
18450 if (!hptr || !*hptr) {
18454 *hptr = entry->next;
18457 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18459 if (edge->node == right) {
18461 memset(edge, 0, sizeof(*edge));
18467 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18469 if (edge->node == left) {
18471 memset(edge, 0, sizeof(*edge));
18479 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18481 struct live_range_edge *edge, *next;
18482 for(edge = range->edges; edge; edge = next) {
18484 remove_live_edge(rstate, range, edge->node);
18488 static void transfer_live_edges(struct reg_state *rstate,
18489 struct live_range *dest, struct live_range *src)
18491 struct live_range_edge *edge, *next;
18492 for(edge = src->edges; edge; edge = next) {
18493 struct live_range *other;
18495 other = edge->node;
18496 remove_live_edge(rstate, src, other);
18497 add_live_edge(rstate, dest, other);
18502 /* Interference graph...
18504 * new(n) --- Return a graph with n nodes but no edges.
18505 * add(g,x,y) --- Return a graph including g with an between x and y
18506 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18507 * x and y in the graph g
18508 * degree(g, x) --- Return the degree of the node x in the graph g
18509 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18511 * Implement with a hash table && a set of adjcency vectors.
18512 * The hash table supports constant time implementations of add and interfere.
18513 * The adjacency vectors support an efficient implementation of neighbors.
18517 * +---------------------------------------------------+
18518 * | +--------------+ |
18520 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18522 * -- In simplify implment optimistic coloring... (No backtracking)
18523 * -- Implement Rematerialization it is the only form of spilling we can perform
18524 * Essentially this means dropping a constant from a register because
18525 * we can regenerate it later.
18527 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18528 * coalesce at phi points...
18529 * --- Bias coloring if at all possible do the coalesing a compile time.
18534 static void different_colored(
18535 struct compile_state *state, struct reg_state *rstate,
18536 struct triple *parent, struct triple *ins)
18538 struct live_range *lr;
18539 struct triple **expr;
18540 lr = rstate->lrd[ins->id].lr;
18541 expr = triple_rhs(state, ins, 0);
18542 for(;expr; expr = triple_rhs(state, ins, expr)) {
18543 struct live_range *lr2;
18544 if (!*expr || (*expr == parent) || (*expr == ins)) {
18547 lr2 = rstate->lrd[(*expr)->id].lr;
18548 if (lr->color == lr2->color) {
18549 internal_error(state, ins, "live range too big");
18555 static struct live_range *coalesce_ranges(
18556 struct compile_state *state, struct reg_state *rstate,
18557 struct live_range *lr1, struct live_range *lr2)
18559 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18565 if (!lr1->defs || !lr2->defs) {
18566 internal_error(state, 0,
18567 "cannot coalese dead live ranges");
18569 if ((lr1->color == REG_UNNEEDED) ||
18570 (lr2->color == REG_UNNEEDED)) {
18571 internal_error(state, 0,
18572 "cannot coalesce live ranges without a possible color");
18574 if ((lr1->color != lr2->color) &&
18575 (lr1->color != REG_UNSET) &&
18576 (lr2->color != REG_UNSET)) {
18577 internal_error(state, lr1->defs->def,
18578 "cannot coalesce live ranges of different colors");
18580 color = lr1->color;
18581 if (color == REG_UNSET) {
18582 color = lr2->color;
18584 classes = lr1->classes & lr2->classes;
18586 internal_error(state, lr1->defs->def,
18587 "cannot coalesce live ranges with dissimilar register classes");
18589 if (state->compiler->debug & DEBUG_COALESCING) {
18590 FILE *fp = state->errout;
18591 fprintf(fp, "coalescing:");
18594 fprintf(fp, " %p", lrd->def);
18596 } while(lrd != lr1->defs);
18600 fprintf(fp, " %p", lrd->def);
18602 } while(lrd != lr2->defs);
18605 /* If there is a clear dominate live range put it in lr1,
18606 * For purposes of this test phi functions are
18607 * considered dominated by the definitions that feed into
18610 if ((lr1->defs->prev->def->op == OP_PHI) ||
18611 ((lr2->defs->prev->def->op != OP_PHI) &&
18612 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18613 struct live_range *tmp;
18619 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18620 fprintf(state->errout, "lr1 post\n");
18622 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18623 fprintf(state->errout, "lr1 pre\n");
18625 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18626 fprintf(state->errout, "lr2 post\n");
18628 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18629 fprintf(state->errout, "lr2 pre\n");
18633 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18640 /* Append lr2 onto lr1 */
18641 #warning "FIXME should this be a merge instead of a splice?"
18642 /* This FIXME item applies to the correctness of live_range_end
18643 * and to the necessity of making multiple passes of coalesce_live_ranges.
18644 * A failure to find some coalesce opportunities in coaleace_live_ranges
18645 * does not impact the correct of the compiler just the efficiency with
18646 * which registers are allocated.
18649 mid1 = lr1->defs->prev;
18651 end = lr2->defs->prev;
18659 /* Fixup the live range in the added live range defs */
18664 } while(lrd != head);
18666 /* Mark lr2 as free. */
18668 lr2->color = REG_UNNEEDED;
18672 internal_error(state, 0, "lr1->defs == 0 ?");
18675 lr1->color = color;
18676 lr1->classes = classes;
18678 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18679 transfer_live_edges(rstate, lr1, lr2);
18684 static struct live_range_def *live_range_head(
18685 struct compile_state *state, struct live_range *lr,
18686 struct live_range_def *last)
18688 struct live_range_def *result;
18693 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18694 result = last->next;
18699 static struct live_range_def *live_range_end(
18700 struct compile_state *state, struct live_range *lr,
18701 struct live_range_def *last)
18703 struct live_range_def *result;
18706 result = lr->defs->prev;
18708 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18709 result = last->prev;
18715 static void initialize_live_ranges(
18716 struct compile_state *state, struct reg_state *rstate)
18718 struct triple *ins, *first;
18719 size_t count, size;
18722 first = state->first;
18723 /* First count how many instructions I have.
18725 count = count_triples(state);
18726 /* Potentially I need one live range definitions for each
18729 rstate->defs = count;
18730 /* Potentially I need one live range for each instruction
18731 * plus an extra for the dummy live range.
18733 rstate->ranges = count + 1;
18734 size = sizeof(rstate->lrd[0]) * rstate->defs;
18735 rstate->lrd = xcmalloc(size, "live_range_def");
18736 size = sizeof(rstate->lr[0]) * rstate->ranges;
18737 rstate->lr = xcmalloc(size, "live_range");
18739 /* Setup the dummy live range */
18740 rstate->lr[0].classes = 0;
18741 rstate->lr[0].color = REG_UNSET;
18742 rstate->lr[0].defs = 0;
18746 /* If the triple is a variable give it a live range */
18747 if (triple_is_def(state, ins)) {
18748 struct reg_info info;
18749 /* Find the architecture specific color information */
18750 info = find_def_color(state, ins);
18752 rstate->lr[i].defs = &rstate->lrd[j];
18753 rstate->lr[i].color = info.reg;
18754 rstate->lr[i].classes = info.regcm;
18755 rstate->lr[i].degree = 0;
18756 rstate->lrd[j].lr = &rstate->lr[i];
18758 /* Otherwise give the triple the dummy live range. */
18760 rstate->lrd[j].lr = &rstate->lr[0];
18763 /* Initalize the live_range_def */
18764 rstate->lrd[j].next = &rstate->lrd[j];
18765 rstate->lrd[j].prev = &rstate->lrd[j];
18766 rstate->lrd[j].def = ins;
18767 rstate->lrd[j].orig_id = ins->id;
18772 } while(ins != first);
18773 rstate->ranges = i;
18775 /* Make a second pass to handle achitecture specific register
18780 int zlhs, zrhs, i, j;
18781 if (ins->id > rstate->defs) {
18782 internal_error(state, ins, "bad id");
18785 /* Walk through the template of ins and coalesce live ranges */
18787 if ((zlhs == 0) && triple_is_def(state, ins)) {
18792 if (state->compiler->debug & DEBUG_COALESCING2) {
18793 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18797 for(i = 0; i < zlhs; i++) {
18798 struct reg_info linfo;
18799 struct live_range_def *lhs;
18800 linfo = arch_reg_lhs(state, ins, i);
18801 if (linfo.reg < MAX_REGISTERS) {
18804 if (triple_is_def(state, ins)) {
18805 lhs = &rstate->lrd[ins->id];
18807 lhs = &rstate->lrd[LHS(ins, i)->id];
18810 if (state->compiler->debug & DEBUG_COALESCING2) {
18811 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18812 i, lhs, linfo.reg);
18815 for(j = 0; j < zrhs; j++) {
18816 struct reg_info rinfo;
18817 struct live_range_def *rhs;
18818 rinfo = arch_reg_rhs(state, ins, j);
18819 if (rinfo.reg < MAX_REGISTERS) {
18822 rhs = &rstate->lrd[RHS(ins, j)->id];
18824 if (state->compiler->debug & DEBUG_COALESCING2) {
18825 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18826 j, rhs, rinfo.reg);
18829 if (rinfo.reg == linfo.reg) {
18830 coalesce_ranges(state, rstate,
18836 } while(ins != first);
18839 static void graph_ins(
18840 struct compile_state *state,
18841 struct reg_block *blocks, struct triple_reg_set *live,
18842 struct reg_block *rb, struct triple *ins, void *arg)
18844 struct reg_state *rstate = arg;
18845 struct live_range *def;
18846 struct triple_reg_set *entry;
18848 /* If the triple is not a definition
18849 * we do not have a definition to add to
18850 * the interference graph.
18852 if (!triple_is_def(state, ins)) {
18855 def = rstate->lrd[ins->id].lr;
18857 /* Create an edge between ins and everything that is
18858 * alive, unless the live_range cannot share
18859 * a physical register with ins.
18861 for(entry = live; entry; entry = entry->next) {
18862 struct live_range *lr;
18863 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18864 internal_error(state, 0, "bad entry?");
18866 lr = rstate->lrd[entry->member->id].lr;
18870 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18873 add_live_edge(rstate, def, lr);
18878 static struct live_range *get_verify_live_range(
18879 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18881 struct live_range *lr;
18882 struct live_range_def *lrd;
18884 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18885 internal_error(state, ins, "bad ins?");
18887 lr = rstate->lrd[ins->id].lr;
18891 if (lrd->def == ins) {
18895 } while(lrd != lr->defs);
18897 internal_error(state, ins, "ins not in live range");
18902 static void verify_graph_ins(
18903 struct compile_state *state,
18904 struct reg_block *blocks, struct triple_reg_set *live,
18905 struct reg_block *rb, struct triple *ins, void *arg)
18907 struct reg_state *rstate = arg;
18908 struct triple_reg_set *entry1, *entry2;
18911 /* Compare live against edges and make certain the code is working */
18912 for(entry1 = live; entry1; entry1 = entry1->next) {
18913 struct live_range *lr1;
18914 lr1 = get_verify_live_range(state, rstate, entry1->member);
18915 for(entry2 = live; entry2; entry2 = entry2->next) {
18916 struct live_range *lr2;
18917 struct live_range_edge *edge2;
18920 if (entry2 == entry1) {
18923 lr2 = get_verify_live_range(state, rstate, entry2->member);
18925 internal_error(state, entry2->member,
18926 "live range with 2 values simultaneously alive");
18928 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
18931 if (!interfere(rstate, lr1, lr2)) {
18932 internal_error(state, entry2->member,
18933 "edges don't interfere?");
18938 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
18940 if (edge2->node == lr1) {
18944 if (lr2_degree != lr2->degree) {
18945 internal_error(state, entry2->member,
18946 "computed degree: %d does not match reported degree: %d\n",
18947 lr2_degree, lr2->degree);
18950 internal_error(state, entry2->member, "missing edge");
18958 static void print_interference_ins(
18959 struct compile_state *state,
18960 struct reg_block *blocks, struct triple_reg_set *live,
18961 struct reg_block *rb, struct triple *ins, void *arg)
18963 struct reg_state *rstate = arg;
18964 struct live_range *lr;
18966 FILE *fp = state->dbgout;
18968 lr = rstate->lrd[ins->id].lr;
18970 ins->id = rstate->lrd[id].orig_id;
18971 SET_REG(ins->id, lr->color);
18972 display_triple(state->dbgout, ins);
18976 struct live_range_def *lrd;
18977 fprintf(fp, " range:");
18980 fprintf(fp, " %-10p", lrd->def);
18982 } while(lrd != lr->defs);
18986 struct triple_reg_set *entry;
18987 fprintf(fp, " live:");
18988 for(entry = live; entry; entry = entry->next) {
18989 fprintf(fp, " %-10p", entry->member);
18994 struct live_range_edge *entry;
18995 fprintf(fp, " edges:");
18996 for(entry = lr->edges; entry; entry = entry->next) {
18997 struct live_range_def *lrd;
18998 lrd = entry->node->defs;
19000 fprintf(fp, " %-10p", lrd->def);
19002 } while(lrd != entry->node->defs);
19007 if (triple_is_branch(state, ins)) {
19013 static int coalesce_live_ranges(
19014 struct compile_state *state, struct reg_state *rstate)
19016 /* At the point where a value is moved from one
19017 * register to another that value requires two
19018 * registers, thus increasing register pressure.
19019 * Live range coaleescing reduces the register
19020 * pressure by keeping a value in one register
19023 * In the case of a phi function all paths leading
19024 * into it must be allocated to the same register
19025 * otherwise the phi function may not be removed.
19027 * Forcing a value to stay in a single register
19028 * for an extended period of time does have
19029 * limitations when applied to non homogenous
19032 * The two cases I have identified are:
19033 * 1) Two forced register assignments may
19035 * 2) Registers may go unused because they
19036 * are only good for storing the value
19037 * and not manipulating it.
19039 * Because of this I need to split live ranges,
19040 * even outside of the context of coalesced live
19041 * ranges. The need to split live ranges does
19042 * impose some constraints on live range coalescing.
19044 * - Live ranges may not be coalesced across phi
19045 * functions. This creates a 2 headed live
19046 * range that cannot be sanely split.
19048 * - phi functions (coalesced in initialize_live_ranges)
19049 * are handled as pre split live ranges so we will
19050 * never attempt to split them.
19056 for(i = 0; i <= rstate->ranges; i++) {
19057 struct live_range *lr1;
19058 struct live_range_def *lrd1;
19059 lr1 = &rstate->lr[i];
19063 lrd1 = live_range_end(state, lr1, 0);
19064 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19065 struct triple_set *set;
19066 if (lrd1->def->op != OP_COPY) {
19069 /* Skip copies that are the result of a live range split. */
19070 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19073 for(set = lrd1->def->use; set; set = set->next) {
19074 struct live_range_def *lrd2;
19075 struct live_range *lr2, *res;
19077 lrd2 = &rstate->lrd[set->member->id];
19079 /* Don't coalesce with instructions
19080 * that are the result of a live range
19083 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19086 lr2 = rstate->lrd[set->member->id].lr;
19090 if ((lr1->color != lr2->color) &&
19091 (lr1->color != REG_UNSET) &&
19092 (lr2->color != REG_UNSET)) {
19095 if ((lr1->classes & lr2->classes) == 0) {
19099 if (interfere(rstate, lr1, lr2)) {
19103 res = coalesce_ranges(state, rstate, lr1, lr2);
19117 static void fix_coalesce_conflicts(struct compile_state *state,
19118 struct reg_block *blocks, struct triple_reg_set *live,
19119 struct reg_block *rb, struct triple *ins, void *arg)
19121 int *conflicts = arg;
19122 int zlhs, zrhs, i, j;
19124 /* See if we have a mandatory coalesce operation between
19125 * a lhs and a rhs value. If so and the rhs value is also
19126 * alive then this triple needs to be pre copied. Otherwise
19127 * we would have two definitions in the same live range simultaneously
19131 if ((zlhs == 0) && triple_is_def(state, ins)) {
19135 for(i = 0; i < zlhs; i++) {
19136 struct reg_info linfo;
19137 linfo = arch_reg_lhs(state, ins, i);
19138 if (linfo.reg < MAX_REGISTERS) {
19141 for(j = 0; j < zrhs; j++) {
19142 struct reg_info rinfo;
19143 struct triple *rhs;
19144 struct triple_reg_set *set;
19147 rinfo = arch_reg_rhs(state, ins, j);
19148 if (rinfo.reg != linfo.reg) {
19152 for(set = live; set && !found; set = set->next) {
19153 if (set->member == rhs) {
19158 struct triple *copy;
19159 copy = pre_copy(state, ins, j);
19160 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19168 static int correct_coalesce_conflicts(
19169 struct compile_state *state, struct reg_block *blocks)
19173 walk_variable_lifetimes(state, &state->bb, blocks,
19174 fix_coalesce_conflicts, &conflicts);
19178 static void replace_set_use(struct compile_state *state,
19179 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19181 struct triple_reg_set *set;
19182 for(set = head; set; set = set->next) {
19183 if (set->member == orig) {
19189 static void replace_block_use(struct compile_state *state,
19190 struct reg_block *blocks, struct triple *orig, struct triple *new)
19193 #warning "WISHLIST visit just those blocks that need it *"
19194 for(i = 1; i <= state->bb.last_vertex; i++) {
19195 struct reg_block *rb;
19197 replace_set_use(state, rb->in, orig, new);
19198 replace_set_use(state, rb->out, orig, new);
19202 static void color_instructions(struct compile_state *state)
19204 struct triple *ins, *first;
19205 first = state->first;
19208 if (triple_is_def(state, ins)) {
19209 struct reg_info info;
19210 info = find_lhs_color(state, ins, 0);
19211 if (info.reg >= MAX_REGISTERS) {
19212 info.reg = REG_UNSET;
19214 SET_INFO(ins->id, info);
19217 } while(ins != first);
19220 static struct reg_info read_lhs_color(
19221 struct compile_state *state, struct triple *ins, int index)
19223 struct reg_info info;
19224 if ((index == 0) && triple_is_def(state, ins)) {
19225 info.reg = ID_REG(ins->id);
19226 info.regcm = ID_REGCM(ins->id);
19228 else if (index < ins->lhs) {
19229 info = read_lhs_color(state, LHS(ins, index), 0);
19232 internal_error(state, ins, "Bad lhs %d", index);
19233 info.reg = REG_UNSET;
19239 static struct triple *resolve_tangle(
19240 struct compile_state *state, struct triple *tangle)
19242 struct reg_info info, uinfo;
19243 struct triple_set *set, *next;
19244 struct triple *copy;
19246 #warning "WISHLIST recalculate all affected instructions colors"
19247 info = find_lhs_color(state, tangle, 0);
19248 for(set = tangle->use; set; set = next) {
19249 struct triple *user;
19252 user = set->member;
19254 for(i = 0; i < zrhs; i++) {
19255 if (RHS(user, i) != tangle) {
19258 uinfo = find_rhs_post_color(state, user, i);
19259 if (uinfo.reg == info.reg) {
19260 copy = pre_copy(state, user, i);
19261 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19262 SET_INFO(copy->id, uinfo);
19267 uinfo = find_lhs_pre_color(state, tangle, 0);
19268 if (uinfo.reg == info.reg) {
19269 struct reg_info linfo;
19270 copy = post_copy(state, tangle);
19271 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19272 linfo = find_lhs_color(state, copy, 0);
19273 SET_INFO(copy->id, linfo);
19275 info = find_lhs_color(state, tangle, 0);
19276 SET_INFO(tangle->id, info);
19282 static void fix_tangles(struct compile_state *state,
19283 struct reg_block *blocks, struct triple_reg_set *live,
19284 struct reg_block *rb, struct triple *ins, void *arg)
19286 int *tangles = arg;
19287 struct triple *tangle;
19289 char used[MAX_REGISTERS];
19290 struct triple_reg_set *set;
19293 /* Find out which registers have multiple uses at this point */
19294 memset(used, 0, sizeof(used));
19295 for(set = live; set; set = set->next) {
19296 struct reg_info info;
19297 info = read_lhs_color(state, set->member, 0);
19298 if (info.reg == REG_UNSET) {
19301 reg_inc_used(state, used, info.reg);
19304 /* Now find the least dominated definition of a register in
19305 * conflict I have seen so far.
19307 for(set = live; set; set = set->next) {
19308 struct reg_info info;
19309 info = read_lhs_color(state, set->member, 0);
19310 if (used[info.reg] < 2) {
19313 /* Changing copies that feed into phi functions
19316 if (set->member->use &&
19317 (set->member->use->member->op == OP_PHI)) {
19320 if (!tangle || tdominates(state, set->member, tangle)) {
19321 tangle = set->member;
19324 /* If I have found a tangle resolve it */
19326 struct triple *post_copy;
19328 post_copy = resolve_tangle(state, tangle);
19330 replace_block_use(state, blocks, tangle, post_copy);
19332 if (post_copy && (tangle != ins)) {
19333 replace_set_use(state, live, tangle, post_copy);
19340 static int correct_tangles(
19341 struct compile_state *state, struct reg_block *blocks)
19345 color_instructions(state);
19346 walk_variable_lifetimes(state, &state->bb, blocks,
19347 fix_tangles, &tangles);
19352 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19353 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19355 struct triple *find_constrained_def(
19356 struct compile_state *state, struct live_range *range, struct triple *constrained)
19358 struct live_range_def *lrd, *lrd_next;
19359 lrd_next = range->defs;
19361 struct reg_info info;
19365 lrd_next = lrd->next;
19367 regcm = arch_type_to_regcm(state, lrd->def->type);
19368 info = find_lhs_color(state, lrd->def, 0);
19369 regcm = arch_regcm_reg_normalize(state, regcm);
19370 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19371 /* If the 2 register class masks are equal then
19372 * the current register class is not constrained.
19374 if (regcm == info.regcm) {
19378 /* If there is just one use.
19379 * That use cannot accept a larger register class.
19380 * There are no intervening definitions except
19381 * definitions that feed into that use.
19382 * Then a triple is not constrained.
19383 * FIXME handle this case!
19385 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19388 /* Of the constrained live ranges deal with the
19389 * least dominated one first.
19391 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19392 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19393 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19395 if (!constrained ||
19396 tdominates(state, lrd->def, constrained))
19398 constrained = lrd->def;
19400 } while(lrd_next != range->defs);
19401 return constrained;
19404 static int split_constrained_ranges(
19405 struct compile_state *state, struct reg_state *rstate,
19406 struct live_range *range)
19408 /* Walk through the edges in conflict and our current live
19409 * range, and find definitions that are more severly constrained
19410 * than they type of data they contain require.
19412 * Then pick one of those ranges and relax the constraints.
19414 struct live_range_edge *edge;
19415 struct triple *constrained;
19418 for(edge = range->edges; edge; edge = edge->next) {
19419 constrained = find_constrained_def(state, edge->node, constrained);
19421 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19422 if (!constrained) {
19423 constrained = find_constrained_def(state, range, constrained);
19426 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19427 fprintf(state->errout, "constrained: ");
19428 display_triple(state->errout, constrained);
19431 ids_from_rstate(state, rstate);
19432 cleanup_rstate(state, rstate);
19433 resolve_tangle(state, constrained);
19435 return !!constrained;
19438 static int split_ranges(
19439 struct compile_state *state, struct reg_state *rstate,
19440 char *used, struct live_range *range)
19443 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19444 fprintf(state->errout, "split_ranges %d %s %p\n",
19445 rstate->passes, tops(range->defs->def->op), range->defs->def);
19447 if ((range->color == REG_UNNEEDED) ||
19448 (rstate->passes >= rstate->max_passes)) {
19451 split = split_constrained_ranges(state, rstate, range);
19453 /* Ideally I would split the live range that will not be used
19454 * for the longest period of time in hopes that this will
19455 * (a) allow me to spill a register or
19456 * (b) allow me to place a value in another register.
19458 * So far I don't have a test case for this, the resolving
19459 * of mandatory constraints has solved all of my
19460 * know issues. So I have choosen not to write any
19461 * code until I cat get a better feel for cases where
19462 * it would be useful to have.
19465 #warning "WISHLIST implement live range splitting..."
19467 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19468 FILE *fp = state->errout;
19469 print_interference_blocks(state, rstate, fp, 0);
19470 print_dominators(state, fp, &state->bb);
19475 static FILE *cgdebug_fp(struct compile_state *state)
19479 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19480 fp = state->errout;
19482 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19483 fp = state->dbgout;
19488 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19491 fp = cgdebug_fp(state);
19494 va_start(args, fmt);
19495 vfprintf(fp, fmt, args);
19500 static void cgdebug_flush(struct compile_state *state)
19503 fp = cgdebug_fp(state);
19509 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19512 fp = cgdebug_fp(state);
19514 loc(fp, state, ins);
19518 static int select_free_color(struct compile_state *state,
19519 struct reg_state *rstate, struct live_range *range)
19521 struct triple_set *entry;
19522 struct live_range_def *lrd;
19523 struct live_range_def *phi;
19524 struct live_range_edge *edge;
19525 char used[MAX_REGISTERS];
19526 struct triple **expr;
19528 /* Instead of doing just the trivial color select here I try
19529 * a few extra things because a good color selection will help reduce
19533 /* Find the registers currently in use */
19534 memset(used, 0, sizeof(used));
19535 for(edge = range->edges; edge; edge = edge->next) {
19536 if (edge->node->color == REG_UNSET) {
19539 reg_fill_used(state, used, edge->node->color);
19542 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19545 for(edge = range->edges; edge; edge = edge->next) {
19548 cgdebug_printf(state, "\n%s edges: %d",
19549 tops(range->defs->def->op), i);
19550 cgdebug_loc(state, range->defs->def);
19551 cgdebug_printf(state, "\n");
19552 for(i = 0; i < MAX_REGISTERS; i++) {
19554 cgdebug_printf(state, "used: %s\n",
19560 /* If a color is already assigned see if it will work */
19561 if (range->color != REG_UNSET) {
19562 struct live_range_def *lrd;
19563 if (!used[range->color]) {
19566 for(edge = range->edges; edge; edge = edge->next) {
19567 if (edge->node->color != range->color) {
19570 warning(state, edge->node->defs->def, "edge: ");
19571 lrd = edge->node->defs;
19573 warning(state, lrd->def, " %p %s",
19574 lrd->def, tops(lrd->def->op));
19576 } while(lrd != edge->node->defs);
19579 warning(state, range->defs->def, "def: ");
19581 warning(state, lrd->def, " %p %s",
19582 lrd->def, tops(lrd->def->op));
19584 } while(lrd != range->defs);
19585 internal_error(state, range->defs->def,
19586 "live range with already used color %s",
19587 arch_reg_str(range->color));
19590 /* If I feed into an expression reuse it's color.
19591 * This should help remove copies in the case of 2 register instructions
19592 * and phi functions.
19595 lrd = live_range_end(state, range, 0);
19596 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19597 entry = lrd->def->use;
19598 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19599 struct live_range_def *insd;
19601 insd = &rstate->lrd[entry->member->id];
19602 if (insd->lr->defs == 0) {
19605 if (!phi && (insd->def->op == OP_PHI) &&
19606 !interfere(rstate, range, insd->lr)) {
19609 if (insd->lr->color == REG_UNSET) {
19612 regcm = insd->lr->classes;
19613 if (((regcm & range->classes) == 0) ||
19614 (used[insd->lr->color])) {
19617 if (interfere(rstate, range, insd->lr)) {
19620 range->color = insd->lr->color;
19623 /* If I feed into a phi function reuse it's color or the color
19624 * of something else that feeds into the phi function.
19627 if (phi->lr->color != REG_UNSET) {
19628 if (used[phi->lr->color]) {
19629 range->color = phi->lr->color;
19633 expr = triple_rhs(state, phi->def, 0);
19634 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19635 struct live_range *lr;
19640 lr = rstate->lrd[(*expr)->id].lr;
19641 if (lr->color == REG_UNSET) {
19644 regcm = lr->classes;
19645 if (((regcm & range->classes) == 0) ||
19646 (used[lr->color])) {
19649 if (interfere(rstate, range, lr)) {
19652 range->color = lr->color;
19656 /* If I don't interfere with a rhs node reuse it's color */
19657 lrd = live_range_head(state, range, 0);
19658 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19659 expr = triple_rhs(state, lrd->def, 0);
19660 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19661 struct live_range *lr;
19666 lr = rstate->lrd[(*expr)->id].lr;
19667 if (lr->color == REG_UNSET) {
19670 regcm = lr->classes;
19671 if (((regcm & range->classes) == 0) ||
19672 (used[lr->color])) {
19675 if (interfere(rstate, range, lr)) {
19678 range->color = lr->color;
19682 /* If I have not opportunitically picked a useful color
19683 * pick the first color that is free.
19685 if (range->color == REG_UNSET) {
19687 arch_select_free_register(state, used, range->classes);
19689 if (range->color == REG_UNSET) {
19690 struct live_range_def *lrd;
19692 if (split_ranges(state, rstate, used, range)) {
19695 for(edge = range->edges; edge; edge = edge->next) {
19696 warning(state, edge->node->defs->def, "edge reg %s",
19697 arch_reg_str(edge->node->color));
19698 lrd = edge->node->defs;
19700 warning(state, lrd->def, " %s %p",
19701 tops(lrd->def->op), lrd->def);
19703 } while(lrd != edge->node->defs);
19705 warning(state, range->defs->def, "range: ");
19708 warning(state, lrd->def, " %s %p",
19709 tops(lrd->def->op), lrd->def);
19711 } while(lrd != range->defs);
19713 warning(state, range->defs->def, "classes: %x",
19715 for(i = 0; i < MAX_REGISTERS; i++) {
19717 warning(state, range->defs->def, "used: %s",
19721 error(state, range->defs->def, "too few registers");
19723 range->classes &= arch_reg_regcm(state, range->color);
19724 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19725 internal_error(state, range->defs->def, "select_free_color did not?");
19730 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19733 struct live_range_edge *edge;
19734 struct live_range *range;
19736 cgdebug_printf(state, "Lo: ");
19737 range = rstate->low;
19738 if (*range->group_prev != range) {
19739 internal_error(state, 0, "lo: *prev != range?");
19741 *range->group_prev = range->group_next;
19742 if (range->group_next) {
19743 range->group_next->group_prev = range->group_prev;
19745 if (&range->group_next == rstate->low_tail) {
19746 rstate->low_tail = range->group_prev;
19748 if (rstate->low == range) {
19749 internal_error(state, 0, "low: next != prev?");
19752 else if (rstate->high) {
19753 cgdebug_printf(state, "Hi: ");
19754 range = rstate->high;
19755 if (*range->group_prev != range) {
19756 internal_error(state, 0, "hi: *prev != range?");
19758 *range->group_prev = range->group_next;
19759 if (range->group_next) {
19760 range->group_next->group_prev = range->group_prev;
19762 if (&range->group_next == rstate->high_tail) {
19763 rstate->high_tail = range->group_prev;
19765 if (rstate->high == range) {
19766 internal_error(state, 0, "high: next != prev?");
19772 cgdebug_printf(state, " %d\n", range - rstate->lr);
19773 range->group_prev = 0;
19774 for(edge = range->edges; edge; edge = edge->next) {
19775 struct live_range *node;
19777 /* Move nodes from the high to the low list */
19778 if (node->group_prev && (node->color == REG_UNSET) &&
19779 (node->degree == regc_max_size(state, node->classes))) {
19780 if (*node->group_prev != node) {
19781 internal_error(state, 0, "move: *prev != node?");
19783 *node->group_prev = node->group_next;
19784 if (node->group_next) {
19785 node->group_next->group_prev = node->group_prev;
19787 if (&node->group_next == rstate->high_tail) {
19788 rstate->high_tail = node->group_prev;
19790 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19791 node->group_prev = rstate->low_tail;
19792 node->group_next = 0;
19793 *rstate->low_tail = node;
19794 rstate->low_tail = &node->group_next;
19795 if (*node->group_prev != node) {
19796 internal_error(state, 0, "move2: *prev != node?");
19801 colored = color_graph(state, rstate);
19803 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19804 cgdebug_loc(state, range->defs->def);
19805 cgdebug_flush(state);
19806 colored = select_free_color(state, rstate, range);
19808 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19814 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19816 struct live_range *lr;
19817 struct live_range_edge *edge;
19818 struct triple *ins, *first;
19819 char used[MAX_REGISTERS];
19820 first = state->first;
19823 if (triple_is_def(state, ins)) {
19824 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19825 internal_error(state, ins,
19826 "triple without a live range def");
19828 lr = rstate->lrd[ins->id].lr;
19829 if (lr->color == REG_UNSET) {
19830 internal_error(state, ins,
19831 "triple without a color");
19833 /* Find the registers used by the edges */
19834 memset(used, 0, sizeof(used));
19835 for(edge = lr->edges; edge; edge = edge->next) {
19836 if (edge->node->color == REG_UNSET) {
19837 internal_error(state, 0,
19838 "live range without a color");
19840 reg_fill_used(state, used, edge->node->color);
19842 if (used[lr->color]) {
19843 internal_error(state, ins,
19844 "triple with already used color");
19848 } while(ins != first);
19851 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19853 struct live_range_def *lrd;
19854 struct live_range *lr;
19855 struct triple *first, *ins;
19856 first = state->first;
19859 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19860 internal_error(state, ins,
19861 "triple without a live range");
19863 lrd = &rstate->lrd[ins->id];
19865 ins->id = lrd->orig_id;
19866 SET_REG(ins->id, lr->color);
19868 } while (ins != first);
19871 static struct live_range *merge_sort_lr(
19872 struct live_range *first, struct live_range *last)
19874 struct live_range *mid, *join, **join_tail, *pick;
19876 size = (last - first) + 1;
19878 mid = first + size/2;
19879 first = merge_sort_lr(first, mid -1);
19880 mid = merge_sort_lr(mid, last);
19884 /* merge the two lists */
19885 while(first && mid) {
19886 if ((first->degree < mid->degree) ||
19887 ((first->degree == mid->degree) &&
19888 (first->length < mid->length))) {
19890 first = first->group_next;
19892 first->group_prev = 0;
19897 mid = mid->group_next;
19899 mid->group_prev = 0;
19902 pick->group_next = 0;
19903 pick->group_prev = join_tail;
19905 join_tail = &pick->group_next;
19907 /* Splice the remaining list */
19908 pick = (first)? first : mid;
19911 pick->group_prev = join_tail;
19915 if (!first->defs) {
19923 static void ids_from_rstate(struct compile_state *state,
19924 struct reg_state *rstate)
19926 struct triple *ins, *first;
19927 if (!rstate->defs) {
19930 /* Display the graph if desired */
19931 if (state->compiler->debug & DEBUG_INTERFERENCE) {
19932 FILE *fp = state->dbgout;
19933 print_interference_blocks(state, rstate, fp, 0);
19934 print_control_flow(state, fp, &state->bb);
19937 first = state->first;
19941 struct live_range_def *lrd;
19942 lrd = &rstate->lrd[ins->id];
19943 ins->id = lrd->orig_id;
19946 } while(ins != first);
19949 static void cleanup_live_edges(struct reg_state *rstate)
19952 /* Free the edges on each node */
19953 for(i = 1; i <= rstate->ranges; i++) {
19954 remove_live_edges(rstate, &rstate->lr[i]);
19958 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
19960 cleanup_live_edges(rstate);
19961 xfree(rstate->lrd);
19964 /* Free the variable lifetime information */
19965 if (rstate->blocks) {
19966 free_variable_lifetimes(state, &state->bb, rstate->blocks);
19969 rstate->ranges = 0;
19972 rstate->blocks = 0;
19975 static void verify_consistency(struct compile_state *state);
19976 static void allocate_registers(struct compile_state *state)
19978 struct reg_state rstate;
19981 /* Clear out the reg_state */
19982 memset(&rstate, 0, sizeof(rstate));
19983 rstate.max_passes = state->compiler->max_allocation_passes;
19986 struct live_range **point, **next;
19991 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19992 FILE *fp = state->errout;
19993 fprintf(fp, "pass: %d\n", rstate.passes);
19998 ids_from_rstate(state, &rstate);
20000 /* Cleanup the temporary data structures */
20001 cleanup_rstate(state, &rstate);
20003 /* Compute the variable lifetimes */
20004 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20006 /* Fix invalid mandatory live range coalesce conflicts */
20007 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20009 /* Fix two simultaneous uses of the same register.
20010 * In a few pathlogical cases a partial untangle moves
20011 * the tangle to a part of the graph we won't revisit.
20012 * So we keep looping until we have no more tangle fixes
20016 tangles = correct_tangles(state, rstate.blocks);
20020 print_blocks(state, "resolve_tangles", state->dbgout);
20021 verify_consistency(state);
20023 /* Allocate and initialize the live ranges */
20024 initialize_live_ranges(state, &rstate);
20026 /* Note currently doing coalescing in a loop appears to
20027 * buys me nothing. The code is left this way in case
20028 * there is some value in it. Or if a future bugfix
20029 * yields some benefit.
20032 if (state->compiler->debug & DEBUG_COALESCING) {
20033 fprintf(state->errout, "coalescing\n");
20036 /* Remove any previous live edge calculations */
20037 cleanup_live_edges(&rstate);
20039 /* Compute the interference graph */
20040 walk_variable_lifetimes(
20041 state, &state->bb, rstate.blocks,
20042 graph_ins, &rstate);
20044 /* Display the interference graph if desired */
20045 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20046 print_interference_blocks(state, &rstate, state->dbgout, 1);
20047 fprintf(state->dbgout, "\nlive variables by instruction\n");
20048 walk_variable_lifetimes(
20049 state, &state->bb, rstate.blocks,
20050 print_interference_ins, &rstate);
20053 coalesced = coalesce_live_ranges(state, &rstate);
20055 if (state->compiler->debug & DEBUG_COALESCING) {
20056 fprintf(state->errout, "coalesced: %d\n", coalesced);
20058 } while(coalesced);
20060 #if DEBUG_CONSISTENCY > 1
20062 fprintf(state->errout, "verify_graph_ins...\n");
20064 /* Verify the interference graph */
20065 walk_variable_lifetimes(
20066 state, &state->bb, rstate.blocks,
20067 verify_graph_ins, &rstate);
20069 fprintf(state->errout, "verify_graph_ins done\n");
20073 /* Build the groups low and high. But with the nodes
20074 * first sorted by degree order.
20076 rstate.low_tail = &rstate.low;
20077 rstate.high_tail = &rstate.high;
20078 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20080 rstate.high->group_prev = &rstate.high;
20082 for(point = &rstate.high; *point; point = &(*point)->group_next)
20084 rstate.high_tail = point;
20085 /* Walk through the high list and move everything that needs
20088 for(point = &rstate.high; *point; point = next) {
20089 struct live_range *range;
20090 next = &(*point)->group_next;
20093 /* If it has a low degree or it already has a color
20094 * place the node in low.
20096 if ((range->degree < regc_max_size(state, range->classes)) ||
20097 (range->color != REG_UNSET)) {
20098 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20099 range - rstate.lr, range->degree,
20100 (range->color != REG_UNSET) ? " (colored)": "");
20101 *range->group_prev = range->group_next;
20102 if (range->group_next) {
20103 range->group_next->group_prev = range->group_prev;
20105 if (&range->group_next == rstate.high_tail) {
20106 rstate.high_tail = range->group_prev;
20108 range->group_prev = rstate.low_tail;
20109 range->group_next = 0;
20110 *rstate.low_tail = range;
20111 rstate.low_tail = &range->group_next;
20115 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20116 range - rstate.lr, range->degree,
20117 (range->color != REG_UNSET) ? " (colored)": "");
20120 /* Color the live_ranges */
20121 colored = color_graph(state, &rstate);
20123 } while (!colored);
20125 /* Verify the graph was properly colored */
20126 verify_colors(state, &rstate);
20128 /* Move the colors from the graph to the triples */
20129 color_triples(state, &rstate);
20131 /* Cleanup the temporary data structures */
20132 cleanup_rstate(state, &rstate);
20134 /* Display the new graph */
20135 print_blocks(state, __func__, state->dbgout);
20138 /* Sparce Conditional Constant Propogation
20139 * =========================================
20143 struct lattice_node {
20145 struct triple *def;
20146 struct ssa_edge *out;
20147 struct flow_block *fblock;
20148 struct triple *val;
20149 /* lattice high val == def
20150 * lattice const is_const(val)
20151 * lattice low other
20155 struct lattice_node *src;
20156 struct lattice_node *dst;
20157 struct ssa_edge *work_next;
20158 struct ssa_edge *work_prev;
20159 struct ssa_edge *out_next;
20162 struct flow_block *src;
20163 struct flow_block *dst;
20164 struct flow_edge *work_next;
20165 struct flow_edge *work_prev;
20166 struct flow_edge *in_next;
20167 struct flow_edge *out_next;
20170 #define MAX_FLOW_BLOCK_EDGES 3
20171 struct flow_block {
20172 struct block *block;
20173 struct flow_edge *in;
20174 struct flow_edge *out;
20175 struct flow_edge *edges;
20180 struct lattice_node *lattice;
20181 struct ssa_edge *ssa_edges;
20182 struct flow_block *flow_blocks;
20183 struct flow_edge *flow_work_list;
20184 struct ssa_edge *ssa_work_list;
20188 static int is_scc_const(struct compile_state *state, struct triple *ins)
20190 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20193 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20195 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20198 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20200 return is_scc_const(state, lnode->val);
20203 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20205 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20208 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20209 struct flow_edge *fedge)
20211 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20212 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20214 fedge->src->block?fedge->src->block->last->id: 0,
20215 fedge->dst->block?fedge->dst->block->first->id: 0);
20217 if ((fedge == scc->flow_work_list) ||
20218 (fedge->work_next != fedge) ||
20219 (fedge->work_prev != fedge)) {
20221 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20222 fprintf(state->errout, "dupped fedge: %p\n",
20227 if (!scc->flow_work_list) {
20228 scc->flow_work_list = fedge;
20229 fedge->work_next = fedge->work_prev = fedge;
20232 struct flow_edge *ftail;
20233 ftail = scc->flow_work_list->work_prev;
20234 fedge->work_next = ftail->work_next;
20235 fedge->work_prev = ftail;
20236 fedge->work_next->work_prev = fedge;
20237 fedge->work_prev->work_next = fedge;
20241 static struct flow_edge *scc_next_fedge(
20242 struct compile_state *state, struct scc_state *scc)
20244 struct flow_edge *fedge;
20245 fedge = scc->flow_work_list;
20247 fedge->work_next->work_prev = fedge->work_prev;
20248 fedge->work_prev->work_next = fedge->work_next;
20249 if (fedge->work_next != fedge) {
20250 scc->flow_work_list = fedge->work_next;
20252 scc->flow_work_list = 0;
20254 fedge->work_next = fedge->work_prev = fedge;
20259 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20260 struct ssa_edge *sedge)
20262 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20263 fprintf(state->errout, "adding sedge: %5d (%4d -> %5d)\n",
20264 sedge - scc->ssa_edges,
20265 sedge->src->def->id,
20266 sedge->dst->def->id);
20268 if ((sedge == scc->ssa_work_list) ||
20269 (sedge->work_next != sedge) ||
20270 (sedge->work_prev != sedge)) {
20272 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20273 fprintf(state->errout, "dupped sedge: %5d\n",
20274 sedge - scc->ssa_edges);
20278 if (!scc->ssa_work_list) {
20279 scc->ssa_work_list = sedge;
20280 sedge->work_next = sedge->work_prev = sedge;
20283 struct ssa_edge *stail;
20284 stail = scc->ssa_work_list->work_prev;
20285 sedge->work_next = stail->work_next;
20286 sedge->work_prev = stail;
20287 sedge->work_next->work_prev = sedge;
20288 sedge->work_prev->work_next = sedge;
20292 static struct ssa_edge *scc_next_sedge(
20293 struct compile_state *state, struct scc_state *scc)
20295 struct ssa_edge *sedge;
20296 sedge = scc->ssa_work_list;
20298 sedge->work_next->work_prev = sedge->work_prev;
20299 sedge->work_prev->work_next = sedge->work_next;
20300 if (sedge->work_next != sedge) {
20301 scc->ssa_work_list = sedge->work_next;
20303 scc->ssa_work_list = 0;
20305 sedge->work_next = sedge->work_prev = sedge;
20310 static void initialize_scc_state(
20311 struct compile_state *state, struct scc_state *scc)
20313 int ins_count, ssa_edge_count;
20314 int ins_index, ssa_edge_index, fblock_index;
20315 struct triple *first, *ins;
20316 struct block *block;
20317 struct flow_block *fblock;
20319 memset(scc, 0, sizeof(*scc));
20321 /* Inialize pass zero find out how much memory we need */
20322 first = state->first;
20324 ins_count = ssa_edge_count = 0;
20326 struct triple_set *edge;
20328 for(edge = ins->use; edge; edge = edge->next) {
20332 } while(ins != first);
20333 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20334 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20335 ins_count, ssa_edge_count, state->bb.last_vertex);
20337 scc->ins_count = ins_count;
20339 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20341 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20343 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20346 /* Initialize pass one collect up the nodes */
20349 ins_index = ssa_edge_index = fblock_index = 0;
20352 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20353 block = ins->u.block;
20355 internal_error(state, ins, "label without block");
20358 block->vertex = fblock_index;
20359 fblock = &scc->flow_blocks[fblock_index];
20360 fblock->block = block;
20361 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20365 struct lattice_node *lnode;
20367 lnode = &scc->lattice[ins_index];
20370 lnode->fblock = fblock;
20371 lnode->val = ins; /* LATTICE HIGH */
20372 if (lnode->val->op == OP_UNKNOWNVAL) {
20373 lnode->val = 0; /* LATTICE LOW by definition */
20375 lnode->old_id = ins->id;
20376 ins->id = ins_index;
20379 } while(ins != first);
20380 /* Initialize pass two collect up the edges */
20386 struct triple_set *edge;
20387 struct ssa_edge **stail;
20388 struct lattice_node *lnode;
20389 lnode = &scc->lattice[ins->id];
20391 stail = &lnode->out;
20392 for(edge = ins->use; edge; edge = edge->next) {
20393 struct ssa_edge *sedge;
20394 ssa_edge_index += 1;
20395 sedge = &scc->ssa_edges[ssa_edge_index];
20397 stail = &sedge->out_next;
20398 sedge->src = lnode;
20399 sedge->dst = &scc->lattice[edge->member->id];
20400 sedge->work_next = sedge->work_prev = sedge;
20401 sedge->out_next = 0;
20404 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20405 struct flow_edge *fedge, **ftail;
20406 struct block_set *bedge;
20407 block = ins->u.block;
20408 fblock = &scc->flow_blocks[block->vertex];
20411 ftail = &fblock->out;
20413 fedge = fblock->edges;
20414 bedge = block->edges;
20415 for(; bedge; bedge = bedge->next, fedge++) {
20416 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20417 if (fedge->dst->block != bedge->member) {
20418 internal_error(state, 0, "block mismatch");
20421 ftail = &fedge->out_next;
20422 fedge->out_next = 0;
20424 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20425 fedge->src = fblock;
20426 fedge->work_next = fedge->work_prev = fedge;
20427 fedge->executable = 0;
20431 } while (ins != first);
20436 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20437 struct flow_edge **ftail;
20438 struct block_set *bedge;
20439 block = ins->u.block;
20440 fblock = &scc->flow_blocks[block->vertex];
20441 ftail = &fblock->in;
20442 for(bedge = block->use; bedge; bedge = bedge->next) {
20443 struct block *src_block;
20444 struct flow_block *sfblock;
20445 struct flow_edge *sfedge;
20446 src_block = bedge->member;
20447 sfblock = &scc->flow_blocks[src_block->vertex];
20448 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20449 if (sfedge->dst == fblock) {
20454 internal_error(state, 0, "edge mismatch");
20457 ftail = &sfedge->in_next;
20458 sfedge->in_next = 0;
20462 } while(ins != first);
20463 /* Setup a dummy block 0 as a node above the start node */
20465 struct flow_block *fblock, *dst;
20466 struct flow_edge *fedge;
20467 fblock = &scc->flow_blocks[0];
20469 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20471 fblock->out = fblock->edges;
20472 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20473 fedge = fblock->edges;
20474 fedge->src = fblock;
20476 fedge->work_next = fedge;
20477 fedge->work_prev = fedge;
20478 fedge->in_next = fedge->dst->in;
20479 fedge->out_next = 0;
20480 fedge->executable = 0;
20481 fedge->dst->in = fedge;
20483 /* Initialize the work lists */
20484 scc->flow_work_list = 0;
20485 scc->ssa_work_list = 0;
20486 scc_add_fedge(state, scc, fedge);
20488 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20489 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20490 ins_index, ssa_edge_index, fblock_index);
20495 static void free_scc_state(
20496 struct compile_state *state, struct scc_state *scc)
20499 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20500 struct flow_block *fblock;
20501 fblock = &scc->flow_blocks[i];
20502 if (fblock->edges) {
20503 xfree(fblock->edges);
20507 xfree(scc->flow_blocks);
20508 xfree(scc->ssa_edges);
20509 xfree(scc->lattice);
20513 static struct lattice_node *triple_to_lattice(
20514 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20516 if (ins->id <= 0) {
20517 internal_error(state, ins, "bad id");
20519 return &scc->lattice[ins->id];
20522 static struct triple *preserve_lval(
20523 struct compile_state *state, struct lattice_node *lnode)
20525 struct triple *old;
20526 /* Preserve the original value */
20528 old = dup_triple(state, lnode->val);
20529 if (lnode->val != lnode->def) {
20539 static int lval_changed(struct compile_state *state,
20540 struct triple *old, struct lattice_node *lnode)
20543 /* See if the lattice value has changed */
20545 if (!old && !lnode->val) {
20549 lnode->val && old &&
20550 (memcmp(lnode->val->param, old->param,
20551 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20552 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20562 static void scc_debug_lnode(
20563 struct compile_state *state, struct scc_state *scc,
20564 struct lattice_node *lnode, int changed)
20566 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20567 display_triple_changes(state->errout, lnode->val, lnode->def);
20569 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20570 FILE *fp = state->errout;
20571 struct triple *val, **expr;
20572 val = lnode->val? lnode->val : lnode->def;
20573 fprintf(fp, "%p %s %3d %10s (",
20575 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20577 tops(lnode->def->op));
20578 expr = triple_rhs(state, lnode->def, 0);
20579 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20581 fprintf(fp, " %d", (*expr)->id);
20584 if (val->op == OP_INTCONST) {
20585 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20587 fprintf(fp, " ) -> %s %s\n",
20588 (is_lattice_hi(state, lnode)? "hi":
20589 is_lattice_const(state, lnode)? "const" : "lo"),
20590 changed? "changed" : ""
20595 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20596 struct lattice_node *lnode)
20599 struct triple *old, *scratch;
20600 struct triple **dexpr, **vexpr;
20603 /* Store the original value */
20604 old = preserve_lval(state, lnode);
20606 /* Reinitialize the value */
20607 lnode->val = scratch = dup_triple(state, lnode->def);
20608 scratch->id = lnode->old_id;
20609 scratch->next = scratch;
20610 scratch->prev = scratch;
20613 count = TRIPLE_SIZE(scratch);
20614 for(i = 0; i < count; i++) {
20615 dexpr = &lnode->def->param[i];
20616 vexpr = &scratch->param[i];
20618 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20619 (i >= TRIPLE_TARG_OFF(scratch))) &&
20621 struct lattice_node *tmp;
20622 tmp = triple_to_lattice(state, scc, *dexpr);
20623 *vexpr = (tmp->val)? tmp->val : tmp->def;
20626 if (triple_is_branch(state, scratch)) {
20627 scratch->next = lnode->def->next;
20629 /* Recompute the value */
20630 #warning "FIXME see if simplify does anything bad"
20631 /* So far it looks like only the strength reduction
20632 * optimization are things I need to worry about.
20634 simplify(state, scratch);
20635 /* Cleanup my value */
20636 if (scratch->use) {
20637 internal_error(state, lnode->def, "scratch used?");
20639 if ((scratch->prev != scratch) ||
20640 ((scratch->next != scratch) &&
20641 (!triple_is_branch(state, lnode->def) ||
20642 (scratch->next != lnode->def->next)))) {
20643 internal_error(state, lnode->def, "scratch in list?");
20645 /* undo any uses... */
20646 count = TRIPLE_SIZE(scratch);
20647 for(i = 0; i < count; i++) {
20648 vexpr = &scratch->param[i];
20650 unuse_triple(*vexpr, scratch);
20653 if (lnode->val->op == OP_UNKNOWNVAL) {
20654 lnode->val = 0; /* Lattice low by definition */
20656 /* Find the case when I am lattice high */
20658 (lnode->val->op == lnode->def->op) &&
20659 (memcmp(lnode->val->param, lnode->def->param,
20660 count * sizeof(lnode->val->param[0])) == 0) &&
20661 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20662 lnode->val = lnode->def;
20664 /* Only allow lattice high when all of my inputs
20665 * are also lattice high. Occassionally I can
20666 * have constants with a lattice low input, so
20667 * I do not need to check that case.
20669 if (is_lattice_hi(state, lnode)) {
20670 struct lattice_node *tmp;
20672 rhs = lnode->val->rhs;
20673 for(i = 0; i < rhs; i++) {
20674 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20675 if (!is_lattice_hi(state, tmp)) {
20681 /* Find the cases that are always lattice lo */
20683 triple_is_def(state, lnode->val) &&
20684 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20687 /* See if the lattice value has changed */
20688 changed = lval_changed(state, old, lnode);
20689 /* See if this value should not change */
20690 if ((lnode->val != lnode->def) &&
20691 (( !triple_is_def(state, lnode->def) &&
20692 !triple_is_cbranch(state, lnode->def)) ||
20693 (lnode->def->op == OP_PIECE))) {
20694 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20696 internal_warning(state, lnode->def, "non def changes value?");
20701 /* See if we need to free the scratch value */
20702 if (lnode->val != scratch) {
20710 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20711 struct lattice_node *lnode)
20713 struct lattice_node *cond;
20714 struct flow_edge *left, *right;
20717 /* Update the branch value */
20718 changed = compute_lnode_val(state, scc, lnode);
20719 scc_debug_lnode(state, scc, lnode, changed);
20721 /* This only applies to conditional branches */
20722 if (!triple_is_cbranch(state, lnode->def)) {
20723 internal_error(state, lnode->def, "not a conditional branch");
20726 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20727 struct flow_edge *fedge;
20728 FILE *fp = state->errout;
20729 fprintf(fp, "%s: %d (",
20730 tops(lnode->def->op),
20733 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20734 fprintf(fp, " %d", fedge->dst->block->vertex);
20737 if (lnode->def->rhs > 0) {
20738 fprintf(fp, " <- %d",
20739 RHS(lnode->def, 0)->id);
20743 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20744 for(left = cond->fblock->out; left; left = left->out_next) {
20745 if (left->dst->block->first == lnode->def->next) {
20750 internal_error(state, lnode->def, "Cannot find left branch edge");
20752 for(right = cond->fblock->out; right; right = right->out_next) {
20753 if (right->dst->block->first == TARG(lnode->def, 0)) {
20758 internal_error(state, lnode->def, "Cannot find right branch edge");
20760 /* I should only come here if the controlling expressions value
20761 * has changed, which means it must be either a constant or lo.
20763 if (is_lattice_hi(state, cond)) {
20764 internal_error(state, cond->def, "condition high?");
20767 if (is_lattice_lo(state, cond)) {
20768 scc_add_fedge(state, scc, left);
20769 scc_add_fedge(state, scc, right);
20771 else if (cond->val->u.cval) {
20772 scc_add_fedge(state, scc, right);
20774 scc_add_fedge(state, scc, left);
20780 static void scc_add_sedge_dst(struct compile_state *state,
20781 struct scc_state *scc, struct ssa_edge *sedge)
20783 if (triple_is_cbranch(state, sedge->dst->def)) {
20784 scc_visit_cbranch(state, scc, sedge->dst);
20786 else if (triple_is_def(state, sedge->dst->def)) {
20787 scc_add_sedge(state, scc, sedge);
20791 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20792 struct lattice_node *lnode)
20794 struct lattice_node *tmp;
20795 struct triple **slot, *old;
20796 struct flow_edge *fedge;
20799 if (lnode->def->op != OP_PHI) {
20800 internal_error(state, lnode->def, "not phi");
20802 /* Store the original value */
20803 old = preserve_lval(state, lnode);
20805 /* default to lattice high */
20806 lnode->val = lnode->def;
20807 slot = &RHS(lnode->def, 0);
20809 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20810 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20811 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20813 fedge->dst->block->vertex,
20817 if (!fedge->executable) {
20820 if (!slot[index]) {
20821 internal_error(state, lnode->def, "no phi value");
20823 tmp = triple_to_lattice(state, scc, slot[index]);
20824 /* meet(X, lattice low) = lattice low */
20825 if (is_lattice_lo(state, tmp)) {
20828 /* meet(X, lattice high) = X */
20829 else if (is_lattice_hi(state, tmp)) {
20830 lnode->val = lnode->val;
20832 /* meet(lattice high, X) = X */
20833 else if (is_lattice_hi(state, lnode)) {
20834 lnode->val = dup_triple(state, tmp->val);
20835 /* Only change the type if necessary */
20836 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20837 lnode->val->type = lnode->def->type;
20840 /* meet(const, const) = const or lattice low */
20841 else if (!constants_equal(state, lnode->val, tmp->val)) {
20845 /* meet(lattice low, X) = lattice low */
20846 if (is_lattice_lo(state, lnode)) {
20851 changed = lval_changed(state, old, lnode);
20852 scc_debug_lnode(state, scc, lnode, changed);
20854 /* If the lattice value has changed update the work lists. */
20856 struct ssa_edge *sedge;
20857 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20858 scc_add_sedge_dst(state, scc, sedge);
20864 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20865 struct lattice_node *lnode)
20869 if (!triple_is_def(state, lnode->def)) {
20870 internal_warning(state, lnode->def, "not visiting an expression?");
20872 changed = compute_lnode_val(state, scc, lnode);
20873 scc_debug_lnode(state, scc, lnode, changed);
20876 struct ssa_edge *sedge;
20877 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20878 scc_add_sedge_dst(state, scc, sedge);
20883 static void scc_writeback_values(
20884 struct compile_state *state, struct scc_state *scc)
20886 struct triple *first, *ins;
20887 first = state->first;
20890 struct lattice_node *lnode;
20891 lnode = triple_to_lattice(state, scc, ins);
20892 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20893 if (is_lattice_hi(state, lnode) &&
20894 (lnode->val->op != OP_NOOP))
20896 struct flow_edge *fedge;
20899 for(fedge = lnode->fblock->in;
20900 !executable && fedge; fedge = fedge->in_next) {
20901 executable |= fedge->executable;
20904 internal_warning(state, lnode->def,
20905 "lattice node %d %s->%s still high?",
20907 tops(lnode->def->op),
20908 tops(lnode->val->op));
20914 ins->id = lnode->old_id;
20915 if (lnode->val && (lnode->val != ins)) {
20916 /* See if it something I know how to write back */
20917 switch(lnode->val->op) {
20919 mkconst(state, ins, lnode->val->u.cval);
20922 mkaddr_const(state, ins,
20923 MISC(lnode->val, 0), lnode->val->u.cval);
20926 /* By default don't copy the changes,
20927 * recompute them in place instead.
20929 simplify(state, ins);
20932 if (is_const(lnode->val) &&
20933 !constants_equal(state, lnode->val, ins)) {
20934 internal_error(state, 0, "constants not equal");
20936 /* Free the lattice nodes */
20941 } while(ins != first);
20944 static void scc_transform(struct compile_state *state)
20946 struct scc_state scc;
20947 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
20951 initialize_scc_state(state, &scc);
20953 while(scc.flow_work_list || scc.ssa_work_list) {
20954 struct flow_edge *fedge;
20955 struct ssa_edge *sedge;
20956 struct flow_edge *fptr;
20957 while((fedge = scc_next_fedge(state, &scc))) {
20958 struct block *block;
20959 struct triple *ptr;
20960 struct flow_block *fblock;
20963 if (fedge->executable) {
20967 internal_error(state, 0, "fedge without dst");
20970 internal_error(state, 0, "fedge without src");
20972 fedge->executable = 1;
20973 fblock = fedge->dst;
20974 block = fblock->block;
20976 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
20977 if (fptr->executable) {
20982 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20983 fprintf(state->errout, "vertex: %d reps: %d\n",
20984 block->vertex, reps);
20988 for(ptr = block->first; !done; ptr = ptr->next) {
20989 struct lattice_node *lnode;
20990 done = (ptr == block->last);
20991 lnode = &scc.lattice[ptr->id];
20992 if (ptr->op == OP_PHI) {
20993 scc_visit_phi(state, &scc, lnode);
20995 else if ((reps == 1) && triple_is_def(state, ptr))
20997 scc_visit_expr(state, &scc, lnode);
21000 /* Add unconditional branch edges */
21001 if (!triple_is_cbranch(state, fblock->block->last)) {
21002 struct flow_edge *out;
21003 for(out = fblock->out; out; out = out->out_next) {
21004 scc_add_fedge(state, &scc, out);
21008 while((sedge = scc_next_sedge(state, &scc))) {
21009 struct lattice_node *lnode;
21010 struct flow_block *fblock;
21011 lnode = sedge->dst;
21012 fblock = lnode->fblock;
21014 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21015 fprintf(state->errout, "sedge: %5d (%5d -> %5d)\n",
21016 sedge - scc.ssa_edges,
21017 sedge->src->def->id,
21018 sedge->dst->def->id);
21021 if (lnode->def->op == OP_PHI) {
21022 scc_visit_phi(state, &scc, lnode);
21025 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21026 if (fptr->executable) {
21031 scc_visit_expr(state, &scc, lnode);
21037 scc_writeback_values(state, &scc);
21038 free_scc_state(state, &scc);
21039 rebuild_ssa_form(state);
21041 print_blocks(state, __func__, state->dbgout);
21045 static void transform_to_arch_instructions(struct compile_state *state)
21047 struct triple *ins, *first;
21048 first = state->first;
21051 ins = transform_to_arch_instruction(state, ins);
21052 } while(ins != first);
21054 print_blocks(state, __func__, state->dbgout);
21057 #if DEBUG_CONSISTENCY
21058 static void verify_uses(struct compile_state *state)
21060 struct triple *first, *ins;
21061 struct triple_set *set;
21062 first = state->first;
21065 struct triple **expr;
21066 expr = triple_rhs(state, ins, 0);
21067 for(; expr; expr = triple_rhs(state, ins, expr)) {
21068 struct triple *rhs;
21070 for(set = rhs?rhs->use:0; set; set = set->next) {
21071 if (set->member == ins) {
21076 internal_error(state, ins, "rhs not used");
21079 expr = triple_lhs(state, ins, 0);
21080 for(; expr; expr = triple_lhs(state, ins, expr)) {
21081 struct triple *lhs;
21083 for(set = lhs?lhs->use:0; set; set = set->next) {
21084 if (set->member == ins) {
21089 internal_error(state, ins, "lhs not used");
21092 expr = triple_misc(state, ins, 0);
21093 if (ins->op != OP_PHI) {
21094 for(; expr; expr = triple_targ(state, ins, expr)) {
21095 struct triple *misc;
21097 for(set = misc?misc->use:0; set; set = set->next) {
21098 if (set->member == ins) {
21103 internal_error(state, ins, "misc not used");
21107 if (!triple_is_ret(state, ins)) {
21108 expr = triple_targ(state, ins, 0);
21109 for(; expr; expr = triple_targ(state, ins, expr)) {
21110 struct triple *targ;
21112 for(set = targ?targ->use:0; set; set = set->next) {
21113 if (set->member == ins) {
21118 internal_error(state, ins, "targ not used");
21123 } while(ins != first);
21126 static void verify_blocks_present(struct compile_state *state)
21128 struct triple *first, *ins;
21129 if (!state->bb.first_block) {
21132 first = state->first;
21135 valid_ins(state, ins);
21136 if (triple_stores_block(state, ins)) {
21137 if (!ins->u.block) {
21138 internal_error(state, ins,
21139 "%p not in a block?", ins);
21143 } while(ins != first);
21148 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21150 struct block_set *bedge;
21151 struct block *targ;
21152 targ = block_of_triple(state, edge);
21153 for(bedge = block->edges; bedge; bedge = bedge->next) {
21154 if (bedge->member == targ) {
21161 static void verify_blocks(struct compile_state *state)
21163 struct triple *ins;
21164 struct block *block;
21166 block = state->bb.first_block;
21173 struct block_set *user, *edge;
21175 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21176 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21177 internal_error(state, ins, "inconsitent block specified");
21179 valid_ins(state, ins);
21182 for(user = block->use; user; user = user->next) {
21184 if (!user->member->first) {
21185 internal_error(state, block->first, "user is empty");
21187 if ((block == state->bb.last_block) &&
21188 (user->member == state->bb.first_block)) {
21191 for(edge = user->member->edges; edge; edge = edge->next) {
21192 if (edge->member == block) {
21197 internal_error(state, user->member->first,
21198 "user does not use block");
21201 if (triple_is_branch(state, block->last)) {
21202 struct triple **expr;
21203 expr = triple_edge_targ(state, block->last, 0);
21204 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21205 if (*expr && !edge_present(state, block, *expr)) {
21206 internal_error(state, block->last, "no edge to targ");
21210 if (!triple_is_ubranch(state, block->last) &&
21211 (block != state->bb.last_block) &&
21212 !edge_present(state, block, block->last->next)) {
21213 internal_error(state, block->last, "no edge to block->last->next");
21215 for(edge = block->edges; edge; edge = edge->next) {
21216 for(user = edge->member->use; user; user = user->next) {
21217 if (user->member == block) {
21221 if (!user || user->member != block) {
21222 internal_error(state, block->first,
21223 "block does not use edge");
21225 if (!edge->member->first) {
21226 internal_error(state, block->first, "edge block is empty");
21229 if (block->users != users) {
21230 internal_error(state, block->first,
21231 "computed users %d != stored users %d",
21232 users, block->users);
21234 if (!triple_stores_block(state, block->last->next)) {
21235 internal_error(state, block->last->next,
21236 "cannot find next block");
21238 block = block->last->next->u.block;
21240 internal_error(state, block->last->next,
21243 } while(block != state->bb.first_block);
21244 if (blocks != state->bb.last_vertex) {
21245 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21246 blocks, state->bb.last_vertex);
21250 static void verify_domination(struct compile_state *state)
21252 struct triple *first, *ins;
21253 struct triple_set *set;
21254 if (!state->bb.first_block) {
21258 first = state->first;
21261 for(set = ins->use; set; set = set->next) {
21262 struct triple **slot;
21263 struct triple *use_point;
21266 zrhs = set->member->rhs;
21267 slot = &RHS(set->member, 0);
21268 /* See if the use is on the right hand side */
21269 for(i = 0; i < zrhs; i++) {
21270 if (slot[i] == ins) {
21275 use_point = set->member;
21276 if (set->member->op == OP_PHI) {
21277 struct block_set *bset;
21279 bset = set->member->u.block->use;
21280 for(edge = 0; bset && (edge < i); edge++) {
21284 internal_error(state, set->member,
21285 "no edge for phi rhs %d", i);
21287 use_point = bset->member->last;
21291 !tdominates(state, ins, use_point)) {
21292 if (is_const(ins)) {
21293 internal_warning(state, ins,
21294 "non dominated rhs use point %p?", use_point);
21297 internal_error(state, ins,
21298 "non dominated rhs use point %p?", use_point);
21303 } while(ins != first);
21306 static void verify_rhs(struct compile_state *state)
21308 struct triple *first, *ins;
21309 first = state->first;
21312 struct triple **slot;
21315 slot = &RHS(ins, 0);
21316 for(i = 0; i < zrhs; i++) {
21317 if (slot[i] == 0) {
21318 internal_error(state, ins,
21319 "missing rhs %d on %s",
21322 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21323 internal_error(state, ins,
21324 "ins == rhs[%d] on %s",
21329 } while(ins != first);
21332 static void verify_piece(struct compile_state *state)
21334 struct triple *first, *ins;
21335 first = state->first;
21338 struct triple *ptr;
21341 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21342 if (ptr != LHS(ins, i)) {
21343 internal_error(state, ins, "malformed lhs on %s",
21346 if (ptr->op != OP_PIECE) {
21347 internal_error(state, ins, "bad lhs op %s at %d on %s",
21348 tops(ptr->op), i, tops(ins->op));
21350 if (ptr->u.cval != i) {
21351 internal_error(state, ins, "bad u.cval of %d %d expected",
21356 } while(ins != first);
21359 static void verify_ins_colors(struct compile_state *state)
21361 struct triple *first, *ins;
21363 first = state->first;
21367 } while(ins != first);
21370 static void verify_unknown(struct compile_state *state)
21372 struct triple *first, *ins;
21373 if ( (unknown_triple.next != &unknown_triple) ||
21374 (unknown_triple.prev != &unknown_triple) ||
21376 (unknown_triple.use != 0) ||
21378 (unknown_triple.op != OP_UNKNOWNVAL) ||
21379 (unknown_triple.lhs != 0) ||
21380 (unknown_triple.rhs != 0) ||
21381 (unknown_triple.misc != 0) ||
21382 (unknown_triple.targ != 0) ||
21383 (unknown_triple.template_id != 0) ||
21384 (unknown_triple.id != -1) ||
21385 (unknown_triple.type != &unknown_type) ||
21386 (unknown_triple.occurance != &dummy_occurance) ||
21387 (unknown_triple.param[0] != 0) ||
21388 (unknown_triple.param[1] != 0)) {
21389 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21391 if ( (dummy_occurance.count != 2) ||
21392 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21393 (strcmp(dummy_occurance.function, "") != 0) ||
21394 (dummy_occurance.col != 0) ||
21395 (dummy_occurance.parent != 0)) {
21396 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21398 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21399 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21401 first = state->first;
21405 if (ins == &unknown_triple) {
21406 internal_error(state, ins, "unknown triple in list");
21408 params = TRIPLE_SIZE(ins);
21409 for(i = 0; i < params; i++) {
21410 if (ins->param[i] == &unknown_triple) {
21411 internal_error(state, ins, "unknown triple used!");
21415 } while(ins != first);
21418 static void verify_types(struct compile_state *state)
21420 struct triple *first, *ins;
21421 first = state->first;
21424 struct type *invalid;
21425 invalid = invalid_type(state, ins->type);
21427 FILE *fp = state->errout;
21428 fprintf(fp, "type: ");
21429 name_of(fp, ins->type);
21431 fprintf(fp, "invalid type: ");
21432 name_of(fp, invalid);
21434 internal_error(state, ins, "invalid ins type");
21436 } while(ins != first);
21439 static void verify_copy(struct compile_state *state)
21441 struct triple *first, *ins, *next;
21442 first = state->first;
21443 next = ins = first;
21447 if (ins->op != OP_COPY) {
21450 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21451 FILE *fp = state->errout;
21452 fprintf(fp, "src type: ");
21453 name_of(fp, RHS(ins, 0)->type);
21455 fprintf(fp, "dst type: ");
21456 name_of(fp, ins->type);
21458 internal_error(state, ins, "type mismatch in copy");
21460 } while(next != first);
21463 static void verify_consistency(struct compile_state *state)
21465 verify_unknown(state);
21466 verify_uses(state);
21467 verify_blocks_present(state);
21468 verify_blocks(state);
21469 verify_domination(state);
21471 verify_piece(state);
21472 verify_ins_colors(state);
21473 verify_types(state);
21474 verify_copy(state);
21475 if (state->compiler->debug & DEBUG_VERIFICATION) {
21476 fprintf(state->dbgout, "consistency verified\n");
21480 static void verify_consistency(struct compile_state *state) {}
21481 #endif /* DEBUG_CONSISTENCY */
21483 static void optimize(struct compile_state *state)
21485 /* Join all of the functions into one giant function */
21486 join_functions(state);
21488 /* Dump what the instruction graph intially looks like */
21489 print_triples(state);
21491 /* Replace structures with simpler data types */
21492 decompose_compound_types(state);
21493 print_triples(state);
21495 verify_consistency(state);
21496 /* Analyze the intermediate code */
21497 state->bb.first = state->first;
21498 analyze_basic_blocks(state, &state->bb);
21500 /* Transform the code to ssa form. */
21502 * The transformation to ssa form puts a phi function
21503 * on each of edge of a dominance frontier where that
21504 * phi function might be needed. At -O2 if we don't
21505 * eleminate the excess phi functions we can get an
21506 * exponential code size growth. So I kill the extra
21507 * phi functions early and I kill them often.
21509 transform_to_ssa_form(state);
21510 verify_consistency(state);
21512 /* Remove dead code */
21513 eliminate_inefectual_code(state);
21514 verify_consistency(state);
21516 /* Do strength reduction and simple constant optimizations */
21517 simplify_all(state);
21518 verify_consistency(state);
21519 /* Propogate constants throughout the code */
21520 scc_transform(state);
21521 verify_consistency(state);
21522 #warning "WISHLIST implement single use constants (least possible register pressure)"
21523 #warning "WISHLIST implement induction variable elimination"
21524 /* Select architecture instructions and an initial partial
21525 * coloring based on architecture constraints.
21527 transform_to_arch_instructions(state);
21528 verify_consistency(state);
21530 /* Remove dead code */
21531 eliminate_inefectual_code(state);
21532 verify_consistency(state);
21534 /* Color all of the variables to see if they will fit in registers */
21535 insert_copies_to_phi(state);
21536 verify_consistency(state);
21538 insert_mandatory_copies(state);
21539 verify_consistency(state);
21541 allocate_registers(state);
21542 verify_consistency(state);
21544 /* Remove the optimization information.
21545 * This is more to check for memory consistency than to free memory.
21547 free_basic_blocks(state, &state->bb);
21550 static void print_op_asm(struct compile_state *state,
21551 struct triple *ins, FILE *fp)
21553 struct asm_info *info;
21555 unsigned lhs, rhs, i;
21556 info = ins->u.ainfo;
21559 /* Don't count the clobbers in lhs */
21560 for(i = 0; i < lhs; i++) {
21561 if (LHS(ins, i)->type == &void_type) {
21566 fprintf(fp, "#ASM\n");
21568 for(ptr = info->str; *ptr; ptr++) {
21570 unsigned long param;
21571 struct triple *piece;
21581 param = strtoul(ptr, &next, 10);
21583 error(state, ins, "Invalid asm template");
21585 if (param >= (lhs + rhs)) {
21586 error(state, ins, "Invalid param %%%u in asm template",
21589 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21591 arch_reg_str(ID_REG(piece->id)));
21594 fprintf(fp, "\n#NOT ASM\n");
21598 /* Only use the low x86 byte registers. This allows me
21599 * allocate the entire register when a byte register is used.
21601 #define X86_4_8BIT_GPRS 1
21604 #define X86_MMX_REGS (1<<0)
21605 #define X86_XMM_REGS (1<<1)
21606 #define X86_NOOP_COPY (1<<2)
21608 /* The x86 register classes */
21609 #define REGC_FLAGS 0
21610 #define REGC_GPR8 1
21611 #define REGC_GPR16 2
21612 #define REGC_GPR32 3
21613 #define REGC_DIVIDEND64 4
21614 #define REGC_DIVIDEND32 5
21617 #define REGC_GPR32_8 8
21618 #define REGC_GPR16_8 9
21619 #define REGC_GPR8_LO 10
21620 #define REGC_IMM32 11
21621 #define REGC_IMM16 12
21622 #define REGC_IMM8 13
21623 #define LAST_REGC REGC_IMM8
21624 #if LAST_REGC >= MAX_REGC
21625 #error "MAX_REGC is to low"
21628 /* Register class masks */
21629 #define REGCM_FLAGS (1 << REGC_FLAGS)
21630 #define REGCM_GPR8 (1 << REGC_GPR8)
21631 #define REGCM_GPR16 (1 << REGC_GPR16)
21632 #define REGCM_GPR32 (1 << REGC_GPR32)
21633 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21634 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21635 #define REGCM_MMX (1 << REGC_MMX)
21636 #define REGCM_XMM (1 << REGC_XMM)
21637 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21638 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21639 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21640 #define REGCM_IMM32 (1 << REGC_IMM32)
21641 #define REGCM_IMM16 (1 << REGC_IMM16)
21642 #define REGCM_IMM8 (1 << REGC_IMM8)
21643 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21644 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21646 /* The x86 registers */
21647 #define REG_EFLAGS 2
21648 #define REGC_FLAGS_FIRST REG_EFLAGS
21649 #define REGC_FLAGS_LAST REG_EFLAGS
21658 #define REGC_GPR8_LO_FIRST REG_AL
21659 #define REGC_GPR8_LO_LAST REG_DL
21660 #define REGC_GPR8_FIRST REG_AL
21661 #define REGC_GPR8_LAST REG_DH
21670 #define REGC_GPR16_FIRST REG_AX
21671 #define REGC_GPR16_LAST REG_SP
21680 #define REGC_GPR32_FIRST REG_EAX
21681 #define REGC_GPR32_LAST REG_ESP
21682 #define REG_EDXEAX 27
21683 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21684 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21685 #define REG_DXAX 28
21686 #define REGC_DIVIDEND32_FIRST REG_DXAX
21687 #define REGC_DIVIDEND32_LAST REG_DXAX
21688 #define REG_MMX0 29
21689 #define REG_MMX1 30
21690 #define REG_MMX2 31
21691 #define REG_MMX3 32
21692 #define REG_MMX4 33
21693 #define REG_MMX5 34
21694 #define REG_MMX6 35
21695 #define REG_MMX7 36
21696 #define REGC_MMX_FIRST REG_MMX0
21697 #define REGC_MMX_LAST REG_MMX7
21698 #define REG_XMM0 37
21699 #define REG_XMM1 38
21700 #define REG_XMM2 39
21701 #define REG_XMM3 40
21702 #define REG_XMM4 41
21703 #define REG_XMM5 42
21704 #define REG_XMM6 43
21705 #define REG_XMM7 44
21706 #define REGC_XMM_FIRST REG_XMM0
21707 #define REGC_XMM_LAST REG_XMM7
21708 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21709 #define LAST_REG REG_XMM7
21711 #define REGC_GPR32_8_FIRST REG_EAX
21712 #define REGC_GPR32_8_LAST REG_EDX
21713 #define REGC_GPR16_8_FIRST REG_AX
21714 #define REGC_GPR16_8_LAST REG_DX
21716 #define REGC_IMM8_FIRST -1
21717 #define REGC_IMM8_LAST -1
21718 #define REGC_IMM16_FIRST -2
21719 #define REGC_IMM16_LAST -1
21720 #define REGC_IMM32_FIRST -4
21721 #define REGC_IMM32_LAST -1
21723 #if LAST_REG >= MAX_REGISTERS
21724 #error "MAX_REGISTERS to low"
21728 static unsigned regc_size[LAST_REGC +1] = {
21729 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21730 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21731 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21732 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21733 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21734 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21735 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21736 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21737 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21738 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21739 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21745 static const struct {
21747 } regcm_bound[LAST_REGC + 1] = {
21748 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21749 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21750 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21751 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21752 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21753 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21754 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21755 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21756 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21757 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21758 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21759 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21760 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21761 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21764 #if ARCH_INPUT_REGS != 4
21765 #error ARCH_INPUT_REGS size mismatch
21767 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21768 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21769 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21770 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21771 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21774 #if ARCH_OUTPUT_REGS != 4
21775 #error ARCH_INPUT_REGS size mismatch
21777 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21778 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21779 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21780 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21781 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21784 static void init_arch_state(struct arch_state *arch)
21786 memset(arch, 0, sizeof(*arch));
21787 arch->features = 0;
21790 static const struct compiler_flag arch_flags[] = {
21791 { "mmx", X86_MMX_REGS },
21792 { "sse", X86_XMM_REGS },
21793 { "noop-copy", X86_NOOP_COPY },
21796 static const struct compiler_flag arch_cpus[] = {
21798 { "p2", X86_MMX_REGS },
21799 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21800 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21801 { "k7", X86_MMX_REGS },
21802 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21803 { "c3", X86_MMX_REGS },
21804 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21807 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21814 if (strncmp(flag, "no-", 3) == 0) {
21818 if (act && strncmp(flag, "cpu=", 4) == 0) {
21820 result = set_flag(arch_cpus, &arch->features, 1, flag);
21823 result = set_flag(arch_flags, &arch->features, act, flag);
21828 static void arch_usage(FILE *fp)
21830 flag_usage(fp, arch_flags, "-m", "-mno-");
21831 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21834 static unsigned arch_regc_size(struct compile_state *state, int class)
21836 if ((class < 0) || (class > LAST_REGC)) {
21839 return regc_size[class];
21842 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21844 /* See if two register classes may have overlapping registers */
21845 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21846 REGCM_GPR32_8 | REGCM_GPR32 |
21847 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21849 /* Special case for the immediates */
21850 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21851 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21852 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21853 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21856 return (regcm1 & regcm2) ||
21857 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21860 static void arch_reg_equivs(
21861 struct compile_state *state, unsigned *equiv, int reg)
21863 if ((reg < 0) || (reg > LAST_REG)) {
21864 internal_error(state, 0, "invalid register");
21869 #if X86_4_8BIT_GPRS
21873 *equiv++ = REG_EAX;
21874 *equiv++ = REG_DXAX;
21875 *equiv++ = REG_EDXEAX;
21878 #if X86_4_8BIT_GPRS
21882 *equiv++ = REG_EAX;
21883 *equiv++ = REG_DXAX;
21884 *equiv++ = REG_EDXEAX;
21887 #if X86_4_8BIT_GPRS
21891 *equiv++ = REG_EBX;
21895 #if X86_4_8BIT_GPRS
21899 *equiv++ = REG_EBX;
21902 #if X86_4_8BIT_GPRS
21906 *equiv++ = REG_ECX;
21910 #if X86_4_8BIT_GPRS
21914 *equiv++ = REG_ECX;
21917 #if X86_4_8BIT_GPRS
21921 *equiv++ = REG_EDX;
21922 *equiv++ = REG_DXAX;
21923 *equiv++ = REG_EDXEAX;
21926 #if X86_4_8BIT_GPRS
21930 *equiv++ = REG_EDX;
21931 *equiv++ = REG_DXAX;
21932 *equiv++ = REG_EDXEAX;
21937 *equiv++ = REG_EAX;
21938 *equiv++ = REG_DXAX;
21939 *equiv++ = REG_EDXEAX;
21944 *equiv++ = REG_EBX;
21949 *equiv++ = REG_ECX;
21954 *equiv++ = REG_EDX;
21955 *equiv++ = REG_DXAX;
21956 *equiv++ = REG_EDXEAX;
21959 *equiv++ = REG_ESI;
21962 *equiv++ = REG_EDI;
21965 *equiv++ = REG_EBP;
21968 *equiv++ = REG_ESP;
21974 *equiv++ = REG_DXAX;
21975 *equiv++ = REG_EDXEAX;
21991 *equiv++ = REG_DXAX;
21992 *equiv++ = REG_EDXEAX;
22013 *equiv++ = REG_EAX;
22014 *equiv++ = REG_EDX;
22015 *equiv++ = REG_EDXEAX;
22024 *equiv++ = REG_EAX;
22025 *equiv++ = REG_EDX;
22026 *equiv++ = REG_DXAX;
22029 *equiv++ = REG_UNSET;
22032 static unsigned arch_avail_mask(struct compile_state *state)
22034 unsigned avail_mask;
22035 /* REGCM_GPR8 is not available */
22036 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22037 REGCM_GPR32 | REGCM_GPR32_8 |
22038 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22039 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22040 if (state->arch->features & X86_MMX_REGS) {
22041 avail_mask |= REGCM_MMX;
22043 if (state->arch->features & X86_XMM_REGS) {
22044 avail_mask |= REGCM_XMM;
22049 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22051 unsigned mask, result;
22055 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22056 if ((result & mask) == 0) {
22059 if (class > LAST_REGC) {
22062 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22063 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22064 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22065 result |= (1 << class2);
22069 result &= arch_avail_mask(state);
22073 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22075 /* Like arch_regcm_normalize except immediate register classes are excluded */
22076 regcm = arch_regcm_normalize(state, regcm);
22077 /* Remove the immediate register classes */
22078 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22083 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22088 for(class = 0; class <= LAST_REGC; class++) {
22089 if ((reg >= regcm_bound[class].first) &&
22090 (reg <= regcm_bound[class].last)) {
22091 mask |= (1 << class);
22095 internal_error(state, 0, "reg %d not in any class", reg);
22100 static struct reg_info arch_reg_constraint(
22101 struct compile_state *state, struct type *type, const char *constraint)
22103 static const struct {
22107 } constraints[] = {
22108 { 'r', REGCM_GPR32, REG_UNSET },
22109 { 'g', REGCM_GPR32, REG_UNSET },
22110 { 'p', REGCM_GPR32, REG_UNSET },
22111 { 'q', REGCM_GPR8_LO, REG_UNSET },
22112 { 'Q', REGCM_GPR32_8, REG_UNSET },
22113 { 'x', REGCM_XMM, REG_UNSET },
22114 { 'y', REGCM_MMX, REG_UNSET },
22115 { 'a', REGCM_GPR32, REG_EAX },
22116 { 'b', REGCM_GPR32, REG_EBX },
22117 { 'c', REGCM_GPR32, REG_ECX },
22118 { 'd', REGCM_GPR32, REG_EDX },
22119 { 'D', REGCM_GPR32, REG_EDI },
22120 { 'S', REGCM_GPR32, REG_ESI },
22121 { '\0', 0, REG_UNSET },
22123 unsigned int regcm;
22124 unsigned int mask, reg;
22125 struct reg_info result;
22127 regcm = arch_type_to_regcm(state, type);
22130 for(ptr = constraint; *ptr; ptr++) {
22135 for(i = 0; constraints[i].class != '\0'; i++) {
22136 if (constraints[i].class == *ptr) {
22140 if (constraints[i].class == '\0') {
22141 error(state, 0, "invalid register constraint ``%c''", *ptr);
22144 if ((constraints[i].mask & regcm) == 0) {
22145 error(state, 0, "invalid register class %c specified",
22148 mask |= constraints[i].mask;
22149 if (constraints[i].reg != REG_UNSET) {
22150 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22151 error(state, 0, "Only one register may be specified");
22153 reg = constraints[i].reg;
22157 result.regcm = mask;
22161 static struct reg_info arch_reg_clobber(
22162 struct compile_state *state, const char *clobber)
22164 struct reg_info result;
22165 if (strcmp(clobber, "memory") == 0) {
22166 result.reg = REG_UNSET;
22169 else if (strcmp(clobber, "eax") == 0) {
22170 result.reg = REG_EAX;
22171 result.regcm = REGCM_GPR32;
22173 else if (strcmp(clobber, "ebx") == 0) {
22174 result.reg = REG_EBX;
22175 result.regcm = REGCM_GPR32;
22177 else if (strcmp(clobber, "ecx") == 0) {
22178 result.reg = REG_ECX;
22179 result.regcm = REGCM_GPR32;
22181 else if (strcmp(clobber, "edx") == 0) {
22182 result.reg = REG_EDX;
22183 result.regcm = REGCM_GPR32;
22185 else if (strcmp(clobber, "esi") == 0) {
22186 result.reg = REG_ESI;
22187 result.regcm = REGCM_GPR32;
22189 else if (strcmp(clobber, "edi") == 0) {
22190 result.reg = REG_EDI;
22191 result.regcm = REGCM_GPR32;
22193 else if (strcmp(clobber, "ebp") == 0) {
22194 result.reg = REG_EBP;
22195 result.regcm = REGCM_GPR32;
22197 else if (strcmp(clobber, "esp") == 0) {
22198 result.reg = REG_ESP;
22199 result.regcm = REGCM_GPR32;
22201 else if (strcmp(clobber, "cc") == 0) {
22202 result.reg = REG_EFLAGS;
22203 result.regcm = REGCM_FLAGS;
22205 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22206 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22207 result.reg = REG_XMM0 + octdigval(clobber[3]);
22208 result.regcm = REGCM_XMM;
22210 else if ((strncmp(clobber, "mm", 2) == 0) &&
22211 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22212 result.reg = REG_MMX0 + octdigval(clobber[3]);
22213 result.regcm = REGCM_MMX;
22216 error(state, 0, "unknown register name `%s' in asm",
22218 result.reg = REG_UNSET;
22224 static int do_select_reg(struct compile_state *state,
22225 char *used, int reg, unsigned classes)
22231 mask = arch_reg_regcm(state, reg);
22232 return (classes & mask) ? reg : REG_UNSET;
22235 static int arch_select_free_register(
22236 struct compile_state *state, char *used, int classes)
22238 /* Live ranges with the most neighbors are colored first.
22240 * Generally it does not matter which colors are given
22241 * as the register allocator attempts to color live ranges
22242 * in an order where you are guaranteed not to run out of colors.
22244 * Occasionally the register allocator cannot find an order
22245 * of register selection that will find a free color. To
22246 * increase the odds the register allocator will work when
22247 * it guesses first give out registers from register classes
22248 * least likely to run out of registers.
22253 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22254 reg = do_select_reg(state, used, i, classes);
22256 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22257 reg = do_select_reg(state, used, i, classes);
22259 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22260 reg = do_select_reg(state, used, i, classes);
22262 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22263 reg = do_select_reg(state, used, i, classes);
22265 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22266 reg = do_select_reg(state, used, i, classes);
22268 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22269 reg = do_select_reg(state, used, i, classes);
22271 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22272 reg = do_select_reg(state, used, i, classes);
22274 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22275 reg = do_select_reg(state, used, i, classes);
22277 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22278 reg = do_select_reg(state, used, i, classes);
22284 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22286 #warning "FIXME force types smaller (if legal) before I get here"
22289 switch(type->type & TYPE_MASK) {
22296 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22297 REGCM_GPR16 | REGCM_GPR16_8 |
22298 REGCM_GPR32 | REGCM_GPR32_8 |
22299 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22300 REGCM_MMX | REGCM_XMM |
22301 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22305 mask = REGCM_GPR16 | REGCM_GPR16_8 |
22306 REGCM_GPR32 | REGCM_GPR32_8 |
22307 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22308 REGCM_MMX | REGCM_XMM |
22309 REGCM_IMM32 | REGCM_IMM16;
22317 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22318 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22319 REGCM_MMX | REGCM_XMM |
22324 mask = arch_type_to_regcm(state, type->left);
22327 mask = arch_type_to_regcm(state, type->left) &
22328 arch_type_to_regcm(state, type->right);
22330 case TYPE_BITFIELD:
22331 mask = arch_type_to_regcm(state, type->left);
22334 fprintf(state->errout, "type: ");
22335 name_of(state->errout, type);
22336 fprintf(state->errout, "\n");
22337 internal_error(state, 0, "no register class for type");
22340 mask = arch_regcm_normalize(state, mask);
22344 static int is_imm32(struct triple *imm)
22346 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22347 (imm->op == OP_ADDRCONST);
22350 static int is_imm16(struct triple *imm)
22352 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22354 static int is_imm8(struct triple *imm)
22356 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22359 static int get_imm32(struct triple *ins, struct triple **expr)
22361 struct triple *imm;
22363 while(imm->op == OP_COPY) {
22366 if (!is_imm32(imm)) {
22369 unuse_triple(*expr, ins);
22370 use_triple(imm, ins);
22375 static int get_imm8(struct triple *ins, struct triple **expr)
22377 struct triple *imm;
22379 while(imm->op == OP_COPY) {
22382 if (!is_imm8(imm)) {
22385 unuse_triple(*expr, ins);
22386 use_triple(imm, ins);
22391 #define TEMPLATE_NOP 0
22392 #define TEMPLATE_INTCONST8 1
22393 #define TEMPLATE_INTCONST32 2
22394 #define TEMPLATE_UNKNOWNVAL 3
22395 #define TEMPLATE_COPY8_REG 5
22396 #define TEMPLATE_COPY16_REG 6
22397 #define TEMPLATE_COPY32_REG 7
22398 #define TEMPLATE_COPY_IMM8 8
22399 #define TEMPLATE_COPY_IMM16 9
22400 #define TEMPLATE_COPY_IMM32 10
22401 #define TEMPLATE_PHI8 11
22402 #define TEMPLATE_PHI16 12
22403 #define TEMPLATE_PHI32 13
22404 #define TEMPLATE_STORE8 14
22405 #define TEMPLATE_STORE16 15
22406 #define TEMPLATE_STORE32 16
22407 #define TEMPLATE_LOAD8 17
22408 #define TEMPLATE_LOAD16 18
22409 #define TEMPLATE_LOAD32 19
22410 #define TEMPLATE_BINARY8_REG 20
22411 #define TEMPLATE_BINARY16_REG 21
22412 #define TEMPLATE_BINARY32_REG 22
22413 #define TEMPLATE_BINARY8_IMM 23
22414 #define TEMPLATE_BINARY16_IMM 24
22415 #define TEMPLATE_BINARY32_IMM 25
22416 #define TEMPLATE_SL8_CL 26
22417 #define TEMPLATE_SL16_CL 27
22418 #define TEMPLATE_SL32_CL 28
22419 #define TEMPLATE_SL8_IMM 29
22420 #define TEMPLATE_SL16_IMM 30
22421 #define TEMPLATE_SL32_IMM 31
22422 #define TEMPLATE_UNARY8 32
22423 #define TEMPLATE_UNARY16 33
22424 #define TEMPLATE_UNARY32 34
22425 #define TEMPLATE_CMP8_REG 35
22426 #define TEMPLATE_CMP16_REG 36
22427 #define TEMPLATE_CMP32_REG 37
22428 #define TEMPLATE_CMP8_IMM 38
22429 #define TEMPLATE_CMP16_IMM 39
22430 #define TEMPLATE_CMP32_IMM 40
22431 #define TEMPLATE_TEST8 41
22432 #define TEMPLATE_TEST16 42
22433 #define TEMPLATE_TEST32 43
22434 #define TEMPLATE_SET 44
22435 #define TEMPLATE_JMP 45
22436 #define TEMPLATE_RET 46
22437 #define TEMPLATE_INB_DX 47
22438 #define TEMPLATE_INB_IMM 48
22439 #define TEMPLATE_INW_DX 49
22440 #define TEMPLATE_INW_IMM 50
22441 #define TEMPLATE_INL_DX 51
22442 #define TEMPLATE_INL_IMM 52
22443 #define TEMPLATE_OUTB_DX 53
22444 #define TEMPLATE_OUTB_IMM 54
22445 #define TEMPLATE_OUTW_DX 55
22446 #define TEMPLATE_OUTW_IMM 56
22447 #define TEMPLATE_OUTL_DX 57
22448 #define TEMPLATE_OUTL_IMM 58
22449 #define TEMPLATE_BSF 59
22450 #define TEMPLATE_RDMSR 60
22451 #define TEMPLATE_WRMSR 61
22452 #define TEMPLATE_UMUL8 62
22453 #define TEMPLATE_UMUL16 63
22454 #define TEMPLATE_UMUL32 64
22455 #define TEMPLATE_DIV8 65
22456 #define TEMPLATE_DIV16 66
22457 #define TEMPLATE_DIV32 67
22458 #define LAST_TEMPLATE TEMPLATE_DIV32
22459 #if LAST_TEMPLATE >= MAX_TEMPLATES
22460 #error "MAX_TEMPLATES to low"
22463 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22464 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22465 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22468 static struct ins_template templates[] = {
22471 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22472 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22473 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22474 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22475 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22476 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22477 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22478 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22479 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22480 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22481 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22482 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22483 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22484 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22485 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22486 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22487 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22488 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22489 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22490 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22491 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22492 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22493 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22494 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22495 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22496 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22497 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22498 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22499 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22500 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22501 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22502 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22503 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22504 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22505 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22506 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22507 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22508 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22509 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22510 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22511 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22512 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22513 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22514 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22515 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22516 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22517 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22518 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22519 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22520 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22521 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22522 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22523 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22524 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22525 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22526 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22527 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22528 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22529 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22530 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22531 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22532 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22533 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22534 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22537 [TEMPLATE_INTCONST8] = {
22538 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22540 [TEMPLATE_INTCONST32] = {
22541 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22543 [TEMPLATE_UNKNOWNVAL] = {
22544 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22546 [TEMPLATE_COPY8_REG] = {
22547 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22548 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22550 [TEMPLATE_COPY16_REG] = {
22551 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22552 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22554 [TEMPLATE_COPY32_REG] = {
22555 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22556 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22558 [TEMPLATE_COPY_IMM8] = {
22559 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22560 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22562 [TEMPLATE_COPY_IMM16] = {
22563 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22564 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22566 [TEMPLATE_COPY_IMM32] = {
22567 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22568 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22570 [TEMPLATE_PHI8] = {
22571 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22572 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22574 [TEMPLATE_PHI16] = {
22575 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22576 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22578 [TEMPLATE_PHI32] = {
22579 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22580 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22582 [TEMPLATE_STORE8] = {
22584 [0] = { REG_UNSET, REGCM_GPR32 },
22585 [1] = { REG_UNSET, REGCM_GPR8_LO },
22588 [TEMPLATE_STORE16] = {
22590 [0] = { REG_UNSET, REGCM_GPR32 },
22591 [1] = { REG_UNSET, REGCM_GPR16 },
22594 [TEMPLATE_STORE32] = {
22596 [0] = { REG_UNSET, REGCM_GPR32 },
22597 [1] = { REG_UNSET, REGCM_GPR32 },
22600 [TEMPLATE_LOAD8] = {
22601 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22602 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22604 [TEMPLATE_LOAD16] = {
22605 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22606 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22608 [TEMPLATE_LOAD32] = {
22609 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22610 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22612 [TEMPLATE_BINARY8_REG] = {
22613 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22615 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22616 [1] = { REG_UNSET, REGCM_GPR8_LO },
22619 [TEMPLATE_BINARY16_REG] = {
22620 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22622 [0] = { REG_VIRT0, REGCM_GPR16 },
22623 [1] = { REG_UNSET, REGCM_GPR16 },
22626 [TEMPLATE_BINARY32_REG] = {
22627 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22629 [0] = { REG_VIRT0, REGCM_GPR32 },
22630 [1] = { REG_UNSET, REGCM_GPR32 },
22633 [TEMPLATE_BINARY8_IMM] = {
22634 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22636 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22637 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22640 [TEMPLATE_BINARY16_IMM] = {
22641 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22643 [0] = { REG_VIRT0, REGCM_GPR16 },
22644 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22647 [TEMPLATE_BINARY32_IMM] = {
22648 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22650 [0] = { REG_VIRT0, REGCM_GPR32 },
22651 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22654 [TEMPLATE_SL8_CL] = {
22655 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22657 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22658 [1] = { REG_CL, REGCM_GPR8_LO },
22661 [TEMPLATE_SL16_CL] = {
22662 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22664 [0] = { REG_VIRT0, REGCM_GPR16 },
22665 [1] = { REG_CL, REGCM_GPR8_LO },
22668 [TEMPLATE_SL32_CL] = {
22669 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22671 [0] = { REG_VIRT0, REGCM_GPR32 },
22672 [1] = { REG_CL, REGCM_GPR8_LO },
22675 [TEMPLATE_SL8_IMM] = {
22676 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22678 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22679 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22682 [TEMPLATE_SL16_IMM] = {
22683 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22685 [0] = { REG_VIRT0, REGCM_GPR16 },
22686 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22689 [TEMPLATE_SL32_IMM] = {
22690 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22692 [0] = { REG_VIRT0, REGCM_GPR32 },
22693 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22696 [TEMPLATE_UNARY8] = {
22697 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22698 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22700 [TEMPLATE_UNARY16] = {
22701 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22702 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22704 [TEMPLATE_UNARY32] = {
22705 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22706 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22708 [TEMPLATE_CMP8_REG] = {
22709 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22711 [0] = { REG_UNSET, REGCM_GPR8_LO },
22712 [1] = { REG_UNSET, REGCM_GPR8_LO },
22715 [TEMPLATE_CMP16_REG] = {
22716 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22718 [0] = { REG_UNSET, REGCM_GPR16 },
22719 [1] = { REG_UNSET, REGCM_GPR16 },
22722 [TEMPLATE_CMP32_REG] = {
22723 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22725 [0] = { REG_UNSET, REGCM_GPR32 },
22726 [1] = { REG_UNSET, REGCM_GPR32 },
22729 [TEMPLATE_CMP8_IMM] = {
22730 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22732 [0] = { REG_UNSET, REGCM_GPR8_LO },
22733 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22736 [TEMPLATE_CMP16_IMM] = {
22737 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22739 [0] = { REG_UNSET, REGCM_GPR16 },
22740 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22743 [TEMPLATE_CMP32_IMM] = {
22744 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22746 [0] = { REG_UNSET, REGCM_GPR32 },
22747 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22750 [TEMPLATE_TEST8] = {
22751 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22752 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22754 [TEMPLATE_TEST16] = {
22755 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22756 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22758 [TEMPLATE_TEST32] = {
22759 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22760 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22763 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22764 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22767 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22770 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22772 [TEMPLATE_INB_DX] = {
22773 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22774 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22776 [TEMPLATE_INB_IMM] = {
22777 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22778 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22780 [TEMPLATE_INW_DX] = {
22781 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22782 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22784 [TEMPLATE_INW_IMM] = {
22785 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22786 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22788 [TEMPLATE_INL_DX] = {
22789 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22790 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22792 [TEMPLATE_INL_IMM] = {
22793 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22794 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22796 [TEMPLATE_OUTB_DX] = {
22798 [0] = { REG_AL, REGCM_GPR8_LO },
22799 [1] = { REG_DX, REGCM_GPR16 },
22802 [TEMPLATE_OUTB_IMM] = {
22804 [0] = { REG_AL, REGCM_GPR8_LO },
22805 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22808 [TEMPLATE_OUTW_DX] = {
22810 [0] = { REG_AX, REGCM_GPR16 },
22811 [1] = { REG_DX, REGCM_GPR16 },
22814 [TEMPLATE_OUTW_IMM] = {
22816 [0] = { REG_AX, REGCM_GPR16 },
22817 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22820 [TEMPLATE_OUTL_DX] = {
22822 [0] = { REG_EAX, REGCM_GPR32 },
22823 [1] = { REG_DX, REGCM_GPR16 },
22826 [TEMPLATE_OUTL_IMM] = {
22828 [0] = { REG_EAX, REGCM_GPR32 },
22829 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22833 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22834 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22836 [TEMPLATE_RDMSR] = {
22838 [0] = { REG_EAX, REGCM_GPR32 },
22839 [1] = { REG_EDX, REGCM_GPR32 },
22841 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22843 [TEMPLATE_WRMSR] = {
22845 [0] = { REG_ECX, REGCM_GPR32 },
22846 [1] = { REG_EAX, REGCM_GPR32 },
22847 [2] = { REG_EDX, REGCM_GPR32 },
22850 [TEMPLATE_UMUL8] = {
22851 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22853 [0] = { REG_AL, REGCM_GPR8_LO },
22854 [1] = { REG_UNSET, REGCM_GPR8_LO },
22857 [TEMPLATE_UMUL16] = {
22858 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22860 [0] = { REG_AX, REGCM_GPR16 },
22861 [1] = { REG_UNSET, REGCM_GPR16 },
22864 [TEMPLATE_UMUL32] = {
22865 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22867 [0] = { REG_EAX, REGCM_GPR32 },
22868 [1] = { REG_UNSET, REGCM_GPR32 },
22871 [TEMPLATE_DIV8] = {
22873 [0] = { REG_AL, REGCM_GPR8_LO },
22874 [1] = { REG_AH, REGCM_GPR8 },
22877 [0] = { REG_AX, REGCM_GPR16 },
22878 [1] = { REG_UNSET, REGCM_GPR8_LO },
22881 [TEMPLATE_DIV16] = {
22883 [0] = { REG_AX, REGCM_GPR16 },
22884 [1] = { REG_DX, REGCM_GPR16 },
22887 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22888 [1] = { REG_UNSET, REGCM_GPR16 },
22891 [TEMPLATE_DIV32] = {
22893 [0] = { REG_EAX, REGCM_GPR32 },
22894 [1] = { REG_EDX, REGCM_GPR32 },
22897 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22898 [1] = { REG_UNSET, REGCM_GPR32 },
22903 static void fixup_branch(struct compile_state *state,
22904 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
22905 struct triple *left, struct triple *right)
22907 struct triple *test;
22909 internal_error(state, branch, "no branch test?");
22911 test = pre_triple(state, branch,
22912 cmp_op, cmp_type, left, right);
22913 test->template_id = TEMPLATE_TEST32;
22914 if (cmp_op == OP_CMP) {
22915 test->template_id = TEMPLATE_CMP32_REG;
22916 if (get_imm32(test, &RHS(test, 1))) {
22917 test->template_id = TEMPLATE_CMP32_IMM;
22920 use_triple(RHS(test, 0), test);
22921 use_triple(RHS(test, 1), test);
22922 unuse_triple(RHS(branch, 0), branch);
22923 RHS(branch, 0) = test;
22924 branch->op = jmp_op;
22925 branch->template_id = TEMPLATE_JMP;
22926 use_triple(RHS(branch, 0), branch);
22929 static void fixup_branches(struct compile_state *state,
22930 struct triple *cmp, struct triple *use, int jmp_op)
22932 struct triple_set *entry, *next;
22933 for(entry = use->use; entry; entry = next) {
22934 next = entry->next;
22935 if (entry->member->op == OP_COPY) {
22936 fixup_branches(state, cmp, entry->member, jmp_op);
22938 else if (entry->member->op == OP_CBRANCH) {
22939 struct triple *branch;
22940 struct triple *left, *right;
22942 left = RHS(cmp, 0);
22943 if (cmp->rhs > 1) {
22944 right = RHS(cmp, 1);
22946 branch = entry->member;
22947 fixup_branch(state, branch, jmp_op,
22948 cmp->op, cmp->type, left, right);
22953 static void bool_cmp(struct compile_state *state,
22954 struct triple *ins, int cmp_op, int jmp_op, int set_op)
22956 struct triple_set *entry, *next;
22957 struct triple *set, *convert;
22959 /* Put a barrier up before the cmp which preceeds the
22960 * copy instruction. If a set actually occurs this gives
22961 * us a chance to move variables in registers out of the way.
22964 /* Modify the comparison operator */
22966 ins->template_id = TEMPLATE_TEST32;
22967 if (cmp_op == OP_CMP) {
22968 ins->template_id = TEMPLATE_CMP32_REG;
22969 if (get_imm32(ins, &RHS(ins, 1))) {
22970 ins->template_id = TEMPLATE_CMP32_IMM;
22973 /* Generate the instruction sequence that will transform the
22974 * result of the comparison into a logical value.
22976 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
22977 use_triple(ins, set);
22978 set->template_id = TEMPLATE_SET;
22981 if (!equiv_types(ins->type, set->type)) {
22982 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
22983 use_triple(set, convert);
22984 convert->template_id = TEMPLATE_COPY32_REG;
22987 for(entry = ins->use; entry; entry = next) {
22988 next = entry->next;
22989 if (entry->member == set) {
22992 replace_rhs_use(state, ins, convert, entry->member);
22994 fixup_branches(state, ins, convert, jmp_op);
22997 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
22999 struct ins_template *template;
23000 struct reg_info result;
23002 if (ins->op == OP_PIECE) {
23003 index = ins->u.cval;
23004 ins = MISC(ins, 0);
23007 if (triple_is_def(state, ins)) {
23010 if (index >= zlhs) {
23011 internal_error(state, ins, "index %d out of range for %s",
23012 index, tops(ins->op));
23016 template = &ins->u.ainfo->tmpl;
23019 if (ins->template_id > LAST_TEMPLATE) {
23020 internal_error(state, ins, "bad template number %d",
23023 template = &templates[ins->template_id];
23026 result = template->lhs[index];
23027 result.regcm = arch_regcm_normalize(state, result.regcm);
23028 if (result.reg != REG_UNNEEDED) {
23029 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23031 if (result.regcm == 0) {
23032 internal_error(state, ins, "lhs %d regcm == 0", index);
23037 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23039 struct reg_info result;
23040 struct ins_template *template;
23041 if ((index > ins->rhs) ||
23042 (ins->op == OP_PIECE)) {
23043 internal_error(state, ins, "index %d out of range for %s\n",
23044 index, tops(ins->op));
23048 template = &ins->u.ainfo->tmpl;
23054 if (ins->template_id > LAST_TEMPLATE) {
23055 internal_error(state, ins, "bad template number %d",
23058 template = &templates[ins->template_id];
23061 result = template->rhs[index];
23062 result.regcm = arch_regcm_normalize(state, result.regcm);
23063 if (result.regcm == 0) {
23064 internal_error(state, ins, "rhs %d regcm == 0", index);
23069 static struct triple *mod_div(struct compile_state *state,
23070 struct triple *ins, int div_op, int index)
23072 struct triple *div, *piece0, *piece1;
23074 /* Generate the appropriate division instruction */
23075 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23076 RHS(div, 0) = RHS(ins, 0);
23077 RHS(div, 1) = RHS(ins, 1);
23078 piece0 = LHS(div, 0);
23079 piece1 = LHS(div, 1);
23080 div->template_id = TEMPLATE_DIV32;
23081 use_triple(RHS(div, 0), div);
23082 use_triple(RHS(div, 1), div);
23083 use_triple(LHS(div, 0), div);
23084 use_triple(LHS(div, 1), div);
23086 /* Replate uses of ins with the appropriate piece of the div */
23087 propogate_use(state, ins, LHS(div, index));
23088 release_triple(state, ins);
23090 /* Return the address of the next instruction */
23091 return piece1->next;
23094 static int noop_adecl(struct triple *adecl)
23096 struct triple_set *use;
23097 /* It's a noop if it doesn't specify stoorage */
23098 if (adecl->lhs == 0) {
23101 /* Is the adecl used? If not it's a noop */
23102 for(use = adecl->use; use ; use = use->next) {
23103 if ((use->member->op != OP_PIECE) ||
23104 (MISC(use->member, 0) != adecl)) {
23111 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23113 struct triple *mask, *nmask, *shift;
23114 struct triple *val, *val_mask, *val_shift;
23115 struct triple *targ, *targ_mask;
23116 struct triple *new;
23117 ulong_t the_mask, the_nmask;
23119 targ = RHS(ins, 0);
23122 /* Get constant for the mask value */
23124 the_mask <<= ins->u.bitfield.size;
23126 the_mask <<= ins->u.bitfield.offset;
23127 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23128 mask->u.cval = the_mask;
23130 /* Get the inverted mask value */
23131 the_nmask = ~the_mask;
23132 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23133 nmask->u.cval = the_nmask;
23135 /* Get constant for the shift value */
23136 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23137 shift->u.cval = ins->u.bitfield.offset;
23139 /* Shift and mask the source value */
23141 if (shift->u.cval != 0) {
23142 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23143 use_triple(val, val_shift);
23144 use_triple(shift, val_shift);
23146 val_mask = val_shift;
23147 if (is_signed(val->type)) {
23148 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23149 use_triple(val_shift, val_mask);
23150 use_triple(mask, val_mask);
23153 /* Mask the target value */
23154 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23155 use_triple(targ, targ_mask);
23156 use_triple(nmask, targ_mask);
23158 /* Now combined them together */
23159 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23160 use_triple(targ_mask, new);
23161 use_triple(val_mask, new);
23163 /* Move all of the users over to the new expression */
23164 propogate_use(state, ins, new);
23166 /* Delete the original triple */
23167 release_triple(state, ins);
23169 /* Restart the transformation at mask */
23173 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23175 struct triple *mask, *shift;
23176 struct triple *val, *val_mask, *val_shift;
23181 /* Get constant for the mask value */
23183 the_mask <<= ins->u.bitfield.size;
23185 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23186 mask->u.cval = the_mask;
23188 /* Get constant for the right shift value */
23189 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23190 shift->u.cval = ins->u.bitfield.offset;
23192 /* Shift arithmetic right, to correct the sign */
23194 if (shift->u.cval != 0) {
23196 if (ins->op == OP_SEXTRACT) {
23201 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23202 use_triple(val, val_shift);
23203 use_triple(shift, val_shift);
23206 /* Finally mask the value */
23207 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23208 use_triple(val_shift, val_mask);
23209 use_triple(mask, val_mask);
23211 /* Move all of the users over to the new expression */
23212 propogate_use(state, ins, val_mask);
23214 /* Release the original instruction */
23215 release_triple(state, ins);
23221 static struct triple *transform_to_arch_instruction(
23222 struct compile_state *state, struct triple *ins)
23224 /* Transform from generic 3 address instructions
23225 * to archtecture specific instructions.
23226 * And apply architecture specific constraints to instructions.
23227 * Copies are inserted to preserve the register flexibility
23228 * of 3 address instructions.
23230 struct triple *next, *value;
23235 ins->template_id = TEMPLATE_INTCONST32;
23236 if (ins->u.cval < 256) {
23237 ins->template_id = TEMPLATE_INTCONST8;
23241 ins->template_id = TEMPLATE_INTCONST32;
23243 case OP_UNKNOWNVAL:
23244 ins->template_id = TEMPLATE_UNKNOWNVAL;
23250 ins->template_id = TEMPLATE_NOP;
23254 size = size_of(state, ins->type);
23255 value = RHS(ins, 0);
23256 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23257 ins->template_id = TEMPLATE_COPY_IMM8;
23259 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23260 ins->template_id = TEMPLATE_COPY_IMM16;
23262 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23263 ins->template_id = TEMPLATE_COPY_IMM32;
23265 else if (is_const(value)) {
23266 internal_error(state, ins, "bad constant passed to copy");
23268 else if (size <= SIZEOF_I8) {
23269 ins->template_id = TEMPLATE_COPY8_REG;
23271 else if (size <= SIZEOF_I16) {
23272 ins->template_id = TEMPLATE_COPY16_REG;
23274 else if (size <= SIZEOF_I32) {
23275 ins->template_id = TEMPLATE_COPY32_REG;
23278 internal_error(state, ins, "bad type passed to copy");
23282 size = size_of(state, ins->type);
23283 if (size <= SIZEOF_I8) {
23284 ins->template_id = TEMPLATE_PHI8;
23286 else if (size <= SIZEOF_I16) {
23287 ins->template_id = TEMPLATE_PHI16;
23289 else if (size <= SIZEOF_I32) {
23290 ins->template_id = TEMPLATE_PHI32;
23293 internal_error(state, ins, "bad type passed to phi");
23297 /* Adecls should always be treated as dead code and
23298 * removed. If we are not optimizing they may linger.
23300 if (!noop_adecl(ins)) {
23301 internal_error(state, ins, "adecl remains?");
23303 ins->template_id = TEMPLATE_NOP;
23304 next = after_lhs(state, ins);
23307 switch(ins->type->type & TYPE_MASK) {
23308 case TYPE_CHAR: case TYPE_UCHAR:
23309 ins->template_id = TEMPLATE_STORE8;
23311 case TYPE_SHORT: case TYPE_USHORT:
23312 ins->template_id = TEMPLATE_STORE16;
23314 case TYPE_INT: case TYPE_UINT:
23315 case TYPE_LONG: case TYPE_ULONG:
23317 ins->template_id = TEMPLATE_STORE32;
23320 internal_error(state, ins, "unknown type in store");
23325 switch(ins->type->type & TYPE_MASK) {
23326 case TYPE_CHAR: case TYPE_UCHAR:
23327 case TYPE_SHORT: case TYPE_USHORT:
23328 case TYPE_INT: case TYPE_UINT:
23329 case TYPE_LONG: case TYPE_ULONG:
23333 internal_error(state, ins, "unknown type in load");
23336 ins->template_id = TEMPLATE_LOAD32;
23344 ins->template_id = TEMPLATE_BINARY32_REG;
23345 if (get_imm32(ins, &RHS(ins, 1))) {
23346 ins->template_id = TEMPLATE_BINARY32_IMM;
23351 ins->template_id = TEMPLATE_DIV32;
23352 next = after_lhs(state, ins);
23355 ins->template_id = TEMPLATE_UMUL32;
23358 next = mod_div(state, ins, OP_UDIVT, 0);
23361 next = mod_div(state, ins, OP_SDIVT, 0);
23364 next = mod_div(state, ins, OP_UDIVT, 1);
23367 next = mod_div(state, ins, OP_SDIVT, 1);
23372 ins->template_id = TEMPLATE_SL32_CL;
23373 if (get_imm8(ins, &RHS(ins, 1))) {
23374 ins->template_id = TEMPLATE_SL32_IMM;
23375 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23376 typed_pre_copy(state, &uchar_type, ins, 1);
23381 ins->template_id = TEMPLATE_UNARY32;
23384 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23387 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23390 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23393 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23396 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23399 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23402 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23405 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23408 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23411 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23414 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23417 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23421 ins->template_id = TEMPLATE_NOP;
23424 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23425 RHS(ins, 0)->type, RHS(ins, 0), 0);
23428 ins->template_id = TEMPLATE_NOP;
23431 ins->template_id = TEMPLATE_RET;
23437 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23438 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23439 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23441 if (get_imm8(ins, &RHS(ins, 0))) {
23442 ins->template_id += 1;
23449 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23450 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23451 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23453 if (get_imm8(ins, &RHS(ins, 1))) {
23454 ins->template_id += 1;
23459 ins->template_id = TEMPLATE_BSF;
23462 ins->template_id = TEMPLATE_RDMSR;
23463 next = after_lhs(state, ins);
23466 ins->template_id = TEMPLATE_WRMSR;
23469 ins->template_id = TEMPLATE_NOP;
23472 ins->template_id = TEMPLATE_NOP;
23473 next = after_lhs(state, ins);
23475 /* Already transformed instructions */
23477 ins->template_id = TEMPLATE_TEST32;
23480 ins->template_id = TEMPLATE_CMP32_REG;
23481 if (get_imm32(ins, &RHS(ins, 1))) {
23482 ins->template_id = TEMPLATE_CMP32_IMM;
23486 ins->template_id = TEMPLATE_NOP;
23488 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23489 case OP_JMP_SLESS: case OP_JMP_ULESS:
23490 case OP_JMP_SMORE: case OP_JMP_UMORE:
23491 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23492 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23493 ins->template_id = TEMPLATE_JMP;
23495 case OP_SET_EQ: case OP_SET_NOTEQ:
23496 case OP_SET_SLESS: case OP_SET_ULESS:
23497 case OP_SET_SMORE: case OP_SET_UMORE:
23498 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23499 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23500 ins->template_id = TEMPLATE_SET;
23503 next = x86_deposit(state, ins);
23507 next = x86_extract(state, ins);
23509 /* Unhandled instructions */
23512 internal_error(state, ins, "unhandled ins: %d %s",
23513 ins->op, tops(ins->op));
23519 static long next_label(struct compile_state *state)
23521 static long label_counter = 1000;
23522 return ++label_counter;
23524 static void generate_local_labels(struct compile_state *state)
23526 struct triple *first, *label;
23527 first = state->first;
23530 if ((label->op == OP_LABEL) ||
23531 (label->op == OP_SDECL)) {
23533 label->u.cval = next_label(state);
23539 label = label->next;
23540 } while(label != first);
23543 static int check_reg(struct compile_state *state,
23544 struct triple *triple, int classes)
23548 reg = ID_REG(triple->id);
23549 if (reg == REG_UNSET) {
23550 internal_error(state, triple, "register not set");
23552 mask = arch_reg_regcm(state, reg);
23553 if (!(classes & mask)) {
23554 internal_error(state, triple, "reg %d in wrong class",
23562 #error "Registers have renumberd fix arch_reg_str"
23564 static const char *arch_regs[] = {
23568 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23569 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23570 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23573 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23574 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23575 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23577 static const char *arch_reg_str(int reg)
23579 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23582 return arch_regs[reg];
23585 static const char *reg(struct compile_state *state, struct triple *triple,
23589 reg = check_reg(state, triple, classes);
23590 return arch_reg_str(reg);
23593 static int arch_reg_size(int reg)
23597 if (reg == REG_EFLAGS) {
23600 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23603 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23606 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23609 else if (reg == REG_EDXEAX) {
23612 else if (reg == REG_DXAX) {
23615 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23618 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23624 static int reg_size(struct compile_state *state, struct triple *ins)
23627 reg = ID_REG(ins->id);
23628 if (reg == REG_UNSET) {
23629 internal_error(state, ins, "register not set");
23631 return arch_reg_size(reg);
23636 const char *type_suffix(struct compile_state *state, struct type *type)
23638 const char *suffix;
23639 switch(size_of(state, type)) {
23640 case SIZEOF_I8: suffix = "b"; break;
23641 case SIZEOF_I16: suffix = "w"; break;
23642 case SIZEOF_I32: suffix = "l"; break;
23644 internal_error(state, 0, "unknown suffix");
23651 static void print_const_val(
23652 struct compile_state *state, struct triple *ins, FILE *fp)
23656 fprintf(fp, " $%ld ",
23657 (long)(ins->u.cval));
23660 if ((MISC(ins, 0)->op != OP_SDECL) &&
23661 (MISC(ins, 0)->op != OP_LABEL))
23663 internal_error(state, ins, "bad base for addrconst");
23665 if (MISC(ins, 0)->u.cval <= 0) {
23666 internal_error(state, ins, "unlabeled constant");
23668 fprintf(fp, " $L%s%lu+%lu ",
23669 state->compiler->label_prefix,
23670 (unsigned long)(MISC(ins, 0)->u.cval),
23671 (unsigned long)(ins->u.cval));
23674 internal_error(state, ins, "unknown constant type");
23679 static void print_const(struct compile_state *state,
23680 struct triple *ins, FILE *fp)
23684 switch(ins->type->type & TYPE_MASK) {
23687 fprintf(fp, ".byte 0x%02lx\n",
23688 (unsigned long)(ins->u.cval));
23692 fprintf(fp, ".short 0x%04lx\n",
23693 (unsigned long)(ins->u.cval));
23700 fprintf(fp, ".int %lu\n",
23701 (unsigned long)(ins->u.cval));
23704 fprintf(state->errout, "type: ");
23705 name_of(state->errout, ins->type);
23706 fprintf(state->errout, "\n");
23707 internal_error(state, ins, "Unknown constant type. Val: %lu",
23708 (unsigned long)(ins->u.cval));
23713 if ((MISC(ins, 0)->op != OP_SDECL) &&
23714 (MISC(ins, 0)->op != OP_LABEL)) {
23715 internal_error(state, ins, "bad base for addrconst");
23717 if (MISC(ins, 0)->u.cval <= 0) {
23718 internal_error(state, ins, "unlabeled constant");
23720 fprintf(fp, ".int L%s%lu+%lu\n",
23721 state->compiler->label_prefix,
23722 (unsigned long)(MISC(ins, 0)->u.cval),
23723 (unsigned long)(ins->u.cval));
23727 unsigned char *blob;
23729 size = size_of_in_bytes(state, ins->type);
23730 blob = ins->u.blob;
23731 for(i = 0; i < size; i++) {
23732 fprintf(fp, ".byte 0x%02x\n",
23738 internal_error(state, ins, "Unknown constant type");
23743 #define TEXT_SECTION ".rom.text"
23744 #define DATA_SECTION ".rom.data"
23746 static long get_const_pool_ref(
23747 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23751 ref = next_label(state);
23752 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23753 fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
23754 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23755 print_const(state, ins, fp);
23756 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23758 fprintf(fp, ".fill %d, 1, 0\n", fill_bytes);
23760 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23764 static long get_mask_pool_ref(
23765 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23768 if (mask == 0xff) {
23771 else if (mask == 0xffff) {
23776 internal_error(state, ins, "unhandled mask value");
23781 static void print_binary_op(struct compile_state *state,
23782 const char *op, struct triple *ins, FILE *fp)
23785 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23786 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23787 internal_error(state, ins, "invalid register assignment");
23789 if (is_const(RHS(ins, 1))) {
23790 fprintf(fp, "\t%s ", op);
23791 print_const_val(state, RHS(ins, 1), fp);
23792 fprintf(fp, ", %s\n",
23793 reg(state, RHS(ins, 0), mask));
23796 unsigned lmask, rmask;
23798 lreg = check_reg(state, RHS(ins, 0), mask);
23799 rreg = check_reg(state, RHS(ins, 1), mask);
23800 lmask = arch_reg_regcm(state, lreg);
23801 rmask = arch_reg_regcm(state, rreg);
23802 mask = lmask & rmask;
23803 fprintf(fp, "\t%s %s, %s\n",
23805 reg(state, RHS(ins, 1), mask),
23806 reg(state, RHS(ins, 0), mask));
23809 static void print_unary_op(struct compile_state *state,
23810 const char *op, struct triple *ins, FILE *fp)
23813 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23814 fprintf(fp, "\t%s %s\n",
23816 reg(state, RHS(ins, 0), mask));
23819 static void print_op_shift(struct compile_state *state,
23820 const char *op, struct triple *ins, FILE *fp)
23823 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23824 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23825 internal_error(state, ins, "invalid register assignment");
23827 if (is_const(RHS(ins, 1))) {
23828 fprintf(fp, "\t%s ", op);
23829 print_const_val(state, RHS(ins, 1), fp);
23830 fprintf(fp, ", %s\n",
23831 reg(state, RHS(ins, 0), mask));
23834 fprintf(fp, "\t%s %s, %s\n",
23836 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23837 reg(state, RHS(ins, 0), mask));
23841 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23848 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23849 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23850 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23852 internal_error(state, ins, "not an in operation");
23856 dreg = check_reg(state, ins, mask);
23857 if (!reg_is_reg(state, dreg, REG_EAX)) {
23858 internal_error(state, ins, "dst != %%eax");
23860 if (is_const(RHS(ins, 0))) {
23861 fprintf(fp, "\t%s ", op);
23862 print_const_val(state, RHS(ins, 0), fp);
23863 fprintf(fp, ", %s\n",
23864 reg(state, ins, mask));
23868 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23869 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23870 internal_error(state, ins, "src != %%dx");
23872 fprintf(fp, "\t%s %s, %s\n",
23874 reg(state, RHS(ins, 0), REGCM_GPR16),
23875 reg(state, ins, mask));
23879 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23886 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23887 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23888 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23890 internal_error(state, ins, "not an out operation");
23894 lreg = check_reg(state, RHS(ins, 0), mask);
23895 if (!reg_is_reg(state, lreg, REG_EAX)) {
23896 internal_error(state, ins, "src != %%eax");
23898 if (is_const(RHS(ins, 1))) {
23899 fprintf(fp, "\t%s %s,",
23900 op, reg(state, RHS(ins, 0), mask));
23901 print_const_val(state, RHS(ins, 1), fp);
23906 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
23907 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23908 internal_error(state, ins, "dst != %%dx");
23910 fprintf(fp, "\t%s %s, %s\n",
23912 reg(state, RHS(ins, 0), mask),
23913 reg(state, RHS(ins, 1), REGCM_GPR16));
23917 static void print_op_move(struct compile_state *state,
23918 struct triple *ins, FILE *fp)
23920 /* op_move is complex because there are many types
23921 * of registers we can move between.
23922 * Because OP_COPY will be introduced in arbitrary locations
23923 * OP_COPY must not affect flags.
23924 * OP_CONVERT can change the flags and it is the only operation
23925 * where it is expected the types in the registers can change.
23927 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
23928 struct triple *dst, *src;
23929 if (state->arch->features & X86_NOOP_COPY) {
23932 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
23937 internal_error(state, ins, "unknown move operation");
23940 if (reg_size(state, dst) < size_of(state, dst->type)) {
23941 internal_error(state, ins, "Invalid destination register");
23943 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
23944 fprintf(state->errout, "src type: ");
23945 name_of(state->errout, src->type);
23946 fprintf(state->errout, "\n");
23947 fprintf(state->errout, "dst type: ");
23948 name_of(state->errout, dst->type);
23949 fprintf(state->errout, "\n");
23950 internal_error(state, ins, "Type mismatch for OP_COPY");
23953 if (!is_const(src)) {
23954 int src_reg, dst_reg;
23955 int src_regcm, dst_regcm;
23956 src_reg = ID_REG(src->id);
23957 dst_reg = ID_REG(dst->id);
23958 src_regcm = arch_reg_regcm(state, src_reg);
23959 dst_regcm = arch_reg_regcm(state, dst_reg);
23960 /* If the class is the same just move the register */
23961 if (src_regcm & dst_regcm &
23962 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
23963 if ((src_reg != dst_reg) || !omit_copy) {
23964 fprintf(fp, "\tmov %s, %s\n",
23965 reg(state, src, src_regcm),
23966 reg(state, dst, dst_regcm));
23969 /* Move 32bit to 16bit */
23970 else if ((src_regcm & REGCM_GPR32) &&
23971 (dst_regcm & REGCM_GPR16)) {
23972 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
23973 if ((src_reg != dst_reg) || !omit_copy) {
23974 fprintf(fp, "\tmovw %s, %s\n",
23975 arch_reg_str(src_reg),
23976 arch_reg_str(dst_reg));
23979 /* Move from 32bit gprs to 16bit gprs */
23980 else if ((src_regcm & REGCM_GPR32) &&
23981 (dst_regcm & REGCM_GPR16)) {
23982 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
23983 if ((src_reg != dst_reg) || !omit_copy) {
23984 fprintf(fp, "\tmov %s, %s\n",
23985 arch_reg_str(src_reg),
23986 arch_reg_str(dst_reg));
23989 /* Move 32bit to 8bit */
23990 else if ((src_regcm & REGCM_GPR32_8) &&
23991 (dst_regcm & REGCM_GPR8_LO))
23993 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
23994 if ((src_reg != dst_reg) || !omit_copy) {
23995 fprintf(fp, "\tmovb %s, %s\n",
23996 arch_reg_str(src_reg),
23997 arch_reg_str(dst_reg));
24000 /* Move 16bit to 8bit */
24001 else if ((src_regcm & REGCM_GPR16_8) &&
24002 (dst_regcm & REGCM_GPR8_LO))
24004 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24005 if ((src_reg != dst_reg) || !omit_copy) {
24006 fprintf(fp, "\tmovb %s, %s\n",
24007 arch_reg_str(src_reg),
24008 arch_reg_str(dst_reg));
24011 /* Move 8/16bit to 16/32bit */
24012 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24013 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24015 op = is_signed(src->type)? "movsx": "movzx";
24016 fprintf(fp, "\t%s %s, %s\n",
24018 reg(state, src, src_regcm),
24019 reg(state, dst, dst_regcm));
24021 /* Move between sse registers */
24022 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24023 if ((src_reg != dst_reg) || !omit_copy) {
24024 fprintf(fp, "\tmovdqa %s, %s\n",
24025 reg(state, src, src_regcm),
24026 reg(state, dst, dst_regcm));
24029 /* Move between mmx registers */
24030 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24031 if ((src_reg != dst_reg) || !omit_copy) {
24032 fprintf(fp, "\tmovq %s, %s\n",
24033 reg(state, src, src_regcm),
24034 reg(state, dst, dst_regcm));
24037 /* Move from sse to mmx registers */
24038 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24039 fprintf(fp, "\tmovdq2q %s, %s\n",
24040 reg(state, src, src_regcm),
24041 reg(state, dst, dst_regcm));
24043 /* Move from mmx to sse registers */
24044 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24045 fprintf(fp, "\tmovq2dq %s, %s\n",
24046 reg(state, src, src_regcm),
24047 reg(state, dst, dst_regcm));
24049 /* Move between 32bit gprs & mmx/sse registers */
24050 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24051 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24052 fprintf(fp, "\tmovd %s, %s\n",
24053 reg(state, src, src_regcm),
24054 reg(state, dst, dst_regcm));
24056 /* Move from 16bit gprs & mmx/sse registers */
24057 else if ((src_regcm & REGCM_GPR16) &&
24058 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24061 op = is_signed(src->type)? "movsx":"movzx";
24062 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24063 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24065 arch_reg_str(src_reg),
24066 arch_reg_str(mid_reg),
24067 arch_reg_str(mid_reg),
24068 arch_reg_str(dst_reg));
24070 /* Move from mmx/sse registers to 16bit gprs */
24071 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24072 (dst_regcm & REGCM_GPR16)) {
24073 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24074 fprintf(fp, "\tmovd %s, %s\n",
24075 arch_reg_str(src_reg),
24076 arch_reg_str(dst_reg));
24078 /* Move from gpr to 64bit dividend */
24079 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24080 (dst_regcm & REGCM_DIVIDEND64)) {
24081 const char *extend;
24082 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24083 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24084 arch_reg_str(src_reg),
24087 /* Move from 64bit gpr to gpr */
24088 else if ((src_regcm & REGCM_DIVIDEND64) &&
24089 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24090 if (dst_regcm & REGCM_GPR32) {
24093 else if (dst_regcm & REGCM_GPR16) {
24096 else if (dst_regcm & REGCM_GPR8_LO) {
24099 fprintf(fp, "\tmov %s, %s\n",
24100 arch_reg_str(src_reg),
24101 arch_reg_str(dst_reg));
24103 /* Move from mmx/sse registers to 64bit gpr */
24104 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24105 (dst_regcm & REGCM_DIVIDEND64)) {
24106 const char *extend;
24107 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24108 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24109 arch_reg_str(src_reg),
24112 /* Move from 64bit gpr to mmx/sse register */
24113 else if ((src_regcm & REGCM_DIVIDEND64) &&
24114 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24115 fprintf(fp, "\tmovd %%eax, %s\n",
24116 arch_reg_str(dst_reg));
24118 #if X86_4_8BIT_GPRS
24119 /* Move from 8bit gprs to mmx/sse registers */
24120 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24121 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24124 op = is_signed(src->type)? "movsx":"movzx";
24125 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24126 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24128 reg(state, src, src_regcm),
24129 arch_reg_str(mid_reg),
24130 arch_reg_str(mid_reg),
24131 reg(state, dst, dst_regcm));
24133 /* Move from mmx/sse registers and 8bit gprs */
24134 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24135 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24137 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24138 fprintf(fp, "\tmovd %s, %s\n",
24139 reg(state, src, src_regcm),
24140 arch_reg_str(mid_reg));
24142 /* Move from 32bit gprs to 8bit gprs */
24143 else if ((src_regcm & REGCM_GPR32) &&
24144 (dst_regcm & REGCM_GPR8_LO)) {
24145 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24146 if ((src_reg != dst_reg) || !omit_copy) {
24147 fprintf(fp, "\tmov %s, %s\n",
24148 arch_reg_str(src_reg),
24149 arch_reg_str(dst_reg));
24152 /* Move from 16bit gprs to 8bit gprs */
24153 else if ((src_regcm & REGCM_GPR16) &&
24154 (dst_regcm & REGCM_GPR8_LO)) {
24155 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24156 if ((src_reg != dst_reg) || !omit_copy) {
24157 fprintf(fp, "\tmov %s, %s\n",
24158 arch_reg_str(src_reg),
24159 arch_reg_str(dst_reg));
24162 #endif /* X86_4_8BIT_GPRS */
24163 /* Move from %eax:%edx to %eax:%edx */
24164 else if ((src_regcm & REGCM_DIVIDEND64) &&
24165 (dst_regcm & REGCM_DIVIDEND64) &&
24166 (src_reg == dst_reg)) {
24168 fprintf(fp, "\t/*mov %s, %s*/\n",
24169 arch_reg_str(src_reg),
24170 arch_reg_str(dst_reg));
24174 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24175 internal_error(state, ins, "attempt to copy from %%eflags!");
24177 internal_error(state, ins, "unknown copy type");
24184 dst_size = size_of(state, dst->type);
24185 dst_reg = ID_REG(dst->id);
24186 dst_regcm = arch_reg_regcm(state, dst_reg);
24187 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24188 fprintf(fp, "\tmov ");
24189 print_const_val(state, src, fp);
24190 fprintf(fp, ", %s\n",
24191 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24193 else if (dst_regcm & REGCM_DIVIDEND64) {
24194 if (dst_size > SIZEOF_I32) {
24195 internal_error(state, ins, "%dbit constant...", dst_size);
24197 fprintf(fp, "\tmov $0, %%edx\n");
24198 fprintf(fp, "\tmov ");
24199 print_const_val(state, src, fp);
24200 fprintf(fp, ", %%eax\n");
24202 else if (dst_regcm & REGCM_DIVIDEND32) {
24203 if (dst_size > SIZEOF_I16) {
24204 internal_error(state, ins, "%dbit constant...", dst_size);
24206 fprintf(fp, "\tmov $0, %%dx\n");
24207 fprintf(fp, "\tmov ");
24208 print_const_val(state, src, fp);
24209 fprintf(fp, ", %%ax");
24211 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24213 if (dst_size > SIZEOF_I32) {
24214 internal_error(state, ins, "%d bit constant...", dst_size);
24216 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24217 fprintf(fp, "\tmovd L%s%lu, %s\n",
24218 state->compiler->label_prefix, ref,
24219 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24222 internal_error(state, ins, "unknown copy immediate type");
24225 /* Leave now if this is not a type conversion */
24226 if (ins->op != OP_CONVERT) {
24229 /* Now make certain I have not logically overflowed the destination */
24230 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24231 (size_of(state, dst->type) < reg_size(state, dst)))
24233 unsigned long mask;
24236 if (size_of(state, dst->type) >= 32) {
24237 fprintf(state->errout, "dst type: ");
24238 name_of(state->errout, dst->type);
24239 fprintf(state->errout, "\n");
24240 internal_error(state, dst, "unhandled dst type size");
24243 mask <<= size_of(state, dst->type);
24246 dst_reg = ID_REG(dst->id);
24247 dst_regcm = arch_reg_regcm(state, dst_reg);
24249 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24250 fprintf(fp, "\tand $0x%lx, %s\n",
24251 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24253 else if (dst_regcm & REGCM_MMX) {
24255 ref = get_mask_pool_ref(state, dst, mask, fp);
24256 fprintf(fp, "\tpand L%s%lu, %s\n",
24257 state->compiler->label_prefix, ref,
24258 reg(state, dst, REGCM_MMX));
24260 else if (dst_regcm & REGCM_XMM) {
24262 ref = get_mask_pool_ref(state, dst, mask, fp);
24263 fprintf(fp, "\tpand L%s%lu, %s\n",
24264 state->compiler->label_prefix, ref,
24265 reg(state, dst, REGCM_XMM));
24268 fprintf(state->errout, "dst type: ");
24269 name_of(state->errout, dst->type);
24270 fprintf(state->errout, "\n");
24271 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24272 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24275 /* Make certain I am properly sign extended */
24276 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24277 (is_signed(src->type)))
24279 int bits, reg_bits, shift_bits;
24283 bits = size_of(state, src->type);
24284 reg_bits = reg_size(state, dst);
24285 if (reg_bits > 32) {
24288 shift_bits = reg_bits - size_of(state, src->type);
24289 dst_reg = ID_REG(dst->id);
24290 dst_regcm = arch_reg_regcm(state, dst_reg);
24292 if (shift_bits < 0) {
24293 internal_error(state, dst, "negative shift?");
24296 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24297 fprintf(fp, "\tshl $%d, %s\n",
24299 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24300 fprintf(fp, "\tsar $%d, %s\n",
24302 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24304 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24305 fprintf(fp, "\tpslld $%d, %s\n",
24307 reg(state, dst, REGCM_MMX | REGCM_XMM));
24308 fprintf(fp, "\tpsrad $%d, %s\n",
24310 reg(state, dst, REGCM_MMX | REGCM_XMM));
24313 fprintf(state->errout, "dst type: ");
24314 name_of(state->errout, dst->type);
24315 fprintf(state->errout, "\n");
24316 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24317 internal_error(state, dst, "failed to signed extend value");
24322 static void print_op_load(struct compile_state *state,
24323 struct triple *ins, FILE *fp)
24325 struct triple *dst, *src;
24329 if (is_const(src) || is_const(dst)) {
24330 internal_error(state, ins, "unknown load operation");
24332 switch(ins->type->type & TYPE_MASK) {
24333 case TYPE_CHAR: op = "movsbl"; break;
24334 case TYPE_UCHAR: op = "movzbl"; break;
24335 case TYPE_SHORT: op = "movswl"; break;
24336 case TYPE_USHORT: op = "movzwl"; break;
24337 case TYPE_INT: case TYPE_UINT:
24338 case TYPE_LONG: case TYPE_ULONG:
24343 internal_error(state, ins, "unknown type in load");
24344 op = "<invalid opcode>";
24347 fprintf(fp, "\t%s (%s), %s\n",
24349 reg(state, src, REGCM_GPR32),
24350 reg(state, dst, REGCM_GPR32));
24354 static void print_op_store(struct compile_state *state,
24355 struct triple *ins, FILE *fp)
24357 struct triple *dst, *src;
24360 if (is_const(src) && (src->op == OP_INTCONST)) {
24362 value = (long_t)(src->u.cval);
24363 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24364 type_suffix(state, src->type),
24366 reg(state, dst, REGCM_GPR32));
24368 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24369 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24370 type_suffix(state, src->type),
24371 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24372 (unsigned long)(dst->u.cval));
24375 if (is_const(src) || is_const(dst)) {
24376 internal_error(state, ins, "unknown store operation");
24378 fprintf(fp, "\tmov%s %s, (%s)\n",
24379 type_suffix(state, src->type),
24380 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24381 reg(state, dst, REGCM_GPR32));
24387 static void print_op_smul(struct compile_state *state,
24388 struct triple *ins, FILE *fp)
24390 if (!is_const(RHS(ins, 1))) {
24391 fprintf(fp, "\timul %s, %s\n",
24392 reg(state, RHS(ins, 1), REGCM_GPR32),
24393 reg(state, RHS(ins, 0), REGCM_GPR32));
24396 fprintf(fp, "\timul ");
24397 print_const_val(state, RHS(ins, 1), fp);
24398 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24402 static void print_op_cmp(struct compile_state *state,
24403 struct triple *ins, FILE *fp)
24407 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24408 dreg = check_reg(state, ins, REGCM_FLAGS);
24409 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24410 internal_error(state, ins, "bad dest register for cmp");
24412 if (is_const(RHS(ins, 1))) {
24413 fprintf(fp, "\tcmp ");
24414 print_const_val(state, RHS(ins, 1), fp);
24415 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24418 unsigned lmask, rmask;
24420 lreg = check_reg(state, RHS(ins, 0), mask);
24421 rreg = check_reg(state, RHS(ins, 1), mask);
24422 lmask = arch_reg_regcm(state, lreg);
24423 rmask = arch_reg_regcm(state, rreg);
24424 mask = lmask & rmask;
24425 fprintf(fp, "\tcmp %s, %s\n",
24426 reg(state, RHS(ins, 1), mask),
24427 reg(state, RHS(ins, 0), mask));
24431 static void print_op_test(struct compile_state *state,
24432 struct triple *ins, FILE *fp)
24435 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24436 fprintf(fp, "\ttest %s, %s\n",
24437 reg(state, RHS(ins, 0), mask),
24438 reg(state, RHS(ins, 0), mask));
24441 static void print_op_branch(struct compile_state *state,
24442 struct triple *branch, FILE *fp)
24444 const char *bop = "j";
24445 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24446 if (branch->rhs != 0) {
24447 internal_error(state, branch, "jmp with condition?");
24452 struct triple *ptr;
24453 if (branch->rhs != 1) {
24454 internal_error(state, branch, "jmpcc without condition?");
24456 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24457 if ((RHS(branch, 0)->op != OP_CMP) &&
24458 (RHS(branch, 0)->op != OP_TEST)) {
24459 internal_error(state, branch, "bad branch test");
24461 #warning "FIXME I have observed instructions between the test and branch instructions"
24462 ptr = RHS(branch, 0);
24463 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24464 if (ptr->op != OP_COPY) {
24465 internal_error(state, branch, "branch does not follow test");
24468 switch(branch->op) {
24469 case OP_JMP_EQ: bop = "jz"; break;
24470 case OP_JMP_NOTEQ: bop = "jnz"; break;
24471 case OP_JMP_SLESS: bop = "jl"; break;
24472 case OP_JMP_ULESS: bop = "jb"; break;
24473 case OP_JMP_SMORE: bop = "jg"; break;
24474 case OP_JMP_UMORE: bop = "ja"; break;
24475 case OP_JMP_SLESSEQ: bop = "jle"; break;
24476 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24477 case OP_JMP_SMOREEQ: bop = "jge"; break;
24478 case OP_JMP_UMOREEQ: bop = "jae"; break;
24480 internal_error(state, branch, "Invalid branch op");
24486 if (branch->op == OP_CALL) {
24487 fprintf(fp, "\t/* call */\n");
24490 fprintf(fp, "\t%s L%s%lu\n",
24492 state->compiler->label_prefix,
24493 (unsigned long)(TARG(branch, 0)->u.cval));
24496 static void print_op_ret(struct compile_state *state,
24497 struct triple *branch, FILE *fp)
24499 fprintf(fp, "\tjmp *%s\n",
24500 reg(state, RHS(branch, 0), REGCM_GPR32));
24503 static void print_op_set(struct compile_state *state,
24504 struct triple *set, FILE *fp)
24506 const char *sop = "set";
24507 if (set->rhs != 1) {
24508 internal_error(state, set, "setcc without condition?");
24510 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24511 if ((RHS(set, 0)->op != OP_CMP) &&
24512 (RHS(set, 0)->op != OP_TEST)) {
24513 internal_error(state, set, "bad set test");
24515 if (RHS(set, 0)->next != set) {
24516 internal_error(state, set, "set does not follow test");
24519 case OP_SET_EQ: sop = "setz"; break;
24520 case OP_SET_NOTEQ: sop = "setnz"; break;
24521 case OP_SET_SLESS: sop = "setl"; break;
24522 case OP_SET_ULESS: sop = "setb"; break;
24523 case OP_SET_SMORE: sop = "setg"; break;
24524 case OP_SET_UMORE: sop = "seta"; break;
24525 case OP_SET_SLESSEQ: sop = "setle"; break;
24526 case OP_SET_ULESSEQ: sop = "setbe"; break;
24527 case OP_SET_SMOREEQ: sop = "setge"; break;
24528 case OP_SET_UMOREEQ: sop = "setae"; break;
24530 internal_error(state, set, "Invalid set op");
24533 fprintf(fp, "\t%s %s\n",
24534 sop, reg(state, set, REGCM_GPR8_LO));
24537 static void print_op_bit_scan(struct compile_state *state,
24538 struct triple *ins, FILE *fp)
24542 case OP_BSF: op = "bsf"; break;
24543 case OP_BSR: op = "bsr"; break;
24545 internal_error(state, ins, "unknown bit scan");
24555 reg(state, RHS(ins, 0), REGCM_GPR32),
24556 reg(state, ins, REGCM_GPR32),
24557 reg(state, ins, REGCM_GPR32));
24561 static void print_sdecl(struct compile_state *state,
24562 struct triple *ins, FILE *fp)
24564 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24565 fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
24566 fprintf(fp, "L%s%lu:\n",
24567 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24568 print_const(state, MISC(ins, 0), fp);
24569 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24573 static void print_instruction(struct compile_state *state,
24574 struct triple *ins, FILE *fp)
24576 /* Assumption: after I have exted the register allocator
24577 * everything is in a valid register.
24581 print_op_asm(state, ins, fp);
24583 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24584 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24585 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24586 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24587 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24588 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24589 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24590 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24591 case OP_POS: break;
24592 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24593 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24598 /* Don't generate anything here for constants */
24600 /* Don't generate anything for variable declarations. */
24602 case OP_UNKNOWNVAL:
24603 fprintf(fp, " /* unknown %s */\n",
24604 reg(state, ins, REGCM_ALL));
24607 print_sdecl(state, ins, fp);
24611 print_op_move(state, ins, fp);
24614 print_op_load(state, ins, fp);
24617 print_op_store(state, ins, fp);
24620 print_op_smul(state, ins, fp);
24622 case OP_CMP: print_op_cmp(state, ins, fp); break;
24623 case OP_TEST: print_op_test(state, ins, fp); break;
24625 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24626 case OP_JMP_SLESS: case OP_JMP_ULESS:
24627 case OP_JMP_SMORE: case OP_JMP_UMORE:
24628 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24629 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24631 print_op_branch(state, ins, fp);
24634 print_op_ret(state, ins, fp);
24636 case OP_SET_EQ: case OP_SET_NOTEQ:
24637 case OP_SET_SLESS: case OP_SET_ULESS:
24638 case OP_SET_SMORE: case OP_SET_UMORE:
24639 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24640 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24641 print_op_set(state, ins, fp);
24643 case OP_INB: case OP_INW: case OP_INL:
24644 print_op_in(state, ins, fp);
24646 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24647 print_op_out(state, ins, fp);
24651 print_op_bit_scan(state, ins, fp);
24654 after_lhs(state, ins);
24655 fprintf(fp, "\trdmsr\n");
24658 fprintf(fp, "\twrmsr\n");
24661 fprintf(fp, "\thlt\n");
24664 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24667 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24670 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24676 fprintf(fp, "L%s%lu:\n",
24677 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24680 /* Ignore adecls with no registers error otherwise */
24681 if (!noop_adecl(ins)) {
24682 internal_error(state, ins, "adecl remains?");
24685 /* Ignore OP_PIECE */
24688 /* Operations that should never get here */
24689 case OP_SDIV: case OP_UDIV:
24690 case OP_SMOD: case OP_UMOD:
24691 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24692 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24693 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24695 internal_error(state, ins, "unknown op: %d %s",
24696 ins->op, tops(ins->op));
24701 static void print_instructions(struct compile_state *state)
24703 struct triple *first, *ins;
24704 int print_location;
24705 struct occurance *last_occurance;
24707 int max_inline_depth;
24708 max_inline_depth = 0;
24709 print_location = 1;
24710 last_occurance = 0;
24711 fp = state->output;
24712 /* Masks for common sizes */
24713 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24714 fprintf(fp, ".balign 16\n");
24715 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24716 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24717 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24718 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24719 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24720 first = state->first;
24723 if (print_location &&
24724 last_occurance != ins->occurance) {
24725 if (!ins->occurance->parent) {
24726 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24727 ins->occurance->function,
24728 ins->occurance->filename,
24729 ins->occurance->line,
24730 ins->occurance->col);
24733 struct occurance *ptr;
24735 fprintf(fp, "\t/*\n");
24737 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24739 fprintf(fp, "\t * %s,%s:%d.%d\n",
24745 fprintf(fp, "\t */\n");
24746 if (inline_depth > max_inline_depth) {
24747 max_inline_depth = inline_depth;
24750 if (last_occurance) {
24751 put_occurance(last_occurance);
24753 get_occurance(ins->occurance);
24754 last_occurance = ins->occurance;
24757 print_instruction(state, ins, fp);
24759 } while(ins != first);
24760 if (print_location) {
24761 fprintf(fp, "/* max inline depth %d */\n",
24766 static void generate_code(struct compile_state *state)
24768 generate_local_labels(state);
24769 print_instructions(state);
24773 static void print_preprocessed_tokens(struct compile_state *state)
24778 const char *filename;
24779 fp = state->output;
24783 struct file_state *file;
24785 const char *token_str;
24787 if (tok == TOK_EOF) {
24790 tk = eat(state, tok);
24792 tk->ident ? tk->ident->name :
24793 tk->str_len ? tk->val.str :
24796 file = state->file;
24797 while(file->macro && file->prev) {
24800 if (!file->macro &&
24801 ((file->line != line) || (file->basename != filename)))
24804 if ((file->basename == filename) &&
24805 (line < file->line)) {
24806 while(line < file->line) {
24812 fprintf(fp, "\n#line %d \"%s\"\n",
24813 file->line, file->basename);
24816 filename = file->basename;
24817 col = get_col(file) - strlen(token_str);
24818 for(i = 0; i < col; i++) {
24823 fprintf(fp, "%s ", token_str);
24825 if (state->compiler->debug & DEBUG_TOKENS) {
24826 loc(state->dbgout, state, 0);
24827 fprintf(state->dbgout, "%s <- `%s'\n",
24828 tokens[tok], token_str);
24833 static void compile(const char *filename,
24834 struct compiler_state *compiler, struct arch_state *arch)
24837 struct compile_state state;
24838 struct triple *ptr;
24839 memset(&state, 0, sizeof(state));
24840 state.compiler = compiler;
24843 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24844 memset(&state.token[i], 0, sizeof(state.token[i]));
24845 state.token[i].tok = -1;
24847 /* Remember the output descriptors */
24848 state.errout = stderr;
24849 state.dbgout = stdout;
24850 /* Remember the output filename */
24851 state.output = fopen(state.compiler->ofilename, "w");
24852 if (!state.output) {
24853 error(&state, 0, "Cannot open output file %s\n",
24854 state.compiler->ofilename);
24856 /* Make certain a good cleanup happens */
24857 exit_state = &state;
24858 atexit(exit_cleanup);
24860 /* Prep the preprocessor */
24861 state.if_depth = 0;
24862 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24863 /* register the C keywords */
24864 register_keywords(&state);
24865 /* register the keywords the macro preprocessor knows */
24866 register_macro_keywords(&state);
24867 /* generate some builtin macros */
24868 register_builtin_macros(&state);
24869 /* Memorize where some special keywords are. */
24870 state.i_switch = lookup(&state, "switch", 6);
24871 state.i_case = lookup(&state, "case", 4);
24872 state.i_continue = lookup(&state, "continue", 8);
24873 state.i_break = lookup(&state, "break", 5);
24874 state.i_default = lookup(&state, "default", 7);
24875 state.i_return = lookup(&state, "return", 6);
24876 /* Memorize where predefined macros are. */
24877 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24878 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24879 state.i___LINE__ = lookup(&state, "__LINE__", 8);
24880 /* Memorize where predefined identifiers are. */
24881 state.i___func__ = lookup(&state, "__func__", 8);
24882 /* Memorize where some attribute keywords are. */
24883 state.i_noinline = lookup(&state, "noinline", 8);
24884 state.i_always_inline = lookup(&state, "always_inline", 13);
24886 /* Process the command line macros */
24887 process_cmdline_macros(&state);
24889 /* Allocate beginning bounding labels for the function list */
24890 state.first = label(&state);
24891 state.first->id |= TRIPLE_FLAG_VOLATILE;
24892 use_triple(state.first, state.first);
24893 ptr = label(&state);
24894 ptr->id |= TRIPLE_FLAG_VOLATILE;
24895 use_triple(ptr, ptr);
24896 flatten(&state, state.first, ptr);
24898 /* Allocate a label for the pool of global variables */
24899 state.global_pool = label(&state);
24900 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
24901 flatten(&state, state.first, state.global_pool);
24903 /* Enter the globl definition scope */
24904 start_scope(&state);
24905 register_builtins(&state);
24906 compile_file(&state, filename, 1);
24908 /* Stop if all we want is preprocessor output */
24909 if (state.compiler->flags & COMPILER_PP_ONLY) {
24910 print_preprocessed_tokens(&state);
24916 /* Exit the global definition scope */
24919 /* Now that basic compilation has happened
24920 * optimize the intermediate code
24924 generate_code(&state);
24925 if (state.compiler->debug) {
24926 fprintf(state.errout, "done\n");
24931 static void version(FILE *fp)
24933 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
24936 static void usage(void)
24941 "\nUsage: romcc [options] <source>.c\n"
24942 "Compile a C source file generating a binary that does not implicilty use RAM\n"
24944 "-o <output file name>\n"
24945 "-f<option> Specify a generic compiler option\n"
24946 "-m<option> Specify a arch dependent option\n"
24947 "-- Specify this is the last option\n"
24948 "\nGeneric compiler options:\n"
24950 compiler_usage(fp);
24952 "\nArchitecture compiler options:\n"
24960 static void arg_error(char *fmt, ...)
24963 va_start(args, fmt);
24964 vfprintf(stderr, fmt, args);
24970 int main(int argc, char **argv)
24972 const char *filename;
24973 struct compiler_state compiler;
24974 struct arch_state arch;
24978 /* I don't want any surprises */
24979 setlocale(LC_ALL, "C");
24981 init_compiler_state(&compiler);
24982 init_arch_state(&arch);
24986 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
24987 compiler.ofilename = argv[2];
24991 else if (!all_opts && argv[1][0] == '-') {
24994 if (strcmp(argv[1], "--") == 0) {
24998 else if (strncmp(argv[1], "-E", 2) == 0) {
24999 result = compiler_encode_flag(&compiler, argv[1]);
25001 else if (strncmp(argv[1], "-O", 2) == 0) {
25002 result = compiler_encode_flag(&compiler, argv[1]);
25004 else if (strncmp(argv[1], "-I", 2) == 0) {
25005 result = compiler_encode_flag(&compiler, argv[1]);
25007 else if (strncmp(argv[1], "-D", 2) == 0) {
25008 result = compiler_encode_flag(&compiler, argv[1]);
25010 else if (strncmp(argv[1], "-U", 2) == 0) {
25011 result = compiler_encode_flag(&compiler, argv[1]);
25013 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25014 result = compiler_encode_flag(&compiler, argv[1]+2);
25016 else if (strncmp(argv[1], "-f", 2) == 0) {
25017 result = compiler_encode_flag(&compiler, argv[1]+2);
25019 else if (strncmp(argv[1], "-m", 2) == 0) {
25020 result = arch_encode_flag(&arch, argv[1]+2);
25023 arg_error("Invalid option specified: %s\n",
25031 arg_error("Only one filename may be specified\n");
25033 filename = argv[1];
25039 arg_error("No filename specified\n");
25041 compile(filename, &compiler, &arch);