5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "72"
7 #define RELEASE_DATE "10 February 2010"
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 /* NOTE: Before you even start thinking to touch anything
29 * in this code, set DEBUG_ROMCC_WARNINGS to 1 to get an
30 * insight on the original author's thoughts. We introduced
31 * this switch as romcc was about the only thing producing
32 * massive warnings in our code..
34 #define DEBUG_ROMCC_WARNINGS 0
36 #define DEBUG_CONSISTENCY 1
37 #define DEBUG_SDP_BLOCKS 0
38 #define DEBUG_TRIPLE_COLOR 0
40 #define DEBUG_DISPLAY_USES 1
41 #define DEBUG_DISPLAY_TYPES 1
42 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
43 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
44 #define DEBUG_DECOMPOSE_HIRES 0
45 #define DEBUG_INITIALIZER 0
46 #define DEBUG_UPDATE_CLOSURE_TYPE 0
47 #define DEBUG_LOCAL_TRIPLE 0
48 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
49 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
50 #define DEBUG_SIMPLIFY_HIRES 0
51 #define DEBUG_SHRINKING 0
52 #define DEBUG_COALESCE_HITCHES 0
53 #define DEBUG_CODE_ELIMINATION 0
55 #define DEBUG_EXPLICIT_CLOSURES 0
57 #if DEBUG_ROMCC_WARNINGS
58 #warning "FIXME give clear error messages about unused variables"
59 #warning "FIXME properly handle multi dimensional arrays"
60 #warning "FIXME handle multiple register sizes"
63 /* Control flow graph of a loop without goto.
74 * |\ GGG HHH | continue;
102 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
103 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
106 * [] == DFlocal(X) U DF(X)
109 * Dominator graph of the same nodes.
113 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
115 * CCC CCC: [ ] ( BBB, JJJ )
117 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
119 * FFF FFF: [ ] ( BBB )
121 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
123 * III III: [ BBB ] ()
126 * BBB and JJJ are definitely the dominance frontier.
127 * Where do I place phi functions and how do I make that decision.
132 const char *filename;
133 struct filelist *next;
136 struct filelist *include_filelist = NULL;
138 static void die(char *fmt, ...)
143 vfprintf(stderr, fmt, args);
150 static void *xmalloc(size_t size, const char *name)
155 die("Cannot malloc %ld bytes to hold %s: %s\n",
156 size + 0UL, name, strerror(errno));
161 static void *xcmalloc(size_t size, const char *name)
164 buf = xmalloc(size, name);
165 memset(buf, 0, size);
169 static void *xrealloc(void *ptr, size_t size, const char *name)
172 buf = realloc(ptr, size);
174 die("Cannot realloc %ld bytes to hold %s: %s\n",
175 size + 0UL, name, strerror(errno));
180 static void xfree(const void *ptr)
185 static char *xstrdup(const char *str)
190 new = xmalloc(len + 1, "xstrdup string");
191 memcpy(new, str, len);
196 static void xchdir(const char *path)
198 if (chdir(path) != 0) {
199 die("chdir to `%s' failed: %s\n",
200 path, strerror(errno));
204 static int exists(const char *dirname, const char *filename)
206 char cwd[MAX_CWD_SIZE];
209 if (getcwd(cwd, sizeof(cwd)) == 0) {
210 die("cwd buffer to small");
214 if (chdir(dirname) != 0) {
217 if (does_exist && (access(filename, O_RDONLY) < 0)) {
218 if ((errno != EACCES) && (errno != EROFS)) {
227 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
229 char cwd[MAX_CWD_SIZE];
231 off_t size, progress;
239 if (getcwd(cwd, sizeof(cwd)) == 0) {
240 die("cwd buffer to small");
243 file = fopen(filename, "rb");
246 die("Cannot open '%s' : %s\n",
247 filename, strerror(errno));
249 fseek(file, 0, SEEK_END);
251 fseek(file, 0, SEEK_SET);
253 buf = xmalloc(size +2, filename);
254 buf[size] = '\n'; /* Make certain the file is newline terminated */
255 buf[size+1] = '\0'; /* Null terminate the file for good measure */
257 while(progress < size) {
258 result = fread(buf + progress, 1, size - progress, file);
260 if ((errno == EINTR) || (errno == EAGAIN))
262 die("read on %s of %ld bytes failed: %s\n",
263 filename, (size - progress)+ 0UL, strerror(errno));
271 /* Types on the destination platform */
272 #if DEBUG_ROMCC_WARNINGS
273 #warning "FIXME this assumes 32bit x86 is the destination"
275 typedef int8_t schar_t;
276 typedef uint8_t uchar_t;
277 typedef int8_t char_t;
278 typedef int16_t short_t;
279 typedef uint16_t ushort_t;
280 typedef int32_t int_t;
281 typedef uint32_t uint_t;
282 typedef int32_t long_t;
283 #define ulong_t uint32_t
285 #define SCHAR_T_MIN (-128)
286 #define SCHAR_T_MAX 127
287 #define UCHAR_T_MAX 255
288 #define CHAR_T_MIN SCHAR_T_MIN
289 #define CHAR_T_MAX SCHAR_T_MAX
290 #define SHRT_T_MIN (-32768)
291 #define SHRT_T_MAX 32767
292 #define USHRT_T_MAX 65535
293 #define INT_T_MIN (-LONG_T_MAX - 1)
294 #define INT_T_MAX 2147483647
295 #define UINT_T_MAX 4294967295U
296 #define LONG_T_MIN (-LONG_T_MAX - 1)
297 #define LONG_T_MAX 2147483647
298 #define ULONG_T_MAX 4294967295U
301 #define SIZEOF_I16 16
302 #define SIZEOF_I32 32
303 #define SIZEOF_I64 64
305 #define SIZEOF_CHAR 8
306 #define SIZEOF_SHORT 16
307 #define SIZEOF_INT 32
308 #define SIZEOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
311 #define ALIGNOF_CHAR 8
312 #define ALIGNOF_SHORT 16
313 #define ALIGNOF_INT 32
314 #define ALIGNOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
316 #define REG_SIZEOF_REG 32
317 #define REG_SIZEOF_CHAR REG_SIZEOF_REG
318 #define REG_SIZEOF_SHORT REG_SIZEOF_REG
319 #define REG_SIZEOF_INT REG_SIZEOF_REG
320 #define REG_SIZEOF_LONG REG_SIZEOF_REG
322 #define REG_ALIGNOF_REG REG_SIZEOF_REG
323 #define REG_ALIGNOF_CHAR REG_SIZEOF_REG
324 #define REG_ALIGNOF_SHORT REG_SIZEOF_REG
325 #define REG_ALIGNOF_INT REG_SIZEOF_REG
326 #define REG_ALIGNOF_LONG REG_SIZEOF_REG
328 /* Additional definitions for clarity.
329 * I currently assume a long is the largest native
330 * machine word and that a pointer fits into it.
332 #define SIZEOF_WORD SIZEOF_LONG
333 #define SIZEOF_POINTER SIZEOF_LONG
334 #define ALIGNOF_WORD ALIGNOF_LONG
335 #define ALIGNOF_POINTER ALIGNOF_LONG
336 #define REG_SIZEOF_POINTER REG_SIZEOF_LONG
337 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
340 struct file_state *prev;
341 const char *basename;
347 const char *line_start;
349 const char *report_name;
350 const char *report_dir;
358 struct hash_entry *ident;
368 /* I have two classes of types:
370 * Logical types. (The type the C standard says the operation is of)
372 * The operational types are:
387 * No memory is useable by the compiler.
388 * There is no floating point support.
389 * All operations take place in general purpose registers.
390 * There is one type of general purpose register.
391 * Unsigned longs are stored in that general purpose register.
394 /* Operations on general purpose registers.
413 #define OP_POS 16 /* Dummy positive operator don't use it */
423 #define OP_SLESSEQ 26
424 #define OP_ULESSEQ 27
425 #define OP_SMOREEQ 28
426 #define OP_UMOREEQ 29
428 #define OP_LFALSE 30 /* Test if the expression is logically false */
429 #define OP_LTRUE 31 /* Test if the expression is logcially true */
433 /* For OP_STORE ->type holds the type
434 * RHS(0) holds the destination address
435 * RHS(1) holds the value to store.
438 #define OP_UEXTRACT 34
439 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
440 * RHS(0) holds the psuedo register to extract from
441 * ->type holds the size of the bitfield.
442 * ->u.bitfield.size holds the size of the bitfield.
443 * ->u.bitfield.offset holds the offset to extract from
445 #define OP_SEXTRACT 35
446 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
447 * RHS(0) holds the psuedo register to extract from
448 * ->type holds the size of the bitfield.
449 * ->u.bitfield.size holds the size of the bitfield.
450 * ->u.bitfield.offset holds the offset to extract from
452 #define OP_DEPOSIT 36
453 /* OP_DEPOSIT replaces a bitfield with a new value.
454 * RHS(0) holds the value to replace a bitifield in.
455 * RHS(1) holds the replacement value
456 * ->u.bitfield.size holds the size of the bitfield.
457 * ->u.bitfield.offset holds the deposit into
462 #define OP_MIN_CONST 50
463 #define OP_MAX_CONST 58
464 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
465 #define OP_INTCONST 50
466 /* For OP_INTCONST ->type holds the type.
467 * ->u.cval holds the constant value.
469 #define OP_BLOBCONST 51
470 /* For OP_BLOBCONST ->type holds the layout and size
471 * information. u.blob holds a pointer to the raw binary
472 * data for the constant initializer.
474 #define OP_ADDRCONST 52
475 /* For OP_ADDRCONST ->type holds the type.
476 * MISC(0) holds the reference to the static variable.
477 * ->u.cval holds an offset from that value.
479 #define OP_UNKNOWNVAL 59
480 /* For OP_UNKNOWNAL ->type holds the type.
481 * For some reason we don't know what value this type has.
482 * This allows for variables that have don't have values
483 * assigned yet, or variables whose value we simply do not know.
487 /* OP_WRITE moves one pseudo register to another.
488 * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
489 * RHS(0) holds the psuedo to move.
493 /* OP_READ reads the value of a variable and makes
494 * it available for the pseudo operation.
495 * Useful for things like def-use chains.
496 * RHS(0) holds points to the triple to read from.
499 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
501 #define OP_CONVERT 63
502 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
503 * And then the type is converted appropriately.
506 /* OP_PIECE returns one piece of a instruction that returns a structure.
507 * MISC(0) is the instruction
508 * u.cval is the LHS piece of the instruction to return.
511 /* OP_ASM holds a sequence of assembly instructions, the result
512 * of a C asm directive.
513 * RHS(x) holds input value x to the assembly sequence.
514 * LHS(x) holds the output value x from the assembly sequence.
515 * u.blob holds the string of assembly instructions.
519 /* OP_DEREF generates an lvalue from a pointer.
520 * RHS(0) holds the pointer value.
521 * OP_DEREF serves as a place holder to indicate all necessary
522 * checks have been done to indicate a value is an lvalue.
525 /* OP_DOT references a submember of a structure lvalue.
526 * MISC(0) holds the lvalue.
527 * ->u.field holds the name of the field we want.
529 * Not seen after structures are flattened.
532 /* OP_INDEX references a submember of a tuple or array lvalue.
533 * MISC(0) holds the lvalue.
534 * ->u.cval holds the index into the lvalue.
536 * Not seen after structures are flattened.
539 /* OP_VAL returns the value of a subexpression of the current expression.
540 * Useful for operators that have side effects.
541 * RHS(0) holds the expression.
542 * MISC(0) holds the subexpression of RHS(0) that is the
543 * value of the expression.
545 * Not seen outside of expressions.
549 /* OP_TUPLE is an array of triples that are either variable
550 * or values for a structure or an array. It is used as
551 * a place holder when flattening compound types.
552 * The value represented by an OP_TUPLE is held in N registers.
553 * LHS(0..N-1) refer to those registers.
554 * ->use is a list of statements that use the value.
556 * Although OP_TUPLE always has register sized pieces they are not
557 * used until structures are flattened/decomposed into their register
559 * ???? registers ????
563 /* OP_BITREF describes a bitfield as an lvalue.
564 * RHS(0) holds the register value.
565 * ->type holds the type of the bitfield.
566 * ->u.bitfield.size holds the size of the bitfield.
567 * ->u.bitfield.offset holds the offset of the bitfield in the register
572 /* OP_FCALL performs a procedure call.
573 * MISC(0) holds a pointer to the OP_LIST of a function
574 * RHS(x) holds argument x of a function
576 * Currently not seen outside of expressions.
579 /* OP_PROG is an expression that holds a list of statements, or
580 * expressions. The final expression is the value of the expression.
581 * RHS(0) holds the start of the list.
586 /* OP_LIST Holds a list of statements that compose a function, and a result value.
587 * RHS(0) holds the list of statements.
588 * A list of all functions is maintained.
591 #define OP_BRANCH 81 /* an unconditional branch */
592 /* For branch instructions
593 * TARG(0) holds the branch target.
594 * ->next holds where to branch to if the branch is not taken.
595 * The branch target can only be a label
598 #define OP_CBRANCH 82 /* a conditional branch */
599 /* For conditional branch instructions
600 * RHS(0) holds the branch condition.
601 * TARG(0) holds the branch target.
602 * ->next holds where to branch to if the branch is not taken.
603 * The branch target can only be a label
606 #define OP_CALL 83 /* an uncontional branch that will return */
607 /* For call instructions
608 * MISC(0) holds the OP_RET that returns from the branch
609 * TARG(0) holds the branch target.
610 * ->next holds where to branch to if the branch is not taken.
611 * The branch target can only be a label
614 #define OP_RET 84 /* an uncontinonal branch through a variable back to an OP_CALL */
615 /* For call instructions
616 * RHS(0) holds the variable with the return address
617 * The branch target can only be a label
621 /* OP_LABEL is a triple that establishes an target for branches.
622 * ->use is the list of all branches that use this label.
626 /* OP_ADECL is a triple that establishes an lvalue for assignments.
627 * A variable takes N registers to contain.
628 * LHS(0..N-1) refer to an OP_PIECE triple that represents
629 * the Xth register that the variable is stored in.
630 * ->use is a list of statements that use the variable.
632 * Although OP_ADECL always has register sized pieces they are not
633 * used until structures are flattened/decomposed into their register
638 /* OP_SDECL is a triple that establishes a variable of static
640 * ->use is a list of statements that use the variable.
641 * MISC(0) holds the initializer expression.
646 /* OP_PHI is a triple used in SSA form code.
647 * It is used when multiple code paths merge and a variable needs
648 * a single assignment from any of those code paths.
649 * The operation is a cross between OP_DECL and OP_WRITE, which
650 * is what OP_PHI is generated from.
652 * RHS(x) points to the value from code path x
653 * The number of RHS entries is the number of control paths into the block
654 * in which OP_PHI resides. The elements of the array point to point
655 * to the variables OP_PHI is derived from.
657 * MISC(0) holds a pointer to the orginal OP_DECL node.
661 /* continuation helpers
663 #define OP_CPS_BRANCH 90 /* an unconditional branch */
664 /* OP_CPS_BRANCH calls a continuation
665 * RHS(x) holds argument x of the function
666 * TARG(0) holds OP_CPS_START target
668 #define OP_CPS_CBRANCH 91 /* a conditional branch */
669 /* OP_CPS_CBRANCH conditionally calls one of two continuations
670 * RHS(0) holds the branch condition
671 * RHS(x + 1) holds argument x of the function
672 * TARG(0) holds the OP_CPS_START to jump to when true
673 * ->next holds the OP_CPS_START to jump to when false
675 #define OP_CPS_CALL 92 /* an uncontional branch that will return */
676 /* For OP_CPS_CALL instructions
677 * RHS(x) holds argument x of the function
678 * MISC(0) holds the OP_CPS_RET that returns from the branch
679 * TARG(0) holds the branch target.
680 * ->next holds where the OP_CPS_RET will return to.
682 #define OP_CPS_RET 93
683 /* OP_CPS_RET conditionally calls one of two continuations
684 * RHS(0) holds the variable with the return function address
685 * RHS(x + 1) holds argument x of the function
686 * The branch target may be any OP_CPS_START
688 #define OP_CPS_END 94
689 /* OP_CPS_END is the triple at the end of the program.
690 * For most practical purposes it is a branch.
692 #define OP_CPS_START 95
693 /* OP_CPS_START is a triple at the start of a continuation
694 * The arguments variables takes N registers to contain.
695 * LHS(0..N-1) refer to an OP_PIECE triple that represents
696 * the Xth register that the arguments are stored in.
700 /* Architecture specific instructions */
703 #define OP_SET_EQ 102
704 #define OP_SET_NOTEQ 103
705 #define OP_SET_SLESS 104
706 #define OP_SET_ULESS 105
707 #define OP_SET_SMORE 106
708 #define OP_SET_UMORE 107
709 #define OP_SET_SLESSEQ 108
710 #define OP_SET_ULESSEQ 109
711 #define OP_SET_SMOREEQ 110
712 #define OP_SET_UMOREEQ 111
715 #define OP_JMP_EQ 113
716 #define OP_JMP_NOTEQ 114
717 #define OP_JMP_SLESS 115
718 #define OP_JMP_ULESS 116
719 #define OP_JMP_SMORE 117
720 #define OP_JMP_UMORE 118
721 #define OP_JMP_SLESSEQ 119
722 #define OP_JMP_ULESSEQ 120
723 #define OP_JMP_SMOREEQ 121
724 #define OP_JMP_UMOREEQ 122
726 /* Builtin operators that it is just simpler to use the compiler for */
742 #define PURE 0x001 /* Triple has no side effects */
743 #define IMPURE 0x002 /* Triple has side effects */
744 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
745 #define DEF 0x004 /* Triple is a variable definition */
746 #define BLOCK 0x008 /* Triple stores the current block */
747 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
748 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
749 #define UBRANCH 0x020 /* Triple is an unconditional branch instruction */
750 #define CBRANCH 0x040 /* Triple is a conditional branch instruction */
751 #define RETBRANCH 0x060 /* Triple is a return instruction */
752 #define CALLBRANCH 0x080 /* Triple is a call instruction */
753 #define ENDBRANCH 0x0a0 /* Triple is an end instruction */
754 #define PART 0x100 /* Triple is really part of another triple */
755 #define BITFIELD 0x200 /* Triple manipulates a bitfield */
756 signed char lhs, rhs, misc, targ;
759 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
767 static const struct op_info table_ops[] = {
768 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
769 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
770 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
771 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
772 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
773 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
774 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
775 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
776 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
777 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
778 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
779 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
780 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
781 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
782 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
783 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
784 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
785 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
786 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
788 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
789 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
790 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
791 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
792 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
793 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
794 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
795 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
796 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
797 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
798 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
799 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
801 [OP_LOAD ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "load"),
802 [OP_STORE ] = OP( 0, 2, 0, 0, PURE | BLOCK , "store"),
804 [OP_UEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
805 [OP_SEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
806 [OP_DEPOSIT ] = OP( 0, 2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
808 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
810 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
811 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE , "blobconst"),
812 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
813 [OP_UNKNOWNVAL ] = OP( 0, 0, 0, 0, PURE | DEF, "unknown"),
815 #if DEBUG_ROMCC_WARNINGS
816 #warning "FIXME is it correct for OP_WRITE to be a def? I currently use it as one..."
818 [OP_WRITE ] = OP( 0, 1, 1, 0, PURE | DEF | BLOCK, "write"),
819 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
820 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
821 [OP_CONVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "convert"),
822 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
823 [OP_ASM ] = OP(-1, -1, 0, 0, PURE, "asm"),
824 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
825 [OP_DOT ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "dot"),
826 [OP_INDEX ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "index"),
828 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
829 [OP_TUPLE ] = OP(-1, 0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
830 [OP_BITREF ] = OP( 0, 1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
831 /* Call is special most it can stand in for anything so it depends on context */
832 [OP_FCALL ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
833 [OP_PROG ] = OP( 0, 1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
834 /* The sizes of OP_FCALL depends upon context */
836 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
837 [OP_BRANCH ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
838 [OP_CBRANCH ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
839 [OP_CALL ] = OP( 0, 0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
840 [OP_RET ] = OP( 0, 1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
841 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
842 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
843 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
844 /* The number of RHS elements of OP_PHI depend upon context */
845 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
848 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH, "cps_branch"),
849 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH, "cps_cbranch"),
850 [OP_CPS_CALL ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH, "cps_call"),
851 [OP_CPS_RET ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH, "cps_ret"),
852 [OP_CPS_END ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
853 [OP_CPS_START ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "cps_start"),
856 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
857 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
858 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
859 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
860 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
861 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
862 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
863 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
864 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
865 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
866 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
867 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
868 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
869 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
870 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
871 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
872 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
873 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
874 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
875 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
876 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
877 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
878 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
880 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
881 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
882 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
883 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
884 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
885 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
886 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
887 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
888 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
889 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
890 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
893 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
895 static const char *tops(int index)
897 static const char unknown[] = "unknown op";
901 if (index > OP_MAX) {
904 return table_ops[index].name;
911 struct triple_set *next;
912 struct triple *member;
922 const char *filename;
923 const char *function;
926 struct occurance *parent;
933 struct triple *next, *prev;
934 struct triple_set *use;
937 unsigned int template_id : 7;
938 unsigned int lhs : 6;
939 unsigned int rhs : 7;
940 unsigned int misc : 2;
941 unsigned int targ : 1;
942 #define TRIPLE_SIZE(TRIPLE) \
943 ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
944 #define TRIPLE_LHS_OFF(PTR) (0)
945 #define TRIPLE_RHS_OFF(PTR) (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
946 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
947 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
948 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
949 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
950 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
951 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
952 unsigned id; /* A scratch value and finally the register */
953 #define TRIPLE_FLAG_FLATTENED (1 << 31)
954 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
955 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
956 #define TRIPLE_FLAG_VOLATILE (1 << 28)
957 #define TRIPLE_FLAG_INLINE (1 << 27) /* ???? */
958 #define TRIPLE_FLAG_LOCAL (1 << 26)
960 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
961 struct occurance *occurance;
964 struct bitfield bitfield;
967 struct hash_entry *field;
968 struct asm_info *ainfo;
970 struct symbol *symbol;
972 struct triple *param[2];
979 struct ins_template {
980 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
984 struct ins_template tmpl;
989 struct block_set *next;
990 struct block *member;
993 struct block *work_next;
994 struct triple *first, *last;
996 struct block_set *edges;
998 struct block_set *use;
999 struct block_set *idominates;
1000 struct block_set *domfrontier;
1002 struct block_set *ipdominates;
1003 struct block_set *ipdomfrontier;
1004 struct block *ipdom;
1010 struct symbol *next;
1011 struct hash_entry *ident;
1018 struct macro_arg *next;
1019 struct hash_entry *ident;
1022 struct hash_entry *ident;
1025 struct macro_arg *args;
1030 struct hash_entry *next;
1034 struct macro *sym_define;
1035 struct symbol *sym_label;
1036 struct symbol *sym_tag;
1037 struct symbol *sym_ident;
1040 #define HASH_TABLE_SIZE 2048
1042 struct compiler_state {
1043 const char *label_prefix;
1044 const char *ofilename;
1045 unsigned long flags;
1046 unsigned long debug;
1047 unsigned long max_allocation_passes;
1049 size_t include_path_count;
1050 const char **include_paths;
1052 size_t define_count;
1053 const char **defines;
1056 const char **undefs;
1059 unsigned long features;
1061 struct basic_blocks {
1062 struct triple *func;
1063 struct triple *first;
1064 struct block *first_block, *last_block;
1067 #define MAX_PP_IF_DEPTH 63
1068 struct compile_state {
1069 struct compiler_state *compiler;
1070 struct arch_state *arch;
1074 struct file_state *file;
1075 struct occurance *last_occurance;
1076 const char *function;
1078 struct token token[6];
1079 struct hash_entry *hash_table[HASH_TABLE_SIZE];
1080 struct hash_entry *i_switch;
1081 struct hash_entry *i_case;
1082 struct hash_entry *i_continue;
1083 struct hash_entry *i_break;
1084 struct hash_entry *i_default;
1085 struct hash_entry *i_return;
1086 struct hash_entry *i_noreturn;
1087 /* Additional hash entries for predefined macros */
1088 struct hash_entry *i_defined;
1089 struct hash_entry *i___VA_ARGS__;
1090 struct hash_entry *i___FILE__;
1091 struct hash_entry *i___LINE__;
1092 /* Additional hash entries for predefined identifiers */
1093 struct hash_entry *i___func__;
1094 /* Additional hash entries for attributes */
1095 struct hash_entry *i_noinline;
1096 struct hash_entry *i_always_inline;
1098 unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1100 int eat_depth, eat_targ;
1101 struct file_state *macro_file;
1102 struct triple *functions;
1103 struct triple *main_function;
1104 struct triple *first;
1105 struct triple *global_pool;
1106 struct basic_blocks bb;
1107 int functions_joined;
1110 /* visibility global/local */
1111 /* static/auto duration */
1112 /* typedef, register, inline */
1113 #define STOR_SHIFT 0
1114 #define STOR_MASK 0x001f
1116 #define STOR_GLOBAL 0x0001
1118 #define STOR_PERM 0x0002
1119 /* Definition locality */
1120 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1121 /* Storage specifiers */
1122 #define STOR_AUTO 0x0000
1123 #define STOR_STATIC 0x0002
1124 #define STOR_LOCAL 0x0003
1125 #define STOR_EXTERN 0x0007
1126 #define STOR_INLINE 0x0008
1127 #define STOR_REGISTER 0x0010
1128 #define STOR_TYPEDEF 0x0018
1130 #define QUAL_SHIFT 5
1131 #define QUAL_MASK 0x00e0
1132 #define QUAL_NONE 0x0000
1133 #define QUAL_CONST 0x0020
1134 #define QUAL_VOLATILE 0x0040
1135 #define QUAL_RESTRICT 0x0080
1137 #define TYPE_SHIFT 8
1138 #define TYPE_MASK 0x1f00
1139 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1140 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1141 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1142 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1143 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1144 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1145 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1146 #define TYPE_DEFAULT 0x0000
1147 #define TYPE_VOID 0x0100
1148 #define TYPE_CHAR 0x0200
1149 #define TYPE_UCHAR 0x0300
1150 #define TYPE_SHORT 0x0400
1151 #define TYPE_USHORT 0x0500
1152 #define TYPE_INT 0x0600
1153 #define TYPE_UINT 0x0700
1154 #define TYPE_LONG 0x0800
1155 #define TYPE_ULONG 0x0900
1156 #define TYPE_LLONG 0x0a00 /* long long */
1157 #define TYPE_ULLONG 0x0b00
1158 #define TYPE_FLOAT 0x0c00
1159 #define TYPE_DOUBLE 0x0d00
1160 #define TYPE_LDOUBLE 0x0e00 /* long double */
1162 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1163 #define TYPE_ENUM 0x1600
1164 #define TYPE_LIST 0x1700
1165 /* TYPE_LIST is a basic building block when defining enumerations
1166 * type->field_ident holds the name of this enumeration entry.
1167 * type->right holds the entry in the list.
1170 #define TYPE_STRUCT 0x1000
1172 * type->left holds the link list of TYPE_PRODUCT entries that
1173 * make up the structure.
1174 * type->elements hold the length of the linked list
1176 #define TYPE_UNION 0x1100
1178 * type->left holds the link list of TYPE_OVERLAP entries that
1179 * make up the union.
1180 * type->elements hold the length of the linked list
1182 #define TYPE_POINTER 0x1200
1183 /* For TYPE_POINTER:
1184 * type->left holds the type pointed to.
1186 #define TYPE_FUNCTION 0x1300
1187 /* For TYPE_FUNCTION:
1188 * type->left holds the return type.
1189 * type->right holds the type of the arguments
1190 * type->elements holds the count of the arguments
1192 #define TYPE_PRODUCT 0x1400
1193 /* TYPE_PRODUCT is a basic building block when defining structures
1194 * type->left holds the type that appears first in memory.
1195 * type->right holds the type that appears next in memory.
1197 #define TYPE_OVERLAP 0x1500
1198 /* TYPE_OVERLAP is a basic building block when defining unions
1199 * type->left and type->right holds to types that overlap
1200 * each other in memory.
1202 #define TYPE_ARRAY 0x1800
1203 /* TYPE_ARRAY is a basic building block when definitng arrays.
1204 * type->left holds the type we are an array of.
1205 * type->elements holds the number of elements.
1207 #define TYPE_TUPLE 0x1900
1208 /* TYPE_TUPLE is a basic building block when defining
1209 * positionally reference type conglomerations. (i.e. closures)
1210 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1211 * except it has no field names.
1212 * type->left holds the liked list of TYPE_PRODUCT entries that
1213 * make up the closure type.
1214 * type->elements hold the number of elements in the closure.
1216 #define TYPE_JOIN 0x1a00
1217 /* TYPE_JOIN is a basic building block when defining
1218 * positionally reference type conglomerations. (i.e. closures)
1219 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1220 * except it has no field names.
1221 * type->left holds the liked list of TYPE_OVERLAP entries that
1222 * make up the closure type.
1223 * type->elements hold the number of elements in the closure.
1225 #define TYPE_BITFIELD 0x1b00
1226 /* TYPE_BITFIED is the type of a bitfield.
1227 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1228 * type->elements holds the number of bits in the bitfield.
1230 #define TYPE_UNKNOWN 0x1c00
1231 /* TYPE_UNKNOWN is the type of an unknown value.
1232 * Used on unknown consts and other places where I don't know the type.
1235 #define ATTRIB_SHIFT 16
1236 #define ATTRIB_MASK 0xffff0000
1237 #define ATTRIB_NOINLINE 0x00010000
1238 #define ATTRIB_ALWAYS_INLINE 0x00020000
1240 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1244 struct type *left, *right;
1246 struct hash_entry *field_ident;
1247 struct hash_entry *type_ident;
1250 #define TEMPLATE_BITS 7
1251 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1252 #define MAX_REG_EQUIVS 16
1254 #define MAX_REGISTERS 75
1255 #define REGISTER_BITS 7
1256 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1259 #define REG_UNNEEDED 2
1260 #define REG_VIRT0 (MAX_REGISTERS + 0)
1261 #define REG_VIRT1 (MAX_REGISTERS + 1)
1262 #define REG_VIRT2 (MAX_REGISTERS + 2)
1263 #define REG_VIRT3 (MAX_REGISTERS + 3)
1264 #define REG_VIRT4 (MAX_REGISTERS + 4)
1265 #define REG_VIRT5 (MAX_REGISTERS + 5)
1266 #define REG_VIRT6 (MAX_REGISTERS + 6)
1267 #define REG_VIRT7 (MAX_REGISTERS + 7)
1268 #define REG_VIRT8 (MAX_REGISTERS + 8)
1269 #define REG_VIRT9 (MAX_REGISTERS + 9)
1271 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1272 #error "MAX_VIRT_REGISTERS to small"
1274 #if (MAX_REGC + REGISTER_BITS) >= 26
1275 #error "Too many id bits used"
1278 /* Provision for 8 register classes */
1280 #define REGC_SHIFT REGISTER_BITS
1281 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1282 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1283 #define ID_REG(ID) ((ID) & REG_MASK)
1284 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1285 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1286 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1287 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1288 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1290 #define ARCH_INPUT_REGS 4
1291 #define ARCH_OUTPUT_REGS 4
1293 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1294 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1295 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1296 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1297 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1298 static void arch_reg_equivs(
1299 struct compile_state *state, unsigned *equiv, int reg);
1300 static int arch_select_free_register(
1301 struct compile_state *state, char *used, int classes);
1302 static unsigned arch_regc_size(struct compile_state *state, int class);
1303 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1304 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1305 static const char *arch_reg_str(int reg);
1306 static struct reg_info arch_reg_constraint(
1307 struct compile_state *state, struct type *type, const char *constraint);
1308 static struct reg_info arch_reg_clobber(
1309 struct compile_state *state, const char *clobber);
1310 static struct reg_info arch_reg_lhs(struct compile_state *state,
1311 struct triple *ins, int index);
1312 static struct reg_info arch_reg_rhs(struct compile_state *state,
1313 struct triple *ins, int index);
1314 static int arch_reg_size(int reg);
1315 static struct triple *transform_to_arch_instruction(
1316 struct compile_state *state, struct triple *ins);
1317 static struct triple *flatten(
1318 struct compile_state *state, struct triple *first, struct triple *ptr);
1319 static void print_dominators(struct compile_state *state,
1320 FILE *fp, struct basic_blocks *bb);
1321 static void print_dominance_frontiers(struct compile_state *state,
1322 FILE *fp, struct basic_blocks *bb);
1326 #define DEBUG_ABORT_ON_ERROR 0x00000001
1327 #define DEBUG_BASIC_BLOCKS 0x00000002
1328 #define DEBUG_FDOMINATORS 0x00000004
1329 #define DEBUG_RDOMINATORS 0x00000008
1330 #define DEBUG_TRIPLES 0x00000010
1331 #define DEBUG_INTERFERENCE 0x00000020
1332 #define DEBUG_SCC_TRANSFORM 0x00000040
1333 #define DEBUG_SCC_TRANSFORM2 0x00000080
1334 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1335 #define DEBUG_INLINE 0x00000200
1336 #define DEBUG_RANGE_CONFLICTS 0x00000400
1337 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1338 #define DEBUG_COLOR_GRAPH 0x00001000
1339 #define DEBUG_COLOR_GRAPH2 0x00002000
1340 #define DEBUG_COALESCING 0x00004000
1341 #define DEBUG_COALESCING2 0x00008000
1342 #define DEBUG_VERIFICATION 0x00010000
1343 #define DEBUG_CALLS 0x00020000
1344 #define DEBUG_CALLS2 0x00040000
1345 #define DEBUG_TOKENS 0x80000000
1347 #define DEBUG_DEFAULT ( \
1348 DEBUG_ABORT_ON_ERROR | \
1349 DEBUG_BASIC_BLOCKS | \
1350 DEBUG_FDOMINATORS | \
1351 DEBUG_RDOMINATORS | \
1355 #define DEBUG_ALL ( \
1356 DEBUG_ABORT_ON_ERROR | \
1357 DEBUG_BASIC_BLOCKS | \
1358 DEBUG_FDOMINATORS | \
1359 DEBUG_RDOMINATORS | \
1361 DEBUG_INTERFERENCE | \
1362 DEBUG_SCC_TRANSFORM | \
1363 DEBUG_SCC_TRANSFORM2 | \
1364 DEBUG_REBUILD_SSA_FORM | \
1366 DEBUG_RANGE_CONFLICTS | \
1367 DEBUG_RANGE_CONFLICTS2 | \
1368 DEBUG_COLOR_GRAPH | \
1369 DEBUG_COLOR_GRAPH2 | \
1370 DEBUG_COALESCING | \
1371 DEBUG_COALESCING2 | \
1372 DEBUG_VERIFICATION | \
1378 #define COMPILER_INLINE_MASK 0x00000007
1379 #define COMPILER_INLINE_ALWAYS 0x00000000
1380 #define COMPILER_INLINE_NEVER 0x00000001
1381 #define COMPILER_INLINE_DEFAULTON 0x00000002
1382 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1383 #define COMPILER_INLINE_NOPENALTY 0x00000004
1384 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1385 #define COMPILER_SIMPLIFY 0x00000010
1386 #define COMPILER_SCC_TRANSFORM 0x00000020
1387 #define COMPILER_SIMPLIFY_OP 0x00000040
1388 #define COMPILER_SIMPLIFY_PHI 0x00000080
1389 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1390 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1391 #define COMPILER_SIMPLIFY_COPY 0x00000400
1392 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1393 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1394 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1395 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1396 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1398 #define COMPILER_TRIGRAPHS 0x40000000
1399 #define COMPILER_PP_ONLY 0x80000000
1401 #define COMPILER_DEFAULT_FLAGS ( \
1402 COMPILER_TRIGRAPHS | \
1403 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1404 COMPILER_INLINE_DEFAULTON | \
1405 COMPILER_SIMPLIFY_OP | \
1406 COMPILER_SIMPLIFY_PHI | \
1407 COMPILER_SIMPLIFY_LABEL | \
1408 COMPILER_SIMPLIFY_BRANCH | \
1409 COMPILER_SIMPLIFY_COPY | \
1410 COMPILER_SIMPLIFY_ARITH | \
1411 COMPILER_SIMPLIFY_SHIFT | \
1412 COMPILER_SIMPLIFY_BITWISE | \
1413 COMPILER_SIMPLIFY_LOGICAL | \
1414 COMPILER_SIMPLIFY_BITFIELD | \
1417 #define GLOBAL_SCOPE_DEPTH 1
1418 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1420 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1424 static void init_compiler_state(struct compiler_state *compiler)
1426 memset(compiler, 0, sizeof(*compiler));
1427 compiler->label_prefix = "";
1428 compiler->ofilename = "auto.inc";
1429 compiler->flags = COMPILER_DEFAULT_FLAGS;
1430 compiler->debug = 0;
1431 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1432 compiler->include_path_count = 1;
1433 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1434 compiler->define_count = 1;
1435 compiler->defines = xcmalloc(sizeof(char *), "defines");
1436 compiler->undef_count = 1;
1437 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1440 struct compiler_flag {
1445 struct compiler_arg {
1448 struct compiler_flag flags[16];
1451 static int set_flag(
1452 const struct compiler_flag *ptr, unsigned long *flags,
1453 int act, const char *flag)
1456 for(; ptr->name; ptr++) {
1457 if (strcmp(ptr->name, flag) == 0) {
1463 *flags &= ~(ptr->flag);
1465 *flags |= ptr->flag;
1472 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1477 val = strchr(arg, '=');
1481 for(; ptr->name; ptr++) {
1482 if (strncmp(ptr->name, arg, len) == 0) {
1487 *flags &= ~ptr->mask;
1488 result = set_flag(&ptr->flags[0], flags, 1, val);
1495 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1496 const char *prefix, const char *invert_prefix)
1498 for(;ptr->name; ptr++) {
1499 fprintf(fp, "%s%s\n", prefix, ptr->name);
1500 if (invert_prefix) {
1501 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1506 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1509 for(;ptr->name; ptr++) {
1510 const struct compiler_flag *flag;
1511 for(flag = &ptr->flags[0]; flag->name; flag++) {
1512 fprintf(fp, "%s%s=%s\n",
1513 prefix, ptr->name, flag->name);
1518 static int append_string(size_t *max, const char ***vec, const char *str,
1523 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1524 (*vec)[count -1] = 0;
1525 (*vec)[count -2] = str;
1529 static void arg_error(char *fmt, ...);
1530 static const char *identifier(const char *str, const char *end);
1532 static int append_include_path(struct compiler_state *compiler, const char *str)
1535 if (!exists(str, ".")) {
1536 arg_error("Nonexistent include path: `%s'\n",
1539 result = append_string(&compiler->include_path_count,
1540 &compiler->include_paths, str, "include_paths");
1544 static int append_define(struct compiler_state *compiler, const char *str)
1546 const char *end, *rest;
1549 end = strchr(str, '=');
1551 end = str + strlen(str);
1553 rest = identifier(str, end);
1555 int len = end - str - 1;
1556 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1559 result = append_string(&compiler->define_count,
1560 &compiler->defines, str, "defines");
1564 static int append_undef(struct compiler_state *compiler, const char *str)
1566 const char *end, *rest;
1569 end = str + strlen(str);
1570 rest = identifier(str, end);
1572 int len = end - str - 1;
1573 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1576 result = append_string(&compiler->undef_count,
1577 &compiler->undefs, str, "undefs");
1581 static const struct compiler_flag romcc_flags[] = {
1582 { "trigraphs", COMPILER_TRIGRAPHS },
1583 { "pp-only", COMPILER_PP_ONLY },
1584 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1585 { "simplify", COMPILER_SIMPLIFY },
1586 { "scc-transform", COMPILER_SCC_TRANSFORM },
1587 { "simplify-op", COMPILER_SIMPLIFY_OP },
1588 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1589 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1590 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1591 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1592 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1593 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1594 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1595 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1596 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1599 static const struct compiler_arg romcc_args[] = {
1600 { "inline-policy", COMPILER_INLINE_MASK,
1602 { "always", COMPILER_INLINE_ALWAYS, },
1603 { "never", COMPILER_INLINE_NEVER, },
1604 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1605 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1606 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1612 static const struct compiler_flag romcc_opt_flags[] = {
1613 { "-O", COMPILER_SIMPLIFY },
1614 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1615 { "-E", COMPILER_PP_ONLY },
1618 static const struct compiler_flag romcc_debug_flags[] = {
1619 { "all", DEBUG_ALL },
1620 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1621 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1622 { "fdominators", DEBUG_FDOMINATORS },
1623 { "rdominators", DEBUG_RDOMINATORS },
1624 { "triples", DEBUG_TRIPLES },
1625 { "interference", DEBUG_INTERFERENCE },
1626 { "scc-transform", DEBUG_SCC_TRANSFORM },
1627 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1628 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1629 { "inline", DEBUG_INLINE },
1630 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1631 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1632 { "color-graph", DEBUG_COLOR_GRAPH },
1633 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1634 { "coalescing", DEBUG_COALESCING },
1635 { "coalescing2", DEBUG_COALESCING2 },
1636 { "verification", DEBUG_VERIFICATION },
1637 { "calls", DEBUG_CALLS },
1638 { "calls2", DEBUG_CALLS2 },
1639 { "tokens", DEBUG_TOKENS },
1643 static int compiler_encode_flag(
1644 struct compiler_state *compiler, const char *flag)
1651 if (strncmp(flag, "no-", 3) == 0) {
1655 if (strncmp(flag, "-O", 2) == 0) {
1656 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1658 else if (strncmp(flag, "-E", 2) == 0) {
1659 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1661 else if (strncmp(flag, "-I", 2) == 0) {
1662 result = append_include_path(compiler, flag + 2);
1664 else if (strncmp(flag, "-D", 2) == 0) {
1665 result = append_define(compiler, flag + 2);
1667 else if (strncmp(flag, "-U", 2) == 0) {
1668 result = append_undef(compiler, flag + 2);
1670 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1672 compiler->label_prefix = flag + 13;
1674 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1675 unsigned long max_passes;
1677 max_passes = strtoul(flag + 22, &end, 10);
1678 if (end[0] == '\0') {
1680 compiler->max_allocation_passes = max_passes;
1683 else if (act && strcmp(flag, "debug") == 0) {
1685 compiler->debug |= DEBUG_DEFAULT;
1687 else if (strncmp(flag, "debug-", 6) == 0) {
1689 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1692 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1694 result = set_arg(romcc_args, &compiler->flags, flag);
1700 static void compiler_usage(FILE *fp)
1702 flag_usage(fp, romcc_opt_flags, "", 0);
1703 flag_usage(fp, romcc_flags, "-f", "-fno-");
1704 arg_usage(fp, romcc_args, "-f");
1705 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1706 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1707 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1708 fprintf(fp, "-I<include path>\n");
1709 fprintf(fp, "-D<macro>[=defn]\n");
1710 fprintf(fp, "-U<macro>\n");
1713 static void do_cleanup(struct compile_state *state)
1715 if (state->output) {
1716 fclose(state->output);
1717 unlink(state->compiler->ofilename);
1720 if (state->dbgout) {
1721 fflush(state->dbgout);
1723 if (state->errout) {
1724 fflush(state->errout);
1728 static struct compile_state *exit_state;
1729 static void exit_cleanup(void)
1732 do_cleanup(exit_state);
1736 static int get_col(struct file_state *file)
1739 const char *ptr, *end;
1740 ptr = file->line_start;
1742 for(col = 0; ptr < end; ptr++) {
1747 col = (col & ~7) + 8;
1753 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1756 if (triple && triple->occurance) {
1757 struct occurance *spot;
1758 for(spot = triple->occurance; spot; spot = spot->parent) {
1759 fprintf(fp, "%s:%d.%d: ",
1760 spot->filename, spot->line, spot->col);
1767 col = get_col(state->file);
1768 fprintf(fp, "%s:%d.%d: ",
1769 state->file->report_name, state->file->report_line, col);
1772 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr,
1773 const char *fmt, ...)
1775 FILE *fp = state->errout;
1777 va_start(args, fmt);
1778 loc(fp, state, ptr);
1781 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1783 fprintf(fp, "Internal compiler error: ");
1784 vfprintf(fp, fmt, args);
1792 static void internal_warning(struct compile_state *state, struct triple *ptr,
1793 const char *fmt, ...)
1795 FILE *fp = state->errout;
1797 va_start(args, fmt);
1798 loc(fp, state, ptr);
1800 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1802 fprintf(fp, "Internal compiler warning: ");
1803 vfprintf(fp, fmt, args);
1810 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr,
1811 const char *fmt, ...)
1813 FILE *fp = state->errout;
1815 va_start(args, fmt);
1816 loc(fp, state, ptr);
1818 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1819 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1821 vfprintf(fp, fmt, args);
1825 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1831 static void warning(struct compile_state *state, struct triple *ptr,
1832 const char *fmt, ...)
1834 FILE *fp = state->errout;
1836 va_start(args, fmt);
1837 loc(fp, state, ptr);
1838 fprintf(fp, "warning: ");
1839 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1840 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1842 vfprintf(fp, fmt, args);
1847 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1849 static void valid_op(struct compile_state *state, int op)
1851 char *fmt = "invalid op: %d";
1853 internal_error(state, 0, fmt, op);
1856 internal_error(state, 0, fmt, op);
1860 static void valid_ins(struct compile_state *state, struct triple *ptr)
1862 valid_op(state, ptr->op);
1865 #if DEBUG_ROMCC_WARNING
1866 static void valid_param_count(struct compile_state *state, struct triple *ins)
1868 int lhs, rhs, misc, targ;
1869 valid_ins(state, ins);
1870 lhs = table_ops[ins->op].lhs;
1871 rhs = table_ops[ins->op].rhs;
1872 misc = table_ops[ins->op].misc;
1873 targ = table_ops[ins->op].targ;
1875 if ((lhs >= 0) && (ins->lhs != lhs)) {
1876 internal_error(state, ins, "Bad lhs count");
1878 if ((rhs >= 0) && (ins->rhs != rhs)) {
1879 internal_error(state, ins, "Bad rhs count");
1881 if ((misc >= 0) && (ins->misc != misc)) {
1882 internal_error(state, ins, "Bad misc count");
1884 if ((targ >= 0) && (ins->targ != targ)) {
1885 internal_error(state, ins, "Bad targ count");
1890 static struct type void_type;
1891 static struct type unknown_type;
1892 static void use_triple(struct triple *used, struct triple *user)
1894 struct triple_set **ptr, *new;
1899 if (used->use == (void*)-1)
1904 if ((*ptr)->member == user) {
1907 ptr = &(*ptr)->next;
1910 /* Append new to the head of the list,
1911 * copy_func and rename_block_variables
1914 new = xcmalloc(sizeof(*new), "triple_set");
1916 new->next = used->use;
1920 static void unuse_triple(struct triple *used, struct triple *unuser)
1922 struct triple_set *use, **ptr;
1929 if (use->member == unuser) {
1939 static void put_occurance(struct occurance *occurance)
1942 occurance->count -= 1;
1943 if (occurance->count <= 0) {
1944 if (occurance->parent) {
1945 put_occurance(occurance->parent);
1952 static void get_occurance(struct occurance *occurance)
1955 occurance->count += 1;
1960 static struct occurance *new_occurance(struct compile_state *state)
1962 struct occurance *result, *last;
1963 const char *filename;
1964 const char *function;
1972 filename = state->file->report_name;
1973 line = state->file->report_line;
1974 col = get_col(state->file);
1976 if (state->function) {
1977 function = state->function;
1979 last = state->last_occurance;
1981 (last->col == col) &&
1982 (last->line == line) &&
1983 (last->function == function) &&
1984 ((last->filename == filename) ||
1985 (strcmp(last->filename, filename) == 0)))
1987 get_occurance(last);
1991 state->last_occurance = 0;
1992 put_occurance(last);
1994 result = xmalloc(sizeof(*result), "occurance");
1996 result->filename = filename;
1997 result->function = function;
1998 result->line = line;
2001 state->last_occurance = result;
2005 static struct occurance *inline_occurance(struct compile_state *state,
2006 struct occurance *base, struct occurance *top)
2008 struct occurance *result, *last;
2010 internal_error(state, 0, "inlining an already inlined function?");
2012 /* If I have a null base treat it that way */
2013 if ((base->parent == 0) &&
2015 (base->line == 0) &&
2016 (base->function[0] == '\0') &&
2017 (base->filename[0] == '\0')) {
2020 /* See if I can reuse the last occurance I had */
2021 last = state->last_occurance;
2023 (last->parent == base) &&
2024 (last->col == top->col) &&
2025 (last->line == top->line) &&
2026 (last->function == top->function) &&
2027 (last->filename == top->filename)) {
2028 get_occurance(last);
2031 /* I can't reuse the last occurance so free it */
2033 state->last_occurance = 0;
2034 put_occurance(last);
2036 /* Generate a new occurance structure */
2037 get_occurance(base);
2038 result = xmalloc(sizeof(*result), "occurance");
2040 result->filename = top->filename;
2041 result->function = top->function;
2042 result->line = top->line;
2043 result->col = top->col;
2044 result->parent = base;
2045 state->last_occurance = result;
2049 static struct occurance dummy_occurance = {
2051 .filename = __FILE__,
2058 /* The undef triple is used as a place holder when we are removing pointers
2059 * from a triple. Having allows certain sanity checks to pass even
2060 * when the original triple that was pointed to is gone.
2062 static struct triple unknown_triple = {
2063 .next = &unknown_triple,
2064 .prev = &unknown_triple,
2066 .op = OP_UNKNOWNVAL,
2071 .type = &unknown_type,
2072 .id = -1, /* An invalid id */
2073 .u = { .cval = 0, },
2074 .occurance = &dummy_occurance,
2075 .param = { [0] = 0, [1] = 0, },
2079 static size_t registers_of(struct compile_state *state, struct type *type);
2081 static struct triple *alloc_triple(struct compile_state *state,
2082 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2083 struct occurance *occurance)
2085 size_t size, extra_count, min_count;
2086 int lhs, rhs, misc, targ;
2087 struct triple *ret, dummy;
2089 dummy.occurance = occurance;
2090 valid_op(state, op);
2091 lhs = table_ops[op].lhs;
2092 rhs = table_ops[op].rhs;
2093 misc = table_ops[op].misc;
2094 targ = table_ops[op].targ;
2104 lhs = registers_of(state, type);
2107 lhs = registers_of(state, type);
2114 if ((rhs < 0) || (rhs > MAX_RHS)) {
2115 internal_error(state, &dummy, "bad rhs count %d", rhs);
2117 if ((lhs < 0) || (lhs > MAX_LHS)) {
2118 internal_error(state, &dummy, "bad lhs count %d", lhs);
2120 if ((misc < 0) || (misc > MAX_MISC)) {
2121 internal_error(state, &dummy, "bad misc count %d", misc);
2123 if ((targ < 0) || (targ > MAX_TARG)) {
2124 internal_error(state, &dummy, "bad targs count %d", targ);
2127 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2128 extra_count = lhs + rhs + misc + targ;
2129 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2131 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2132 ret = xcmalloc(size, "tripple");
2141 ret->occurance = occurance;
2142 /* A simple sanity check */
2143 if ((ret->op != op) ||
2144 (ret->lhs != lhs) ||
2145 (ret->rhs != rhs) ||
2146 (ret->misc != misc) ||
2147 (ret->targ != targ) ||
2148 (ret->type != type) ||
2149 (ret->next != ret) ||
2150 (ret->prev != ret) ||
2151 (ret->occurance != occurance)) {
2152 internal_error(state, ret, "huh?");
2157 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2160 int src_lhs, src_rhs, src_size;
2163 src_size = TRIPLE_SIZE(src);
2164 get_occurance(src->occurance);
2165 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2167 memcpy(dup, src, sizeof(*src));
2168 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2172 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2174 struct triple *copy;
2175 copy = dup_triple(state, src);
2177 copy->next = copy->prev = copy;
2181 static struct triple *new_triple(struct compile_state *state,
2182 int op, struct type *type, int lhs, int rhs)
2185 struct occurance *occurance;
2186 occurance = new_occurance(state);
2187 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2191 static struct triple *build_triple(struct compile_state *state,
2192 int op, struct type *type, struct triple *left, struct triple *right,
2193 struct occurance *occurance)
2197 ret = alloc_triple(state, op, type, -1, -1, occurance);
2198 count = TRIPLE_SIZE(ret);
2200 ret->param[0] = left;
2203 ret->param[1] = right;
2208 static struct triple *triple(struct compile_state *state,
2209 int op, struct type *type, struct triple *left, struct triple *right)
2213 ret = new_triple(state, op, type, -1, -1);
2214 count = TRIPLE_SIZE(ret);
2216 ret->param[0] = left;
2219 ret->param[1] = right;
2224 static struct triple *branch(struct compile_state *state,
2225 struct triple *targ, struct triple *test)
2229 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2232 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2234 TARG(ret, 0) = targ;
2235 /* record the branch target was used */
2236 if (!targ || (targ->op != OP_LABEL)) {
2237 internal_error(state, 0, "branch not to label");
2242 static int triple_is_label(struct compile_state *state, struct triple *ins);
2243 static int triple_is_call(struct compile_state *state, struct triple *ins);
2244 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2245 static void insert_triple(struct compile_state *state,
2246 struct triple *first, struct triple *ptr)
2249 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2250 internal_error(state, ptr, "expression already used");
2253 ptr->prev = first->prev;
2254 ptr->prev->next = ptr;
2255 ptr->next->prev = ptr;
2257 if (triple_is_cbranch(state, ptr->prev) ||
2258 triple_is_call(state, ptr->prev)) {
2259 unuse_triple(first, ptr->prev);
2260 use_triple(ptr, ptr->prev);
2265 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2267 /* This function is used to determine if u.block
2268 * is utilized to store the current block number.
2271 valid_ins(state, ins);
2272 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2273 return stores_block;
2276 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2277 static struct block *block_of_triple(struct compile_state *state,
2280 struct triple *first;
2281 if (!ins || ins == &unknown_triple) {
2284 first = state->first;
2285 while(ins != first && !triple_is_branch(state, ins->prev) &&
2286 !triple_stores_block(state, ins))
2288 if (ins == ins->prev) {
2289 internal_error(state, ins, "ins == ins->prev?");
2293 return triple_stores_block(state, ins)? ins->u.block: 0;
2296 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2297 static struct triple *pre_triple(struct compile_state *state,
2298 struct triple *base,
2299 int op, struct type *type, struct triple *left, struct triple *right)
2301 struct block *block;
2304 /* If I am an OP_PIECE jump to the real instruction */
2305 if (base->op == OP_PIECE) {
2306 base = MISC(base, 0);
2308 block = block_of_triple(state, base);
2309 get_occurance(base->occurance);
2310 ret = build_triple(state, op, type, left, right, base->occurance);
2311 generate_lhs_pieces(state, ret);
2312 if (triple_stores_block(state, ret)) {
2313 ret->u.block = block;
2315 insert_triple(state, base, ret);
2316 for(i = 0; i < ret->lhs; i++) {
2317 struct triple *piece;
2318 piece = LHS(ret, i);
2319 insert_triple(state, base, piece);
2320 use_triple(ret, piece);
2321 use_triple(piece, ret);
2323 if (block && (block->first == base)) {
2329 static struct triple *post_triple(struct compile_state *state,
2330 struct triple *base,
2331 int op, struct type *type, struct triple *left, struct triple *right)
2333 struct block *block;
2334 struct triple *ret, *next;
2336 /* If I am an OP_PIECE jump to the real instruction */
2337 if (base->op == OP_PIECE) {
2338 base = MISC(base, 0);
2340 /* If I have a left hand side skip over it */
2343 base = LHS(base, zlhs - 1);
2346 block = block_of_triple(state, base);
2347 get_occurance(base->occurance);
2348 ret = build_triple(state, op, type, left, right, base->occurance);
2349 generate_lhs_pieces(state, ret);
2350 if (triple_stores_block(state, ret)) {
2351 ret->u.block = block;
2354 insert_triple(state, next, ret);
2356 for(i = 0; i < zlhs; i++) {
2357 struct triple *piece;
2358 piece = LHS(ret, i);
2359 insert_triple(state, next, piece);
2360 use_triple(ret, piece);
2361 use_triple(piece, ret);
2363 if (block && (block->last == base)) {
2366 block->last = LHS(ret, zlhs - 1);
2372 static struct type *reg_type(
2373 struct compile_state *state, struct type *type, int reg);
2375 static void generate_lhs_piece(
2376 struct compile_state *state, struct triple *ins, int index)
2378 struct type *piece_type;
2379 struct triple *piece;
2380 get_occurance(ins->occurance);
2381 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2383 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2384 piece_type = piece_type->left;
2388 static void name_of(FILE *fp, struct type *type);
2389 FILE * fp = state->errout;
2390 fprintf(fp, "piece_type(%d): ", index);
2391 name_of(fp, piece_type);
2395 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2396 piece->u.cval = index;
2397 LHS(ins, piece->u.cval) = piece;
2398 MISC(piece, 0) = ins;
2401 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2405 for(i = 0; i < zlhs; i++) {
2406 generate_lhs_piece(state, ins, i);
2410 static struct triple *label(struct compile_state *state)
2412 /* Labels don't get a type */
2413 struct triple *result;
2414 result = triple(state, OP_LABEL, &void_type, 0, 0);
2418 static struct triple *mkprog(struct compile_state *state, ...)
2420 struct triple *prog, *head, *arg;
2424 head = label(state);
2425 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2426 RHS(prog, 0) = head;
2427 va_start(args, state);
2429 while((arg = va_arg(args, struct triple *)) != 0) {
2431 internal_error(state, 0, "too many arguments to mkprog");
2433 flatten(state, head, arg);
2436 prog->type = head->prev->type;
2439 static void name_of(FILE *fp, struct type *type);
2440 static void display_triple(FILE *fp, struct triple *ins)
2442 struct occurance *ptr;
2444 char pre, post, vol;
2445 pre = post = vol = ' ';
2447 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2450 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2453 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2456 reg = arch_reg_str(ID_REG(ins->id));
2459 fprintf(fp, "(%p) <nothing> ", ins);
2461 else if (ins->op == OP_INTCONST) {
2462 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2463 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2464 (unsigned long)(ins->u.cval));
2466 else if (ins->op == OP_ADDRCONST) {
2467 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2468 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2469 MISC(ins, 0), (unsigned long)(ins->u.cval));
2471 else if (ins->op == OP_INDEX) {
2472 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2473 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2474 RHS(ins, 0), (unsigned long)(ins->u.cval));
2476 else if (ins->op == OP_PIECE) {
2477 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2478 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2479 MISC(ins, 0), (unsigned long)(ins->u.cval));
2483 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2484 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2485 if (table_ops[ins->op].flags & BITFIELD) {
2486 fprintf(fp, " <%2d-%2d:%2d>",
2487 ins->u.bitfield.offset,
2488 ins->u.bitfield.offset + ins->u.bitfield.size,
2489 ins->u.bitfield.size);
2491 count = TRIPLE_SIZE(ins);
2492 for(i = 0; i < count; i++) {
2493 fprintf(fp, " %-10p", ins->param[i]);
2500 struct triple_set *user;
2501 #if DEBUG_DISPLAY_TYPES
2503 name_of(fp, ins->type);
2506 #if DEBUG_DISPLAY_USES
2508 for(user = ins->use; user; user = user->next) {
2509 fprintf(fp, " %-10p", user->member);
2514 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2515 fprintf(fp, " %s,%s:%d.%d",
2521 if (ins->op == OP_ASM) {
2522 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2529 static int equiv_types(struct type *left, struct type *right);
2530 static void display_triple_changes(
2531 FILE *fp, const struct triple *new, const struct triple *orig)
2534 int new_count, orig_count;
2535 new_count = TRIPLE_SIZE(new);
2536 orig_count = TRIPLE_SIZE(orig);
2537 if ((new->op != orig->op) ||
2538 (new_count != orig_count) ||
2539 (memcmp(orig->param, new->param,
2540 orig_count * sizeof(orig->param[0])) != 0) ||
2541 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2543 struct occurance *ptr;
2544 int i, min_count, indent;
2545 fprintf(fp, "(%p %p)", new, orig);
2546 if (orig->op == new->op) {
2547 fprintf(fp, " %-11s", tops(orig->op));
2549 fprintf(fp, " [%-10s %-10s]",
2550 tops(new->op), tops(orig->op));
2552 min_count = new_count;
2553 if (min_count > orig_count) {
2554 min_count = orig_count;
2556 for(indent = i = 0; i < min_count; i++) {
2557 if (orig->param[i] == new->param[i]) {
2558 fprintf(fp, " %-11p",
2562 fprintf(fp, " [%-10p %-10p]",
2568 for(; i < orig_count; i++) {
2569 fprintf(fp, " [%-9p]", orig->param[i]);
2572 for(; i < new_count; i++) {
2573 fprintf(fp, " [%-9p]", new->param[i]);
2576 if ((new->op == OP_INTCONST)||
2577 (new->op == OP_ADDRCONST)) {
2578 fprintf(fp, " <0x%08lx>",
2579 (unsigned long)(new->u.cval));
2582 for(;indent < 36; indent++) {
2586 #if DEBUG_DISPLAY_TYPES
2588 name_of(fp, new->type);
2589 if (!equiv_types(new->type, orig->type)) {
2590 fprintf(fp, " -- ");
2591 name_of(fp, orig->type);
2597 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2598 fprintf(fp, " %s,%s:%d.%d",
2610 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2612 /* Does the triple have no side effects.
2613 * I.e. Rexecuting the triple with the same arguments
2614 * gives the same value.
2617 valid_ins(state, ins);
2618 pure = PURE_BITS(table_ops[ins->op].flags);
2619 if ((pure != PURE) && (pure != IMPURE)) {
2620 internal_error(state, 0, "Purity of %s not known",
2623 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2626 static int triple_is_branch_type(struct compile_state *state,
2627 struct triple *ins, unsigned type)
2629 /* Is this one of the passed branch types? */
2630 valid_ins(state, ins);
2631 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2634 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2636 /* Is this triple a branch instruction? */
2637 valid_ins(state, ins);
2638 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2641 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2643 /* Is this triple a conditional branch instruction? */
2644 return triple_is_branch_type(state, ins, CBRANCH);
2647 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2649 /* Is this triple a unconditional branch instruction? */
2651 valid_ins(state, ins);
2652 type = BRANCH_BITS(table_ops[ins->op].flags);
2653 return (type != 0) && (type != CBRANCH);
2656 static int triple_is_call(struct compile_state *state, struct triple *ins)
2658 /* Is this triple a call instruction? */
2659 return triple_is_branch_type(state, ins, CALLBRANCH);
2662 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2664 /* Is this triple a return instruction? */
2665 return triple_is_branch_type(state, ins, RETBRANCH);
2668 #if DEBUG_ROMCC_WARNING
2669 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2671 /* Is this triple an unconditional branch and not a call or a
2673 return triple_is_branch_type(state, ins, UBRANCH);
2677 static int triple_is_end(struct compile_state *state, struct triple *ins)
2679 return triple_is_branch_type(state, ins, ENDBRANCH);
2682 static int triple_is_label(struct compile_state *state, struct triple *ins)
2684 valid_ins(state, ins);
2685 return (ins->op == OP_LABEL);
2688 static struct triple *triple_to_block_start(
2689 struct compile_state *state, struct triple *start)
2691 while(!triple_is_branch(state, start->prev) &&
2692 (!triple_is_label(state, start) || !start->use)) {
2693 start = start->prev;
2698 static int triple_is_def(struct compile_state *state, struct triple *ins)
2700 /* This function is used to determine which triples need
2704 valid_ins(state, ins);
2705 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2706 if (ins->lhs >= 1) {
2712 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2715 valid_ins(state, ins);
2716 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2717 return is_structural;
2720 static int triple_is_part(struct compile_state *state, struct triple *ins)
2723 valid_ins(state, ins);
2724 is_part = (table_ops[ins->op].flags & PART) == PART;
2728 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2730 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2733 static struct triple **triple_iter(struct compile_state *state,
2734 size_t count, struct triple **vector,
2735 struct triple *ins, struct triple **last)
2737 struct triple **ret;
2743 else if ((last >= vector) && (last < (vector + count - 1))) {
2751 static struct triple **triple_lhs(struct compile_state *state,
2752 struct triple *ins, struct triple **last)
2754 return triple_iter(state, ins->lhs, &LHS(ins,0),
2758 static struct triple **triple_rhs(struct compile_state *state,
2759 struct triple *ins, struct triple **last)
2761 return triple_iter(state, ins->rhs, &RHS(ins,0),
2765 static struct triple **triple_misc(struct compile_state *state,
2766 struct triple *ins, struct triple **last)
2768 return triple_iter(state, ins->misc, &MISC(ins,0),
2772 static struct triple **do_triple_targ(struct compile_state *state,
2773 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2776 struct triple **ret, **vector;
2781 if (triple_is_cbranch(state, ins)) {
2784 if (!call_edges && triple_is_call(state, ins)) {
2787 if (next_edges && triple_is_call(state, ins)) {
2790 vector = &TARG(ins, 0);
2791 if (!ret && next_is_targ) {
2794 } else if (last == &ins->next) {
2798 if (!ret && count) {
2802 else if ((last >= vector) && (last < (vector + count - 1))) {
2805 else if (last == vector + count - 1) {
2809 if (!ret && triple_is_ret(state, ins) && call_edges) {
2810 struct triple_set *use;
2811 for(use = ins->use; use; use = use->next) {
2812 if (!triple_is_call(state, use->member)) {
2816 ret = &use->member->next;
2819 else if (last == &use->member->next) {
2827 static struct triple **triple_targ(struct compile_state *state,
2828 struct triple *ins, struct triple **last)
2830 return do_triple_targ(state, ins, last, 1, 1);
2833 static struct triple **triple_edge_targ(struct compile_state *state,
2834 struct triple *ins, struct triple **last)
2836 return do_triple_targ(state, ins, last,
2837 state->functions_joined, !state->functions_joined);
2840 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2842 struct triple *next;
2846 for(i = 0; i < lhs; i++) {
2847 struct triple *piece;
2848 piece = LHS(ins, i);
2849 if (next != piece) {
2850 internal_error(state, ins, "malformed lhs on %s",
2853 if (next->op != OP_PIECE) {
2854 internal_error(state, ins, "bad lhs op %s at %d on %s",
2855 tops(next->op), i, tops(ins->op));
2857 if (next->u.cval != i) {
2858 internal_error(state, ins, "bad u.cval of %d %d expected",
2866 /* Function piece accessor functions */
2867 static struct triple *do_farg(struct compile_state *state,
2868 struct triple *func, unsigned index)
2871 struct triple *first, *arg;
2875 if((index < 0) || (index >= (ftype->elements + 2))) {
2876 internal_error(state, func, "bad argument index: %d", index);
2878 first = RHS(func, 0);
2880 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2883 if (arg->op != OP_ADECL) {
2884 internal_error(state, 0, "arg not adecl?");
2888 static struct triple *fresult(struct compile_state *state, struct triple *func)
2890 return do_farg(state, func, 0);
2892 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2894 return do_farg(state, func, 1);
2896 static struct triple *farg(struct compile_state *state,
2897 struct triple *func, unsigned index)
2899 return do_farg(state, func, index + 2);
2903 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2905 struct triple *first, *ins;
2906 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2907 first = ins = RHS(func, 0);
2909 if (triple_is_label(state, ins) && ins->use) {
2910 fprintf(fp, "%p:\n", ins);
2912 display_triple(fp, ins);
2914 if (triple_is_branch(state, ins)) {
2917 if (ins->next->prev != ins) {
2918 internal_error(state, ins->next, "bad prev");
2921 } while(ins != first);
2924 static void verify_use(struct compile_state *state,
2925 struct triple *user, struct triple *used)
2928 size = TRIPLE_SIZE(user);
2929 for(i = 0; i < size; i++) {
2930 if (user->param[i] == used) {
2934 if (triple_is_branch(state, user)) {
2935 if (user->next == used) {
2940 internal_error(state, user, "%s(%p) does not use %s(%p)",
2941 tops(user->op), user, tops(used->op), used);
2945 static int find_rhs_use(struct compile_state *state,
2946 struct triple *user, struct triple *used)
2948 struct triple **param;
2950 verify_use(state, user, used);
2952 #if DEBUG_ROMCC_WARNINGS
2953 #warning "AUDIT ME ->rhs"
2956 param = &RHS(user, 0);
2957 for(i = 0; i < size; i++) {
2958 if (param[i] == used) {
2965 static void free_triple(struct compile_state *state, struct triple *ptr)
2968 size = sizeof(*ptr) - sizeof(ptr->param) +
2969 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2970 ptr->prev->next = ptr->next;
2971 ptr->next->prev = ptr->prev;
2973 internal_error(state, ptr, "ptr->use != 0");
2975 put_occurance(ptr->occurance);
2976 memset(ptr, -1, size);
2980 static void release_triple(struct compile_state *state, struct triple *ptr)
2982 struct triple_set *set, *next;
2983 struct triple **expr;
2984 struct block *block;
2985 if (ptr == &unknown_triple) {
2988 valid_ins(state, ptr);
2989 /* Make certain the we are not the first or last element of a block */
2990 block = block_of_triple(state, ptr);
2992 if ((block->last == ptr) && (block->first == ptr)) {
2993 block->last = block->first = 0;
2995 else if (block->last == ptr) {
2996 block->last = ptr->prev;
2998 else if (block->first == ptr) {
2999 block->first = ptr->next;
3002 /* Remove ptr from use chains where it is the user */
3003 expr = triple_rhs(state, ptr, 0);
3004 for(; expr; expr = triple_rhs(state, ptr, expr)) {
3006 unuse_triple(*expr, ptr);
3009 expr = triple_lhs(state, ptr, 0);
3010 for(; expr; expr = triple_lhs(state, ptr, expr)) {
3012 unuse_triple(*expr, ptr);
3015 expr = triple_misc(state, ptr, 0);
3016 for(; expr; expr = triple_misc(state, ptr, expr)) {
3018 unuse_triple(*expr, ptr);
3021 expr = triple_targ(state, ptr, 0);
3022 for(; expr; expr = triple_targ(state, ptr, expr)) {
3024 unuse_triple(*expr, ptr);
3027 /* Reomve ptr from use chains where it is used */
3028 for(set = ptr->use; set; set = next) {
3030 valid_ins(state, set->member);
3031 expr = triple_rhs(state, set->member, 0);
3032 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3034 *expr = &unknown_triple;
3037 expr = triple_lhs(state, set->member, 0);
3038 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3040 *expr = &unknown_triple;
3043 expr = triple_misc(state, set->member, 0);
3044 for(; expr; expr = triple_misc(state, set->member, expr)) {
3046 *expr = &unknown_triple;
3049 expr = triple_targ(state, set->member, 0);
3050 for(; expr; expr = triple_targ(state, set->member, expr)) {
3052 *expr = &unknown_triple;
3055 unuse_triple(ptr, set->member);
3057 free_triple(state, ptr);
3060 static void print_triples(struct compile_state *state);
3061 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3063 #define TOK_UNKNOWN 0
3066 #define TOK_LBRACE 3
3067 #define TOK_RBRACE 4
3071 #define TOK_LBRACKET 8
3072 #define TOK_RBRACKET 9
3073 #define TOK_LPAREN 10
3074 #define TOK_RPAREN 11
3079 #define TOK_TIMESEQ 16
3080 #define TOK_DIVEQ 17
3081 #define TOK_MODEQ 18
3082 #define TOK_PLUSEQ 19
3083 #define TOK_MINUSEQ 20
3086 #define TOK_ANDEQ 23
3087 #define TOK_XOREQ 24
3090 #define TOK_NOTEQ 27
3091 #define TOK_QUEST 28
3092 #define TOK_LOGOR 29
3093 #define TOK_LOGAND 30
3097 #define TOK_LESSEQ 34
3098 #define TOK_MOREEQ 35
3102 #define TOK_MINUS 39
3105 #define TOK_PLUSPLUS 42
3106 #define TOK_MINUSMINUS 43
3108 #define TOK_ARROW 45
3110 #define TOK_TILDE 47
3111 #define TOK_LIT_STRING 48
3112 #define TOK_LIT_CHAR 49
3113 #define TOK_LIT_INT 50
3114 #define TOK_LIT_FLOAT 51
3115 #define TOK_MACRO 52
3116 #define TOK_CONCATENATE 53
3118 #define TOK_IDENT 54
3119 #define TOK_STRUCT_NAME 55
3120 #define TOK_ENUM_CONST 56
3121 #define TOK_TYPE_NAME 57
3124 #define TOK_BREAK 59
3127 #define TOK_CONST 62
3128 #define TOK_CONTINUE 63
3129 #define TOK_DEFAULT 64
3131 #define TOK_DOUBLE 66
3134 #define TOK_EXTERN 69
3135 #define TOK_FLOAT 70
3139 #define TOK_INLINE 74
3142 #define TOK_REGISTER 77
3143 #define TOK_RESTRICT 78
3144 #define TOK_RETURN 79
3145 #define TOK_SHORT 80
3146 #define TOK_SIGNED 81
3147 #define TOK_SIZEOF 82
3148 #define TOK_STATIC 83
3149 #define TOK_STRUCT 84
3150 #define TOK_SWITCH 85
3151 #define TOK_TYPEDEF 86
3152 #define TOK_UNION 87
3153 #define TOK_UNSIGNED 88
3155 #define TOK_VOLATILE 90
3156 #define TOK_WHILE 91
3158 #define TOK_ATTRIBUTE 93
3159 #define TOK_ALIGNOF 94
3160 #define TOK_FIRST_KEYWORD TOK_AUTO
3161 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3163 #define TOK_MDEFINE 100
3164 #define TOK_MDEFINED 101
3165 #define TOK_MUNDEF 102
3166 #define TOK_MINCLUDE 103
3167 #define TOK_MLINE 104
3168 #define TOK_MERROR 105
3169 #define TOK_MWARNING 106
3170 #define TOK_MPRAGMA 107
3171 #define TOK_MIFDEF 108
3172 #define TOK_MIFNDEF 109
3173 #define TOK_MELIF 110
3174 #define TOK_MENDIF 111
3176 #define TOK_FIRST_MACRO TOK_MDEFINE
3177 #define TOK_LAST_MACRO TOK_MENDIF
3180 #define TOK_MELSE 113
3181 #define TOK_MIDENT 114
3186 static const char *tokens[] = {
3187 [TOK_UNKNOWN ] = ":unknown:",
3188 [TOK_SPACE ] = ":space:",
3190 [TOK_LBRACE ] = "{",
3191 [TOK_RBRACE ] = "}",
3195 [TOK_LBRACKET ] = "[",
3196 [TOK_RBRACKET ] = "]",
3197 [TOK_LPAREN ] = "(",
3198 [TOK_RPAREN ] = ")",
3200 [TOK_DOTS ] = "...",
3203 [TOK_TIMESEQ ] = "*=",
3204 [TOK_DIVEQ ] = "/=",
3205 [TOK_MODEQ ] = "%=",
3206 [TOK_PLUSEQ ] = "+=",
3207 [TOK_MINUSEQ ] = "-=",
3208 [TOK_SLEQ ] = "<<=",
3209 [TOK_SREQ ] = ">>=",
3210 [TOK_ANDEQ ] = "&=",
3211 [TOK_XOREQ ] = "^=",
3214 [TOK_NOTEQ ] = "!=",
3216 [TOK_LOGOR ] = "||",
3217 [TOK_LOGAND ] = "&&",
3221 [TOK_LESSEQ ] = "<=",
3222 [TOK_MOREEQ ] = ">=",
3229 [TOK_PLUSPLUS ] = "++",
3230 [TOK_MINUSMINUS ] = "--",
3232 [TOK_ARROW ] = "->",
3235 [TOK_LIT_STRING ] = ":string:",
3236 [TOK_IDENT ] = ":ident:",
3237 [TOK_TYPE_NAME ] = ":typename:",
3238 [TOK_LIT_CHAR ] = ":char:",
3239 [TOK_LIT_INT ] = ":integer:",
3240 [TOK_LIT_FLOAT ] = ":float:",
3242 [TOK_CONCATENATE ] = "##",
3244 [TOK_AUTO ] = "auto",
3245 [TOK_BREAK ] = "break",
3246 [TOK_CASE ] = "case",
3247 [TOK_CHAR ] = "char",
3248 [TOK_CONST ] = "const",
3249 [TOK_CONTINUE ] = "continue",
3250 [TOK_DEFAULT ] = "default",
3252 [TOK_DOUBLE ] = "double",
3253 [TOK_ELSE ] = "else",
3254 [TOK_ENUM ] = "enum",
3255 [TOK_EXTERN ] = "extern",
3256 [TOK_FLOAT ] = "float",
3258 [TOK_GOTO ] = "goto",
3260 [TOK_INLINE ] = "inline",
3262 [TOK_LONG ] = "long",
3263 [TOK_REGISTER ] = "register",
3264 [TOK_RESTRICT ] = "restrict",
3265 [TOK_RETURN ] = "return",
3266 [TOK_SHORT ] = "short",
3267 [TOK_SIGNED ] = "signed",
3268 [TOK_SIZEOF ] = "sizeof",
3269 [TOK_STATIC ] = "static",
3270 [TOK_STRUCT ] = "struct",
3271 [TOK_SWITCH ] = "switch",
3272 [TOK_TYPEDEF ] = "typedef",
3273 [TOK_UNION ] = "union",
3274 [TOK_UNSIGNED ] = "unsigned",
3275 [TOK_VOID ] = "void",
3276 [TOK_VOLATILE ] = "volatile",
3277 [TOK_WHILE ] = "while",
3279 [TOK_ATTRIBUTE ] = "__attribute__",
3280 [TOK_ALIGNOF ] = "__alignof__",
3282 [TOK_MDEFINE ] = "#define",
3283 [TOK_MDEFINED ] = "#defined",
3284 [TOK_MUNDEF ] = "#undef",
3285 [TOK_MINCLUDE ] = "#include",
3286 [TOK_MLINE ] = "#line",
3287 [TOK_MERROR ] = "#error",
3288 [TOK_MWARNING ] = "#warning",
3289 [TOK_MPRAGMA ] = "#pragma",
3290 [TOK_MIFDEF ] = "#ifdef",
3291 [TOK_MIFNDEF ] = "#ifndef",
3292 [TOK_MELIF ] = "#elif",
3293 [TOK_MENDIF ] = "#endif",
3296 [TOK_MELSE ] = "#else",
3297 [TOK_MIDENT ] = "#:ident:",
3302 static unsigned int hash(const char *str, int str_len)
3306 end = str + str_len;
3308 for(; str < end; str++) {
3309 hash = (hash *263) + *str;
3311 hash = hash & (HASH_TABLE_SIZE -1);
3315 static struct hash_entry *lookup(
3316 struct compile_state *state, const char *name, int name_len)
3318 struct hash_entry *entry;
3320 index = hash(name, name_len);
3321 entry = state->hash_table[index];
3323 ((entry->name_len != name_len) ||
3324 (memcmp(entry->name, name, name_len) != 0))) {
3325 entry = entry->next;
3329 /* Get a private copy of the name */
3330 new_name = xmalloc(name_len + 1, "hash_name");
3331 memcpy(new_name, name, name_len);
3332 new_name[name_len] = '\0';
3334 /* Create a new hash entry */
3335 entry = xcmalloc(sizeof(*entry), "hash_entry");
3336 entry->next = state->hash_table[index];
3337 entry->name = new_name;
3338 entry->name_len = name_len;
3340 /* Place the new entry in the hash table */
3341 state->hash_table[index] = entry;
3346 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3348 struct hash_entry *entry;
3350 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3351 (entry->tok == TOK_ENUM_CONST) ||
3352 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3353 (entry->tok <= TOK_LAST_KEYWORD)))) {
3354 tk->tok = entry->tok;
3358 static void ident_to_macro(struct compile_state *state, struct token *tk)
3360 struct hash_entry *entry;
3364 if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3365 tk->tok = entry->tok;
3367 else if (entry->tok == TOK_IF) {
3370 else if (entry->tok == TOK_ELSE) {
3371 tk->tok = TOK_MELSE;
3374 tk->tok = TOK_MIDENT;
3378 static void hash_keyword(
3379 struct compile_state *state, const char *keyword, int tok)
3381 struct hash_entry *entry;
3382 entry = lookup(state, keyword, strlen(keyword));
3383 if (entry && entry->tok != TOK_UNKNOWN) {
3384 die("keyword %s already hashed", keyword);
3389 static void romcc_symbol(
3390 struct compile_state *state, struct hash_entry *ident,
3391 struct symbol **chain, struct triple *def, struct type *type, int depth)
3394 if (*chain && ((*chain)->scope_depth >= depth)) {
3395 error(state, 0, "%s already defined", ident->name);
3397 sym = xcmalloc(sizeof(*sym), "symbol");
3401 sym->scope_depth = depth;
3407 struct compile_state *state, struct hash_entry *ident,
3408 struct symbol **chain, struct triple *def, struct type *type)
3410 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3413 static void var_symbol(struct compile_state *state,
3414 struct hash_entry *ident, struct triple *def)
3416 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3417 internal_error(state, 0, "bad var type");
3419 symbol(state, ident, &ident->sym_ident, def, def->type);
3422 static void label_symbol(struct compile_state *state,
3423 struct hash_entry *ident, struct triple *label, int depth)
3425 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3428 static void start_scope(struct compile_state *state)
3430 state->scope_depth++;
3433 static void end_scope_syms(struct compile_state *state,
3434 struct symbol **chain, int depth)
3436 struct symbol *sym, *next;
3438 while(sym && (sym->scope_depth == depth)) {
3446 static void end_scope(struct compile_state *state)
3450 /* Walk through the hash table and remove all symbols
3451 * in the current scope.
3453 depth = state->scope_depth;
3454 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3455 struct hash_entry *entry;
3456 entry = state->hash_table[i];
3458 end_scope_syms(state, &entry->sym_label, depth);
3459 end_scope_syms(state, &entry->sym_tag, depth);
3460 end_scope_syms(state, &entry->sym_ident, depth);
3461 entry = entry->next;
3464 state->scope_depth = depth - 1;
3467 static void register_keywords(struct compile_state *state)
3469 hash_keyword(state, "auto", TOK_AUTO);
3470 hash_keyword(state, "break", TOK_BREAK);
3471 hash_keyword(state, "case", TOK_CASE);
3472 hash_keyword(state, "char", TOK_CHAR);
3473 hash_keyword(state, "const", TOK_CONST);
3474 hash_keyword(state, "continue", TOK_CONTINUE);
3475 hash_keyword(state, "default", TOK_DEFAULT);
3476 hash_keyword(state, "do", TOK_DO);
3477 hash_keyword(state, "double", TOK_DOUBLE);
3478 hash_keyword(state, "else", TOK_ELSE);
3479 hash_keyword(state, "enum", TOK_ENUM);
3480 hash_keyword(state, "extern", TOK_EXTERN);
3481 hash_keyword(state, "float", TOK_FLOAT);
3482 hash_keyword(state, "for", TOK_FOR);
3483 hash_keyword(state, "goto", TOK_GOTO);
3484 hash_keyword(state, "if", TOK_IF);
3485 hash_keyword(state, "inline", TOK_INLINE);
3486 hash_keyword(state, "int", TOK_INT);
3487 hash_keyword(state, "long", TOK_LONG);
3488 hash_keyword(state, "register", TOK_REGISTER);
3489 hash_keyword(state, "restrict", TOK_RESTRICT);
3490 hash_keyword(state, "return", TOK_RETURN);
3491 hash_keyword(state, "short", TOK_SHORT);
3492 hash_keyword(state, "signed", TOK_SIGNED);
3493 hash_keyword(state, "sizeof", TOK_SIZEOF);
3494 hash_keyword(state, "static", TOK_STATIC);
3495 hash_keyword(state, "struct", TOK_STRUCT);
3496 hash_keyword(state, "switch", TOK_SWITCH);
3497 hash_keyword(state, "typedef", TOK_TYPEDEF);
3498 hash_keyword(state, "union", TOK_UNION);
3499 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3500 hash_keyword(state, "void", TOK_VOID);
3501 hash_keyword(state, "volatile", TOK_VOLATILE);
3502 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3503 hash_keyword(state, "while", TOK_WHILE);
3504 hash_keyword(state, "asm", TOK_ASM);
3505 hash_keyword(state, "__asm__", TOK_ASM);
3506 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3507 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3510 static void register_macro_keywords(struct compile_state *state)
3512 hash_keyword(state, "define", TOK_MDEFINE);
3513 hash_keyword(state, "defined", TOK_MDEFINED);
3514 hash_keyword(state, "undef", TOK_MUNDEF);
3515 hash_keyword(state, "include", TOK_MINCLUDE);
3516 hash_keyword(state, "line", TOK_MLINE);
3517 hash_keyword(state, "error", TOK_MERROR);
3518 hash_keyword(state, "warning", TOK_MWARNING);
3519 hash_keyword(state, "pragma", TOK_MPRAGMA);
3520 hash_keyword(state, "ifdef", TOK_MIFDEF);
3521 hash_keyword(state, "ifndef", TOK_MIFNDEF);
3522 hash_keyword(state, "elif", TOK_MELIF);
3523 hash_keyword(state, "endif", TOK_MENDIF);
3527 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3529 if (ident->sym_define != 0) {
3530 struct macro *macro;
3531 struct macro_arg *arg, *anext;
3532 macro = ident->sym_define;
3533 ident->sym_define = 0;
3535 /* Free the macro arguments... */
3536 anext = macro->args;
3543 /* Free the macro buffer */
3546 /* Now free the macro itself */
3551 static void do_define_macro(struct compile_state *state,
3552 struct hash_entry *ident, const char *body,
3553 int argc, struct macro_arg *args)
3555 struct macro *macro;
3556 struct macro_arg *arg;
3559 /* Find the length of the body */
3560 body_len = strlen(body);
3561 macro = ident->sym_define;
3563 int identical_bodies, identical_args;
3564 struct macro_arg *oarg;
3565 /* Explicitly allow identical redfinitions of the same macro */
3567 (macro->buf_len == body_len) &&
3568 (memcmp(macro->buf, body, body_len) == 0);
3569 identical_args = macro->argc == argc;
3572 while(identical_args && arg) {
3573 identical_args = oarg->ident == arg->ident;
3577 if (identical_bodies && identical_args) {
3581 error(state, 0, "macro %s already defined\n", ident->name);
3584 fprintf(state->errout, "#define %s: `%*.*s'\n",
3585 ident->name, body_len, body_len, body);
3587 macro = xmalloc(sizeof(*macro), "macro");
3588 macro->ident = ident;
3590 macro->buf_len = body_len;
3594 ident->sym_define = macro;
3597 static void define_macro(
3598 struct compile_state *state,
3599 struct hash_entry *ident,
3600 const char *body, int body_len,
3601 int argc, struct macro_arg *args)
3604 buf = xmalloc(body_len + 1, "macro buf");
3605 memcpy(buf, body, body_len);
3606 buf[body_len] = '\0';
3607 do_define_macro(state, ident, buf, argc, args);
3610 static void register_builtin_macro(struct compile_state *state,
3611 const char *name, const char *value)
3613 struct hash_entry *ident;
3615 if (value[0] == '(') {
3616 internal_error(state, 0, "Builtin macros with arguments not supported");
3618 ident = lookup(state, name, strlen(name));
3619 define_macro(state, ident, value, strlen(value), -1, 0);
3622 static void register_builtin_macros(struct compile_state *state)
3629 tm = localtime(&now);
3631 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3632 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3633 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3634 register_builtin_macro(state, "__LINE__", "54321");
3636 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3637 sprintf(buf, "\"%s\"", scratch);
3638 register_builtin_macro(state, "__DATE__", buf);
3640 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3641 sprintf(buf, "\"%s\"", scratch);
3642 register_builtin_macro(state, "__TIME__", buf);
3644 /* I can't be a conforming implementation of C :( */
3645 register_builtin_macro(state, "__STDC__", "0");
3646 /* In particular I don't conform to C99 */
3647 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3651 static void process_cmdline_macros(struct compile_state *state)
3653 const char **macro, *name;
3654 struct hash_entry *ident;
3655 for(macro = state->compiler->defines; (name = *macro); macro++) {
3659 name_len = strlen(name);
3660 body = strchr(name, '=');
3664 name_len = body - name;
3667 ident = lookup(state, name, name_len);
3668 define_macro(state, ident, body, strlen(body), -1, 0);
3670 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3671 ident = lookup(state, name, strlen(name));
3672 undef_macro(state, ident);
3676 static int spacep(int c)
3691 static int digitp(int c)
3695 case '0': case '1': case '2': case '3': case '4':
3696 case '5': case '6': case '7': case '8': case '9':
3702 static int digval(int c)
3705 if ((c >= '0') && (c <= '9')) {
3711 static int hexdigitp(int c)
3715 case '0': case '1': case '2': case '3': case '4':
3716 case '5': case '6': case '7': case '8': case '9':
3717 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3718 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3724 static int hexdigval(int c)
3727 if ((c >= '0') && (c <= '9')) {
3730 else if ((c >= 'A') && (c <= 'F')) {
3731 val = 10 + (c - 'A');
3733 else if ((c >= 'a') && (c <= 'f')) {
3734 val = 10 + (c - 'a');
3739 static int octdigitp(int c)
3743 case '0': case '1': case '2': case '3':
3744 case '4': case '5': case '6': case '7':
3750 static int octdigval(int c)
3753 if ((c >= '0') && (c <= '7')) {
3759 static int letterp(int c)
3763 case 'a': case 'b': case 'c': case 'd': case 'e':
3764 case 'f': case 'g': case 'h': case 'i': case 'j':
3765 case 'k': case 'l': case 'm': case 'n': case 'o':
3766 case 'p': case 'q': case 'r': case 's': case 't':
3767 case 'u': case 'v': case 'w': case 'x': case 'y':
3769 case 'A': case 'B': case 'C': case 'D': case 'E':
3770 case 'F': case 'G': case 'H': case 'I': case 'J':
3771 case 'K': case 'L': case 'M': case 'N': case 'O':
3772 case 'P': case 'Q': case 'R': case 'S': case 'T':
3773 case 'U': case 'V': case 'W': case 'X': case 'Y':
3782 static const char *identifier(const char *str, const char *end)
3784 if (letterp(*str)) {
3785 for(; str < end; str++) {
3788 if (!letterp(c) && !digitp(c)) {
3796 static int char_value(struct compile_state *state,
3797 const signed char **strp, const signed char *end)
3799 const signed char *str;
3803 if ((c == '\\') && (str < end)) {
3805 case 'n': c = '\n'; str++; break;
3806 case 't': c = '\t'; str++; break;
3807 case 'v': c = '\v'; str++; break;
3808 case 'b': c = '\b'; str++; break;
3809 case 'r': c = '\r'; str++; break;
3810 case 'f': c = '\f'; str++; break;
3811 case 'a': c = '\a'; str++; break;
3812 case '\\': c = '\\'; str++; break;
3813 case '?': c = '?'; str++; break;
3814 case '\'': c = '\''; str++; break;
3815 case '"': c = '"'; str++; break;
3819 while((str < end) && hexdigitp(*str)) {
3821 c += hexdigval(*str);
3825 case '0': case '1': case '2': case '3':
3826 case '4': case '5': case '6': case '7':
3828 while((str < end) && octdigitp(*str)) {
3830 c += octdigval(*str);
3835 error(state, 0, "Invalid character constant");
3843 static const char *next_char(struct file_state *file, const char *pos, int index)
3845 const char *end = file->buf + file->size;
3847 /* Lookup the character */
3850 /* Is this a trigraph? */
3851 if (file->trigraphs &&
3852 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3855 case '=': c = '#'; break;
3856 case '/': c = '\\'; break;
3857 case '\'': c = '^'; break;
3858 case '(': c = '['; break;
3859 case ')': c = ']'; break;
3860 case '!': c = '!'; break;
3861 case '<': c = '{'; break;
3862 case '>': c = '}'; break;
3863 case '-': c = '~'; break;
3869 /* Is this an escaped newline? */
3870 if (file->join_lines &&
3871 (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3873 int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3874 /* At the start of a line just eat it */
3875 if (pos == file->pos) {
3877 file->report_line++;
3878 file->line_start = pos + size + 1 + cr_offset;
3880 pos += size + 1 + cr_offset;
3882 /* Do I need to ga any farther? */
3883 else if (index == 0) {
3886 /* Process a normal character */
3895 static int get_char(struct file_state *file, const char *pos)
3897 const char *end = file->buf + file->size;
3900 pos = next_char(file, pos, 0);
3902 /* Lookup the character */
3904 /* If it is a trigraph get the trigraph value */
3905 if (file->trigraphs &&
3906 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3909 case '=': c = '#'; break;
3910 case '/': c = '\\'; break;
3911 case '\'': c = '^'; break;
3912 case '(': c = '['; break;
3913 case ')': c = ']'; break;
3914 case '!': c = '!'; break;
3915 case '<': c = '{'; break;
3916 case '>': c = '}'; break;
3917 case '-': c = '~'; break;
3924 static void eat_chars(struct file_state *file, const char *targ)
3926 const char *pos = file->pos;
3928 /* Do we have a newline? */
3929 if (pos[0] == '\n') {
3931 file->report_line++;
3932 file->line_start = pos + 1;
3940 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3945 src = next_char(file, src, 1);
3951 static void char_strcpy(char *dest,
3952 struct file_state *file, const char *src, const char *end)
3956 c = get_char(file, src);
3957 src = next_char(file, src, 1);
3962 static char *char_strdup(struct file_state *file,
3963 const char *start, const char *end, const char *id)
3967 str_len = char_strlen(file, start, end);
3968 str = xcmalloc(str_len + 1, id);
3969 char_strcpy(str, file, start, end);
3970 str[str_len] = '\0';
3974 static const char *after_digits(struct file_state *file, const char *ptr)
3976 while(digitp(get_char(file, ptr))) {
3977 ptr = next_char(file, ptr, 1);
3982 static const char *after_octdigits(struct file_state *file, const char *ptr)
3984 while(octdigitp(get_char(file, ptr))) {
3985 ptr = next_char(file, ptr, 1);
3990 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3992 while(hexdigitp(get_char(file, ptr))) {
3993 ptr = next_char(file, ptr, 1);
3998 static const char *after_alnums(struct file_state *file, const char *ptr)
4001 c = get_char(file, ptr);
4002 while(letterp(c) || digitp(c)) {
4003 ptr = next_char(file, ptr, 1);
4004 c = get_char(file, ptr);
4009 static void save_string(struct file_state *file,
4010 struct token *tk, const char *start, const char *end, const char *id)
4014 /* Create a private copy of the string */
4015 str = char_strdup(file, start, end, id);
4017 /* Store the copy in the token */
4019 tk->str_len = strlen(str);
4022 static void raw_next_token(struct compile_state *state,
4023 struct file_state *file, struct token *tk)
4033 token = tokp = next_char(file, file->pos, 0);
4035 c = get_char(file, tokp);
4036 tokp = next_char(file, tokp, 1);
4038 c1 = get_char(file, tokp);
4039 c2 = get_char(file, next_char(file, tokp, 1));
4040 c3 = get_char(file, next_char(file, tokp, 2));
4042 /* The end of the file */
4047 else if (spacep(c)) {
4049 while (spacep(get_char(file, tokp))) {
4050 tokp = next_char(file, tokp, 1);
4054 else if ((c == '/') && (c1 == '/')) {
4056 tokp = next_char(file, tokp, 1);
4057 while((c = get_char(file, tokp)) != -1) {
4058 /* Advance to the next character only after we verify
4059 * the current character is not a newline.
4060 * EOL is special to the preprocessor so we don't
4061 * want to loose any.
4066 tokp = next_char(file, tokp, 1);
4070 else if ((c == '/') && (c1 == '*')) {
4071 tokp = next_char(file, tokp, 2);
4073 while((c1 = get_char(file, tokp)) != -1) {
4074 tokp = next_char(file, tokp, 1);
4075 if ((c == '*') && (c1 == '/')) {
4081 if (tok == TOK_UNKNOWN) {
4082 error(state, 0, "unterminated comment");
4085 /* string constants */
4086 else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4087 int wchar, multiline;
4093 tokp = next_char(file, tokp, 1);
4095 while((c = get_char(file, tokp)) != -1) {
4096 tokp = next_char(file, tokp, 1);
4100 else if (c == '\\') {
4101 tokp = next_char(file, tokp, 1);
4103 else if (c == '"') {
4104 tok = TOK_LIT_STRING;
4108 if (tok == TOK_UNKNOWN) {
4109 error(state, 0, "unterminated string constant");
4112 warning(state, 0, "multiline string constant");
4115 /* Save the string value */
4116 save_string(file, tk, token, tokp, "literal string");
4118 /* character constants */
4119 else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4120 int wchar, multiline;
4126 tokp = next_char(file, tokp, 1);
4128 while((c = get_char(file, tokp)) != -1) {
4129 tokp = next_char(file, tokp, 1);
4133 else if (c == '\\') {
4134 tokp = next_char(file, tokp, 1);
4136 else if (c == '\'') {
4141 if (tok == TOK_UNKNOWN) {
4142 error(state, 0, "unterminated character constant");
4145 warning(state, 0, "multiline character constant");
4148 /* Save the character value */
4149 save_string(file, tk, token, tokp, "literal character");
4151 /* integer and floating constants
4157 * Floating constants
4158 * {digits}.{digits}[Ee][+-]?{digits}
4160 * {digits}[Ee][+-]?{digits}
4161 * .{digits}[Ee][+-]?{digits}
4164 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4170 next = after_digits(file, tokp);
4175 cn = get_char(file, next);
4177 next = next_char(file, next, 1);
4178 next = after_digits(file, next);
4181 cn = get_char(file, next);
4182 if ((cn == 'e') || (cn == 'E')) {
4184 next = next_char(file, next, 1);
4185 cn = get_char(file, next);
4186 if ((cn == '+') || (cn == '-')) {
4187 next = next_char(file, next, 1);
4189 new = after_digits(file, next);
4190 is_float |= (new != next);
4194 tok = TOK_LIT_FLOAT;
4195 cn = get_char(file, next);
4196 if ((cn == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4197 next = next_char(file, next, 1);
4200 if (!is_float && digitp(c)) {
4202 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4203 next = next_char(file, tokp, 1);
4204 next = after_hexdigits(file, next);
4206 else if (c == '0') {
4207 next = after_octdigits(file, tokp);
4210 next = after_digits(file, tokp);
4212 /* crazy integer suffixes */
4213 cn = get_char(file, next);
4214 if ((cn == 'u') || (cn == 'U')) {
4215 next = next_char(file, next, 1);
4216 cn = get_char(file, next);
4217 if ((cn == 'l') || (cn == 'L')) {
4218 next = next_char(file, next, 1);
4219 cn = get_char(file, next);
4221 if ((cn == 'l') || (cn == 'L')) {
4222 next = next_char(file, next, 1);
4225 else if ((cn == 'l') || (cn == 'L')) {
4226 next = next_char(file, next, 1);
4227 cn = get_char(file, next);
4228 if ((cn == 'l') || (cn == 'L')) {
4229 next = next_char(file, next, 1);
4230 cn = get_char(file, next);
4232 if ((cn == 'u') || (cn == 'U')) {
4233 next = next_char(file, next, 1);
4239 /* Save the integer/floating point value */
4240 save_string(file, tk, token, tokp, "literal number");
4243 else if (letterp(c)) {
4246 /* Find and save the identifier string */
4247 tokp = after_alnums(file, tokp);
4248 save_string(file, tk, token, tokp, "identifier");
4250 /* Look up to see which identifier it is */
4251 tk->ident = lookup(state, tk->val.str, tk->str_len);
4253 /* Free the identifier string */
4257 /* See if this identifier can be macro expanded */
4258 tk->val.notmacro = 0;
4259 c = get_char(file, tokp);
4261 tokp = next_char(file, tokp, 1);
4262 tk->val.notmacro = 1;
4265 /* C99 alternate macro characters */
4266 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4268 tok = TOK_CONCATENATE;
4270 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4271 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4272 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4273 else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4274 else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4275 else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4276 else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4277 else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4278 else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4279 else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4280 else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4281 else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4282 else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4283 else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4284 else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4285 else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4286 else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4287 else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4288 else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4289 else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4290 else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4291 else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4292 else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4293 else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4294 else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4295 else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4296 else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4297 else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4298 else if (c == ';') { tok = TOK_SEMI; }
4299 else if (c == '{') { tok = TOK_LBRACE; }
4300 else if (c == '}') { tok = TOK_RBRACE; }
4301 else if (c == ',') { tok = TOK_COMMA; }
4302 else if (c == '=') { tok = TOK_EQ; }
4303 else if (c == ':') { tok = TOK_COLON; }
4304 else if (c == '[') { tok = TOK_LBRACKET; }
4305 else if (c == ']') { tok = TOK_RBRACKET; }
4306 else if (c == '(') { tok = TOK_LPAREN; }
4307 else if (c == ')') { tok = TOK_RPAREN; }
4308 else if (c == '*') { tok = TOK_STAR; }
4309 else if (c == '>') { tok = TOK_MORE; }
4310 else if (c == '<') { tok = TOK_LESS; }
4311 else if (c == '?') { tok = TOK_QUEST; }
4312 else if (c == '|') { tok = TOK_OR; }
4313 else if (c == '&') { tok = TOK_AND; }
4314 else if (c == '^') { tok = TOK_XOR; }
4315 else if (c == '+') { tok = TOK_PLUS; }
4316 else if (c == '-') { tok = TOK_MINUS; }
4317 else if (c == '/') { tok = TOK_DIV; }
4318 else if (c == '%') { tok = TOK_MOD; }
4319 else if (c == '!') { tok = TOK_BANG; }
4320 else if (c == '.') { tok = TOK_DOT; }
4321 else if (c == '~') { tok = TOK_TILDE; }
4322 else if (c == '#') { tok = TOK_MACRO; }
4323 else if (c == '\n') { tok = TOK_EOL; }
4325 tokp = next_char(file, tokp, eat);
4326 eat_chars(file, tokp);
4331 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4333 if (tk->tok != tok) {
4334 const char *name1, *name2;
4335 name1 = tokens[tk->tok];
4337 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4338 name2 = tk->ident->name;
4340 error(state, 0, "\tfound %s %s expected %s",
4341 name1, name2, tokens[tok]);
4345 struct macro_arg_value {
4346 struct hash_entry *ident;
4350 static struct macro_arg_value *read_macro_args(
4351 struct compile_state *state, struct macro *macro,
4352 struct file_state *file, struct token *tk)
4354 struct macro_arg_value *argv;
4355 struct macro_arg *arg;
4359 if (macro->argc == 0) {
4361 raw_next_token(state, file, tk);
4362 } while(tk->tok == TOK_SPACE);
4365 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4366 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4369 argv[i].ident = arg->ident;
4378 raw_next_token(state, file, tk);
4380 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4381 (argv[i].ident != state->i___VA_ARGS__))
4384 if (i >= macro->argc) {
4385 error(state, 0, "too many args to %s\n",
4386 macro->ident->name);
4391 if (tk->tok == TOK_LPAREN) {
4395 if (tk->tok == TOK_RPAREN) {
4396 if (paren_depth == 0) {
4401 if (tk->tok == TOK_EOF) {
4402 error(state, 0, "End of file encountered while parsing macro arguments");
4405 len = char_strlen(file, start, file->pos);
4406 argv[i].value = xrealloc(
4407 argv[i].value, argv[i].len + len, "macro args");
4408 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4411 if (i != macro->argc -1) {
4412 error(state, 0, "missing %s arg %d\n",
4413 macro->ident->name, i +2);
4419 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4422 for(i = 0; i < macro->argc; i++) {
4423 xfree(argv[i].value);
4433 static void grow_macro_buf(struct compile_state *state,
4434 const char *id, struct macro_buf *buf,
4437 if ((buf->pos + grow) >= buf->len) {
4438 buf->str = xrealloc(buf->str, buf->len + grow, id);
4443 static void append_macro_text(struct compile_state *state,
4444 const char *id, struct macro_buf *buf,
4445 const char *fstart, size_t flen)
4447 grow_macro_buf(state, id, buf, flen);
4448 memcpy(buf->str + buf->pos, fstart, flen);
4450 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4451 buf->pos, buf->pos, buf->str,
4452 flen, flen, buf->str + buf->pos);
4458 static void append_macro_chars(struct compile_state *state,
4459 const char *id, struct macro_buf *buf,
4460 struct file_state *file, const char *start, const char *end)
4463 flen = char_strlen(file, start, end);
4464 grow_macro_buf(state, id, buf, flen);
4465 char_strcpy(buf->str + buf->pos, file, start, end);
4467 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4468 buf->pos, buf->pos, buf->str,
4469 flen, flen, buf->str + buf->pos);
4474 static int compile_macro(struct compile_state *state,
4475 struct file_state **filep, struct token *tk);
4477 static void macro_expand_args(struct compile_state *state,
4478 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4482 for(i = 0; i < macro->argc; i++) {
4483 struct file_state fmacro, *file;
4484 struct macro_buf buf;
4487 fmacro.basename = argv[i].ident->name;
4488 fmacro.dirname = "";
4489 fmacro.buf = (char *)argv[i].value;
4490 fmacro.size = argv[i].len;
4491 fmacro.pos = fmacro.buf;
4493 fmacro.line_start = fmacro.buf;
4494 fmacro.report_line = 1;
4495 fmacro.report_name = fmacro.basename;
4496 fmacro.report_dir = fmacro.dirname;
4498 fmacro.trigraphs = 0;
4499 fmacro.join_lines = 0;
4501 buf.len = argv[i].len;
4502 buf.str = xmalloc(buf.len, argv[i].ident->name);
4507 raw_next_token(state, file, tk);
4509 /* If we have recursed into another macro body
4512 if (tk->tok == TOK_EOF) {
4513 struct file_state *old;
4519 /* old->basename is used keep it */
4520 xfree(old->dirname);
4525 else if (tk->ident && tk->ident->sym_define) {
4526 if (compile_macro(state, &file, tk)) {
4531 append_macro_chars(state, macro->ident->name, &buf,
4532 file, tk->pos, file->pos);
4535 xfree(argv[i].value);
4536 argv[i].value = buf.str;
4537 argv[i].len = buf.pos;
4542 static void expand_macro(struct compile_state *state,
4543 struct macro *macro, struct macro_buf *buf,
4544 struct macro_arg_value *argv, struct token *tk)
4546 struct file_state fmacro;
4547 const char space[] = " ";
4552 /* Place the macro body in a dummy file */
4554 fmacro.basename = macro->ident->name;
4555 fmacro.dirname = "";
4556 fmacro.buf = macro->buf;
4557 fmacro.size = macro->buf_len;
4558 fmacro.pos = fmacro.buf;
4560 fmacro.line_start = fmacro.buf;
4561 fmacro.report_line = 1;
4562 fmacro.report_name = fmacro.basename;
4563 fmacro.report_dir = fmacro.dirname;
4565 fmacro.trigraphs = 0;
4566 fmacro.join_lines = 0;
4568 /* Allocate a buffer to hold the macro expansion */
4569 buf->len = macro->buf_len + 3;
4570 buf->str = xmalloc(buf->len, macro->ident->name);
4573 fstart = fmacro.pos;
4574 raw_next_token(state, &fmacro, tk);
4575 while(tk->tok != TOK_EOF) {
4576 flen = fmacro.pos - fstart;
4579 for(i = 0; i < macro->argc; i++) {
4580 if (argv[i].ident == tk->ident) {
4584 if (i >= macro->argc) {
4587 /* Substitute macro parameter */
4588 fstart = argv[i].value;
4592 if (macro->argc < 0) {
4596 raw_next_token(state, &fmacro, tk);
4597 } while(tk->tok == TOK_SPACE);
4598 check_tok(state, tk, TOK_IDENT);
4599 for(i = 0; i < macro->argc; i++) {
4600 if (argv[i].ident == tk->ident) {
4604 if (i >= macro->argc) {
4605 error(state, 0, "parameter `%s' not found",
4608 /* Stringize token */
4609 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4610 for(j = 0; j < argv[i].len; j++) {
4611 char *str = argv[i].value + j;
4617 else if (*str == '"') {
4621 append_macro_text(state, macro->ident->name, buf, str, len);
4623 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4627 case TOK_CONCATENATE:
4628 /* Concatenate tokens */
4629 /* Delete the previous whitespace token */
4630 if (buf->str[buf->pos - 1] == ' ') {
4633 /* Skip the next sequence of whitspace tokens */
4635 fstart = fmacro.pos;
4636 raw_next_token(state, &fmacro, tk);
4637 } while(tk->tok == TOK_SPACE);
4638 /* Restart at the top of the loop.
4639 * I need to process the non white space token.
4644 /* Collapse multiple spaces into one */
4645 if (buf->str[buf->pos - 1] != ' ') {
4657 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4659 fstart = fmacro.pos;
4660 raw_next_token(state, &fmacro, tk);
4664 static void tag_macro_name(struct compile_state *state,
4665 struct macro *macro, struct macro_buf *buf,
4668 /* Guard all instances of the macro name in the replacement
4669 * text from further macro expansion.
4671 struct file_state fmacro;
4675 /* Put the old macro expansion buffer in a file */
4677 fmacro.basename = macro->ident->name;
4678 fmacro.dirname = "";
4679 fmacro.buf = buf->str;
4680 fmacro.size = buf->pos;
4681 fmacro.pos = fmacro.buf;
4683 fmacro.line_start = fmacro.buf;
4684 fmacro.report_line = 1;
4685 fmacro.report_name = fmacro.basename;
4686 fmacro.report_dir = fmacro.dirname;
4688 fmacro.trigraphs = 0;
4689 fmacro.join_lines = 0;
4691 /* Allocate a new macro expansion buffer */
4692 buf->len = macro->buf_len + 3;
4693 buf->str = xmalloc(buf->len, macro->ident->name);
4696 fstart = fmacro.pos;
4697 raw_next_token(state, &fmacro, tk);
4698 while(tk->tok != TOK_EOF) {
4699 flen = fmacro.pos - fstart;
4700 if ((tk->tok == TOK_IDENT) &&
4701 (tk->ident == macro->ident) &&
4702 (tk->val.notmacro == 0))
4704 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4709 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4711 fstart = fmacro.pos;
4712 raw_next_token(state, &fmacro, tk);
4717 static int compile_macro(struct compile_state *state,
4718 struct file_state **filep, struct token *tk)
4720 struct file_state *file;
4721 struct hash_entry *ident;
4722 struct macro *macro;
4723 struct macro_arg_value *argv;
4724 struct macro_buf buf;
4727 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4730 macro = ident->sym_define;
4732 /* If this token comes from a macro expansion ignore it */
4733 if (tk->val.notmacro) {
4736 /* If I am a function like macro and the identifier is not followed
4737 * by a left parenthesis, do nothing.
4739 if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4743 /* Read in the macro arguments */
4745 if (macro->argc >= 0) {
4746 raw_next_token(state, *filep, tk);
4747 check_tok(state, tk, TOK_LPAREN);
4749 argv = read_macro_args(state, macro, *filep, tk);
4751 check_tok(state, tk, TOK_RPAREN);
4753 /* Macro expand the macro arguments */
4754 macro_expand_args(state, macro, argv, tk);
4759 if (ident == state->i___FILE__) {
4760 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4761 buf.str = xmalloc(buf.len, ident->name);
4762 sprintf(buf.str, "\"%s\"", state->file->basename);
4763 buf.pos = strlen(buf.str);
4765 else if (ident == state->i___LINE__) {
4767 buf.str = xmalloc(buf.len, ident->name);
4768 sprintf(buf.str, "%d", state->file->line);
4769 buf.pos = strlen(buf.str);
4772 expand_macro(state, macro, &buf, argv, tk);
4774 /* Tag the macro name with a $ so it will no longer
4775 * be regonized as a canidate for macro expansion.
4777 tag_macro_name(state, macro, &buf, tk);
4780 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4781 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4784 free_macro_args(macro, argv);
4786 file = xmalloc(sizeof(*file), "file_state");
4787 file->prev = *filep;
4788 file->basename = xstrdup(ident->name);
4789 file->dirname = xstrdup("");
4790 file->buf = buf.str;
4791 file->size = buf.pos;
4792 file->pos = file->buf;
4794 file->line_start = file->pos;
4795 file->report_line = 1;
4796 file->report_name = file->basename;
4797 file->report_dir = file->dirname;
4799 file->trigraphs = 0;
4800 file->join_lines = 0;
4805 static void eat_tokens(struct compile_state *state, int targ_tok)
4807 if (state->eat_depth > 0) {
4808 internal_error(state, 0, "Already eating...");
4810 state->eat_depth = state->if_depth;
4811 state->eat_targ = targ_tok;
4813 static int if_eat(struct compile_state *state)
4815 return state->eat_depth > 0;
4817 static int if_value(struct compile_state *state)
4820 index = state->if_depth / CHAR_BIT;
4821 offset = state->if_depth % CHAR_BIT;
4822 return !!(state->if_bytes[index] & (1 << (offset)));
4824 static void set_if_value(struct compile_state *state, int value)
4827 index = state->if_depth / CHAR_BIT;
4828 offset = state->if_depth % CHAR_BIT;
4830 state->if_bytes[index] &= ~(1 << offset);
4832 state->if_bytes[index] |= (1 << offset);
4835 static void in_if(struct compile_state *state, const char *name)
4837 if (state->if_depth <= 0) {
4838 error(state, 0, "%s without #if", name);
4841 static void enter_if(struct compile_state *state)
4843 state->if_depth += 1;
4844 if (state->if_depth > MAX_PP_IF_DEPTH) {
4845 error(state, 0, "#if depth too great");
4848 static void reenter_if(struct compile_state *state, const char *name)
4851 if ((state->eat_depth == state->if_depth) &&
4852 (state->eat_targ == TOK_MELSE)) {
4853 state->eat_depth = 0;
4854 state->eat_targ = 0;
4857 static void enter_else(struct compile_state *state, const char *name)
4860 if ((state->eat_depth == state->if_depth) &&
4861 (state->eat_targ == TOK_MELSE)) {
4862 state->eat_depth = 0;
4863 state->eat_targ = 0;
4866 static void exit_if(struct compile_state *state, const char *name)
4869 if (state->eat_depth == state->if_depth) {
4870 state->eat_depth = 0;
4871 state->eat_targ = 0;
4873 state->if_depth -= 1;
4876 static void raw_token(struct compile_state *state, struct token *tk)
4878 struct file_state *file;
4882 raw_next_token(state, file, tk);
4886 /* Exit out of an include directive or macro call */
4887 if ((tk->tok == TOK_EOF) &&
4888 (file != state->macro_file) && file->prev)
4890 state->file = file->prev;
4891 /* file->basename is used keep it */
4892 xfree(file->dirname);
4896 raw_next_token(state, state->file, tk);
4902 static void pp_token(struct compile_state *state, struct token *tk)
4904 struct file_state *file;
4907 raw_token(state, tk);
4911 if (tk->tok == TOK_SPACE) {
4912 raw_token(state, tk);
4915 else if (tk->tok == TOK_IDENT) {
4916 if (state->token_base == 0) {
4917 ident_to_keyword(state, tk);
4919 ident_to_macro(state, tk);
4925 static void preprocess(struct compile_state *state, struct token *tk);
4927 static void token(struct compile_state *state, struct token *tk)
4930 pp_token(state, tk);
4933 /* Process a macro directive */
4934 if (tk->tok == TOK_MACRO) {
4935 /* Only match preprocessor directives at the start of a line */
4937 ptr = state->file->line_start;
4938 while((ptr < tk->pos)
4939 && spacep(get_char(state->file, ptr)))
4941 ptr = next_char(state->file, ptr, 1);
4943 if (ptr == tk->pos) {
4944 preprocess(state, tk);
4948 /* Expand a macro call */
4949 else if (tk->ident && tk->ident->sym_define) {
4950 rescan = compile_macro(state, &state->file, tk);
4952 pp_token(state, tk);
4955 /* Eat tokens disabled by the preprocessor
4956 * (Unless we are parsing a preprocessor directive
4958 else if (if_eat(state) && (state->token_base == 0)) {
4959 pp_token(state, tk);
4962 /* Make certain EOL only shows up in preprocessor directives */
4963 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4964 pp_token(state, tk);
4967 /* Error on unknown tokens */
4968 else if (tk->tok == TOK_UNKNOWN) {
4969 error(state, 0, "unknown token");
4975 static inline struct token *get_token(struct compile_state *state, int offset)
4978 index = state->token_base + offset;
4979 if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4980 internal_error(state, 0, "token array to small");
4982 return &state->token[index];
4985 static struct token *do_eat_token(struct compile_state *state, int tok)
4989 check_tok(state, get_token(state, 1), tok);
4991 /* Free the old token value */
4992 tk = get_token(state, 0);
4994 memset((void *)tk->val.str, -1, tk->str_len);
4997 /* Overwrite the old token with newer tokens */
4998 for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4999 state->token[i] = state->token[i + 1];
5001 /* Clear the last token */
5002 memset(&state->token[i], 0, sizeof(state->token[i]));
5003 state->token[i].tok = -1;
5005 /* Return the token */
5009 static int raw_peek(struct compile_state *state)
5012 tk1 = get_token(state, 1);
5013 if (tk1->tok == -1) {
5014 raw_token(state, tk1);
5019 static struct token *raw_eat(struct compile_state *state, int tok)
5022 return do_eat_token(state, tok);
5025 static int pp_peek(struct compile_state *state)
5028 tk1 = get_token(state, 1);
5029 if (tk1->tok == -1) {
5030 pp_token(state, tk1);
5035 static struct token *pp_eat(struct compile_state *state, int tok)
5038 return do_eat_token(state, tok);
5041 static int peek(struct compile_state *state)
5044 tk1 = get_token(state, 1);
5045 if (tk1->tok == -1) {
5051 static int peek2(struct compile_state *state)
5053 struct token *tk1, *tk2;
5054 tk1 = get_token(state, 1);
5055 tk2 = get_token(state, 2);
5056 if (tk1->tok == -1) {
5059 if (tk2->tok == -1) {
5065 static struct token *eat(struct compile_state *state, int tok)
5068 return do_eat_token(state, tok);
5071 static void compile_file(struct compile_state *state, const char *filename, int local)
5073 char cwd[MAX_CWD_SIZE];
5074 const char *subdir, *base;
5076 struct file_state *file;
5078 file = xmalloc(sizeof(*file), "file_state");
5080 base = strrchr(filename, '/');
5083 subdir_len = base - filename;
5090 basename = xmalloc(strlen(base) +1, "basename");
5091 strcpy(basename, base);
5092 file->basename = basename;
5094 if (getcwd(cwd, sizeof(cwd)) == 0) {
5095 die("cwd buffer to small");
5097 if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5098 file->dirname = xmalloc(subdir_len + 1, "dirname");
5099 memcpy(file->dirname, subdir, subdir_len);
5100 file->dirname[subdir_len] = '\0';
5106 /* Find the appropriate directory... */
5108 if (!state->file && exists(cwd, filename)) {
5111 if (local && state->file && exists(state->file->dirname, filename)) {
5112 dir = state->file->dirname;
5114 for(path = state->compiler->include_paths; !dir && *path; path++) {
5115 if (exists(*path, filename)) {
5120 error(state, 0, "Cannot open `%s'\n", filename);
5122 dirlen = strlen(dir);
5123 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5124 memcpy(file->dirname, dir, dirlen);
5125 file->dirname[dirlen] = '/';
5126 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5127 file->dirname[dirlen + 1 + subdir_len] = '\0';
5129 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5131 file->pos = file->buf;
5132 file->line_start = file->pos;
5135 file->report_line = 1;
5136 file->report_name = file->basename;
5137 file->report_dir = file->dirname;
5139 file->trigraphs = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5140 file->join_lines = 1;
5142 file->prev = state->file;
5146 static struct triple *constant_expr(struct compile_state *state);
5147 static void integral(struct compile_state *state, struct triple *def);
5149 static int mcexpr(struct compile_state *state)
5151 struct triple *cvalue;
5152 cvalue = constant_expr(state);
5153 integral(state, cvalue);
5154 if (cvalue->op != OP_INTCONST) {
5155 error(state, 0, "integer constant expected");
5157 return cvalue->u.cval != 0;
5160 static void preprocess(struct compile_state *state, struct token *current_token)
5162 /* Doing much more with the preprocessor would require
5163 * a parser and a major restructuring.
5164 * Postpone that for later.
5169 state->macro_file = state->file;
5171 old_token_base = state->token_base;
5172 state->token_base = current_token - state->token;
5174 tok = pp_peek(state);
5180 tk = pp_eat(state, TOK_LIT_INT);
5181 override_line = strtoul(tk->val.str, 0, 10);
5182 /* I have a preprocessor line marker parse it */
5183 if (pp_peek(state) == TOK_LIT_STRING) {
5184 const char *token, *base;
5186 int name_len, dir_len;
5187 tk = pp_eat(state, TOK_LIT_STRING);
5188 name = xmalloc(tk->str_len, "report_name");
5189 token = tk->val.str + 1;
5190 base = strrchr(token, '/');
5191 name_len = tk->str_len -2;
5193 dir_len = base - token;
5195 name_len -= base - token;
5200 memcpy(name, base, name_len);
5201 name[name_len] = '\0';
5202 dir = xmalloc(dir_len + 1, "report_dir");
5203 memcpy(dir, token, dir_len);
5204 dir[dir_len] = '\0';
5205 state->file->report_line = override_line - 1;
5206 state->file->report_name = name;
5207 state->file->report_dir = dir;
5208 state->file->macro = 0;
5215 pp_eat(state, TOK_MLINE);
5216 tk = eat(state, TOK_LIT_INT);
5217 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5218 if (pp_peek(state) == TOK_LIT_STRING) {
5219 const char *token, *base;
5221 int name_len, dir_len;
5222 tk = pp_eat(state, TOK_LIT_STRING);
5223 name = xmalloc(tk->str_len, "report_name");
5224 token = tk->val.str + 1;
5225 base = strrchr(token, '/');
5226 name_len = tk->str_len - 2;
5228 dir_len = base - token;
5230 name_len -= base - token;
5235 memcpy(name, base, name_len);
5236 name[name_len] = '\0';
5237 dir = xmalloc(dir_len + 1, "report_dir");
5238 memcpy(dir, token, dir_len);
5239 dir[dir_len] = '\0';
5240 state->file->report_name = name;
5241 state->file->report_dir = dir;
5242 state->file->macro = 0;
5248 struct hash_entry *ident;
5249 pp_eat(state, TOK_MUNDEF);
5250 if (if_eat(state)) /* quit early when #if'd out */
5253 ident = pp_eat(state, TOK_MIDENT)->ident;
5255 undef_macro(state, ident);
5259 pp_eat(state, TOK_MPRAGMA);
5260 if (if_eat(state)) /* quit early when #if'd out */
5262 warning(state, 0, "Ignoring pragma");
5265 pp_eat(state, TOK_MELIF);
5266 reenter_if(state, "#elif");
5267 if (if_eat(state)) /* quit early when #if'd out */
5269 /* If the #if was taken the #elif just disables the following code */
5270 if (if_value(state)) {
5271 eat_tokens(state, TOK_MENDIF);
5273 /* If the previous #if was not taken see if the #elif enables the
5277 set_if_value(state, mcexpr(state));
5278 if (!if_value(state)) {
5279 eat_tokens(state, TOK_MELSE);
5284 pp_eat(state, TOK_MIF);
5286 if (if_eat(state)) /* quit early when #if'd out */
5288 set_if_value(state, mcexpr(state));
5289 if (!if_value(state)) {
5290 eat_tokens(state, TOK_MELSE);
5295 struct hash_entry *ident;
5297 pp_eat(state, TOK_MIFNDEF);
5299 if (if_eat(state)) /* quit early when #if'd out */
5301 ident = pp_eat(state, TOK_MIDENT)->ident;
5302 set_if_value(state, ident->sym_define == 0);
5303 if (!if_value(state)) {
5304 eat_tokens(state, TOK_MELSE);
5310 struct hash_entry *ident;
5311 pp_eat(state, TOK_MIFDEF);
5313 if (if_eat(state)) /* quit early when #if'd out */
5315 ident = pp_eat(state, TOK_MIDENT)->ident;
5316 set_if_value(state, ident->sym_define != 0);
5317 if (!if_value(state)) {
5318 eat_tokens(state, TOK_MELSE);
5323 pp_eat(state, TOK_MELSE);
5324 enter_else(state, "#else");
5325 if (!if_eat(state) && if_value(state)) {
5326 eat_tokens(state, TOK_MENDIF);
5330 pp_eat(state, TOK_MENDIF);
5331 exit_if(state, "#endif");
5335 struct hash_entry *ident;
5336 struct macro_arg *args, **larg;
5337 const char *mstart, *mend;
5340 pp_eat(state, TOK_MDEFINE);
5341 if (if_eat(state)) /* quit early when #if'd out */
5343 ident = pp_eat(state, TOK_MIDENT)->ident;
5348 /* Parse macro parameters */
5349 if (raw_peek(state) == TOK_LPAREN) {
5350 raw_eat(state, TOK_LPAREN);
5354 struct macro_arg *narg, *arg;
5355 struct hash_entry *aident;
5358 tok = pp_peek(state);
5359 if (!args && (tok == TOK_RPAREN)) {
5362 else if (tok == TOK_DOTS) {
5363 pp_eat(state, TOK_DOTS);
5364 aident = state->i___VA_ARGS__;
5367 aident = pp_eat(state, TOK_MIDENT)->ident;
5370 narg = xcmalloc(sizeof(*arg), "macro arg");
5371 narg->ident = aident;
5373 /* Verify I don't have a duplicate identifier */
5374 for(arg = args; arg; arg = arg->next) {
5375 if (arg->ident == narg->ident) {
5376 error(state, 0, "Duplicate macro arg `%s'",
5380 /* Add the new argument to the end of the list */
5385 if ((aident == state->i___VA_ARGS__) ||
5386 (pp_peek(state) != TOK_COMMA)) {
5389 pp_eat(state, TOK_COMMA);
5391 pp_eat(state, TOK_RPAREN);
5393 /* Remove leading whitespace */
5394 while(raw_peek(state) == TOK_SPACE) {
5395 raw_eat(state, TOK_SPACE);
5398 /* Remember the start of the macro body */
5399 tok = raw_peek(state);
5400 mend = mstart = get_token(state, 1)->pos;
5402 /* Find the end of the macro */
5403 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5404 raw_eat(state, tok);
5405 /* Remember the end of the last non space token */
5407 if (tok != TOK_SPACE) {
5408 mend = get_token(state, 1)->pos;
5412 /* Now that I have found the body defined the token */
5413 do_define_macro(state, ident,
5414 char_strdup(state->file, mstart, mend, "macro buf"),
5420 const char *start, *end;
5423 pp_eat(state, TOK_MERROR);
5424 /* Find the start of the line */
5426 start = get_token(state, 1)->pos;
5428 /* Find the end of the line */
5429 while((tok = raw_peek(state)) != TOK_EOL) {
5430 raw_eat(state, tok);
5432 end = get_token(state, 1)->pos;
5434 if (!if_eat(state)) {
5435 error(state, 0, "%*.*s", len, len, start);
5441 const char *start, *end;
5444 pp_eat(state, TOK_MWARNING);
5446 /* Find the start of the line */
5448 start = get_token(state, 1)->pos;
5450 /* Find the end of the line */
5451 while((tok = raw_peek(state)) != TOK_EOL) {
5452 raw_eat(state, tok);
5454 end = get_token(state, 1)->pos;
5456 if (!if_eat(state)) {
5457 warning(state, 0, "%*.*s", len, len, start);
5468 pp_eat(state, TOK_MINCLUDE);
5469 if (if_eat(state)) {
5470 /* Find the end of the line */
5471 while((tok = raw_peek(state)) != TOK_EOL) {
5472 raw_eat(state, tok);
5477 if (tok == TOK_LIT_STRING) {
5481 tk = eat(state, TOK_LIT_STRING);
5482 name = xmalloc(tk->str_len, "include");
5483 token = tk->val.str +1;
5484 name_len = tk->str_len -2;
5485 if (*token == '"') {
5489 memcpy(name, token, name_len);
5490 name[name_len] = '\0';
5493 else if (tok == TOK_LESS) {
5494 struct macro_buf buf;
5495 eat(state, TOK_LESS);
5498 buf.str = xmalloc(buf.len, "include");
5502 while((tok != TOK_MORE) &&
5503 (tok != TOK_EOL) && (tok != TOK_EOF))
5506 tk = eat(state, tok);
5507 append_macro_chars(state, "include", &buf,
5508 state->file, tk->pos, state->file->pos);
5511 append_macro_text(state, "include", &buf, "\0", 1);
5512 if (peek(state) != TOK_MORE) {
5513 error(state, 0, "Unterminated include directive");
5515 eat(state, TOK_MORE);
5520 error(state, 0, "Invalid include directive");
5522 /* Error if there are any tokens after the include */
5523 if (pp_peek(state) != TOK_EOL) {
5524 error(state, 0, "garbage after include directive");
5526 if (!if_eat(state)) {
5527 compile_file(state, name, local);
5533 /* Ignore # without a follwing ident */
5537 const char *name1, *name2;
5538 name1 = tokens[tok];
5540 if (tok == TOK_MIDENT) {
5541 name2 = get_token(state, 1)->ident->name;
5543 error(state, 0, "Invalid preprocessor directive: %s %s",
5548 /* Consume the rest of the macro line */
5550 tok = pp_peek(state);
5552 } while((tok != TOK_EOF) && (tok != TOK_EOL));
5553 state->token_base = old_token_base;
5554 state->macro_file = NULL;
5558 /* Type helper functions */
5560 static struct type *new_type(
5561 unsigned int type, struct type *left, struct type *right)
5563 struct type *result;
5564 result = xmalloc(sizeof(*result), "type");
5565 result->type = type;
5566 result->left = left;
5567 result->right = right;
5568 result->field_ident = 0;
5569 result->type_ident = 0;
5570 result->elements = 0;
5574 static struct type *clone_type(unsigned int specifiers, struct type *old)
5576 struct type *result;
5577 result = xmalloc(sizeof(*result), "type");
5578 memcpy(result, old, sizeof(*result));
5579 result->type &= TYPE_MASK;
5580 result->type |= specifiers;
5584 static struct type *dup_type(struct compile_state *state, struct type *orig)
5587 new = xcmalloc(sizeof(*new), "type");
5588 new->type = orig->type;
5589 new->field_ident = orig->field_ident;
5590 new->type_ident = orig->type_ident;
5591 new->elements = orig->elements;
5593 new->left = dup_type(state, orig->left);
5596 new->right = dup_type(state, orig->right);
5602 static struct type *invalid_type(struct compile_state *state, struct type *type)
5604 struct type *invalid, *member;
5607 internal_error(state, 0, "type missing?");
5609 switch(type->type & TYPE_MASK) {
5611 case TYPE_CHAR: case TYPE_UCHAR:
5612 case TYPE_SHORT: case TYPE_USHORT:
5613 case TYPE_INT: case TYPE_UINT:
5614 case TYPE_LONG: case TYPE_ULONG:
5615 case TYPE_LLONG: case TYPE_ULLONG:
5620 invalid = invalid_type(state, type->left);
5623 invalid = invalid_type(state, type->left);
5627 member = type->left;
5628 while(member && (invalid == 0) &&
5629 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5630 invalid = invalid_type(state, member->left);
5631 member = member->right;
5634 invalid = invalid_type(state, member);
5639 member = type->left;
5640 while(member && (invalid == 0) &&
5641 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5642 invalid = invalid_type(state, member->left);
5643 member = member->right;
5646 invalid = invalid_type(state, member);
5657 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5658 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5659 static inline ulong_t mask_uint(ulong_t x)
5661 if (SIZEOF_INT < SIZEOF_LONG) {
5662 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5667 #define MASK_UINT(X) (mask_uint(X))
5668 #define MASK_ULONG(X) (X)
5670 static struct type void_type = { .type = TYPE_VOID };
5671 static struct type char_type = { .type = TYPE_CHAR };
5672 static struct type uchar_type = { .type = TYPE_UCHAR };
5673 #if DEBUG_ROMCC_WARNING
5674 static struct type short_type = { .type = TYPE_SHORT };
5676 static struct type ushort_type = { .type = TYPE_USHORT };
5677 static struct type int_type = { .type = TYPE_INT };
5678 static struct type uint_type = { .type = TYPE_UINT };
5679 static struct type long_type = { .type = TYPE_LONG };
5680 static struct type ulong_type = { .type = TYPE_ULONG };
5681 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5683 static struct type void_ptr_type = {
5684 .type = TYPE_POINTER,
5688 #if DEBUG_ROMCC_WARNING
5689 static struct type void_func_type = {
5690 .type = TYPE_FUNCTION,
5692 .right = &void_type,
5696 static size_t bits_to_bytes(size_t size)
5698 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5701 static struct triple *variable(struct compile_state *state, struct type *type)
5703 struct triple *result;
5704 if ((type->type & STOR_MASK) != STOR_PERM) {
5705 result = triple(state, OP_ADECL, type, 0, 0);
5706 generate_lhs_pieces(state, result);
5709 result = triple(state, OP_SDECL, type, 0, 0);
5714 static void stor_of(FILE *fp, struct type *type)
5716 switch(type->type & STOR_MASK) {
5718 fprintf(fp, "auto ");
5721 fprintf(fp, "static ");
5724 fprintf(fp, "local ");
5727 fprintf(fp, "extern ");
5730 fprintf(fp, "register ");
5733 fprintf(fp, "typedef ");
5735 case STOR_INLINE | STOR_LOCAL:
5736 fprintf(fp, "inline ");
5738 case STOR_INLINE | STOR_STATIC:
5739 fprintf(fp, "static inline");
5741 case STOR_INLINE | STOR_EXTERN:
5742 fprintf(fp, "extern inline");
5745 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5749 static void qual_of(FILE *fp, struct type *type)
5751 if (type->type & QUAL_CONST) {
5752 fprintf(fp, " const");
5754 if (type->type & QUAL_VOLATILE) {
5755 fprintf(fp, " volatile");
5757 if (type->type & QUAL_RESTRICT) {
5758 fprintf(fp, " restrict");
5762 static void name_of(FILE *fp, struct type *type)
5764 unsigned int base_type;
5765 base_type = type->type & TYPE_MASK;
5766 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5771 fprintf(fp, "void");
5775 fprintf(fp, "signed char");
5779 fprintf(fp, "unsigned char");
5783 fprintf(fp, "signed short");
5787 fprintf(fp, "unsigned short");
5791 fprintf(fp, "signed int");
5795 fprintf(fp, "unsigned int");
5799 fprintf(fp, "signed long");
5803 fprintf(fp, "unsigned long");
5807 name_of(fp, type->left);
5812 name_of(fp, type->left);
5814 name_of(fp, type->right);
5817 name_of(fp, type->left);
5819 name_of(fp, type->right);
5822 fprintf(fp, "enum %s",
5823 (type->type_ident)? type->type_ident->name : "");
5827 fprintf(fp, "struct %s { ",
5828 (type->type_ident)? type->type_ident->name : "");
5829 name_of(fp, type->left);
5834 fprintf(fp, "union %s { ",
5835 (type->type_ident)? type->type_ident->name : "");
5836 name_of(fp, type->left);
5841 name_of(fp, type->left);
5842 fprintf(fp, " (*)(");
5843 name_of(fp, type->right);
5847 name_of(fp, type->left);
5848 fprintf(fp, " [%ld]", (long)(type->elements));
5851 fprintf(fp, "tuple { ");
5852 name_of(fp, type->left);
5857 fprintf(fp, "join { ");
5858 name_of(fp, type->left);
5863 name_of(fp, type->left);
5864 fprintf(fp, " : %d ", type->elements);
5868 fprintf(fp, "unknown_t");
5871 fprintf(fp, "????: %x", base_type);
5874 if (type->field_ident && type->field_ident->name) {
5875 fprintf(fp, " .%s", type->field_ident->name);
5879 static size_t align_of(struct compile_state *state, struct type *type)
5883 switch(type->type & TYPE_MASK) {
5892 align = ALIGNOF_CHAR;
5896 align = ALIGNOF_SHORT;
5901 align = ALIGNOF_INT;
5905 align = ALIGNOF_LONG;
5908 align = ALIGNOF_POINTER;
5913 size_t left_align, right_align;
5914 left_align = align_of(state, type->left);
5915 right_align = align_of(state, type->right);
5916 align = (left_align >= right_align) ? left_align : right_align;
5920 align = align_of(state, type->left);
5926 align = align_of(state, type->left);
5929 error(state, 0, "alignof not yet defined for type\n");
5935 static size_t reg_align_of(struct compile_state *state, struct type *type)
5939 switch(type->type & TYPE_MASK) {
5948 align = REG_ALIGNOF_CHAR;
5952 align = REG_ALIGNOF_SHORT;
5957 align = REG_ALIGNOF_INT;
5961 align = REG_ALIGNOF_LONG;
5964 align = REG_ALIGNOF_POINTER;
5969 size_t left_align, right_align;
5970 left_align = reg_align_of(state, type->left);
5971 right_align = reg_align_of(state, type->right);
5972 align = (left_align >= right_align) ? left_align : right_align;
5976 align = reg_align_of(state, type->left);
5982 align = reg_align_of(state, type->left);
5985 error(state, 0, "alignof not yet defined for type\n");
5991 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5993 return bits_to_bytes(align_of(state, type));
5995 static size_t size_of(struct compile_state *state, struct type *type);
5996 static size_t reg_size_of(struct compile_state *state, struct type *type);
5998 static size_t needed_padding(struct compile_state *state,
5999 struct type *type, size_t offset)
6001 size_t padding, align;
6002 align = align_of(state, type);
6003 /* Align to the next machine word if the bitfield does completely
6004 * fit into the current word.
6006 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
6008 size = size_of(state, type);
6009 if ((offset + type->elements)/size != offset/size) {
6014 if (offset % align) {
6015 padding = align - (offset % align);
6020 static size_t reg_needed_padding(struct compile_state *state,
6021 struct type *type, size_t offset)
6023 size_t padding, align;
6024 align = reg_align_of(state, type);
6025 /* Align to the next register word if the bitfield does completely
6026 * fit into the current register.
6028 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6029 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6031 align = REG_SIZEOF_REG;
6034 if (offset % align) {
6035 padding = align - (offset % align);
6040 static size_t size_of(struct compile_state *state, struct type *type)
6044 switch(type->type & TYPE_MASK) {
6049 size = type->elements;
6057 size = SIZEOF_SHORT;
6069 size = SIZEOF_POINTER;
6075 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6076 pad = needed_padding(state, type->left, size);
6077 size = size + pad + size_of(state, type->left);
6080 pad = needed_padding(state, type, size);
6081 size = size + pad + size_of(state, type);
6086 size_t size_left, size_right;
6087 size_left = size_of(state, type->left);
6088 size_right = size_of(state, type->right);
6089 size = (size_left >= size_right)? size_left : size_right;
6093 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6094 internal_error(state, 0, "Invalid array type");
6096 size = size_of(state, type->left) * type->elements;
6103 size = size_of(state, type->left);
6104 /* Pad structures so their size is a multiples of their alignment */
6105 pad = needed_padding(state, type, size);
6113 size = size_of(state, type->left);
6114 /* Pad unions so their size is a multiple of their alignment */
6115 pad = needed_padding(state, type, size);
6120 internal_error(state, 0, "sizeof not yet defined for type");
6126 static size_t reg_size_of(struct compile_state *state, struct type *type)
6130 switch(type->type & TYPE_MASK) {
6135 size = type->elements;
6139 size = REG_SIZEOF_CHAR;
6143 size = REG_SIZEOF_SHORT;
6148 size = REG_SIZEOF_INT;
6152 size = REG_SIZEOF_LONG;
6155 size = REG_SIZEOF_POINTER;
6161 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6162 pad = reg_needed_padding(state, type->left, size);
6163 size = size + pad + reg_size_of(state, type->left);
6166 pad = reg_needed_padding(state, type, size);
6167 size = size + pad + reg_size_of(state, type);
6172 size_t size_left, size_right;
6173 size_left = reg_size_of(state, type->left);
6174 size_right = reg_size_of(state, type->right);
6175 size = (size_left >= size_right)? size_left : size_right;
6179 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6180 internal_error(state, 0, "Invalid array type");
6182 size = reg_size_of(state, type->left) * type->elements;
6189 size = reg_size_of(state, type->left);
6190 /* Pad structures so their size is a multiples of their alignment */
6191 pad = reg_needed_padding(state, type, size);
6199 size = reg_size_of(state, type->left);
6200 /* Pad unions so their size is a multiple of their alignment */
6201 pad = reg_needed_padding(state, type, size);
6206 internal_error(state, 0, "sizeof not yet defined for type");
6212 static size_t registers_of(struct compile_state *state, struct type *type)
6215 registers = reg_size_of(state, type);
6216 registers += REG_SIZEOF_REG - 1;
6217 registers /= REG_SIZEOF_REG;
6221 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6223 return bits_to_bytes(size_of(state, type));
6226 static size_t field_offset(struct compile_state *state,
6227 struct type *type, struct hash_entry *field)
6229 struct type *member;
6234 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6235 member = type->left;
6236 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6237 size += needed_padding(state, member->left, size);
6238 if (member->left->field_ident == field) {
6239 member = member->left;
6242 size += size_of(state, member->left);
6243 member = member->right;
6245 size += needed_padding(state, member, size);
6247 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6248 member = type->left;
6249 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6250 if (member->left->field_ident == field) {
6251 member = member->left;
6254 member = member->right;
6258 internal_error(state, 0, "field_offset only works on structures and unions");
6261 if (!member || (member->field_ident != field)) {
6262 error(state, 0, "member %s not present", field->name);
6267 static size_t field_reg_offset(struct compile_state *state,
6268 struct type *type, struct hash_entry *field)
6270 struct type *member;
6275 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6276 member = type->left;
6277 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6278 size += reg_needed_padding(state, member->left, size);
6279 if (member->left->field_ident == field) {
6280 member = member->left;
6283 size += reg_size_of(state, member->left);
6284 member = member->right;
6287 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6288 member = type->left;
6289 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6290 if (member->left->field_ident == field) {
6291 member = member->left;
6294 member = member->right;
6298 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6301 size += reg_needed_padding(state, member, size);
6302 if (!member || (member->field_ident != field)) {
6303 error(state, 0, "member %s not present", field->name);
6308 static struct type *field_type(struct compile_state *state,
6309 struct type *type, struct hash_entry *field)
6311 struct type *member;
6314 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6315 member = type->left;
6316 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6317 if (member->left->field_ident == field) {
6318 member = member->left;
6321 member = member->right;
6324 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6325 member = type->left;
6326 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6327 if (member->left->field_ident == field) {
6328 member = member->left;
6331 member = member->right;
6335 internal_error(state, 0, "field_type only works on structures and unions");
6338 if (!member || (member->field_ident != field)) {
6339 error(state, 0, "member %s not present", field->name);
6344 static size_t index_offset(struct compile_state *state,
6345 struct type *type, ulong_t index)
6347 struct type *member;
6350 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6351 size = size_of(state, type->left) * index;
6353 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6355 member = type->left;
6357 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6358 size += needed_padding(state, member->left, size);
6360 member = member->left;
6363 size += size_of(state, member->left);
6365 member = member->right;
6367 size += needed_padding(state, member, size);
6369 internal_error(state, 0, "Missing member index: %u", index);
6372 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6375 member = type->left;
6377 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6379 member = member->left;
6383 member = member->right;
6386 internal_error(state, 0, "Missing member index: %u", index);
6390 internal_error(state, 0,
6391 "request for index %u in something not an array, tuple or join",
6397 static size_t index_reg_offset(struct compile_state *state,
6398 struct type *type, ulong_t index)
6400 struct type *member;
6403 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6404 size = reg_size_of(state, type->left) * index;
6406 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6408 member = type->left;
6410 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6411 size += reg_needed_padding(state, member->left, size);
6413 member = member->left;
6416 size += reg_size_of(state, member->left);
6418 member = member->right;
6420 size += reg_needed_padding(state, member, size);
6422 internal_error(state, 0, "Missing member index: %u", index);
6426 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6429 member = type->left;
6431 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6433 member = member->left;
6437 member = member->right;
6440 internal_error(state, 0, "Missing member index: %u", index);
6444 internal_error(state, 0,
6445 "request for index %u in something not an array, tuple or join",
6451 static struct type *index_type(struct compile_state *state,
6452 struct type *type, ulong_t index)
6454 struct type *member;
6455 if (index >= type->elements) {
6456 internal_error(state, 0, "Invalid element %u requested", index);
6458 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6459 member = type->left;
6461 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6463 member = type->left;
6465 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6467 member = member->left;
6471 member = member->right;
6474 internal_error(state, 0, "Missing member index: %u", index);
6477 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6479 member = type->left;
6481 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6483 member = member->left;
6487 member = member->right;
6490 internal_error(state, 0, "Missing member index: %u", index);
6495 internal_error(state, 0,
6496 "request for index %u in something not an array, tuple or join",
6502 static struct type *unpack_type(struct compile_state *state, struct type *type)
6504 /* If I have a single register compound type not a bit-field
6505 * find the real type.
6507 struct type *start_type;
6509 /* Get out early if I need multiple registers for this type */
6510 size = reg_size_of(state, type);
6511 if (size > REG_SIZEOF_REG) {
6514 /* Get out early if I don't need any registers for this type */
6518 /* Loop until I have no more layers I can remove */
6521 switch(type->type & TYPE_MASK) {
6523 /* If I have a single element the unpacked type
6526 if (type->elements == 1) {
6532 /* If I have a single element the unpacked type
6535 if (type->elements == 1) {
6538 /* If I have multiple elements the unpacked
6539 * type is the non-void element.
6542 struct type *next, *member;
6543 struct type *sub_type;
6549 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6550 next = member->right;
6551 member = member->left;
6553 if (reg_size_of(state, member) > 0) {
6555 internal_error(state, 0, "true compound type in a register");
6568 /* If I have a single element the unpacked type
6571 if (type->elements == 1) {
6574 /* I can't in general unpack union types */
6577 /* If I'm not a compound type I can't unpack it */
6580 } while(start_type != type);
6581 switch(type->type & TYPE_MASK) {
6585 internal_error(state, 0, "irredicible type?");
6591 static int equiv_types(struct type *left, struct type *right);
6592 static int is_compound_type(struct type *type);
6594 static struct type *reg_type(
6595 struct compile_state *state, struct type *type, int reg_offset)
6597 struct type *member;
6600 struct type *invalid;
6601 invalid = invalid_type(state, type);
6603 fprintf(state->errout, "type: ");
6604 name_of(state->errout, type);
6605 fprintf(state->errout, "\n");
6606 fprintf(state->errout, "invalid: ");
6607 name_of(state->errout, invalid);
6608 fprintf(state->errout, "\n");
6609 internal_error(state, 0, "bad input type?");
6613 size = reg_size_of(state, type);
6614 if (reg_offset > size) {
6616 fprintf(state->errout, "type: ");
6617 name_of(state->errout, type);
6618 fprintf(state->errout, "\n");
6619 internal_error(state, 0, "offset outside of type");
6622 switch(type->type & TYPE_MASK) {
6623 /* Don't do anything with the basic types */
6625 case TYPE_CHAR: case TYPE_UCHAR:
6626 case TYPE_SHORT: case TYPE_USHORT:
6627 case TYPE_INT: case TYPE_UINT:
6628 case TYPE_LONG: case TYPE_ULONG:
6629 case TYPE_LLONG: case TYPE_ULLONG:
6630 case TYPE_FLOAT: case TYPE_DOUBLE:
6638 member = type->left;
6639 size = reg_size_of(state, member);
6640 if (size > REG_SIZEOF_REG) {
6641 member = reg_type(state, member, reg_offset % size);
6649 member = type->left;
6650 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6651 size = reg_size_of(state, member->left);
6652 offset += reg_needed_padding(state, member->left, offset);
6653 if ((offset + size) > reg_offset) {
6654 member = member->left;
6658 member = member->right;
6660 offset += reg_needed_padding(state, member, offset);
6661 member = reg_type(state, member, reg_offset - offset);
6667 struct type *join, **jnext, *mnext;
6668 join = new_type(TYPE_JOIN, 0, 0);
6669 jnext = &join->left;
6675 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6676 mnext = member->right;
6677 member = member->left;
6679 size = reg_size_of(state, member);
6680 if (size > reg_offset) {
6681 struct type *part, *hunt;
6682 part = reg_type(state, member, reg_offset);
6683 /* See if this type is already in the union */
6686 struct type *test = hunt;
6688 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6692 if (equiv_types(part, test)) {
6700 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6701 jnext = &(*jnext)->right;
6708 if (join->elements == 0) {
6709 internal_error(state, 0, "No elements?");
6716 fprintf(state->errout, "type: ");
6717 name_of(state->errout, type);
6718 fprintf(state->errout, "\n");
6719 internal_error(state, 0, "reg_type not yet defined for type");
6723 /* If I have a single register compound type not a bit-field
6724 * find the real type.
6726 member = unpack_type(state, member);
6728 size = reg_size_of(state, member);
6729 if (size > REG_SIZEOF_REG) {
6730 internal_error(state, 0, "Cannot find type of single register");
6733 invalid = invalid_type(state, member);
6735 fprintf(state->errout, "type: ");
6736 name_of(state->errout, member);
6737 fprintf(state->errout, "\n");
6738 fprintf(state->errout, "invalid: ");
6739 name_of(state->errout, invalid);
6740 fprintf(state->errout, "\n");
6741 internal_error(state, 0, "returning bad type?");
6747 static struct type *next_field(struct compile_state *state,
6748 struct type *type, struct type *prev_member)
6750 struct type *member;
6751 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6752 internal_error(state, 0, "next_field only works on structures");
6754 member = type->left;
6755 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6757 member = member->left;
6760 if (member->left == prev_member) {
6763 member = member->right;
6765 if (member == prev_member) {
6769 internal_error(state, 0, "prev_member %s not present",
6770 prev_member->field_ident->name);
6775 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6776 size_t ret_offset, size_t mem_offset, void *arg);
6778 static void walk_type_fields(struct compile_state *state,
6779 struct type *type, size_t reg_offset, size_t mem_offset,
6780 walk_type_fields_cb_t cb, void *arg);
6782 static void walk_struct_fields(struct compile_state *state,
6783 struct type *type, size_t reg_offset, size_t mem_offset,
6784 walk_type_fields_cb_t cb, void *arg)
6788 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6789 internal_error(state, 0, "walk_struct_fields only works on structures");
6792 for(i = 0; i < type->elements; i++) {
6795 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6796 mtype = mtype->left;
6798 walk_type_fields(state, mtype,
6800 field_reg_offset(state, type, mtype->field_ident),
6802 field_offset(state, type, mtype->field_ident),
6809 static void walk_type_fields(struct compile_state *state,
6810 struct type *type, size_t reg_offset, size_t mem_offset,
6811 walk_type_fields_cb_t cb, void *arg)
6813 switch(type->type & TYPE_MASK) {
6815 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6825 cb(state, type, reg_offset, mem_offset, arg);
6830 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6834 static void arrays_complete(struct compile_state *state, struct type *type)
6836 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6837 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6838 error(state, 0, "array size not specified");
6840 arrays_complete(state, type->left);
6844 static unsigned int get_basic_type(struct type *type)
6847 basic = type->type & TYPE_MASK;
6848 /* Convert enums to ints */
6849 if (basic == TYPE_ENUM) {
6852 /* Convert bitfields to standard types */
6853 else if (basic == TYPE_BITFIELD) {
6854 if (type->elements <= SIZEOF_CHAR) {
6857 else if (type->elements <= SIZEOF_SHORT) {
6860 else if (type->elements <= SIZEOF_INT) {
6863 else if (type->elements <= SIZEOF_LONG) {
6866 if (!TYPE_SIGNED(type->left->type)) {
6873 static unsigned int do_integral_promotion(unsigned int type)
6875 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6881 static unsigned int do_arithmetic_conversion(
6882 unsigned int left, unsigned int right)
6884 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6885 return TYPE_LDOUBLE;
6887 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6890 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6893 left = do_integral_promotion(left);
6894 right = do_integral_promotion(right);
6895 /* If both operands have the same size done */
6896 if (left == right) {
6899 /* If both operands have the same signedness pick the larger */
6900 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6901 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6903 /* If the signed type can hold everything use it */
6904 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6907 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6910 /* Convert to the unsigned type with the same rank as the signed type */
6911 else if (TYPE_SIGNED(left)) {
6912 return TYPE_MKUNSIGNED(left);
6915 return TYPE_MKUNSIGNED(right);
6919 /* see if two types are the same except for qualifiers */
6920 static int equiv_types(struct type *left, struct type *right)
6923 /* Error if the basic types do not match */
6924 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6927 type = left->type & TYPE_MASK;
6928 /* If the basic types match and it is a void type we are done */
6929 if (type == TYPE_VOID) {
6932 /* For bitfields we need to compare the sizes */
6933 else if (type == TYPE_BITFIELD) {
6934 return (left->elements == right->elements) &&
6935 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6937 /* if the basic types match and it is an arithmetic type we are done */
6938 else if (TYPE_ARITHMETIC(type)) {
6941 /* If it is a pointer type recurse and keep testing */
6942 else if (type == TYPE_POINTER) {
6943 return equiv_types(left->left, right->left);
6945 else if (type == TYPE_ARRAY) {
6946 return (left->elements == right->elements) &&
6947 equiv_types(left->left, right->left);
6949 /* test for struct equality */
6950 else if (type == TYPE_STRUCT) {
6951 return left->type_ident == right->type_ident;
6953 /* test for union equality */
6954 else if (type == TYPE_UNION) {
6955 return left->type_ident == right->type_ident;
6957 /* Test for equivalent functions */
6958 else if (type == TYPE_FUNCTION) {
6959 return equiv_types(left->left, right->left) &&
6960 equiv_types(left->right, right->right);
6962 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6963 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6964 else if (type == TYPE_PRODUCT) {
6965 return equiv_types(left->left, right->left) &&
6966 equiv_types(left->right, right->right);
6968 /* We should see TYPE_OVERLAP when comparing joins */
6969 else if (type == TYPE_OVERLAP) {
6970 return equiv_types(left->left, right->left) &&
6971 equiv_types(left->right, right->right);
6973 /* Test for equivalence of tuples */
6974 else if (type == TYPE_TUPLE) {
6975 return (left->elements == right->elements) &&
6976 equiv_types(left->left, right->left);
6978 /* Test for equivalence of joins */
6979 else if (type == TYPE_JOIN) {
6980 return (left->elements == right->elements) &&
6981 equiv_types(left->left, right->left);
6988 static int equiv_ptrs(struct type *left, struct type *right)
6990 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6991 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6994 return equiv_types(left->left, right->left);
6997 static struct type *compatible_types(struct type *left, struct type *right)
6999 struct type *result;
7000 unsigned int type, qual_type;
7001 /* Error if the basic types do not match */
7002 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7005 type = left->type & TYPE_MASK;
7006 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7008 /* if the basic types match and it is an arithmetic type we are done */
7009 if (TYPE_ARITHMETIC(type)) {
7010 result = new_type(qual_type, 0, 0);
7012 /* If it is a pointer type recurse and keep testing */
7013 else if (type == TYPE_POINTER) {
7014 result = compatible_types(left->left, right->left);
7016 result = new_type(qual_type, result, 0);
7019 /* test for struct equality */
7020 else if (type == TYPE_STRUCT) {
7021 if (left->type_ident == right->type_ident) {
7025 /* test for union equality */
7026 else if (type == TYPE_UNION) {
7027 if (left->type_ident == right->type_ident) {
7031 /* Test for equivalent functions */
7032 else if (type == TYPE_FUNCTION) {
7033 struct type *lf, *rf;
7034 lf = compatible_types(left->left, right->left);
7035 rf = compatible_types(left->right, right->right);
7037 result = new_type(qual_type, lf, rf);
7040 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7041 else if (type == TYPE_PRODUCT) {
7042 struct type *lf, *rf;
7043 lf = compatible_types(left->left, right->left);
7044 rf = compatible_types(left->right, right->right);
7046 result = new_type(qual_type, lf, rf);
7050 /* Nothing else is compatible */
7055 /* See if left is a equivalent to right or right is a union member of left */
7056 static int is_subset_type(struct type *left, struct type *right)
7058 if (equiv_types(left, right)) {
7061 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7062 struct type *member, *mnext;
7067 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7068 mnext = member->right;
7069 member = member->left;
7071 if (is_subset_type( member, right)) {
7079 static struct type *compatible_ptrs(struct type *left, struct type *right)
7081 struct type *result;
7082 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7083 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7086 result = compatible_types(left->left, right->left);
7088 unsigned int qual_type;
7089 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7090 result = new_type(qual_type, result, 0);
7095 static struct triple *integral_promotion(
7096 struct compile_state *state, struct triple *def)
7100 /* As all operations are carried out in registers
7101 * the values are converted on load I just convert
7102 * logical type of the operand.
7104 if (TYPE_INTEGER(type->type)) {
7105 unsigned int int_type;
7106 int_type = type->type & ~TYPE_MASK;
7107 int_type |= do_integral_promotion(get_basic_type(type));
7108 if (int_type != type->type) {
7109 if (def->op != OP_LOAD) {
7110 def->type = new_type(int_type, 0, 0);
7113 def = triple(state, OP_CONVERT,
7114 new_type(int_type, 0, 0), def, 0);
7122 static void arithmetic(struct compile_state *state, struct triple *def)
7124 if (!TYPE_ARITHMETIC(def->type->type)) {
7125 error(state, 0, "arithmetic type expexted");
7129 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7131 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7132 error(state, def, "pointer or arithmetic type expected");
7136 static int is_integral(struct triple *ins)
7138 return TYPE_INTEGER(ins->type->type);
7141 static void integral(struct compile_state *state, struct triple *def)
7143 if (!is_integral(def)) {
7144 error(state, 0, "integral type expected");
7149 static void bool(struct compile_state *state, struct triple *def)
7151 if (!TYPE_ARITHMETIC(def->type->type) &&
7152 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7153 error(state, 0, "arithmetic or pointer type expected");
7157 static int is_signed(struct type *type)
7159 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7162 return !!TYPE_SIGNED(type->type);
7164 static int is_compound_type(struct type *type)
7167 switch((type->type & TYPE_MASK)) {
7182 /* Is this value located in a register otherwise it must be in memory */
7183 static int is_in_reg(struct compile_state *state, struct triple *def)
7186 if (def->op == OP_ADECL) {
7189 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7192 else if (triple_is_part(state, def)) {
7193 in_reg = is_in_reg(state, MISC(def, 0));
7196 internal_error(state, def, "unknown expr storage location");
7202 /* Is this an auto or static variable location? Something that can
7203 * be assigned to. Otherwise it must must be a pure value, a temporary.
7205 static int is_lvalue(struct compile_state *state, struct triple *def)
7212 if ((def->op == OP_ADECL) ||
7213 (def->op == OP_SDECL) ||
7214 (def->op == OP_DEREF) ||
7215 (def->op == OP_BLOBCONST) ||
7216 (def->op == OP_LIST)) {
7219 else if (triple_is_part(state, def)) {
7220 ret = is_lvalue(state, MISC(def, 0));
7225 static void clvalue(struct compile_state *state, struct triple *def)
7228 internal_error(state, def, "nothing where lvalue expected?");
7230 if (!is_lvalue(state, def)) {
7231 error(state, def, "lvalue expected");
7234 static void lvalue(struct compile_state *state, struct triple *def)
7236 clvalue(state, def);
7237 if (def->type->type & QUAL_CONST) {
7238 error(state, def, "modifable lvalue expected");
7242 static int is_pointer(struct triple *def)
7244 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7247 static void pointer(struct compile_state *state, struct triple *def)
7249 if (!is_pointer(def)) {
7250 error(state, def, "pointer expected");
7254 static struct triple *int_const(
7255 struct compile_state *state, struct type *type, ulong_t value)
7257 struct triple *result;
7258 switch(type->type & TYPE_MASK) {
7260 case TYPE_INT: case TYPE_UINT:
7261 case TYPE_LONG: case TYPE_ULONG:
7264 internal_error(state, 0, "constant for unknown type");
7266 result = triple(state, OP_INTCONST, type, 0, 0);
7267 result->u.cval = value;
7272 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7274 static struct triple *do_mk_addr_expr(struct compile_state *state,
7275 struct triple *expr, struct type *type, ulong_t offset)
7277 struct triple *result;
7278 struct type *ptr_type;
7279 clvalue(state, expr);
7281 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7285 if (expr->op == OP_ADECL) {
7286 error(state, expr, "address of auto variables not supported");
7288 else if (expr->op == OP_SDECL) {
7289 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7290 MISC(result, 0) = expr;
7291 result->u.cval = offset;
7293 else if (expr->op == OP_DEREF) {
7294 result = triple(state, OP_ADD, ptr_type,
7296 int_const(state, &ulong_type, offset));
7298 else if (expr->op == OP_BLOBCONST) {
7300 internal_error(state, expr, "not yet implemented");
7302 else if (expr->op == OP_LIST) {
7303 error(state, 0, "Function addresses not supported");
7305 else if (triple_is_part(state, expr)) {
7306 struct triple *part;
7308 expr = MISC(expr, 0);
7309 if (part->op == OP_DOT) {
7310 offset += bits_to_bytes(
7311 field_offset(state, expr->type, part->u.field));
7313 else if (part->op == OP_INDEX) {
7314 offset += bits_to_bytes(
7315 index_offset(state, expr->type, part->u.cval));
7318 internal_error(state, part, "unhandled part type");
7320 result = do_mk_addr_expr(state, expr, type, offset);
7323 internal_error(state, expr, "cannot take address of expression");
7328 static struct triple *mk_addr_expr(
7329 struct compile_state *state, struct triple *expr, ulong_t offset)
7331 return do_mk_addr_expr(state, expr, expr->type, offset);
7334 static struct triple *mk_deref_expr(
7335 struct compile_state *state, struct triple *expr)
7337 struct type *base_type;
7338 pointer(state, expr);
7339 base_type = expr->type->left;
7340 return triple(state, OP_DEREF, base_type, expr, 0);
7343 /* lvalue conversions always apply except when certain operators
7344 * are applied. So I apply apply it when I know no more
7345 * operators will be applied.
7347 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7349 /* Tranform an array to a pointer to the first element */
7350 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7353 TYPE_POINTER | (def->type->type & QUAL_MASK),
7354 def->type->left, 0);
7355 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7356 struct triple *addrconst;
7357 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7358 internal_error(state, def, "bad array constant");
7360 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7361 MISC(addrconst, 0) = def;
7365 def = triple(state, OP_CONVERT, type, def, 0);
7368 /* Transform a function to a pointer to it */
7369 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7370 def = mk_addr_expr(state, def, 0);
7375 static struct triple *deref_field(
7376 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7378 struct triple *result;
7379 struct type *type, *member;
7382 internal_error(state, 0, "No field passed to deref_field");
7386 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7387 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7388 error(state, 0, "request for member %s in something not a struct or union",
7391 member = field_type(state, type, field);
7392 if ((type->type & STOR_MASK) == STOR_PERM) {
7393 /* Do the pointer arithmetic to get a deref the field */
7394 offset = bits_to_bytes(field_offset(state, type, field));
7395 result = do_mk_addr_expr(state, expr, member, offset);
7396 result = mk_deref_expr(state, result);
7399 /* Find the variable for the field I want. */
7400 result = triple(state, OP_DOT, member, expr, 0);
7401 result->u.field = field;
7406 static struct triple *deref_index(
7407 struct compile_state *state, struct triple *expr, size_t index)
7409 struct triple *result;
7410 struct type *type, *member;
7415 member = index_type(state, type, index);
7417 if ((type->type & STOR_MASK) == STOR_PERM) {
7418 offset = bits_to_bytes(index_offset(state, type, index));
7419 result = do_mk_addr_expr(state, expr, member, offset);
7420 result = mk_deref_expr(state, result);
7423 result = triple(state, OP_INDEX, member, expr, 0);
7424 result->u.cval = index;
7429 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7435 #if DEBUG_ROMCC_WARNINGS
7436 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7438 /* Transform lvalues into something we can read */
7439 def = lvalue_conversion(state, def);
7440 if (!is_lvalue(state, def)) {
7443 if (is_in_reg(state, def)) {
7446 if (def->op == OP_SDECL) {
7447 def = mk_addr_expr(state, def, 0);
7448 def = mk_deref_expr(state, def);
7452 def = triple(state, op, def->type, def, 0);
7453 if (def->type->type & QUAL_VOLATILE) {
7454 def->id |= TRIPLE_FLAG_VOLATILE;
7459 int is_write_compatible(struct compile_state *state,
7460 struct type *dest, struct type *rval)
7463 /* Both operands have arithmetic type */
7464 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7467 /* One operand is a pointer and the other is a pointer to void */
7468 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7469 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7470 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7471 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7474 /* If both types are the same without qualifiers we are good */
7475 else if (equiv_ptrs(dest, rval)) {
7478 /* test for struct/union equality */
7479 else if (equiv_types(dest, rval)) {
7485 static void write_compatible(struct compile_state *state,
7486 struct type *dest, struct type *rval)
7488 if (!is_write_compatible(state, dest, rval)) {
7489 FILE *fp = state->errout;
7490 fprintf(fp, "dest: ");
7492 fprintf(fp,"\nrval: ");
7495 error(state, 0, "Incompatible types in assignment");
7499 static int is_init_compatible(struct compile_state *state,
7500 struct type *dest, struct type *rval)
7503 if (is_write_compatible(state, dest, rval)) {
7506 else if (equiv_types(dest, rval)) {
7512 static struct triple *write_expr(
7513 struct compile_state *state, struct triple *dest, struct triple *rval)
7520 internal_error(state, 0, "missing rval");
7523 if (rval->op == OP_LIST) {
7524 internal_error(state, 0, "expression of type OP_LIST?");
7526 if (!is_lvalue(state, dest)) {
7527 internal_error(state, 0, "writing to a non lvalue?");
7529 if (dest->type->type & QUAL_CONST) {
7530 internal_error(state, 0, "modifable lvalue expexted");
7533 write_compatible(state, dest->type, rval->type);
7534 if (!equiv_types(dest->type, rval->type)) {
7535 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7538 /* Now figure out which assignment operator to use */
7540 if (is_in_reg(state, dest)) {
7541 def = triple(state, OP_WRITE, dest->type, rval, dest);
7542 if (MISC(def, 0) != dest) {
7543 internal_error(state, def, "huh?");
7545 if (RHS(def, 0) != rval) {
7546 internal_error(state, def, "huh?");
7549 def = triple(state, OP_STORE, dest->type, dest, rval);
7551 if (def->type->type & QUAL_VOLATILE) {
7552 def->id |= TRIPLE_FLAG_VOLATILE;
7557 static struct triple *init_expr(
7558 struct compile_state *state, struct triple *dest, struct triple *rval)
7564 internal_error(state, 0, "missing rval");
7566 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7567 rval = read_expr(state, rval);
7568 def = write_expr(state, dest, rval);
7571 /* Fill in the array size if necessary */
7572 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7573 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7574 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7575 dest->type->elements = rval->type->elements;
7578 if (!equiv_types(dest->type, rval->type)) {
7579 error(state, 0, "Incompatible types in inializer");
7581 MISC(dest, 0) = rval;
7582 insert_triple(state, dest, rval);
7583 rval->id |= TRIPLE_FLAG_FLATTENED;
7584 use_triple(MISC(dest, 0), dest);
7589 struct type *arithmetic_result(
7590 struct compile_state *state, struct triple *left, struct triple *right)
7593 /* Sanity checks to ensure I am working with arithmetic types */
7594 arithmetic(state, left);
7595 arithmetic(state, right);
7597 do_arithmetic_conversion(
7598 get_basic_type(left->type),
7599 get_basic_type(right->type)),
7604 struct type *ptr_arithmetic_result(
7605 struct compile_state *state, struct triple *left, struct triple *right)
7608 /* Sanity checks to ensure I am working with the proper types */
7609 ptr_arithmetic(state, left);
7610 arithmetic(state, right);
7611 if (TYPE_ARITHMETIC(left->type->type) &&
7612 TYPE_ARITHMETIC(right->type->type)) {
7613 type = arithmetic_result(state, left, right);
7615 else if (TYPE_PTR(left->type->type)) {
7619 internal_error(state, 0, "huh?");
7625 /* boolean helper function */
7627 static struct triple *ltrue_expr(struct compile_state *state,
7628 struct triple *expr)
7631 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7632 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7633 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7634 /* If the expression is already boolean do nothing */
7637 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7643 static struct triple *lfalse_expr(struct compile_state *state,
7644 struct triple *expr)
7646 return triple(state, OP_LFALSE, &int_type, expr, 0);
7649 static struct triple *mkland_expr(
7650 struct compile_state *state,
7651 struct triple *left, struct triple *right)
7653 struct triple *def, *val, *var, *jmp, *mid, *end;
7654 struct triple *lstore, *rstore;
7656 /* Generate some intermediate triples */
7658 var = variable(state, &int_type);
7660 /* Store the left hand side value */
7661 lstore = write_expr(state, var, left);
7663 /* Jump if the value is false */
7664 jmp = branch(state, end,
7665 lfalse_expr(state, read_expr(state, var)));
7668 /* Store the right hand side value */
7669 rstore = write_expr(state, var, right);
7671 /* An expression for the computed value */
7672 val = read_expr(state, var);
7674 /* Generate the prog for a logical and */
7675 def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0UL);
7680 static struct triple *mklor_expr(
7681 struct compile_state *state,
7682 struct triple *left, struct triple *right)
7684 struct triple *def, *val, *var, *jmp, *mid, *end;
7686 /* Generate some intermediate triples */
7688 var = variable(state, &int_type);
7690 /* Store the left hand side value */
7691 left = write_expr(state, var, left);
7693 /* Jump if the value is true */
7694 jmp = branch(state, end, read_expr(state, var));
7697 /* Store the right hand side value */
7698 right = write_expr(state, var, right);
7700 /* An expression for the computed value*/
7701 val = read_expr(state, var);
7703 /* Generate the prog for a logical or */
7704 def = mkprog(state, var, left, jmp, mid, right, end, val, 0UL);
7709 static struct triple *mkcond_expr(
7710 struct compile_state *state,
7711 struct triple *test, struct triple *left, struct triple *right)
7713 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7714 struct type *result_type;
7715 unsigned int left_type, right_type;
7717 left_type = left->type->type;
7718 right_type = right->type->type;
7720 /* Both operands have arithmetic type */
7721 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7722 result_type = arithmetic_result(state, left, right);
7724 /* Both operands have void type */
7725 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7726 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7727 result_type = &void_type;
7729 /* pointers to the same type... */
7730 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7733 /* Both operands are pointers and left is a pointer to void */
7734 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7735 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7736 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7737 result_type = right->type;
7739 /* Both operands are pointers and right is a pointer to void */
7740 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7741 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7742 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7743 result_type = left->type;
7746 error(state, 0, "Incompatible types in conditional expression");
7748 /* Generate some intermediate triples */
7751 var = variable(state, result_type);
7753 /* Branch if the test is false */
7754 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7757 /* Store the left hand side value */
7758 left = write_expr(state, var, left);
7760 /* Branch to the end */
7761 jmp2 = branch(state, end, 0);
7763 /* Store the right hand side value */
7764 right = write_expr(state, var, right);
7766 /* An expression for the computed value */
7767 val = read_expr(state, var);
7769 /* Generate the prog for a conditional expression */
7770 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0UL);
7776 static int expr_depth(struct compile_state *state, struct triple *ins)
7778 #if DEBUG_ROMCC_WARNINGS
7779 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7783 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7786 else if (ins->op == OP_DEREF) {
7787 count = expr_depth(state, RHS(ins, 0)) - 1;
7789 else if (ins->op == OP_VAL) {
7790 count = expr_depth(state, RHS(ins, 0)) - 1;
7792 else if (ins->op == OP_FCALL) {
7793 /* Don't figure the depth of a call just guess it is huge */
7797 struct triple **expr;
7798 expr = triple_rhs(state, ins, 0);
7799 for(;expr; expr = triple_rhs(state, ins, expr)) {
7802 depth = expr_depth(state, *expr);
7803 if (depth > count) {
7812 static struct triple *flatten_generic(
7813 struct compile_state *state, struct triple *first, struct triple *ptr,
7818 struct triple **ins;
7821 /* Only operations with just a rhs and a lhs should come here */
7824 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7825 internal_error(state, ptr, "unexpected args for: %d %s",
7826 ptr->op, tops(ptr->op));
7828 /* Find the depth of the rhs elements */
7829 for(i = 0; i < rhs; i++) {
7830 vector[i].ins = &RHS(ptr, i);
7831 vector[i].depth = expr_depth(state, *vector[i].ins);
7833 /* Selection sort the rhs */
7834 for(i = 0; i < rhs; i++) {
7836 for(j = i + 1; j < rhs; j++ ) {
7837 if (vector[j].depth > vector[max].depth) {
7842 struct rhs_vector tmp;
7844 vector[i] = vector[max];
7848 /* Now flatten the rhs elements */
7849 for(i = 0; i < rhs; i++) {
7850 *vector[i].ins = flatten(state, first, *vector[i].ins);
7851 use_triple(*vector[i].ins, ptr);
7854 insert_triple(state, first, ptr);
7855 ptr->id |= TRIPLE_FLAG_FLATTENED;
7856 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7858 /* Now flatten the lhs elements */
7859 for(i = 0; i < lhs; i++) {
7860 struct triple **ins = &LHS(ptr, i);
7861 *ins = flatten(state, first, *ins);
7862 use_triple(*ins, ptr);
7868 static struct triple *flatten_prog(
7869 struct compile_state *state, struct triple *first, struct triple *ptr)
7871 struct triple *head, *body, *val;
7876 release_triple(state, head);
7877 release_triple(state, ptr);
7879 body->prev = first->prev;
7880 body->prev->next = body;
7881 val->next->prev = val;
7883 if (triple_is_cbranch(state, body->prev) ||
7884 triple_is_call(state, body->prev)) {
7885 unuse_triple(first, body->prev);
7886 use_triple(body, body->prev);
7889 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7890 internal_error(state, val, "val not flattened?");
7897 static struct triple *flatten_part(
7898 struct compile_state *state, struct triple *first, struct triple *ptr)
7900 if (!triple_is_part(state, ptr)) {
7901 internal_error(state, ptr, "not a part");
7903 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7904 internal_error(state, ptr, "unexpected args for: %d %s",
7905 ptr->op, tops(ptr->op));
7907 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7908 use_triple(MISC(ptr, 0), ptr);
7909 return flatten_generic(state, first, ptr, 1);
7912 static struct triple *flatten(
7913 struct compile_state *state, struct triple *first, struct triple *ptr)
7915 struct triple *orig_ptr;
7920 /* Only flatten triples once */
7921 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7926 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7927 return MISC(ptr, 0);
7930 ptr = flatten_prog(state, first, ptr);
7933 ptr = flatten_generic(state, first, ptr, 1);
7934 insert_triple(state, first, ptr);
7935 ptr->id |= TRIPLE_FLAG_FLATTENED;
7936 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7937 if (ptr->next != ptr) {
7938 use_triple(ptr->next, ptr);
7943 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7944 use_triple(RHS(ptr, 0), ptr);
7947 ptr = flatten_generic(state, first, ptr, 1);
7948 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7949 use_triple(MISC(ptr, 0), ptr);
7952 use_triple(TARG(ptr, 0), ptr);
7955 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7956 use_triple(RHS(ptr, 0), ptr);
7957 use_triple(TARG(ptr, 0), ptr);
7958 insert_triple(state, first, ptr);
7959 ptr->id |= TRIPLE_FLAG_FLATTENED;
7960 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7961 if (ptr->next != ptr) {
7962 use_triple(ptr->next, ptr);
7966 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7967 use_triple(MISC(ptr, 0), ptr);
7968 use_triple(TARG(ptr, 0), ptr);
7969 insert_triple(state, first, ptr);
7970 ptr->id |= TRIPLE_FLAG_FLATTENED;
7971 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7972 if (ptr->next != ptr) {
7973 use_triple(ptr->next, ptr);
7977 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7978 use_triple(RHS(ptr, 0), ptr);
7981 insert_triple(state, state->global_pool, ptr);
7982 ptr->id |= TRIPLE_FLAG_FLATTENED;
7983 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7984 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7985 use_triple(MISC(ptr, 0), ptr);
7988 /* Since OP_DEREF is just a marker delete it when I flatten it */
7990 RHS(orig_ptr, 0) = 0;
7991 free_triple(state, orig_ptr);
7994 if (RHS(ptr, 0)->op == OP_DEREF) {
7995 struct triple *base, *left;
7997 base = MISC(ptr, 0);
7998 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7999 left = RHS(base, 0);
8000 ptr = triple(state, OP_ADD, left->type,
8001 read_expr(state, left),
8002 int_const(state, &ulong_type, offset));
8003 free_triple(state, base);
8006 ptr = flatten_part(state, first, ptr);
8010 if (RHS(ptr, 0)->op == OP_DEREF) {
8011 struct triple *base, *left;
8013 base = MISC(ptr, 0);
8014 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8015 left = RHS(base, 0);
8016 ptr = triple(state, OP_ADD, left->type,
8017 read_expr(state, left),
8018 int_const(state, &long_type, offset));
8019 free_triple(state, base);
8022 ptr = flatten_part(state, first, ptr);
8026 ptr = flatten_part(state, first, ptr);
8027 use_triple(ptr, MISC(ptr, 0));
8030 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8031 use_triple(MISC(ptr, 0), ptr);
8034 first = state->global_pool;
8035 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8036 use_triple(MISC(ptr, 0), ptr);
8037 insert_triple(state, first, ptr);
8038 ptr->id |= TRIPLE_FLAG_FLATTENED;
8039 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8042 ptr = flatten_generic(state, first, ptr, 0);
8045 /* Flatten the easy cases we don't override */
8046 ptr = flatten_generic(state, first, ptr, 0);
8049 } while(ptr && (ptr != orig_ptr));
8050 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8051 insert_triple(state, first, ptr);
8052 ptr->id |= TRIPLE_FLAG_FLATTENED;
8053 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8058 static void release_expr(struct compile_state *state, struct triple *expr)
8060 struct triple *head;
8061 head = label(state);
8062 flatten(state, head, expr);
8063 while(head->next != head) {
8064 release_triple(state, head->next);
8066 free_triple(state, head);
8069 static int replace_rhs_use(struct compile_state *state,
8070 struct triple *orig, struct triple *new, struct triple *use)
8072 struct triple **expr;
8075 expr = triple_rhs(state, use, 0);
8076 for(;expr; expr = triple_rhs(state, use, expr)) {
8077 if (*expr == orig) {
8083 unuse_triple(orig, use);
8084 use_triple(new, use);
8089 static int replace_lhs_use(struct compile_state *state,
8090 struct triple *orig, struct triple *new, struct triple *use)
8092 struct triple **expr;
8095 expr = triple_lhs(state, use, 0);
8096 for(;expr; expr = triple_lhs(state, use, expr)) {
8097 if (*expr == orig) {
8103 unuse_triple(orig, use);
8104 use_triple(new, use);
8109 static int replace_misc_use(struct compile_state *state,
8110 struct triple *orig, struct triple *new, struct triple *use)
8112 struct triple **expr;
8115 expr = triple_misc(state, use, 0);
8116 for(;expr; expr = triple_misc(state, use, expr)) {
8117 if (*expr == orig) {
8123 unuse_triple(orig, use);
8124 use_triple(new, use);
8129 static int replace_targ_use(struct compile_state *state,
8130 struct triple *orig, struct triple *new, struct triple *use)
8132 struct triple **expr;
8135 expr = triple_targ(state, use, 0);
8136 for(;expr; expr = triple_targ(state, use, expr)) {
8137 if (*expr == orig) {
8143 unuse_triple(orig, use);
8144 use_triple(new, use);
8149 static void replace_use(struct compile_state *state,
8150 struct triple *orig, struct triple *new, struct triple *use)
8154 found |= replace_rhs_use(state, orig, new, use);
8155 found |= replace_lhs_use(state, orig, new, use);
8156 found |= replace_misc_use(state, orig, new, use);
8157 found |= replace_targ_use(state, orig, new, use);
8159 internal_error(state, use, "use without use");
8163 static void propogate_use(struct compile_state *state,
8164 struct triple *orig, struct triple *new)
8166 struct triple_set *user, *next;
8167 for(user = orig->use; user; user = next) {
8168 /* Careful replace_use modifies the use chain and
8169 * removes use. So we must get a copy of the next
8173 replace_use(state, orig, new, user->member);
8176 internal_error(state, orig, "used after propogate_use");
8182 * ===========================
8185 static struct triple *mk_cast_expr(
8186 struct compile_state *state, struct type *type, struct triple *expr)
8189 def = read_expr(state, expr);
8190 def = triple(state, OP_CONVERT, type, def, 0);
8194 static struct triple *mk_add_expr(
8195 struct compile_state *state, struct triple *left, struct triple *right)
8197 struct type *result_type;
8198 /* Put pointer operands on the left */
8199 if (is_pointer(right)) {
8205 left = read_expr(state, left);
8206 right = read_expr(state, right);
8207 result_type = ptr_arithmetic_result(state, left, right);
8208 if (is_pointer(left)) {
8209 struct type *ptr_math;
8211 if (is_signed(right->type)) {
8212 ptr_math = &long_type;
8215 ptr_math = &ulong_type;
8218 if (!equiv_types(right->type, ptr_math)) {
8219 right = mk_cast_expr(state, ptr_math, right);
8221 right = triple(state, op, ptr_math, right,
8222 int_const(state, ptr_math,
8223 size_of_in_bytes(state, left->type->left)));
8225 return triple(state, OP_ADD, result_type, left, right);
8228 static struct triple *mk_sub_expr(
8229 struct compile_state *state, struct triple *left, struct triple *right)
8231 struct type *result_type;
8232 result_type = ptr_arithmetic_result(state, left, right);
8233 left = read_expr(state, left);
8234 right = read_expr(state, right);
8235 if (is_pointer(left)) {
8236 struct type *ptr_math;
8238 if (is_signed(right->type)) {
8239 ptr_math = &long_type;
8242 ptr_math = &ulong_type;
8245 if (!equiv_types(right->type, ptr_math)) {
8246 right = mk_cast_expr(state, ptr_math, right);
8248 right = triple(state, op, ptr_math, right,
8249 int_const(state, ptr_math,
8250 size_of_in_bytes(state, left->type->left)));
8252 return triple(state, OP_SUB, result_type, left, right);
8255 static struct triple *mk_pre_inc_expr(
8256 struct compile_state *state, struct triple *def)
8260 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8261 return triple(state, OP_VAL, def->type,
8262 write_expr(state, def, val),
8266 static struct triple *mk_pre_dec_expr(
8267 struct compile_state *state, struct triple *def)
8271 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8272 return triple(state, OP_VAL, def->type,
8273 write_expr(state, def, val),
8277 static struct triple *mk_post_inc_expr(
8278 struct compile_state *state, struct triple *def)
8282 val = read_expr(state, def);
8283 return triple(state, OP_VAL, def->type,
8284 write_expr(state, def,
8285 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8289 static struct triple *mk_post_dec_expr(
8290 struct compile_state *state, struct triple *def)
8294 val = read_expr(state, def);
8295 return triple(state, OP_VAL, def->type,
8296 write_expr(state, def,
8297 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8301 static struct triple *mk_subscript_expr(
8302 struct compile_state *state, struct triple *left, struct triple *right)
8304 left = read_expr(state, left);
8305 right = read_expr(state, right);
8306 if (!is_pointer(left) && !is_pointer(right)) {
8307 error(state, left, "subscripted value is not a pointer");
8309 return mk_deref_expr(state, mk_add_expr(state, left, right));
8314 * Compile time evaluation
8315 * ===========================
8317 static int is_const(struct triple *ins)
8319 return IS_CONST_OP(ins->op);
8322 static int is_simple_const(struct triple *ins)
8324 /* Is this a constant that u.cval has the value.
8325 * Or equivalently is this a constant that read_const
8327 * So far only OP_INTCONST qualifies.
8329 return (ins->op == OP_INTCONST);
8332 static int constants_equal(struct compile_state *state,
8333 struct triple *left, struct triple *right)
8336 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8339 else if (!is_const(left) || !is_const(right)) {
8342 else if (left->op != right->op) {
8345 else if (!equiv_types(left->type, right->type)) {
8352 if (left->u.cval == right->u.cval) {
8358 size_t lsize, rsize, bytes;
8359 lsize = size_of(state, left->type);
8360 rsize = size_of(state, right->type);
8361 if (lsize != rsize) {
8364 bytes = bits_to_bytes(lsize);
8365 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8371 if ((MISC(left, 0) == MISC(right, 0)) &&
8372 (left->u.cval == right->u.cval)) {
8377 internal_error(state, left, "uknown constant type");
8384 static int is_zero(struct triple *ins)
8386 return is_simple_const(ins) && (ins->u.cval == 0);
8389 static int is_one(struct triple *ins)
8391 return is_simple_const(ins) && (ins->u.cval == 1);
8394 #if DEBUG_ROMCC_WARNING
8395 static long_t bit_count(ulong_t value)
8400 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8413 static long_t bsr(ulong_t value)
8416 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8427 static long_t bsf(ulong_t value)
8430 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8441 static long_t ilog2(ulong_t value)
8446 static long_t tlog2(struct triple *ins)
8448 return ilog2(ins->u.cval);
8451 static int is_pow2(struct triple *ins)
8453 ulong_t value, mask;
8455 if (!is_const(ins)) {
8458 value = ins->u.cval;
8465 return ((value & mask) == value);
8468 static ulong_t read_const(struct compile_state *state,
8469 struct triple *ins, struct triple *rhs)
8471 switch(rhs->type->type &TYPE_MASK) {
8484 fprintf(state->errout, "type: ");
8485 name_of(state->errout, rhs->type);
8486 fprintf(state->errout, "\n");
8487 internal_warning(state, rhs, "bad type to read_const");
8490 if (!is_simple_const(rhs)) {
8491 internal_error(state, rhs, "bad op to read_const");
8496 static long_t read_sconst(struct compile_state *state,
8497 struct triple *ins, struct triple *rhs)
8499 return (long_t)(rhs->u.cval);
8502 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8504 if (!is_const(rhs)) {
8505 internal_error(state, 0, "non const passed to const_true");
8507 return !is_zero(rhs);
8510 int const_eq(struct compile_state *state, struct triple *ins,
8511 struct triple *left, struct triple *right)
8514 if (!is_const(left) || !is_const(right)) {
8515 internal_warning(state, ins, "non const passed to const_eq");
8518 else if (left == right) {
8521 else if (is_simple_const(left) && is_simple_const(right)) {
8523 lval = read_const(state, ins, left);
8524 rval = read_const(state, ins, right);
8525 result = (lval == rval);
8527 else if ((left->op == OP_ADDRCONST) &&
8528 (right->op == OP_ADDRCONST)) {
8529 result = (MISC(left, 0) == MISC(right, 0)) &&
8530 (left->u.cval == right->u.cval);
8533 internal_warning(state, ins, "incomparable constants passed to const_eq");
8540 int const_ucmp(struct compile_state *state, struct triple *ins,
8541 struct triple *left, struct triple *right)
8544 if (!is_const(left) || !is_const(right)) {
8545 internal_warning(state, ins, "non const past to const_ucmp");
8548 else if (left == right) {
8551 else if (is_simple_const(left) && is_simple_const(right)) {
8553 lval = read_const(state, ins, left);
8554 rval = read_const(state, ins, right);
8558 } else if (rval > lval) {
8562 else if ((left->op == OP_ADDRCONST) &&
8563 (right->op == OP_ADDRCONST) &&
8564 (MISC(left, 0) == MISC(right, 0))) {
8566 if (left->u.cval > right->u.cval) {
8568 } else if (left->u.cval < right->u.cval) {
8573 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8579 int const_scmp(struct compile_state *state, struct triple *ins,
8580 struct triple *left, struct triple *right)
8583 if (!is_const(left) || !is_const(right)) {
8584 internal_warning(state, ins, "non const past to ucmp_const");
8587 else if (left == right) {
8590 else if (is_simple_const(left) && is_simple_const(right)) {
8592 lval = read_sconst(state, ins, left);
8593 rval = read_sconst(state, ins, right);
8597 } else if (rval > lval) {
8602 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8608 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8610 struct triple **expr;
8611 expr = triple_rhs(state, ins, 0);
8612 for(;expr;expr = triple_rhs(state, ins, expr)) {
8614 unuse_triple(*expr, ins);
8620 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8622 struct triple **expr;
8623 expr = triple_lhs(state, ins, 0);
8624 for(;expr;expr = triple_lhs(state, ins, expr)) {
8625 unuse_triple(*expr, ins);
8630 #if DEBUG_ROMCC_WARNING
8631 static void unuse_misc(struct compile_state *state, struct triple *ins)
8633 struct triple **expr;
8634 expr = triple_misc(state, ins, 0);
8635 for(;expr;expr = triple_misc(state, ins, expr)) {
8636 unuse_triple(*expr, ins);
8641 static void unuse_targ(struct compile_state *state, struct triple *ins)
8644 struct triple **slot;
8645 slot = &TARG(ins, 0);
8646 for(i = 0; i < ins->targ; i++) {
8647 unuse_triple(slot[i], ins);
8652 static void check_lhs(struct compile_state *state, struct triple *ins)
8654 struct triple **expr;
8655 expr = triple_lhs(state, ins, 0);
8656 for(;expr;expr = triple_lhs(state, ins, expr)) {
8657 internal_error(state, ins, "unexpected lhs");
8663 static void check_misc(struct compile_state *state, struct triple *ins)
8665 struct triple **expr;
8666 expr = triple_misc(state, ins, 0);
8667 for(;expr;expr = triple_misc(state, ins, expr)) {
8669 internal_error(state, ins, "unexpected misc");
8674 static void check_targ(struct compile_state *state, struct triple *ins)
8676 struct triple **expr;
8677 expr = triple_targ(state, ins, 0);
8678 for(;expr;expr = triple_targ(state, ins, expr)) {
8679 internal_error(state, ins, "unexpected targ");
8683 static void wipe_ins(struct compile_state *state, struct triple *ins)
8685 /* Becareful which instructions you replace the wiped
8686 * instruction with, as there are not enough slots
8687 * in all instructions to hold all others.
8689 check_targ(state, ins);
8690 check_misc(state, ins);
8691 unuse_rhs(state, ins);
8692 unuse_lhs(state, ins);
8699 #if DEBUG_ROMCC_WARNING
8700 static void wipe_branch(struct compile_state *state, struct triple *ins)
8702 /* Becareful which instructions you replace the wiped
8703 * instruction with, as there are not enough slots
8704 * in all instructions to hold all others.
8706 unuse_rhs(state, ins);
8707 unuse_lhs(state, ins);
8708 unuse_misc(state, ins);
8709 unuse_targ(state, ins);
8717 static void mkcopy(struct compile_state *state,
8718 struct triple *ins, struct triple *rhs)
8720 struct block *block;
8721 if (!equiv_types(ins->type, rhs->type)) {
8722 FILE *fp = state->errout;
8723 fprintf(fp, "src type: ");
8724 name_of(fp, rhs->type);
8725 fprintf(fp, "\ndst type: ");
8726 name_of(fp, ins->type);
8728 internal_error(state, ins, "mkcopy type mismatch");
8730 block = block_of_triple(state, ins);
8731 wipe_ins(state, ins);
8734 ins->u.block = block;
8736 use_triple(RHS(ins, 0), ins);
8739 static void mkconst(struct compile_state *state,
8740 struct triple *ins, ulong_t value)
8742 if (!is_integral(ins) && !is_pointer(ins)) {
8743 fprintf(state->errout, "type: ");
8744 name_of(state->errout, ins->type);
8745 fprintf(state->errout, "\n");
8746 internal_error(state, ins, "unknown type to make constant value: %ld",
8749 wipe_ins(state, ins);
8750 ins->op = OP_INTCONST;
8751 ins->u.cval = value;
8754 static void mkaddr_const(struct compile_state *state,
8755 struct triple *ins, struct triple *sdecl, ulong_t value)
8757 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8758 internal_error(state, ins, "bad base for addrconst");
8760 wipe_ins(state, ins);
8761 ins->op = OP_ADDRCONST;
8763 MISC(ins, 0) = sdecl;
8764 ins->u.cval = value;
8765 use_triple(sdecl, ins);
8768 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8769 static void print_tuple(struct compile_state *state,
8770 struct triple *ins, struct triple *tuple)
8772 FILE *fp = state->dbgout;
8773 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8774 name_of(fp, tuple->type);
8775 if (tuple->lhs > 0) {
8776 fprintf(fp, " lhs: ");
8777 name_of(fp, LHS(tuple, 0)->type);
8784 static struct triple *decompose_with_tuple(struct compile_state *state,
8785 struct triple *ins, struct triple *tuple)
8787 struct triple *next;
8789 flatten(state, next, tuple);
8790 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8791 print_tuple(state, ins, tuple);
8794 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8796 if (tuple->lhs != 1) {
8797 internal_error(state, tuple, "plain type in multiple registers?");
8799 tmp = LHS(tuple, 0);
8800 release_triple(state, tuple);
8804 propogate_use(state, ins, tuple);
8805 release_triple(state, ins);
8810 static struct triple *decompose_unknownval(struct compile_state *state,
8813 struct triple *tuple;
8816 #if DEBUG_DECOMPOSE_HIRES
8817 FILE *fp = state->dbgout;
8818 fprintf(fp, "unknown type: ");
8819 name_of(fp, ins->type);
8823 get_occurance(ins->occurance);
8824 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8827 for(i = 0; i < tuple->lhs; i++) {
8828 struct type *piece_type;
8829 struct triple *unknown;
8831 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8832 get_occurance(tuple->occurance);
8833 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8835 LHS(tuple, i) = unknown;
8837 return decompose_with_tuple(state, ins, tuple);
8841 static struct triple *decompose_read(struct compile_state *state,
8844 struct triple *tuple, *lval;
8849 if (lval->op == OP_PIECE) {
8852 get_occurance(ins->occurance);
8853 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8856 if ((tuple->lhs != lval->lhs) &&
8857 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8859 internal_error(state, ins, "lhs size inconsistency?");
8861 for(i = 0; i < tuple->lhs; i++) {
8862 struct triple *piece, *read, *bitref;
8863 if ((i != 0) || !triple_is_def(state, lval)) {
8864 piece = LHS(lval, i);
8869 /* See if the piece is really a bitref */
8871 if (piece->op == OP_BITREF) {
8873 piece = RHS(bitref, 0);
8876 get_occurance(tuple->occurance);
8877 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8879 RHS(read, 0) = piece;
8882 struct triple *extract;
8884 if (is_signed(bitref->type->left)) {
8889 get_occurance(tuple->occurance);
8890 extract = alloc_triple(state, op, bitref->type, -1, -1,
8892 RHS(extract, 0) = read;
8893 extract->u.bitfield.size = bitref->u.bitfield.size;
8894 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8899 LHS(tuple, i) = read;
8901 return decompose_with_tuple(state, ins, tuple);
8904 static struct triple *decompose_write(struct compile_state *state,
8907 struct triple *tuple, *lval, *val;
8910 lval = MISC(ins, 0);
8912 get_occurance(ins->occurance);
8913 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8916 if ((tuple->lhs != lval->lhs) &&
8917 (!triple_is_def(state, lval) || tuple->lhs != 1))
8919 internal_error(state, ins, "lhs size inconsistency?");
8921 for(i = 0; i < tuple->lhs; i++) {
8922 struct triple *piece, *write, *pval, *bitref;
8923 if ((i != 0) || !triple_is_def(state, lval)) {
8924 piece = LHS(lval, i);
8928 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8933 internal_error(state, ins, "lhs size inconsistency?");
8938 /* See if the piece is really a bitref */
8940 if (piece->op == OP_BITREF) {
8941 struct triple *read, *deposit;
8943 piece = RHS(bitref, 0);
8945 /* Read the destination register */
8946 get_occurance(tuple->occurance);
8947 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8949 RHS(read, 0) = piece;
8951 /* Deposit the new bitfield value */
8952 get_occurance(tuple->occurance);
8953 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8955 RHS(deposit, 0) = read;
8956 RHS(deposit, 1) = pval;
8957 deposit->u.bitfield.size = bitref->u.bitfield.size;
8958 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8960 /* Now write the newly generated value */
8964 get_occurance(tuple->occurance);
8965 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
8967 MISC(write, 0) = piece;
8968 RHS(write, 0) = pval;
8969 LHS(tuple, i) = write;
8971 return decompose_with_tuple(state, ins, tuple);
8974 struct decompose_load_info {
8975 struct occurance *occurance;
8976 struct triple *lval;
8977 struct triple *tuple;
8979 static void decompose_load_cb(struct compile_state *state,
8980 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8982 struct decompose_load_info *info = arg;
8983 struct triple *load;
8985 if (reg_offset > info->tuple->lhs) {
8986 internal_error(state, info->tuple, "lhs to small?");
8988 get_occurance(info->occurance);
8989 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8990 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8991 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8994 static struct triple *decompose_load(struct compile_state *state,
8997 struct triple *tuple;
8998 struct decompose_load_info info;
9000 if (!is_compound_type(ins->type)) {
9003 get_occurance(ins->occurance);
9004 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9007 info.occurance = ins->occurance;
9008 info.lval = RHS(ins, 0);
9010 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
9012 return decompose_with_tuple(state, ins, tuple);
9016 struct decompose_store_info {
9017 struct occurance *occurance;
9018 struct triple *lval;
9020 struct triple *tuple;
9022 static void decompose_store_cb(struct compile_state *state,
9023 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9025 struct decompose_store_info *info = arg;
9026 struct triple *store;
9028 if (reg_offset > info->tuple->lhs) {
9029 internal_error(state, info->tuple, "lhs to small?");
9031 get_occurance(info->occurance);
9032 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9033 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9034 RHS(store, 1) = LHS(info->val, reg_offset);
9035 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9038 static struct triple *decompose_store(struct compile_state *state,
9041 struct triple *tuple;
9042 struct decompose_store_info info;
9044 if (!is_compound_type(ins->type)) {
9047 get_occurance(ins->occurance);
9048 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9051 info.occurance = ins->occurance;
9052 info.lval = RHS(ins, 0);
9053 info.val = RHS(ins, 1);
9055 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9057 return decompose_with_tuple(state, ins, tuple);
9060 static struct triple *decompose_dot(struct compile_state *state,
9063 struct triple *tuple, *lval;
9068 lval = MISC(ins, 0);
9069 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9070 idx = reg_offset/REG_SIZEOF_REG;
9071 type = field_type(state, lval->type, ins->u.field);
9072 #if DEBUG_DECOMPOSE_HIRES
9074 FILE *fp = state->dbgout;
9075 fprintf(fp, "field type: ");
9081 get_occurance(ins->occurance);
9082 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9085 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9088 internal_error(state, ins, "multi register bitfield?");
9091 for(i = 0; i < tuple->lhs; i++, idx++) {
9092 struct triple *piece;
9093 if (!triple_is_def(state, lval)) {
9094 if (idx > lval->lhs) {
9095 internal_error(state, ins, "inconsistent lhs count");
9097 piece = LHS(lval, idx);
9100 internal_error(state, ins, "bad reg_offset into def");
9103 internal_error(state, ins, "bad reg count from def");
9108 /* Remember the offset of the bitfield */
9109 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9110 get_occurance(ins->occurance);
9111 piece = build_triple(state, OP_BITREF, type, piece, 0,
9113 piece->u.bitfield.size = size_of(state, type);
9114 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9116 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9117 internal_error(state, ins,
9118 "request for a nonbitfield sub register?");
9121 LHS(tuple, i) = piece;
9124 return decompose_with_tuple(state, ins, tuple);
9127 static struct triple *decompose_index(struct compile_state *state,
9130 struct triple *tuple, *lval;
9134 lval = MISC(ins, 0);
9135 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9136 type = index_type(state, lval->type, ins->u.cval);
9137 #if DEBUG_DECOMPOSE_HIRES
9139 FILE *fp = state->dbgout;
9140 fprintf(fp, "index type: ");
9146 get_occurance(ins->occurance);
9147 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9150 for(i = 0; i < tuple->lhs; i++, idx++) {
9151 struct triple *piece;
9152 if (!triple_is_def(state, lval)) {
9153 if (idx > lval->lhs) {
9154 internal_error(state, ins, "inconsistent lhs count");
9156 piece = LHS(lval, idx);
9159 internal_error(state, ins, "bad reg_offset into def");
9162 internal_error(state, ins, "bad reg count from def");
9166 LHS(tuple, i) = piece;
9169 return decompose_with_tuple(state, ins, tuple);
9172 static void decompose_compound_types(struct compile_state *state)
9174 struct triple *ins, *next, *first;
9177 first = state->first;
9180 /* Pass one expand compound values into pseudo registers.
9188 next = decompose_unknownval(state, ins);
9192 next = decompose_read(state, ins);
9196 next = decompose_write(state, ins);
9200 /* Be very careful with the load/store logic. These
9201 * operations must convert from the in register layout
9202 * to the in memory layout, which is nontrivial.
9205 next = decompose_load(state, ins);
9208 next = decompose_store(state, ins);
9212 next = decompose_dot(state, ins);
9215 next = decompose_index(state, ins);
9219 #if DEBUG_DECOMPOSE_HIRES
9220 fprintf(fp, "decompose next: %p \n", next);
9222 fprintf(fp, "next->op: %d %s\n",
9223 next->op, tops(next->op));
9224 /* High resolution debugging mode */
9225 print_triples(state);
9227 } while (next != first);
9229 /* Pass two remove the tuples.
9234 if (ins->op == OP_TUPLE) {
9236 internal_error(state, ins, "tuple used");
9239 release_triple(state, ins);
9243 } while(ins != first);
9247 if (ins->op == OP_BITREF) {
9249 internal_error(state, ins, "bitref used");
9252 release_triple(state, ins);
9256 } while(ins != first);
9258 /* Pass three verify the state and set ->id to 0.
9264 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9265 if (triple_stores_block(state, ins)) {
9268 if (triple_is_def(state, ins)) {
9269 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9270 internal_error(state, ins, "multi register value remains?");
9273 if (ins->op == OP_DOT) {
9274 internal_error(state, ins, "OP_DOT remains?");
9276 if (ins->op == OP_INDEX) {
9277 internal_error(state, ins, "OP_INDEX remains?");
9279 if (ins->op == OP_BITREF) {
9280 internal_error(state, ins, "OP_BITREF remains?");
9282 if (ins->op == OP_TUPLE) {
9283 internal_error(state, ins, "OP_TUPLE remains?");
9285 } while(next != first);
9288 /* For those operations that cannot be simplified */
9289 static void simplify_noop(struct compile_state *state, struct triple *ins)
9294 static void simplify_smul(struct compile_state *state, struct triple *ins)
9296 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9299 RHS(ins, 0) = RHS(ins, 1);
9302 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9304 left = read_sconst(state, ins, RHS(ins, 0));
9305 right = read_sconst(state, ins, RHS(ins, 1));
9306 mkconst(state, ins, left * right);
9308 else if (is_zero(RHS(ins, 1))) {
9309 mkconst(state, ins, 0);
9311 else if (is_one(RHS(ins, 1))) {
9312 mkcopy(state, ins, RHS(ins, 0));
9314 else if (is_pow2(RHS(ins, 1))) {
9316 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9318 insert_triple(state, state->global_pool, val);
9319 unuse_triple(RHS(ins, 1), ins);
9320 use_triple(val, ins);
9325 static void simplify_umul(struct compile_state *state, struct triple *ins)
9327 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9330 RHS(ins, 0) = RHS(ins, 1);
9333 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9334 ulong_t left, right;
9335 left = read_const(state, ins, RHS(ins, 0));
9336 right = read_const(state, ins, RHS(ins, 1));
9337 mkconst(state, ins, left * right);
9339 else if (is_zero(RHS(ins, 1))) {
9340 mkconst(state, ins, 0);
9342 else if (is_one(RHS(ins, 1))) {
9343 mkcopy(state, ins, RHS(ins, 0));
9345 else if (is_pow2(RHS(ins, 1))) {
9347 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9349 insert_triple(state, state->global_pool, val);
9350 unuse_triple(RHS(ins, 1), ins);
9351 use_triple(val, ins);
9356 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9358 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9360 left = read_sconst(state, ins, RHS(ins, 0));
9361 right = read_sconst(state, ins, RHS(ins, 1));
9362 mkconst(state, ins, left / right);
9364 else if (is_zero(RHS(ins, 0))) {
9365 mkconst(state, ins, 0);
9367 else if (is_zero(RHS(ins, 1))) {
9368 error(state, ins, "division by zero");
9370 else if (is_one(RHS(ins, 1))) {
9371 mkcopy(state, ins, RHS(ins, 0));
9373 else if (is_pow2(RHS(ins, 1))) {
9375 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9377 insert_triple(state, state->global_pool, val);
9378 unuse_triple(RHS(ins, 1), ins);
9379 use_triple(val, ins);
9384 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9386 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9387 ulong_t left, right;
9388 left = read_const(state, ins, RHS(ins, 0));
9389 right = read_const(state, ins, RHS(ins, 1));
9390 mkconst(state, ins, left / right);
9392 else if (is_zero(RHS(ins, 0))) {
9393 mkconst(state, ins, 0);
9395 else if (is_zero(RHS(ins, 1))) {
9396 error(state, ins, "division by zero");
9398 else if (is_one(RHS(ins, 1))) {
9399 mkcopy(state, ins, RHS(ins, 0));
9401 else if (is_pow2(RHS(ins, 1))) {
9403 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9405 insert_triple(state, state->global_pool, val);
9406 unuse_triple(RHS(ins, 1), ins);
9407 use_triple(val, ins);
9412 static void simplify_smod(struct compile_state *state, struct triple *ins)
9414 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9416 left = read_const(state, ins, RHS(ins, 0));
9417 right = read_const(state, ins, RHS(ins, 1));
9418 mkconst(state, ins, left % right);
9420 else if (is_zero(RHS(ins, 0))) {
9421 mkconst(state, ins, 0);
9423 else if (is_zero(RHS(ins, 1))) {
9424 error(state, ins, "division by zero");
9426 else if (is_one(RHS(ins, 1))) {
9427 mkconst(state, ins, 0);
9429 else if (is_pow2(RHS(ins, 1))) {
9431 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9433 insert_triple(state, state->global_pool, val);
9434 unuse_triple(RHS(ins, 1), ins);
9435 use_triple(val, ins);
9440 static void simplify_umod(struct compile_state *state, struct triple *ins)
9442 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9443 ulong_t left, right;
9444 left = read_const(state, ins, RHS(ins, 0));
9445 right = read_const(state, ins, RHS(ins, 1));
9446 mkconst(state, ins, left % right);
9448 else if (is_zero(RHS(ins, 0))) {
9449 mkconst(state, ins, 0);
9451 else if (is_zero(RHS(ins, 1))) {
9452 error(state, ins, "division by zero");
9454 else if (is_one(RHS(ins, 1))) {
9455 mkconst(state, ins, 0);
9457 else if (is_pow2(RHS(ins, 1))) {
9459 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9461 insert_triple(state, state->global_pool, val);
9462 unuse_triple(RHS(ins, 1), ins);
9463 use_triple(val, ins);
9468 static void simplify_add(struct compile_state *state, struct triple *ins)
9470 /* start with the pointer on the left */
9471 if (is_pointer(RHS(ins, 1))) {
9474 RHS(ins, 0) = RHS(ins, 1);
9477 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9478 if (RHS(ins, 0)->op == OP_INTCONST) {
9479 ulong_t left, right;
9480 left = read_const(state, ins, RHS(ins, 0));
9481 right = read_const(state, ins, RHS(ins, 1));
9482 mkconst(state, ins, left + right);
9484 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9485 struct triple *sdecl;
9486 ulong_t left, right;
9487 sdecl = MISC(RHS(ins, 0), 0);
9488 left = RHS(ins, 0)->u.cval;
9489 right = RHS(ins, 1)->u.cval;
9490 mkaddr_const(state, ins, sdecl, left + right);
9493 internal_warning(state, ins, "Optimize me!");
9496 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9499 RHS(ins, 1) = RHS(ins, 0);
9504 static void simplify_sub(struct compile_state *state, struct triple *ins)
9506 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9507 if (RHS(ins, 0)->op == OP_INTCONST) {
9508 ulong_t left, right;
9509 left = read_const(state, ins, RHS(ins, 0));
9510 right = read_const(state, ins, RHS(ins, 1));
9511 mkconst(state, ins, left - right);
9513 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9514 struct triple *sdecl;
9515 ulong_t left, right;
9516 sdecl = MISC(RHS(ins, 0), 0);
9517 left = RHS(ins, 0)->u.cval;
9518 right = RHS(ins, 1)->u.cval;
9519 mkaddr_const(state, ins, sdecl, left - right);
9522 internal_warning(state, ins, "Optimize me!");
9527 static void simplify_sl(struct compile_state *state, struct triple *ins)
9529 if (is_simple_const(RHS(ins, 1))) {
9531 right = read_const(state, ins, RHS(ins, 1));
9532 if (right >= (size_of(state, ins->type))) {
9533 warning(state, ins, "left shift count >= width of type");
9536 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9537 ulong_t left, right;
9538 left = read_const(state, ins, RHS(ins, 0));
9539 right = read_const(state, ins, RHS(ins, 1));
9540 mkconst(state, ins, left << right);
9544 static void simplify_usr(struct compile_state *state, struct triple *ins)
9546 if (is_simple_const(RHS(ins, 1))) {
9548 right = read_const(state, ins, RHS(ins, 1));
9549 if (right >= (size_of(state, ins->type))) {
9550 warning(state, ins, "right shift count >= width of type");
9553 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9554 ulong_t left, right;
9555 left = read_const(state, ins, RHS(ins, 0));
9556 right = read_const(state, ins, RHS(ins, 1));
9557 mkconst(state, ins, left >> right);
9561 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9563 if (is_simple_const(RHS(ins, 1))) {
9565 right = read_const(state, ins, RHS(ins, 1));
9566 if (right >= (size_of(state, ins->type))) {
9567 warning(state, ins, "right shift count >= width of type");
9570 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9572 left = read_sconst(state, ins, RHS(ins, 0));
9573 right = read_sconst(state, ins, RHS(ins, 1));
9574 mkconst(state, ins, left >> right);
9578 static void simplify_and(struct compile_state *state, struct triple *ins)
9580 struct triple *left, *right;
9582 right = RHS(ins, 1);
9584 if (is_simple_const(left) && is_simple_const(right)) {
9586 lval = read_const(state, ins, left);
9587 rval = read_const(state, ins, right);
9588 mkconst(state, ins, lval & rval);
9590 else if (is_zero(right) || is_zero(left)) {
9591 mkconst(state, ins, 0);
9595 static void simplify_or(struct compile_state *state, struct triple *ins)
9597 struct triple *left, *right;
9599 right = RHS(ins, 1);
9601 if (is_simple_const(left) && is_simple_const(right)) {
9603 lval = read_const(state, ins, left);
9604 rval = read_const(state, ins, right);
9605 mkconst(state, ins, lval | rval);
9607 #if 0 /* I need to handle type mismatches here... */
9608 else if (is_zero(right)) {
9609 mkcopy(state, ins, left);
9611 else if (is_zero(left)) {
9612 mkcopy(state, ins, right);
9617 static void simplify_xor(struct compile_state *state, struct triple *ins)
9619 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9620 ulong_t left, right;
9621 left = read_const(state, ins, RHS(ins, 0));
9622 right = read_const(state, ins, RHS(ins, 1));
9623 mkconst(state, ins, left ^ right);
9627 static void simplify_pos(struct compile_state *state, struct triple *ins)
9629 if (is_const(RHS(ins, 0))) {
9630 mkconst(state, ins, RHS(ins, 0)->u.cval);
9633 mkcopy(state, ins, RHS(ins, 0));
9637 static void simplify_neg(struct compile_state *state, struct triple *ins)
9639 if (is_simple_const(RHS(ins, 0))) {
9641 left = read_const(state, ins, RHS(ins, 0));
9642 mkconst(state, ins, -left);
9644 else if (RHS(ins, 0)->op == OP_NEG) {
9645 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9649 static void simplify_invert(struct compile_state *state, struct triple *ins)
9651 if (is_simple_const(RHS(ins, 0))) {
9653 left = read_const(state, ins, RHS(ins, 0));
9654 mkconst(state, ins, ~left);
9658 static void simplify_eq(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_eq(state, ins, left, right);
9668 mkconst(state, ins, val == 1);
9671 else if (left == right) {
9672 mkconst(state, ins, 1);
9676 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9678 struct triple *left, *right;
9680 right = RHS(ins, 1);
9682 if (is_const(left) && is_const(right)) {
9684 val = const_eq(state, ins, left, right);
9686 mkconst(state, ins, val != 1);
9689 if (left == right) {
9690 mkconst(state, ins, 0);
9694 static void simplify_sless(struct compile_state *state, struct triple *ins)
9696 struct triple *left, *right;
9698 right = RHS(ins, 1);
9700 if (is_const(left) && is_const(right)) {
9702 val = const_scmp(state, ins, left, right);
9703 if ((val >= -1) && (val <= 1)) {
9704 mkconst(state, ins, val < 0);
9707 else if (left == right) {
9708 mkconst(state, ins, 0);
9712 static void simplify_uless(struct compile_state *state, struct triple *ins)
9714 struct triple *left, *right;
9716 right = RHS(ins, 1);
9718 if (is_const(left) && is_const(right)) {
9720 val = const_ucmp(state, ins, left, right);
9721 if ((val >= -1) && (val <= 1)) {
9722 mkconst(state, ins, val < 0);
9725 else if (is_zero(right)) {
9726 mkconst(state, ins, 0);
9728 else if (left == right) {
9729 mkconst(state, ins, 0);
9733 static void simplify_smore(struct compile_state *state, struct triple *ins)
9735 struct triple *left, *right;
9737 right = RHS(ins, 1);
9739 if (is_const(left) && is_const(right)) {
9741 val = const_scmp(state, ins, left, right);
9742 if ((val >= -1) && (val <= 1)) {
9743 mkconst(state, ins, val > 0);
9746 else if (left == right) {
9747 mkconst(state, ins, 0);
9751 static void simplify_umore(struct compile_state *state, struct triple *ins)
9753 struct triple *left, *right;
9755 right = RHS(ins, 1);
9757 if (is_const(left) && is_const(right)) {
9759 val = const_ucmp(state, ins, left, right);
9760 if ((val >= -1) && (val <= 1)) {
9761 mkconst(state, ins, val > 0);
9764 else if (is_zero(left)) {
9765 mkconst(state, ins, 0);
9767 else if (left == right) {
9768 mkconst(state, ins, 0);
9773 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9775 struct triple *left, *right;
9777 right = RHS(ins, 1);
9779 if (is_const(left) && is_const(right)) {
9781 val = const_scmp(state, ins, left, right);
9782 if ((val >= -1) && (val <= 1)) {
9783 mkconst(state, ins, val <= 0);
9786 else if (left == right) {
9787 mkconst(state, ins, 1);
9791 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9793 struct triple *left, *right;
9795 right = RHS(ins, 1);
9797 if (is_const(left) && is_const(right)) {
9799 val = const_ucmp(state, ins, left, right);
9800 if ((val >= -1) && (val <= 1)) {
9801 mkconst(state, ins, val <= 0);
9804 else if (is_zero(left)) {
9805 mkconst(state, ins, 1);
9807 else if (left == right) {
9808 mkconst(state, ins, 1);
9812 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9814 struct triple *left, *right;
9816 right = RHS(ins, 1);
9818 if (is_const(left) && is_const(right)) {
9820 val = const_scmp(state, ins, left, right);
9821 if ((val >= -1) && (val <= 1)) {
9822 mkconst(state, ins, val >= 0);
9825 else if (left == right) {
9826 mkconst(state, ins, 1);
9830 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9832 struct triple *left, *right;
9834 right = RHS(ins, 1);
9836 if (is_const(left) && is_const(right)) {
9838 val = const_ucmp(state, ins, left, right);
9839 if ((val >= -1) && (val <= 1)) {
9840 mkconst(state, ins, val >= 0);
9843 else if (is_zero(right)) {
9844 mkconst(state, ins, 1);
9846 else if (left == right) {
9847 mkconst(state, ins, 1);
9851 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9856 if (is_const(rhs)) {
9857 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9859 /* Otherwise if I am the only user... */
9860 else if ((rhs->use) &&
9861 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9863 /* Invert a boolean operation */
9865 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9866 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9867 case OP_EQ: rhs->op = OP_NOTEQ; break;
9868 case OP_NOTEQ: rhs->op = OP_EQ; break;
9869 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9870 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9871 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9872 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9873 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9874 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9875 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9876 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9882 mkcopy(state, ins, rhs);
9887 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9892 if (is_const(rhs)) {
9893 mkconst(state, ins, const_ltrue(state, ins, rhs));
9895 else switch(rhs->op) {
9896 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9897 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9898 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9899 mkcopy(state, ins, rhs);
9904 static void simplify_load(struct compile_state *state, struct triple *ins)
9906 struct triple *addr, *sdecl, *blob;
9908 /* If I am doing a load with a constant pointer from a constant
9909 * table get the value.
9912 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9913 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9914 (blob->op == OP_BLOBCONST)) {
9915 unsigned char buffer[SIZEOF_WORD];
9916 size_t reg_size, mem_size;
9917 const char *src, *end;
9919 reg_size = reg_size_of(state, ins->type);
9920 if (reg_size > REG_SIZEOF_REG) {
9921 internal_error(state, ins, "load size greater than register");
9923 mem_size = size_of(state, ins->type);
9925 end += bits_to_bytes(size_of(state, sdecl->type));
9927 src += addr->u.cval;
9930 error(state, ins, "Load address out of bounds");
9933 memset(buffer, 0, sizeof(buffer));
9934 memcpy(buffer, src, bits_to_bytes(mem_size));
9937 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
9938 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9939 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9940 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9942 internal_error(state, ins, "mem_size: %d not handled",
9947 mkconst(state, ins, val);
9951 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9953 if (is_simple_const(RHS(ins, 0))) {
9956 val = read_const(state, ins, RHS(ins, 0));
9958 mask <<= ins->u.bitfield.size;
9960 val >>= ins->u.bitfield.offset;
9962 mkconst(state, ins, val);
9966 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9968 if (is_simple_const(RHS(ins, 0))) {
9972 val = read_const(state, ins, RHS(ins, 0));
9974 mask <<= ins->u.bitfield.size;
9976 val >>= ins->u.bitfield.offset;
9978 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9980 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9981 mkconst(state, ins, sval);
9985 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9987 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9990 targ = read_const(state, ins, RHS(ins, 0));
9991 val = read_const(state, ins, RHS(ins, 1));
9993 mask <<= ins->u.bitfield.size;
9995 mask <<= ins->u.bitfield.offset;
9997 val <<= ins->u.bitfield.offset;
10000 mkconst(state, ins, targ);
10004 static void simplify_copy(struct compile_state *state, struct triple *ins)
10006 struct triple *right;
10007 right = RHS(ins, 0);
10008 if (is_subset_type(ins->type, right->type)) {
10009 ins->type = right->type;
10011 if (equiv_types(ins->type, right->type)) {
10012 ins->op = OP_COPY;/* I don't need to convert if the types match */
10014 if (ins->op == OP_COPY) {
10015 internal_error(state, ins, "type mismatch on copy");
10018 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10019 struct triple *sdecl;
10021 sdecl = MISC(right, 0);
10022 offset = right->u.cval;
10023 mkaddr_const(state, ins, sdecl, offset);
10025 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10026 switch(right->op) {
10030 left = read_const(state, ins, right);
10031 /* Ensure I have not overflowed the destination. */
10032 if (size_of(state, right->type) > size_of(state, ins->type)) {
10035 mask <<= size_of(state, ins->type);
10039 /* Ensure I am properly sign extended */
10040 if (size_of(state, right->type) < size_of(state, ins->type) &&
10041 is_signed(right->type)) {
10044 shift = SIZEOF_LONG - size_of(state, right->type);
10050 mkconst(state, ins, left);
10054 internal_error(state, ins, "uknown constant");
10060 static int phi_present(struct block *block)
10062 struct triple *ptr;
10066 ptr = block->first;
10068 if (ptr->op == OP_PHI) {
10072 } while(ptr != block->last);
10076 static int phi_dependency(struct block *block)
10078 /* A block has a phi dependency if a phi function
10079 * depends on that block to exist, and makes a block
10080 * that is otherwise useless unsafe to remove.
10083 struct block_set *edge;
10084 for(edge = block->edges; edge; edge = edge->next) {
10085 if (phi_present(edge->member)) {
10093 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10095 struct triple *targ;
10096 targ = TARG(ins, 0);
10097 /* During scc_transform temporary triples are allocated that
10098 * loop back onto themselves. If I see one don't advance the
10101 while(triple_is_structural(state, targ) &&
10102 (targ->next != targ) && (targ->next != state->first)) {
10109 static void simplify_branch(struct compile_state *state, struct triple *ins)
10111 int simplified, loops;
10112 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10113 internal_error(state, ins, "not branch");
10115 if (ins->use != 0) {
10116 internal_error(state, ins, "branch use");
10118 /* The challenge here with simplify branch is that I need to
10119 * make modifications to the control flow graph as well
10120 * as to the branch instruction itself. That is handled
10121 * by rebuilding the basic blocks after simplify all is called.
10124 /* If we have a branch to an unconditional branch update
10125 * our target. But watch out for dependencies from phi
10127 * Also only do this a limited number of times so
10128 * we don't get into an infinite loop.
10132 struct triple *targ;
10134 targ = branch_target(state, ins);
10135 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10136 !phi_dependency(targ->u.block))
10138 unuse_triple(TARG(ins, 0), ins);
10139 TARG(ins, 0) = TARG(targ, 0);
10140 use_triple(TARG(ins, 0), ins);
10143 } while(simplified && (++loops < 20));
10145 /* If we have a conditional branch with a constant condition
10146 * make it an unconditional branch.
10148 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10149 struct triple *targ;
10151 value = read_const(state, ins, RHS(ins, 0));
10152 unuse_triple(RHS(ins, 0), ins);
10153 targ = TARG(ins, 0);
10156 ins->op = OP_BRANCH;
10158 unuse_triple(ins->next, ins);
10159 TARG(ins, 0) = targ;
10162 unuse_triple(targ, ins);
10163 TARG(ins, 0) = ins->next;
10167 /* If we have a branch to the next instruction,
10170 if (TARG(ins, 0) == ins->next) {
10171 unuse_triple(TARG(ins, 0), ins);
10172 if (ins->op == OP_CBRANCH) {
10173 unuse_triple(RHS(ins, 0), ins);
10174 unuse_triple(ins->next, ins);
10182 internal_error(state, ins, "noop use != 0");
10187 static void simplify_label(struct compile_state *state, struct triple *ins)
10189 /* Ignore volatile labels */
10190 if (!triple_is_pure(state, ins, ins->id)) {
10193 if (ins->use == 0) {
10196 else if (ins->prev->op == OP_LABEL) {
10197 /* In general it is not safe to merge one label that
10198 * imediately follows another. The problem is that the empty
10199 * looking block may have phi functions that depend on it.
10201 if (!phi_dependency(ins->prev->u.block)) {
10202 struct triple_set *user, *next;
10204 for(user = ins->use; user; user = next) {
10205 struct triple *use, **expr;
10207 use = user->member;
10208 expr = triple_targ(state, use, 0);
10209 for(;expr; expr = triple_targ(state, use, expr)) {
10210 if (*expr == ins) {
10212 unuse_triple(ins, use);
10213 use_triple(ins->prev, use);
10219 internal_error(state, ins, "noop use != 0");
10225 static void simplify_phi(struct compile_state *state, struct triple *ins)
10227 struct triple **slot;
10228 struct triple *value;
10231 slot = &RHS(ins, 0);
10236 /* See if all of the rhs members of a phi have the same value */
10237 if (slot[0] && is_simple_const(slot[0])) {
10238 cvalue = read_const(state, ins, slot[0]);
10239 for(i = 1; i < zrhs; i++) {
10241 !is_simple_const(slot[i]) ||
10242 !equiv_types(slot[0]->type, slot[i]->type) ||
10243 (cvalue != read_const(state, ins, slot[i]))) {
10248 mkconst(state, ins, cvalue);
10253 /* See if all of rhs members of a phi are the same */
10255 for(i = 1; i < zrhs; i++) {
10256 if (slot[i] != value) {
10261 /* If the phi has a single value just copy it */
10262 if (!is_subset_type(ins->type, value->type)) {
10263 internal_error(state, ins, "bad input type to phi");
10265 /* Make the types match */
10266 if (!equiv_types(ins->type, value->type)) {
10267 ins->type = value->type;
10269 /* Now make the actual copy */
10270 mkcopy(state, ins, value);
10276 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10278 if (is_simple_const(RHS(ins, 0))) {
10280 left = read_const(state, ins, RHS(ins, 0));
10281 mkconst(state, ins, bsf(left));
10285 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10287 if (is_simple_const(RHS(ins, 0))) {
10289 left = read_const(state, ins, RHS(ins, 0));
10290 mkconst(state, ins, bsr(left));
10295 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10296 static const struct simplify_table {
10298 unsigned long flag;
10299 } table_simplify[] = {
10300 #define simplify_sdivt simplify_noop
10301 #define simplify_udivt simplify_noop
10302 #define simplify_piece simplify_noop
10304 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10305 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10306 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10307 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10308 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10309 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10310 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10311 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10312 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10313 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10314 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10315 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10316 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10317 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10318 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10319 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10320 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10321 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10322 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10324 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10325 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10326 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10327 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10328 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10329 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10330 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10331 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10332 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10333 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10334 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10335 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10337 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10338 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10340 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10341 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10342 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10344 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10346 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10347 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10348 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10349 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10351 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10352 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10353 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10354 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10355 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10356 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10358 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10359 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10361 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10362 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10363 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10364 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10365 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10366 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10367 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10368 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10369 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10371 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10372 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10373 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10374 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10375 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10376 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10377 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10378 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10379 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10380 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10381 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10384 static inline void debug_simplify(struct compile_state *state,
10385 simplify_t do_simplify, struct triple *ins)
10387 #if DEBUG_SIMPLIFY_HIRES
10388 if (state->functions_joined && (do_simplify != simplify_noop)) {
10389 /* High resolution debugging mode */
10390 fprintf(state->dbgout, "simplifing: ");
10391 display_triple(state->dbgout, ins);
10394 do_simplify(state, ins);
10395 #if DEBUG_SIMPLIFY_HIRES
10396 if (state->functions_joined && (do_simplify != simplify_noop)) {
10397 /* High resolution debugging mode */
10398 fprintf(state->dbgout, "simplified: ");
10399 display_triple(state->dbgout, ins);
10403 static void simplify(struct compile_state *state, struct triple *ins)
10406 simplify_t do_simplify;
10407 if (ins == &unknown_triple) {
10408 internal_error(state, ins, "simplifying the unknown triple?");
10413 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10417 do_simplify = table_simplify[op].func;
10420 !(state->compiler->flags & table_simplify[op].flag)) {
10421 do_simplify = simplify_noop;
10423 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10424 do_simplify = simplify_noop;
10427 if (!do_simplify) {
10428 internal_error(state, ins, "cannot simplify op: %d %s",
10432 debug_simplify(state, do_simplify, ins);
10433 } while(ins->op != op);
10436 static void rebuild_ssa_form(struct compile_state *state);
10438 static void simplify_all(struct compile_state *state)
10440 struct triple *ins, *first;
10441 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10444 first = state->first;
10447 simplify(state, ins);
10449 } while(ins != first->prev);
10452 simplify(state, ins);
10454 }while(ins != first);
10455 rebuild_ssa_form(state);
10457 print_blocks(state, __func__, state->dbgout);
10462 * ============================
10465 static void register_builtin_function(struct compile_state *state,
10466 const char *name, int op, struct type *rtype, ...)
10468 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10469 struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10470 struct hash_entry *ident;
10471 struct file_state file;
10477 /* Dummy file state to get debug handling right */
10478 memset(&file, 0, sizeof(file));
10479 file.basename = "<built-in>";
10481 file.report_line = 1;
10482 file.report_name = file.basename;
10483 file.prev = state->file;
10484 state->file = &file;
10485 state->function = name;
10487 /* Find the Parameter count */
10488 valid_op(state, op);
10489 parameters = table_ops[op].rhs;
10490 if (parameters < 0 ) {
10491 internal_error(state, 0, "Invalid builtin parameter count");
10494 /* Find the function type */
10495 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10496 ftype->elements = parameters;
10497 next = &ftype->right;
10498 va_start(args, rtype);
10499 for(i = 0; i < parameters; i++) {
10500 atype = va_arg(args, struct type *);
10504 *next = new_type(TYPE_PRODUCT, *next, atype);
10505 next = &((*next)->right);
10509 *next = &void_type;
10513 /* Get the initial closure type */
10514 ctype = new_type(TYPE_JOIN, &void_type, 0);
10515 ctype->elements = 1;
10517 /* Get the return type */
10518 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10519 crtype->elements = 2;
10521 /* Generate the needed triples */
10522 def = triple(state, OP_LIST, ftype, 0, 0);
10523 first = label(state);
10524 RHS(def, 0) = first;
10525 result = flatten(state, first, variable(state, crtype));
10526 retvar = flatten(state, first, variable(state, &void_ptr_type));
10527 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10529 /* Now string them together */
10530 param = ftype->right;
10531 for(i = 0; i < parameters; i++) {
10532 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10533 atype = param->left;
10537 arg = flatten(state, first, variable(state, atype));
10538 param = param->right;
10540 work = new_triple(state, op, rtype, -1, parameters);
10541 generate_lhs_pieces(state, work);
10542 for(i = 0; i < parameters; i++) {
10543 RHS(work, i) = read_expr(state, farg(state, def, i));
10545 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10546 work = write_expr(state, deref_index(state, result, 1), work);
10548 work = flatten(state, first, work);
10549 last = flatten(state, first, label(state));
10550 ret = flatten(state, first, ret);
10551 name_len = strlen(name);
10552 ident = lookup(state, name, name_len);
10553 ftype->type_ident = ident;
10554 symbol(state, ident, &ident->sym_ident, def, ftype);
10556 state->file = file.prev;
10557 state->function = 0;
10558 state->main_function = 0;
10560 if (!state->functions) {
10561 state->functions = def;
10563 insert_triple(state, state->functions, def);
10565 if (state->compiler->debug & DEBUG_INLINE) {
10566 FILE *fp = state->dbgout;
10569 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10570 display_func(state, fp, def);
10571 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10575 static struct type *partial_struct(struct compile_state *state,
10576 const char *field_name, struct type *type, struct type *rest)
10578 struct hash_entry *field_ident;
10579 struct type *result;
10580 int field_name_len;
10582 field_name_len = strlen(field_name);
10583 field_ident = lookup(state, field_name, field_name_len);
10585 result = clone_type(0, type);
10586 result->field_ident = field_ident;
10589 result = new_type(TYPE_PRODUCT, result, rest);
10594 static struct type *register_builtin_type(struct compile_state *state,
10595 const char *name, struct type *type)
10597 struct hash_entry *ident;
10600 name_len = strlen(name);
10601 ident = lookup(state, name, name_len);
10603 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10604 ulong_t elements = 0;
10605 struct type *field;
10606 type = new_type(TYPE_STRUCT, type, 0);
10607 field = type->left;
10608 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10610 field = field->right;
10613 symbol(state, ident, &ident->sym_tag, 0, type);
10614 type->type_ident = ident;
10615 type->elements = elements;
10617 symbol(state, ident, &ident->sym_ident, 0, type);
10618 ident->tok = TOK_TYPE_NAME;
10623 static void register_builtins(struct compile_state *state)
10625 struct type *div_type, *ldiv_type;
10626 struct type *udiv_type, *uldiv_type;
10627 struct type *msr_type;
10629 div_type = register_builtin_type(state, "__builtin_div_t",
10630 partial_struct(state, "quot", &int_type,
10631 partial_struct(state, "rem", &int_type, 0)));
10632 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10633 partial_struct(state, "quot", &long_type,
10634 partial_struct(state, "rem", &long_type, 0)));
10635 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10636 partial_struct(state, "quot", &uint_type,
10637 partial_struct(state, "rem", &uint_type, 0)));
10638 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10639 partial_struct(state, "quot", &ulong_type,
10640 partial_struct(state, "rem", &ulong_type, 0)));
10642 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10643 &int_type, &int_type);
10644 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10645 &long_type, &long_type);
10646 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10647 &uint_type, &uint_type);
10648 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10649 &ulong_type, &ulong_type);
10651 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10653 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10655 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10658 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10659 &uchar_type, &ushort_type);
10660 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10661 &ushort_type, &ushort_type);
10662 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10663 &uint_type, &ushort_type);
10665 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10667 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10670 msr_type = register_builtin_type(state, "__builtin_msr_t",
10671 partial_struct(state, "lo", &ulong_type,
10672 partial_struct(state, "hi", &ulong_type, 0)));
10674 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10676 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10677 &ulong_type, &ulong_type, &ulong_type);
10679 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10683 static struct type *declarator(
10684 struct compile_state *state, struct type *type,
10685 struct hash_entry **ident, int need_ident);
10686 static void decl(struct compile_state *state, struct triple *first);
10687 static struct type *specifier_qualifier_list(struct compile_state *state);
10688 #if DEBUG_ROMCC_WARNING
10689 static int isdecl_specifier(int tok);
10691 static struct type *decl_specifiers(struct compile_state *state);
10692 static int istype(int tok);
10693 static struct triple *expr(struct compile_state *state);
10694 static struct triple *assignment_expr(struct compile_state *state);
10695 static struct type *type_name(struct compile_state *state);
10696 static void statement(struct compile_state *state, struct triple *first);
10698 static struct triple *call_expr(
10699 struct compile_state *state, struct triple *func)
10701 struct triple *def;
10702 struct type *param, *type;
10703 ulong_t pvals, index;
10705 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10706 error(state, 0, "Called object is not a function");
10708 if (func->op != OP_LIST) {
10709 internal_error(state, 0, "improper function");
10711 eat(state, TOK_LPAREN);
10712 /* Find the return type without any specifiers */
10713 type = clone_type(0, func->type->left);
10714 /* Count the number of rhs entries for OP_FCALL */
10715 param = func->type->right;
10717 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10719 param = param->right;
10721 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10724 def = new_triple(state, OP_FCALL, type, -1, pvals);
10725 MISC(def, 0) = func;
10727 param = func->type->right;
10728 for(index = 0; index < pvals; index++) {
10729 struct triple *val;
10730 struct type *arg_type;
10731 val = read_expr(state, assignment_expr(state));
10733 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10734 arg_type = param->left;
10736 write_compatible(state, arg_type, val->type);
10737 RHS(def, index) = val;
10738 if (index != (pvals - 1)) {
10739 eat(state, TOK_COMMA);
10740 param = param->right;
10743 eat(state, TOK_RPAREN);
10748 static struct triple *character_constant(struct compile_state *state)
10750 struct triple *def;
10752 const signed char *str, *end;
10755 tk = eat(state, TOK_LIT_CHAR);
10756 str = (signed char *)tk->val.str + 1;
10757 str_len = tk->str_len - 2;
10758 if (str_len <= 0) {
10759 error(state, 0, "empty character constant");
10761 end = str + str_len;
10762 c = char_value(state, &str, end);
10764 error(state, 0, "multibyte character constant not supported");
10766 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10770 static struct triple *string_constant(struct compile_state *state)
10772 struct triple *def;
10775 const signed char *str, *end;
10776 signed char *buf, *ptr;
10780 type = new_type(TYPE_ARRAY, &char_type, 0);
10781 type->elements = 0;
10782 /* The while loop handles string concatenation */
10784 tk = eat(state, TOK_LIT_STRING);
10785 str = (signed char *)tk->val.str + 1;
10786 str_len = tk->str_len - 2;
10788 error(state, 0, "negative string constant length");
10790 /* ignore empty string tokens */
10791 if ('"' == *str && 0 == str[1])
10793 end = str + str_len;
10795 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10796 memcpy(buf, ptr, type->elements);
10797 ptr = buf + type->elements;
10799 *ptr++ = char_value(state, &str, end);
10800 } while(str < end);
10801 type->elements = ptr - buf;
10802 } while(peek(state) == TOK_LIT_STRING);
10804 type->elements += 1;
10805 def = triple(state, OP_BLOBCONST, type, 0, 0);
10812 static struct triple *integer_constant(struct compile_state *state)
10814 struct triple *def;
10821 tk = eat(state, TOK_LIT_INT);
10823 decimal = (tk->val.str[0] != '0');
10824 val = strtoul(tk->val.str, &end, 0);
10825 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10826 error(state, 0, "Integer constant to large");
10829 if ((*end == 'u') || (*end == 'U')) {
10833 if ((*end == 'l') || (*end == 'L')) {
10837 if ((*end == 'u') || (*end == 'U')) {
10842 error(state, 0, "Junk at end of integer constant");
10845 type = &ulong_type;
10849 if (!decimal && (val > LONG_T_MAX)) {
10850 type = &ulong_type;
10855 if (val > UINT_T_MAX) {
10856 type = &ulong_type;
10861 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10864 else if (!decimal && (val > LONG_T_MAX)) {
10865 type = &ulong_type;
10867 else if (val > INT_T_MAX) {
10871 def = int_const(state, type, val);
10875 static struct triple *primary_expr(struct compile_state *state)
10877 struct triple *def;
10883 struct hash_entry *ident;
10884 /* Here ident is either:
10888 ident = eat(state, TOK_IDENT)->ident;
10889 if (!ident->sym_ident) {
10890 error(state, 0, "%s undeclared", ident->name);
10892 def = ident->sym_ident->def;
10895 case TOK_ENUM_CONST:
10897 struct hash_entry *ident;
10898 /* Here ident is an enumeration constant */
10899 ident = eat(state, TOK_ENUM_CONST)->ident;
10900 if (!ident->sym_ident) {
10901 error(state, 0, "%s undeclared", ident->name);
10903 def = ident->sym_ident->def;
10908 struct hash_entry *ident;
10909 ident = eat(state, TOK_MIDENT)->ident;
10910 warning(state, 0, "Replacing undefined macro: %s with 0",
10912 def = int_const(state, &int_type, 0);
10916 eat(state, TOK_LPAREN);
10918 eat(state, TOK_RPAREN);
10921 def = integer_constant(state);
10923 case TOK_LIT_FLOAT:
10924 eat(state, TOK_LIT_FLOAT);
10925 error(state, 0, "Floating point constants not supported");
10930 def = character_constant(state);
10932 case TOK_LIT_STRING:
10933 def = string_constant(state);
10937 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10942 static struct triple *postfix_expr(struct compile_state *state)
10944 struct triple *def;
10946 def = primary_expr(state);
10948 struct triple *left;
10952 switch((tok = peek(state))) {
10954 eat(state, TOK_LBRACKET);
10955 def = mk_subscript_expr(state, left, expr(state));
10956 eat(state, TOK_RBRACKET);
10959 def = call_expr(state, def);
10963 struct hash_entry *field;
10964 eat(state, TOK_DOT);
10965 field = eat(state, TOK_IDENT)->ident;
10966 def = deref_field(state, def, field);
10971 struct hash_entry *field;
10972 eat(state, TOK_ARROW);
10973 field = eat(state, TOK_IDENT)->ident;
10974 def = mk_deref_expr(state, read_expr(state, def));
10975 def = deref_field(state, def, field);
10979 eat(state, TOK_PLUSPLUS);
10980 def = mk_post_inc_expr(state, left);
10982 case TOK_MINUSMINUS:
10983 eat(state, TOK_MINUSMINUS);
10984 def = mk_post_dec_expr(state, left);
10994 static struct triple *cast_expr(struct compile_state *state);
10996 static struct triple *unary_expr(struct compile_state *state)
10998 struct triple *def, *right;
11000 switch((tok = peek(state))) {
11002 eat(state, TOK_PLUSPLUS);
11003 def = mk_pre_inc_expr(state, unary_expr(state));
11005 case TOK_MINUSMINUS:
11006 eat(state, TOK_MINUSMINUS);
11007 def = mk_pre_dec_expr(state, unary_expr(state));
11010 eat(state, TOK_AND);
11011 def = mk_addr_expr(state, cast_expr(state), 0);
11014 eat(state, TOK_STAR);
11015 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11018 eat(state, TOK_PLUS);
11019 right = read_expr(state, cast_expr(state));
11020 arithmetic(state, right);
11021 def = integral_promotion(state, right);
11024 eat(state, TOK_MINUS);
11025 right = read_expr(state, cast_expr(state));
11026 arithmetic(state, right);
11027 def = integral_promotion(state, right);
11028 def = triple(state, OP_NEG, def->type, def, 0);
11031 eat(state, TOK_TILDE);
11032 right = read_expr(state, cast_expr(state));
11033 integral(state, right);
11034 def = integral_promotion(state, right);
11035 def = triple(state, OP_INVERT, def->type, def, 0);
11038 eat(state, TOK_BANG);
11039 right = read_expr(state, cast_expr(state));
11040 bool(state, right);
11041 def = lfalse_expr(state, right);
11047 eat(state, TOK_SIZEOF);
11048 tok1 = peek(state);
11049 tok2 = peek2(state);
11050 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11051 eat(state, TOK_LPAREN);
11052 type = type_name(state);
11053 eat(state, TOK_RPAREN);
11056 struct triple *expr;
11057 expr = unary_expr(state);
11059 release_expr(state, expr);
11061 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11068 eat(state, TOK_ALIGNOF);
11069 tok1 = peek(state);
11070 tok2 = peek2(state);
11071 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11072 eat(state, TOK_LPAREN);
11073 type = type_name(state);
11074 eat(state, TOK_RPAREN);
11077 struct triple *expr;
11078 expr = unary_expr(state);
11080 release_expr(state, expr);
11082 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11087 /* We only come here if we are called from the preprocessor */
11088 struct hash_entry *ident;
11090 eat(state, TOK_MDEFINED);
11092 if (pp_peek(state) == TOK_LPAREN) {
11093 pp_eat(state, TOK_LPAREN);
11096 ident = pp_eat(state, TOK_MIDENT)->ident;
11098 eat(state, TOK_RPAREN);
11100 def = int_const(state, &int_type, ident->sym_define != 0);
11104 def = postfix_expr(state);
11110 static struct triple *cast_expr(struct compile_state *state)
11112 struct triple *def;
11114 tok1 = peek(state);
11115 tok2 = peek2(state);
11116 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11118 eat(state, TOK_LPAREN);
11119 type = type_name(state);
11120 eat(state, TOK_RPAREN);
11121 def = mk_cast_expr(state, type, cast_expr(state));
11124 def = unary_expr(state);
11129 static struct triple *mult_expr(struct compile_state *state)
11131 struct triple *def;
11133 def = cast_expr(state);
11135 struct triple *left, *right;
11136 struct type *result_type;
11144 left = read_expr(state, def);
11145 arithmetic(state, left);
11149 right = read_expr(state, cast_expr(state));
11150 arithmetic(state, right);
11152 result_type = arithmetic_result(state, left, right);
11153 sign = is_signed(result_type);
11156 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11157 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11158 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11160 def = triple(state, op, result_type, left, right);
11170 static struct triple *add_expr(struct compile_state *state)
11172 struct triple *def;
11174 def = mult_expr(state);
11177 switch( peek(state)) {
11179 eat(state, TOK_PLUS);
11180 def = mk_add_expr(state, def, mult_expr(state));
11183 eat(state, TOK_MINUS);
11184 def = mk_sub_expr(state, def, mult_expr(state));
11194 static struct triple *shift_expr(struct compile_state *state)
11196 struct triple *def;
11198 def = add_expr(state);
11200 struct triple *left, *right;
11203 switch((tok = peek(state))) {
11206 left = read_expr(state, def);
11207 integral(state, left);
11208 left = integral_promotion(state, left);
11212 right = read_expr(state, add_expr(state));
11213 integral(state, right);
11214 right = integral_promotion(state, right);
11216 op = (tok == TOK_SL)? OP_SL :
11217 is_signed(left->type)? OP_SSR: OP_USR;
11219 def = triple(state, op, left->type, left, right);
11229 static struct triple *relational_expr(struct compile_state *state)
11231 #if DEBUG_ROMCC_WARNINGS
11232 #warning "Extend relational exprs to work on more than arithmetic types"
11234 struct triple *def;
11236 def = shift_expr(state);
11238 struct triple *left, *right;
11239 struct type *arg_type;
11242 switch((tok = peek(state))) {
11247 left = read_expr(state, def);
11248 arithmetic(state, left);
11252 right = read_expr(state, shift_expr(state));
11253 arithmetic(state, right);
11255 arg_type = arithmetic_result(state, left, right);
11256 sign = is_signed(arg_type);
11259 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11260 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11261 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11262 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11264 def = triple(state, op, &int_type, left, right);
11274 static struct triple *equality_expr(struct compile_state *state)
11276 #if DEBUG_ROMCC_WARNINGS
11277 #warning "Extend equality exprs to work on more than arithmetic types"
11279 struct triple *def;
11281 def = relational_expr(state);
11283 struct triple *left, *right;
11286 switch((tok = peek(state))) {
11289 left = read_expr(state, def);
11290 arithmetic(state, left);
11292 right = read_expr(state, relational_expr(state));
11293 arithmetic(state, right);
11294 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11295 def = triple(state, op, &int_type, left, right);
11305 static struct triple *and_expr(struct compile_state *state)
11307 struct triple *def;
11308 def = equality_expr(state);
11309 while(peek(state) == TOK_AND) {
11310 struct triple *left, *right;
11311 struct type *result_type;
11312 left = read_expr(state, def);
11313 integral(state, left);
11314 eat(state, TOK_AND);
11315 right = read_expr(state, equality_expr(state));
11316 integral(state, right);
11317 result_type = arithmetic_result(state, left, right);
11318 def = triple(state, OP_AND, result_type, left, right);
11323 static struct triple *xor_expr(struct compile_state *state)
11325 struct triple *def;
11326 def = and_expr(state);
11327 while(peek(state) == TOK_XOR) {
11328 struct triple *left, *right;
11329 struct type *result_type;
11330 left = read_expr(state, def);
11331 integral(state, left);
11332 eat(state, TOK_XOR);
11333 right = read_expr(state, and_expr(state));
11334 integral(state, right);
11335 result_type = arithmetic_result(state, left, right);
11336 def = triple(state, OP_XOR, result_type, left, right);
11341 static struct triple *or_expr(struct compile_state *state)
11343 struct triple *def;
11344 def = xor_expr(state);
11345 while(peek(state) == TOK_OR) {
11346 struct triple *left, *right;
11347 struct type *result_type;
11348 left = read_expr(state, def);
11349 integral(state, left);
11350 eat(state, TOK_OR);
11351 right = read_expr(state, xor_expr(state));
11352 integral(state, right);
11353 result_type = arithmetic_result(state, left, right);
11354 def = triple(state, OP_OR, result_type, left, right);
11359 static struct triple *land_expr(struct compile_state *state)
11361 struct triple *def;
11362 def = or_expr(state);
11363 while(peek(state) == TOK_LOGAND) {
11364 struct triple *left, *right;
11365 left = read_expr(state, def);
11367 eat(state, TOK_LOGAND);
11368 right = read_expr(state, or_expr(state));
11369 bool(state, right);
11371 def = mkland_expr(state,
11372 ltrue_expr(state, left),
11373 ltrue_expr(state, right));
11378 static struct triple *lor_expr(struct compile_state *state)
11380 struct triple *def;
11381 def = land_expr(state);
11382 while(peek(state) == TOK_LOGOR) {
11383 struct triple *left, *right;
11384 left = read_expr(state, def);
11386 eat(state, TOK_LOGOR);
11387 right = read_expr(state, land_expr(state));
11388 bool(state, right);
11390 def = mklor_expr(state,
11391 ltrue_expr(state, left),
11392 ltrue_expr(state, right));
11397 static struct triple *conditional_expr(struct compile_state *state)
11399 struct triple *def;
11400 def = lor_expr(state);
11401 if (peek(state) == TOK_QUEST) {
11402 struct triple *test, *left, *right;
11404 test = ltrue_expr(state, read_expr(state, def));
11405 eat(state, TOK_QUEST);
11406 left = read_expr(state, expr(state));
11407 eat(state, TOK_COLON);
11408 right = read_expr(state, conditional_expr(state));
11410 def = mkcond_expr(state, test, left, right);
11416 struct triple *val;
11420 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11421 struct triple *dest, struct triple *val)
11423 if (cv[dest->id].val) {
11424 free_triple(state, cv[dest->id].val);
11426 cv[dest->id].val = val;
11428 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11429 struct triple *src)
11431 return cv[src->id].val;
11434 static struct triple *eval_const_expr(
11435 struct compile_state *state, struct triple *expr)
11437 struct triple *def;
11438 if (is_const(expr)) {
11442 /* If we don't start out as a constant simplify into one */
11443 struct triple *head, *ptr;
11444 struct cv_triple *cv;
11446 head = label(state); /* dummy initial triple */
11447 flatten(state, head, expr);
11449 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11452 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11454 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11456 cv[i].id = ptr->id;
11462 valid_ins(state, ptr);
11463 if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11464 internal_error(state, ptr,
11465 "unexpected %s in constant expression",
11468 else if (ptr->op == OP_LIST) {
11470 else if (triple_is_structural(state, ptr)) {
11473 else if (triple_is_ubranch(state, ptr)) {
11474 ptr = TARG(ptr, 0);
11476 else if (triple_is_cbranch(state, ptr)) {
11477 struct triple *cond_val;
11478 cond_val = get_cv(state, cv, RHS(ptr, 0));
11479 if (!cond_val || !is_const(cond_val) ||
11480 (cond_val->op != OP_INTCONST))
11482 internal_error(state, ptr, "bad branch condition");
11484 if (cond_val->u.cval == 0) {
11487 ptr = TARG(ptr, 0);
11490 else if (triple_is_branch(state, ptr)) {
11491 error(state, ptr, "bad branch type in constant expression");
11493 else if (ptr->op == OP_WRITE) {
11494 struct triple *val;
11495 val = get_cv(state, cv, RHS(ptr, 0));
11497 set_cv(state, cv, MISC(ptr, 0),
11498 copy_triple(state, val));
11499 set_cv(state, cv, ptr,
11500 copy_triple(state, val));
11503 else if (ptr->op == OP_READ) {
11504 set_cv(state, cv, ptr,
11506 get_cv(state, cv, RHS(ptr, 0))));
11509 else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11510 struct triple *val, **rhs;
11511 val = copy_triple(state, ptr);
11512 rhs = triple_rhs(state, val, 0);
11513 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11515 internal_error(state, ptr, "Missing rhs");
11517 *rhs = get_cv(state, cv, *rhs);
11519 simplify(state, val);
11520 set_cv(state, cv, ptr, val);
11524 error(state, ptr, "impure operation in constant expression");
11527 } while(ptr != head);
11529 /* Get the result value */
11530 def = get_cv(state, cv, head->prev);
11531 cv[head->prev->id].val = 0;
11533 /* Free the temporary values */
11534 for(i = 0; i < count; i++) {
11536 free_triple(state, cv[i].val);
11541 /* Free the intermediate expressions */
11542 while(head->next != head) {
11543 release_triple(state, head->next);
11545 free_triple(state, head);
11547 if (!is_const(def)) {
11548 error(state, expr, "Not a constant expression");
11553 static struct triple *constant_expr(struct compile_state *state)
11555 return eval_const_expr(state, conditional_expr(state));
11558 static struct triple *assignment_expr(struct compile_state *state)
11560 struct triple *def, *left, *right;
11562 /* The C grammer in K&R shows assignment expressions
11563 * only taking unary expressions as input on their
11564 * left hand side. But specifies the precedence of
11565 * assignemnt as the lowest operator except for comma.
11567 * Allowing conditional expressions on the left hand side
11568 * of an assignement results in a grammar that accepts
11569 * a larger set of statements than standard C. As long
11570 * as the subset of the grammar that is standard C behaves
11571 * correctly this should cause no problems.
11573 * For the extra token strings accepted by the grammar
11574 * none of them should produce a valid lvalue, so they
11575 * should not produce functioning programs.
11577 * GCC has this bug as well, so surprises should be minimal.
11579 def = conditional_expr(state);
11581 switch((tok = peek(state))) {
11583 lvalue(state, left);
11584 eat(state, TOK_EQ);
11585 def = write_expr(state, left,
11586 read_expr(state, assignment_expr(state)));
11591 lvalue(state, left);
11592 arithmetic(state, left);
11594 right = read_expr(state, assignment_expr(state));
11595 arithmetic(state, right);
11597 sign = is_signed(left->type);
11600 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11601 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11602 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11604 def = write_expr(state, left,
11605 triple(state, op, left->type,
11606 read_expr(state, copy_triple(state, left)), right));
11609 lvalue(state, left);
11610 eat(state, TOK_PLUSEQ);
11611 def = write_expr(state, left,
11612 mk_add_expr(state, copy_triple(state, left), assignment_expr(state)));
11615 lvalue(state, left);
11616 eat(state, TOK_MINUSEQ);
11617 def = write_expr(state, left,
11618 mk_sub_expr(state, copy_triple(state, left), assignment_expr(state)));
11625 lvalue(state, left);
11626 integral(state, left);
11628 right = read_expr(state, assignment_expr(state));
11629 integral(state, right);
11630 right = integral_promotion(state, right);
11631 sign = is_signed(left->type);
11634 case TOK_SLEQ: op = OP_SL; break;
11635 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11636 case TOK_ANDEQ: op = OP_AND; break;
11637 case TOK_XOREQ: op = OP_XOR; break;
11638 case TOK_OREQ: op = OP_OR; break;
11640 def = write_expr(state, left,
11641 triple(state, op, left->type,
11642 read_expr(state, copy_triple(state,left)), right));
11648 static struct triple *expr(struct compile_state *state)
11650 struct triple *def;
11651 def = assignment_expr(state);
11652 while(peek(state) == TOK_COMMA) {
11653 eat(state, TOK_COMMA);
11654 def = mkprog(state, def, assignment_expr(state), 0UL);
11659 static void expr_statement(struct compile_state *state, struct triple *first)
11661 if (peek(state) != TOK_SEMI) {
11662 /* lvalue conversions always apply except when certian operators
11663 * are applied. I apply the lvalue conversions here
11664 * as I know no more operators will be applied.
11666 flatten(state, first, lvalue_conversion(state, expr(state)));
11668 eat(state, TOK_SEMI);
11671 static void if_statement(struct compile_state *state, struct triple *first)
11673 struct triple *test, *jmp1, *jmp2, *middle, *end;
11675 jmp1 = jmp2 = middle = 0;
11676 eat(state, TOK_IF);
11677 eat(state, TOK_LPAREN);
11678 test = expr(state);
11680 /* Cleanup and invert the test */
11681 test = lfalse_expr(state, read_expr(state, test));
11682 eat(state, TOK_RPAREN);
11683 /* Generate the needed pieces */
11684 middle = label(state);
11685 jmp1 = branch(state, middle, test);
11686 /* Thread the pieces together */
11687 flatten(state, first, test);
11688 flatten(state, first, jmp1);
11689 flatten(state, first, label(state));
11690 statement(state, first);
11691 if (peek(state) == TOK_ELSE) {
11692 eat(state, TOK_ELSE);
11693 /* Generate the rest of the pieces */
11694 end = label(state);
11695 jmp2 = branch(state, end, 0);
11696 /* Thread them together */
11697 flatten(state, first, jmp2);
11698 flatten(state, first, middle);
11699 statement(state, first);
11700 flatten(state, first, end);
11703 flatten(state, first, middle);
11707 static void for_statement(struct compile_state *state, struct triple *first)
11709 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11710 struct triple *label1, *label2, *label3;
11711 struct hash_entry *ident;
11713 eat(state, TOK_FOR);
11714 eat(state, TOK_LPAREN);
11715 head = test = tail = jmp1 = jmp2 = 0;
11716 if (peek(state) != TOK_SEMI) {
11717 head = expr(state);
11719 eat(state, TOK_SEMI);
11720 if (peek(state) != TOK_SEMI) {
11721 test = expr(state);
11723 test = ltrue_expr(state, read_expr(state, test));
11725 eat(state, TOK_SEMI);
11726 if (peek(state) != TOK_RPAREN) {
11727 tail = expr(state);
11729 eat(state, TOK_RPAREN);
11730 /* Generate the needed pieces */
11731 label1 = label(state);
11732 label2 = label(state);
11733 label3 = label(state);
11735 jmp1 = branch(state, label3, 0);
11736 jmp2 = branch(state, label1, test);
11739 jmp2 = branch(state, label1, 0);
11741 end = label(state);
11742 /* Remember where break and continue go */
11743 start_scope(state);
11744 ident = state->i_break;
11745 symbol(state, ident, &ident->sym_ident, end, end->type);
11746 ident = state->i_continue;
11747 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11748 /* Now include the body */
11749 flatten(state, first, head);
11750 flatten(state, first, jmp1);
11751 flatten(state, first, label1);
11752 statement(state, first);
11753 flatten(state, first, label2);
11754 flatten(state, first, tail);
11755 flatten(state, first, label3);
11756 flatten(state, first, test);
11757 flatten(state, first, jmp2);
11758 flatten(state, first, end);
11759 /* Cleanup the break/continue scope */
11763 static void while_statement(struct compile_state *state, struct triple *first)
11765 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11766 struct hash_entry *ident;
11767 eat(state, TOK_WHILE);
11768 eat(state, TOK_LPAREN);
11769 test = expr(state);
11771 test = ltrue_expr(state, read_expr(state, test));
11772 eat(state, TOK_RPAREN);
11773 /* Generate the needed pieces */
11774 label1 = label(state);
11775 label2 = label(state);
11776 jmp1 = branch(state, label2, 0);
11777 jmp2 = branch(state, label1, test);
11778 end = label(state);
11779 /* Remember where break and continue go */
11780 start_scope(state);
11781 ident = state->i_break;
11782 symbol(state, ident, &ident->sym_ident, end, end->type);
11783 ident = state->i_continue;
11784 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11785 /* Thread them together */
11786 flatten(state, first, jmp1);
11787 flatten(state, first, label1);
11788 statement(state, first);
11789 flatten(state, first, label2);
11790 flatten(state, first, test);
11791 flatten(state, first, jmp2);
11792 flatten(state, first, end);
11793 /* Cleanup the break/continue scope */
11797 static void do_statement(struct compile_state *state, struct triple *first)
11799 struct triple *label1, *label2, *test, *end;
11800 struct hash_entry *ident;
11801 eat(state, TOK_DO);
11802 /* Generate the needed pieces */
11803 label1 = label(state);
11804 label2 = label(state);
11805 end = label(state);
11806 /* Remember where break and continue go */
11807 start_scope(state);
11808 ident = state->i_break;
11809 symbol(state, ident, &ident->sym_ident, end, end->type);
11810 ident = state->i_continue;
11811 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11812 /* Now include the body */
11813 flatten(state, first, label1);
11814 statement(state, first);
11815 /* Cleanup the break/continue scope */
11817 /* Eat the rest of the loop */
11818 eat(state, TOK_WHILE);
11819 eat(state, TOK_LPAREN);
11820 test = read_expr(state, expr(state));
11822 eat(state, TOK_RPAREN);
11823 eat(state, TOK_SEMI);
11824 /* Thread the pieces together */
11825 test = ltrue_expr(state, test);
11826 flatten(state, first, label2);
11827 flatten(state, first, test);
11828 flatten(state, first, branch(state, label1, test));
11829 flatten(state, first, end);
11833 static void return_statement(struct compile_state *state, struct triple *first)
11835 struct triple *jmp, *mv, *dest, *var, *val;
11837 eat(state, TOK_RETURN);
11839 #if DEBUG_ROMCC_WARNINGS
11840 #warning "FIXME implement a more general excess branch elimination"
11843 /* If we have a return value do some more work */
11844 if (peek(state) != TOK_SEMI) {
11845 val = read_expr(state, expr(state));
11847 eat(state, TOK_SEMI);
11849 /* See if this last statement in a function */
11850 last = ((peek(state) == TOK_RBRACE) &&
11851 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11853 /* Find the return variable */
11854 var = fresult(state, state->main_function);
11856 /* Find the return destination */
11857 dest = state->i_return->sym_ident->def;
11859 /* If needed generate a jump instruction */
11861 jmp = branch(state, dest, 0);
11863 /* If needed generate an assignment instruction */
11865 mv = write_expr(state, deref_index(state, var, 1), val);
11867 /* Now put the code together */
11869 flatten(state, first, mv);
11870 flatten(state, first, jmp);
11873 flatten(state, first, jmp);
11877 static void break_statement(struct compile_state *state, struct triple *first)
11879 struct triple *dest;
11880 eat(state, TOK_BREAK);
11881 eat(state, TOK_SEMI);
11882 if (!state->i_break->sym_ident) {
11883 error(state, 0, "break statement not within loop or switch");
11885 dest = state->i_break->sym_ident->def;
11886 flatten(state, first, branch(state, dest, 0));
11889 static void continue_statement(struct compile_state *state, struct triple *first)
11891 struct triple *dest;
11892 eat(state, TOK_CONTINUE);
11893 eat(state, TOK_SEMI);
11894 if (!state->i_continue->sym_ident) {
11895 error(state, 0, "continue statement outside of a loop");
11897 dest = state->i_continue->sym_ident->def;
11898 flatten(state, first, branch(state, dest, 0));
11901 static void goto_statement(struct compile_state *state, struct triple *first)
11903 struct hash_entry *ident;
11904 eat(state, TOK_GOTO);
11905 ident = eat(state, TOK_IDENT)->ident;
11906 if (!ident->sym_label) {
11907 /* If this is a forward branch allocate the label now,
11908 * it will be flattend in the appropriate location later.
11910 struct triple *ins;
11911 ins = label(state);
11912 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11914 eat(state, TOK_SEMI);
11916 flatten(state, first, branch(state, ident->sym_label->def, 0));
11919 static void labeled_statement(struct compile_state *state, struct triple *first)
11921 struct triple *ins;
11922 struct hash_entry *ident;
11924 ident = eat(state, TOK_IDENT)->ident;
11925 if (ident->sym_label && ident->sym_label->def) {
11926 ins = ident->sym_label->def;
11927 put_occurance(ins->occurance);
11928 ins->occurance = new_occurance(state);
11931 ins = label(state);
11932 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11934 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11935 error(state, 0, "label %s already defined", ident->name);
11937 flatten(state, first, ins);
11939 eat(state, TOK_COLON);
11940 statement(state, first);
11943 static void switch_statement(struct compile_state *state, struct triple *first)
11945 struct triple *value, *top, *end, *dbranch;
11946 struct hash_entry *ident;
11948 /* See if we have a valid switch statement */
11949 eat(state, TOK_SWITCH);
11950 eat(state, TOK_LPAREN);
11951 value = expr(state);
11952 integral(state, value);
11953 value = read_expr(state, value);
11954 eat(state, TOK_RPAREN);
11955 /* Generate the needed pieces */
11956 top = label(state);
11957 end = label(state);
11958 dbranch = branch(state, end, 0);
11959 /* Remember where case branches and break goes */
11960 start_scope(state);
11961 ident = state->i_switch;
11962 symbol(state, ident, &ident->sym_ident, value, value->type);
11963 ident = state->i_case;
11964 symbol(state, ident, &ident->sym_ident, top, top->type);
11965 ident = state->i_break;
11966 symbol(state, ident, &ident->sym_ident, end, end->type);
11967 ident = state->i_default;
11968 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11969 /* Thread them together */
11970 flatten(state, first, value);
11971 flatten(state, first, top);
11972 flatten(state, first, dbranch);
11973 statement(state, first);
11974 flatten(state, first, end);
11975 /* Cleanup the switch scope */
11979 static void case_statement(struct compile_state *state, struct triple *first)
11981 struct triple *cvalue, *dest, *test, *jmp;
11982 struct triple *ptr, *value, *top, *dbranch;
11984 /* See if w have a valid case statement */
11985 eat(state, TOK_CASE);
11986 cvalue = constant_expr(state);
11987 integral(state, cvalue);
11988 if (cvalue->op != OP_INTCONST) {
11989 error(state, 0, "integer constant expected");
11991 eat(state, TOK_COLON);
11992 if (!state->i_case->sym_ident) {
11993 error(state, 0, "case statement not within a switch");
11996 /* Lookup the interesting pieces */
11997 top = state->i_case->sym_ident->def;
11998 value = state->i_switch->sym_ident->def;
11999 dbranch = state->i_default->sym_ident->def;
12001 /* See if this case label has already been used */
12002 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
12003 if (ptr->op != OP_EQ) {
12006 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
12007 error(state, 0, "duplicate case %d statement",
12011 /* Generate the needed pieces */
12012 dest = label(state);
12013 test = triple(state, OP_EQ, &int_type, value, cvalue);
12014 jmp = branch(state, dest, test);
12015 /* Thread the pieces together */
12016 flatten(state, dbranch, test);
12017 flatten(state, dbranch, jmp);
12018 flatten(state, dbranch, label(state));
12019 flatten(state, first, dest);
12020 statement(state, first);
12023 static void default_statement(struct compile_state *state, struct triple *first)
12025 struct triple *dest;
12026 struct triple *dbranch, *end;
12028 /* See if we have a valid default statement */
12029 eat(state, TOK_DEFAULT);
12030 eat(state, TOK_COLON);
12032 if (!state->i_case->sym_ident) {
12033 error(state, 0, "default statement not within a switch");
12036 /* Lookup the interesting pieces */
12037 dbranch = state->i_default->sym_ident->def;
12038 end = state->i_break->sym_ident->def;
12040 /* See if a default statement has already happened */
12041 if (TARG(dbranch, 0) != end) {
12042 error(state, 0, "duplicate default statement");
12045 /* Generate the needed pieces */
12046 dest = label(state);
12048 /* Blame the branch on the default statement */
12049 put_occurance(dbranch->occurance);
12050 dbranch->occurance = new_occurance(state);
12052 /* Thread the pieces together */
12053 TARG(dbranch, 0) = dest;
12054 use_triple(dest, dbranch);
12055 flatten(state, first, dest);
12056 statement(state, first);
12059 static void asm_statement(struct compile_state *state, struct triple *first)
12061 struct asm_info *info;
12063 struct triple *constraint;
12064 struct triple *expr;
12065 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12066 struct triple *def, *asm_str;
12067 int out, in, clobbers, more, colons, i;
12071 eat(state, TOK_ASM);
12072 /* For now ignore the qualifiers */
12073 switch(peek(state)) {
12075 eat(state, TOK_CONST);
12078 eat(state, TOK_VOLATILE);
12079 flags |= TRIPLE_FLAG_VOLATILE;
12082 eat(state, TOK_LPAREN);
12083 asm_str = string_constant(state);
12086 out = in = clobbers = 0;
12088 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12089 eat(state, TOK_COLON);
12091 more = (peek(state) == TOK_LIT_STRING);
12093 struct triple *var;
12094 struct triple *constraint;
12097 if (out > MAX_LHS) {
12098 error(state, 0, "Maximum output count exceeded.");
12100 constraint = string_constant(state);
12101 str = constraint->u.blob;
12102 if (str[0] != '=') {
12103 error(state, 0, "Output constraint does not start with =");
12105 constraint->u.blob = str + 1;
12106 eat(state, TOK_LPAREN);
12107 var = conditional_expr(state);
12108 eat(state, TOK_RPAREN);
12110 lvalue(state, var);
12111 out_param[out].constraint = constraint;
12112 out_param[out].expr = var;
12113 if (peek(state) == TOK_COMMA) {
12114 eat(state, TOK_COMMA);
12121 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12122 eat(state, TOK_COLON);
12124 more = (peek(state) == TOK_LIT_STRING);
12126 struct triple *val;
12127 struct triple *constraint;
12130 if (in > MAX_RHS) {
12131 error(state, 0, "Maximum input count exceeded.");
12133 constraint = string_constant(state);
12134 str = constraint->u.blob;
12135 if (digitp(str[0] && str[1] == '\0')) {
12137 val = digval(str[0]);
12138 if ((val < 0) || (val >= out)) {
12139 error(state, 0, "Invalid input constraint %d", val);
12142 eat(state, TOK_LPAREN);
12143 val = conditional_expr(state);
12144 eat(state, TOK_RPAREN);
12146 in_param[in].constraint = constraint;
12147 in_param[in].expr = val;
12148 if (peek(state) == TOK_COMMA) {
12149 eat(state, TOK_COMMA);
12157 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12158 eat(state, TOK_COLON);
12160 more = (peek(state) == TOK_LIT_STRING);
12162 struct triple *clobber;
12164 if ((clobbers + out) > MAX_LHS) {
12165 error(state, 0, "Maximum clobber limit exceeded.");
12167 clobber = string_constant(state);
12169 clob_param[clobbers].constraint = clobber;
12170 if (peek(state) == TOK_COMMA) {
12171 eat(state, TOK_COMMA);
12177 eat(state, TOK_RPAREN);
12178 eat(state, TOK_SEMI);
12181 info = xcmalloc(sizeof(*info), "asm_info");
12182 info->str = asm_str->u.blob;
12183 free_triple(state, asm_str);
12185 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12186 def->u.ainfo = info;
12189 /* Find the register constraints */
12190 for(i = 0; i < out; i++) {
12191 struct triple *constraint;
12192 constraint = out_param[i].constraint;
12193 info->tmpl.lhs[i] = arch_reg_constraint(state,
12194 out_param[i].expr->type, constraint->u.blob);
12195 free_triple(state, constraint);
12197 for(; i - out < clobbers; i++) {
12198 struct triple *constraint;
12199 constraint = clob_param[i - out].constraint;
12200 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12201 free_triple(state, constraint);
12203 for(i = 0; i < in; i++) {
12204 struct triple *constraint;
12206 constraint = in_param[i].constraint;
12207 str = constraint->u.blob;
12208 if (digitp(str[0]) && str[1] == '\0') {
12209 struct reg_info cinfo;
12211 val = digval(str[0]);
12212 cinfo.reg = info->tmpl.lhs[val].reg;
12213 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12214 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12215 if (cinfo.reg == REG_UNSET) {
12216 cinfo.reg = REG_VIRT0 + val;
12218 if (cinfo.regcm == 0) {
12219 error(state, 0, "No registers for %d", val);
12221 info->tmpl.lhs[val] = cinfo;
12222 info->tmpl.rhs[i] = cinfo;
12225 info->tmpl.rhs[i] = arch_reg_constraint(state,
12226 in_param[i].expr->type, str);
12228 free_triple(state, constraint);
12231 /* Now build the helper expressions */
12232 for(i = 0; i < in; i++) {
12233 RHS(def, i) = read_expr(state, in_param[i].expr);
12235 flatten(state, first, def);
12236 for(i = 0; i < (out + clobbers); i++) {
12238 struct triple *piece;
12240 type = out_param[i].expr->type;
12242 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12243 if (size >= SIZEOF_LONG) {
12244 type = &ulong_type;
12246 else if (size >= SIZEOF_INT) {
12249 else if (size >= SIZEOF_SHORT) {
12250 type = &ushort_type;
12253 type = &uchar_type;
12256 piece = triple(state, OP_PIECE, type, def, 0);
12258 LHS(def, i) = piece;
12259 flatten(state, first, piece);
12261 /* And write the helpers to their destinations */
12262 for(i = 0; i < out; i++) {
12263 struct triple *piece;
12264 piece = LHS(def, i);
12265 flatten(state, first,
12266 write_expr(state, out_param[i].expr, piece));
12271 static int isdecl(int tok)
12294 case TOK_TYPE_NAME: /* typedef name */
12301 static void compound_statement(struct compile_state *state, struct triple *first)
12303 eat(state, TOK_LBRACE);
12304 start_scope(state);
12306 /* statement-list opt */
12307 while (peek(state) != TOK_RBRACE) {
12308 statement(state, first);
12311 eat(state, TOK_RBRACE);
12314 static void statement(struct compile_state *state, struct triple *first)
12318 if (tok == TOK_LBRACE) {
12319 compound_statement(state, first);
12321 else if (tok == TOK_IF) {
12322 if_statement(state, first);
12324 else if (tok == TOK_FOR) {
12325 for_statement(state, first);
12327 else if (tok == TOK_WHILE) {
12328 while_statement(state, first);
12330 else if (tok == TOK_DO) {
12331 do_statement(state, first);
12333 else if (tok == TOK_RETURN) {
12334 return_statement(state, first);
12336 else if (tok == TOK_BREAK) {
12337 break_statement(state, first);
12339 else if (tok == TOK_CONTINUE) {
12340 continue_statement(state, first);
12342 else if (tok == TOK_GOTO) {
12343 goto_statement(state, first);
12345 else if (tok == TOK_SWITCH) {
12346 switch_statement(state, first);
12348 else if (tok == TOK_ASM) {
12349 asm_statement(state, first);
12351 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12352 labeled_statement(state, first);
12354 else if (tok == TOK_CASE) {
12355 case_statement(state, first);
12357 else if (tok == TOK_DEFAULT) {
12358 default_statement(state, first);
12360 else if (isdecl(tok)) {
12361 /* This handles C99 intermixing of statements and decls */
12362 decl(state, first);
12365 expr_statement(state, first);
12369 static struct type *param_decl(struct compile_state *state)
12372 struct hash_entry *ident;
12373 /* Cheat so the declarator will know we are not global */
12374 start_scope(state);
12376 type = decl_specifiers(state);
12377 type = declarator(state, type, &ident, 0);
12378 type->field_ident = ident;
12383 static struct type *param_type_list(struct compile_state *state, struct type *type)
12385 struct type *ftype, **next;
12386 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12387 next = &ftype->right;
12388 ftype->elements = 1;
12389 while(peek(state) == TOK_COMMA) {
12390 eat(state, TOK_COMMA);
12391 if (peek(state) == TOK_DOTS) {
12392 eat(state, TOK_DOTS);
12393 error(state, 0, "variadic functions not supported");
12396 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12397 next = &((*next)->right);
12404 static struct type *type_name(struct compile_state *state)
12407 type = specifier_qualifier_list(state);
12408 /* abstract-declarator (may consume no tokens) */
12409 type = declarator(state, type, 0, 0);
12413 static struct type *direct_declarator(
12414 struct compile_state *state, struct type *type,
12415 struct hash_entry **pident, int need_ident)
12417 struct hash_entry *ident;
12418 struct type *outer;
12421 arrays_complete(state, type);
12422 switch(peek(state)) {
12424 ident = eat(state, TOK_IDENT)->ident;
12426 error(state, 0, "Unexpected identifier found");
12428 /* The name of what we are declaring */
12432 eat(state, TOK_LPAREN);
12433 outer = declarator(state, type, pident, need_ident);
12434 eat(state, TOK_RPAREN);
12438 error(state, 0, "Identifier expected");
12444 arrays_complete(state, type);
12445 switch(peek(state)) {
12447 eat(state, TOK_LPAREN);
12448 type = param_type_list(state, type);
12449 eat(state, TOK_RPAREN);
12453 unsigned int qualifiers;
12454 struct triple *value;
12456 eat(state, TOK_LBRACKET);
12457 if (peek(state) != TOK_RBRACKET) {
12458 value = constant_expr(state);
12459 integral(state, value);
12461 eat(state, TOK_RBRACKET);
12463 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12464 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12466 type->elements = value->u.cval;
12467 free_triple(state, value);
12469 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12480 struct type *inner;
12481 arrays_complete(state, type);
12483 for(inner = outer; inner->left; inner = inner->left)
12485 inner->left = type;
12491 static struct type *declarator(
12492 struct compile_state *state, struct type *type,
12493 struct hash_entry **pident, int need_ident)
12495 while(peek(state) == TOK_STAR) {
12496 eat(state, TOK_STAR);
12497 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12499 type = direct_declarator(state, type, pident, need_ident);
12503 static struct type *typedef_name(
12504 struct compile_state *state, unsigned int specifiers)
12506 struct hash_entry *ident;
12508 ident = eat(state, TOK_TYPE_NAME)->ident;
12509 type = ident->sym_ident->type;
12510 specifiers |= type->type & QUAL_MASK;
12511 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12512 (type->type & (STOR_MASK | QUAL_MASK))) {
12513 type = clone_type(specifiers, type);
12518 static struct type *enum_specifier(
12519 struct compile_state *state, unsigned int spec)
12521 struct hash_entry *ident;
12524 struct type *enum_type;
12527 eat(state, TOK_ENUM);
12529 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12530 ident = eat(state, tok)->ident;
12533 if (!ident || (peek(state) == TOK_LBRACE)) {
12534 struct type **next;
12535 eat(state, TOK_LBRACE);
12536 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12537 enum_type->type_ident = ident;
12538 next = &enum_type->right;
12540 struct hash_entry *eident;
12541 struct triple *value;
12542 struct type *entry;
12543 eident = eat(state, TOK_IDENT)->ident;
12544 if (eident->sym_ident) {
12545 error(state, 0, "%s already declared",
12548 eident->tok = TOK_ENUM_CONST;
12549 if (peek(state) == TOK_EQ) {
12550 struct triple *val;
12551 eat(state, TOK_EQ);
12552 val = constant_expr(state);
12553 integral(state, val);
12554 base = val->u.cval;
12556 value = int_const(state, &int_type, base);
12557 symbol(state, eident, &eident->sym_ident, value, &int_type);
12558 entry = new_type(TYPE_LIST, 0, 0);
12559 entry->field_ident = eident;
12561 next = &entry->right;
12563 if (peek(state) == TOK_COMMA) {
12564 eat(state, TOK_COMMA);
12566 } while(peek(state) != TOK_RBRACE);
12567 eat(state, TOK_RBRACE);
12569 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12572 if (ident && ident->sym_tag &&
12573 ident->sym_tag->type &&
12574 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12575 enum_type = clone_type(spec, ident->sym_tag->type);
12577 else if (ident && !enum_type) {
12578 error(state, 0, "enum %s undeclared", ident->name);
12583 static struct type *struct_declarator(
12584 struct compile_state *state, struct type *type, struct hash_entry **ident)
12586 if (peek(state) != TOK_COLON) {
12587 type = declarator(state, type, ident, 1);
12589 if (peek(state) == TOK_COLON) {
12590 struct triple *value;
12591 eat(state, TOK_COLON);
12592 value = constant_expr(state);
12593 if (value->op != OP_INTCONST) {
12594 error(state, 0, "Invalid constant expression");
12596 if (value->u.cval > size_of(state, type)) {
12597 error(state, 0, "bitfield larger than base type");
12599 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12600 error(state, 0, "bitfield base not an integer type");
12602 type = new_type(TYPE_BITFIELD, type, 0);
12603 type->elements = value->u.cval;
12608 static struct type *struct_or_union_specifier(
12609 struct compile_state *state, unsigned int spec)
12611 struct type *struct_type;
12612 struct hash_entry *ident;
12613 unsigned int type_main;
12614 unsigned int type_join;
12618 switch(peek(state)) {
12620 eat(state, TOK_STRUCT);
12621 type_main = TYPE_STRUCT;
12622 type_join = TYPE_PRODUCT;
12625 eat(state, TOK_UNION);
12626 type_main = TYPE_UNION;
12627 type_join = TYPE_OVERLAP;
12630 eat(state, TOK_STRUCT);
12631 type_main = TYPE_STRUCT;
12632 type_join = TYPE_PRODUCT;
12636 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12637 ident = eat(state, tok)->ident;
12639 if (!ident || (peek(state) == TOK_LBRACE)) {
12641 struct type **next;
12643 eat(state, TOK_LBRACE);
12644 next = &struct_type;
12646 struct type *base_type;
12648 base_type = specifier_qualifier_list(state);
12651 struct hash_entry *fident;
12653 type = struct_declarator(state, base_type, &fident);
12655 if (peek(state) == TOK_COMMA) {
12657 eat(state, TOK_COMMA);
12659 type = clone_type(0, type);
12660 type->field_ident = fident;
12662 *next = new_type(type_join, *next, type);
12663 next = &((*next)->right);
12668 eat(state, TOK_SEMI);
12669 } while(peek(state) != TOK_RBRACE);
12670 eat(state, TOK_RBRACE);
12671 struct_type = new_type(type_main | spec, struct_type, 0);
12672 struct_type->type_ident = ident;
12673 struct_type->elements = elements;
12675 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12678 if (ident && ident->sym_tag &&
12679 ident->sym_tag->type &&
12680 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12681 struct_type = clone_type(spec, ident->sym_tag->type);
12683 else if (ident && !struct_type) {
12684 error(state, 0, "%s %s undeclared",
12685 (type_main == TYPE_STRUCT)?"struct" : "union",
12688 return struct_type;
12691 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12693 unsigned int specifiers;
12694 switch(peek(state)) {
12696 eat(state, TOK_AUTO);
12697 specifiers = STOR_AUTO;
12700 eat(state, TOK_REGISTER);
12701 specifiers = STOR_REGISTER;
12704 eat(state, TOK_STATIC);
12705 specifiers = STOR_STATIC;
12708 eat(state, TOK_EXTERN);
12709 specifiers = STOR_EXTERN;
12712 eat(state, TOK_TYPEDEF);
12713 specifiers = STOR_TYPEDEF;
12716 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12717 specifiers = STOR_LOCAL;
12720 specifiers = STOR_AUTO;
12726 static unsigned int function_specifier_opt(struct compile_state *state)
12728 /* Ignore the inline keyword */
12729 unsigned int specifiers;
12731 switch(peek(state)) {
12733 eat(state, TOK_INLINE);
12734 specifiers = STOR_INLINE;
12739 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12741 int tok = peek(state);
12745 /* The empty attribute ignore it */
12748 case TOK_ENUM_CONST:
12749 case TOK_TYPE_NAME:
12751 struct hash_entry *ident;
12752 ident = eat(state, TOK_IDENT)->ident;
12754 if (ident == state->i_noinline) {
12755 if (attributes & ATTRIB_ALWAYS_INLINE) {
12756 error(state, 0, "both always_inline and noinline attribtes");
12758 attributes |= ATTRIB_NOINLINE;
12760 else if (ident == state->i_always_inline) {
12761 if (attributes & ATTRIB_NOINLINE) {
12762 error(state, 0, "both noinline and always_inline attribtes");
12764 attributes |= ATTRIB_ALWAYS_INLINE;
12766 else if (ident == state->i_noreturn) {
12767 // attribute((noreturn)) does nothing (yet?)
12770 error(state, 0, "Unknown attribute:%s", ident->name);
12775 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12781 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12783 type = attrib(state, type);
12784 while(peek(state) == TOK_COMMA) {
12785 eat(state, TOK_COMMA);
12786 type = attrib(state, type);
12791 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12793 if (peek(state) == TOK_ATTRIBUTE) {
12794 eat(state, TOK_ATTRIBUTE);
12795 eat(state, TOK_LPAREN);
12796 eat(state, TOK_LPAREN);
12797 type = attribute_list(state, type);
12798 eat(state, TOK_RPAREN);
12799 eat(state, TOK_RPAREN);
12804 static unsigned int type_qualifiers(struct compile_state *state)
12806 unsigned int specifiers;
12809 specifiers = QUAL_NONE;
12811 switch(peek(state)) {
12813 eat(state, TOK_CONST);
12814 specifiers |= QUAL_CONST;
12817 eat(state, TOK_VOLATILE);
12818 specifiers |= QUAL_VOLATILE;
12821 eat(state, TOK_RESTRICT);
12822 specifiers |= QUAL_RESTRICT;
12832 static struct type *type_specifier(
12833 struct compile_state *state, unsigned int spec)
12838 switch((tok = peek(state))) {
12840 eat(state, TOK_VOID);
12841 type = new_type(TYPE_VOID | spec, 0, 0);
12844 eat(state, TOK_CHAR);
12845 type = new_type(TYPE_CHAR | spec, 0, 0);
12848 eat(state, TOK_SHORT);
12849 if (peek(state) == TOK_INT) {
12850 eat(state, TOK_INT);
12852 type = new_type(TYPE_SHORT | spec, 0, 0);
12855 eat(state, TOK_INT);
12856 type = new_type(TYPE_INT | spec, 0, 0);
12859 eat(state, TOK_LONG);
12860 switch(peek(state)) {
12862 eat(state, TOK_LONG);
12863 error(state, 0, "long long not supported");
12866 eat(state, TOK_DOUBLE);
12867 error(state, 0, "long double not supported");
12870 eat(state, TOK_INT);
12871 type = new_type(TYPE_LONG | spec, 0, 0);
12874 type = new_type(TYPE_LONG | spec, 0, 0);
12879 eat(state, TOK_FLOAT);
12880 error(state, 0, "type float not supported");
12883 eat(state, TOK_DOUBLE);
12884 error(state, 0, "type double not supported");
12887 eat(state, TOK_SIGNED);
12888 switch(peek(state)) {
12890 eat(state, TOK_LONG);
12891 switch(peek(state)) {
12893 eat(state, TOK_LONG);
12894 error(state, 0, "type long long not supported");
12897 eat(state, TOK_INT);
12898 type = new_type(TYPE_LONG | spec, 0, 0);
12901 type = new_type(TYPE_LONG | spec, 0, 0);
12906 eat(state, TOK_INT);
12907 type = new_type(TYPE_INT | spec, 0, 0);
12910 eat(state, TOK_SHORT);
12911 type = new_type(TYPE_SHORT | spec, 0, 0);
12914 eat(state, TOK_CHAR);
12915 type = new_type(TYPE_CHAR | spec, 0, 0);
12918 type = new_type(TYPE_INT | spec, 0, 0);
12923 eat(state, TOK_UNSIGNED);
12924 switch(peek(state)) {
12926 eat(state, TOK_LONG);
12927 switch(peek(state)) {
12929 eat(state, TOK_LONG);
12930 error(state, 0, "unsigned long long not supported");
12933 eat(state, TOK_INT);
12934 type = new_type(TYPE_ULONG | spec, 0, 0);
12937 type = new_type(TYPE_ULONG | spec, 0, 0);
12942 eat(state, TOK_INT);
12943 type = new_type(TYPE_UINT | spec, 0, 0);
12946 eat(state, TOK_SHORT);
12947 type = new_type(TYPE_USHORT | spec, 0, 0);
12950 eat(state, TOK_CHAR);
12951 type = new_type(TYPE_UCHAR | spec, 0, 0);
12954 type = new_type(TYPE_UINT | spec, 0, 0);
12958 /* struct or union specifier */
12961 type = struct_or_union_specifier(state, spec);
12963 /* enum-spefifier */
12965 type = enum_specifier(state, spec);
12968 case TOK_TYPE_NAME:
12969 type = typedef_name(state, spec);
12972 error(state, 0, "bad type specifier %s",
12979 static int istype(int tok)
12997 case TOK_TYPE_NAME:
13005 static struct type *specifier_qualifier_list(struct compile_state *state)
13008 unsigned int specifiers = 0;
13010 /* type qualifiers */
13011 specifiers |= type_qualifiers(state);
13013 /* type specifier */
13014 type = type_specifier(state, specifiers);
13019 #if DEBUG_ROMCC_WARNING
13020 static int isdecl_specifier(int tok)
13023 /* storage class specifier */
13029 /* type qualifier */
13033 /* type specifiers */
13043 /* struct or union specifier */
13046 /* enum-spefifier */
13049 case TOK_TYPE_NAME:
13050 /* function specifiers */
13059 static struct type *decl_specifiers(struct compile_state *state)
13062 unsigned int specifiers;
13063 /* I am overly restrictive in the arragement of specifiers supported.
13064 * C is overly flexible in this department it makes interpreting
13065 * the parse tree difficult.
13069 /* storage class specifier */
13070 specifiers |= storage_class_specifier_opt(state);
13072 /* function-specifier */
13073 specifiers |= function_specifier_opt(state);
13076 specifiers |= attributes_opt(state, 0);
13078 /* type qualifier */
13079 specifiers |= type_qualifiers(state);
13081 /* type specifier */
13082 type = type_specifier(state, specifiers);
13086 struct field_info {
13091 static struct field_info designator(struct compile_state *state, struct type *type)
13094 struct field_info info;
13098 switch(peek(state)) {
13101 struct triple *value;
13102 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13103 error(state, 0, "Array designator not in array initializer");
13105 eat(state, TOK_LBRACKET);
13106 value = constant_expr(state);
13107 eat(state, TOK_RBRACKET);
13109 info.type = type->left;
13110 info.offset = value->u.cval * size_of(state, info.type);
13115 struct hash_entry *field;
13116 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13117 ((type->type & TYPE_MASK) != TYPE_UNION))
13119 error(state, 0, "Struct designator not in struct initializer");
13121 eat(state, TOK_DOT);
13122 field = eat(state, TOK_IDENT)->ident;
13123 info.offset = field_offset(state, type, field);
13124 info.type = field_type(state, type, field);
13128 error(state, 0, "Invalid designator");
13131 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13132 eat(state, TOK_EQ);
13136 static struct triple *initializer(
13137 struct compile_state *state, struct type *type)
13139 struct triple *result;
13140 #if DEBUG_ROMCC_WARNINGS
13141 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13143 if (peek(state) != TOK_LBRACE) {
13144 result = assignment_expr(state);
13145 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13146 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13147 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13148 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13149 (equiv_types(type->left, result->type->left))) {
13150 type->elements = result->type->elements;
13152 if (is_lvalue(state, result) &&
13153 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13154 (type->type & TYPE_MASK) != TYPE_ARRAY)
13156 result = lvalue_conversion(state, result);
13158 if (!is_init_compatible(state, type, result->type)) {
13159 error(state, 0, "Incompatible types in initializer");
13161 if (!equiv_types(type, result->type)) {
13162 result = mk_cast_expr(state, type, result);
13168 struct field_info info;
13170 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13171 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13172 internal_error(state, 0, "unknown initializer type");
13175 info.type = type->left;
13176 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13177 info.type = next_field(state, type, 0);
13179 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13182 max_offset = size_of(state, type);
13184 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13185 eat(state, TOK_LBRACE);
13187 struct triple *value;
13188 struct type *value_type;
13194 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13195 info = designator(state, type);
13197 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13198 (info.offset >= max_offset)) {
13199 error(state, 0, "element beyond bounds");
13201 value_type = info.type;
13202 value = eval_const_expr(state, initializer(state, value_type));
13203 value_size = size_of(state, value_type);
13204 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13205 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13206 (max_offset <= info.offset)) {
13210 old_size = max_offset;
13211 max_offset = info.offset + value_size;
13212 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13213 memcpy(buf, old_buf, bits_to_bytes(old_size));
13216 dest = ((char *)buf) + bits_to_bytes(info.offset);
13217 #if DEBUG_INITIALIZER
13218 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13220 bits_to_bytes(max_offset),
13221 bits_to_bytes(value_size),
13224 if (value->op == OP_BLOBCONST) {
13225 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13227 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13228 #if DEBUG_INITIALIZER
13229 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13231 *((uint8_t *)dest) = value->u.cval & 0xff;
13233 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13234 *((uint16_t *)dest) = value->u.cval & 0xffff;
13236 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13237 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13240 internal_error(state, 0, "unhandled constant initializer");
13242 free_triple(state, value);
13243 if (peek(state) == TOK_COMMA) {
13244 eat(state, TOK_COMMA);
13247 info.offset += value_size;
13248 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13249 info.type = next_field(state, type, info.type);
13250 info.offset = field_offset(state, type,
13251 info.type->field_ident);
13253 } while(comma && (peek(state) != TOK_RBRACE));
13254 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13255 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13256 type->elements = max_offset / size_of(state, type->left);
13258 eat(state, TOK_RBRACE);
13259 result = triple(state, OP_BLOBCONST, type, 0, 0);
13260 result->u.blob = buf;
13265 static void resolve_branches(struct compile_state *state, struct triple *first)
13267 /* Make a second pass and finish anything outstanding
13268 * with respect to branches. The only outstanding item
13269 * is to see if there are goto to labels that have not
13270 * been defined and to error about them.
13273 struct triple *ins;
13274 /* Also error on branches that do not use their targets */
13277 if (!triple_is_ret(state, ins)) {
13278 struct triple **expr ;
13279 struct triple_set *set;
13280 expr = triple_targ(state, ins, 0);
13281 for(; expr; expr = triple_targ(state, ins, expr)) {
13282 struct triple *targ;
13284 for(set = targ?targ->use:0; set; set = set->next) {
13285 if (set->member == ins) {
13290 internal_error(state, ins, "targ not used");
13295 } while(ins != first);
13296 /* See if there are goto to labels that have not been defined */
13297 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13298 struct hash_entry *entry;
13299 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13300 struct triple *ins;
13301 if (!entry->sym_label) {
13304 ins = entry->sym_label->def;
13305 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13306 error(state, ins, "label `%s' used but not defined",
13313 static struct triple *function_definition(
13314 struct compile_state *state, struct type *type)
13316 struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13317 struct triple *fname;
13318 struct type *fname_type;
13319 struct hash_entry *ident;
13320 struct type *param, *crtype, *ctype;
13322 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13323 error(state, 0, "Invalid function header");
13326 /* Verify the function type */
13327 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13328 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13329 (type->right->field_ident == 0)) {
13330 error(state, 0, "Invalid function parameters");
13332 param = type->right;
13334 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13336 if (!param->left->field_ident) {
13337 error(state, 0, "No identifier for parameter %d\n", i);
13339 param = param->right;
13342 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13343 error(state, 0, "No identifier for paramter %d\n", i);
13346 /* Get a list of statements for this function. */
13347 def = triple(state, OP_LIST, type, 0, 0);
13349 /* Start a new scope for the passed parameters */
13350 start_scope(state);
13352 /* Put a label at the very start of a function */
13353 first = label(state);
13354 RHS(def, 0) = first;
13356 /* Put a label at the very end of a function */
13357 end = label(state);
13358 flatten(state, first, end);
13359 /* Remember where return goes */
13360 ident = state->i_return;
13361 symbol(state, ident, &ident->sym_ident, end, end->type);
13363 /* Get the initial closure type */
13364 ctype = new_type(TYPE_JOIN, &void_type, 0);
13365 ctype->elements = 1;
13367 /* Add a variable for the return value */
13368 crtype = new_type(TYPE_TUPLE,
13369 /* Remove all type qualifiers from the return type */
13370 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13371 crtype->elements = 2;
13372 result = flatten(state, end, variable(state, crtype));
13374 /* Allocate a variable for the return address */
13375 retvar = flatten(state, end, variable(state, &void_ptr_type));
13377 /* Add in the return instruction */
13378 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13379 ret = flatten(state, first, ret);
13381 /* Walk through the parameters and create symbol table entries
13384 param = type->right;
13385 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13386 ident = param->left->field_ident;
13387 tmp = variable(state, param->left);
13388 var_symbol(state, ident, tmp);
13389 flatten(state, end, tmp);
13390 param = param->right;
13392 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13393 /* And don't forget the last parameter */
13394 ident = param->field_ident;
13395 tmp = variable(state, param);
13396 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13397 flatten(state, end, tmp);
13400 /* Add the declaration static const char __func__ [] = "func-name" */
13401 fname_type = new_type(TYPE_ARRAY,
13402 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13403 fname_type->type |= QUAL_CONST | STOR_STATIC;
13404 fname_type->elements = strlen(state->function) + 1;
13406 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13407 fname->u.blob = (void *)state->function;
13408 fname = flatten(state, end, fname);
13410 ident = state->i___func__;
13411 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13413 /* Remember which function I am compiling.
13414 * Also assume the last defined function is the main function.
13416 state->main_function = def;
13418 /* Now get the actual function definition */
13419 compound_statement(state, end);
13421 /* Finish anything unfinished with branches */
13422 resolve_branches(state, first);
13424 /* Remove the parameter scope */
13428 /* Remember I have defined a function */
13429 if (!state->functions) {
13430 state->functions = def;
13432 insert_triple(state, state->functions, def);
13434 if (state->compiler->debug & DEBUG_INLINE) {
13435 FILE *fp = state->dbgout;
13438 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13439 display_func(state, fp, def);
13440 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13446 static struct triple *do_decl(struct compile_state *state,
13447 struct type *type, struct hash_entry *ident)
13449 struct triple *def;
13451 /* Clean up the storage types used */
13452 switch (type->type & STOR_MASK) {
13455 /* These are the good types I am aiming for */
13457 case STOR_REGISTER:
13458 type->type &= ~STOR_MASK;
13459 type->type |= STOR_AUTO;
13463 type->type &= ~STOR_MASK;
13464 type->type |= STOR_STATIC;
13468 error(state, 0, "typedef without name");
13470 symbol(state, ident, &ident->sym_ident, 0, type);
13471 ident->tok = TOK_TYPE_NAME;
13475 internal_error(state, 0, "Undefined storage class");
13477 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13478 error(state, 0, "Function prototypes not supported");
13481 ((type->type & STOR_MASK) == STOR_STATIC) &&
13482 ((type->type & QUAL_CONST) == 0)) {
13483 error(state, 0, "non const static variables not supported");
13486 def = variable(state, type);
13487 var_symbol(state, ident, def);
13492 static void decl(struct compile_state *state, struct triple *first)
13494 struct type *base_type, *type;
13495 struct hash_entry *ident;
13496 struct triple *def;
13498 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13499 base_type = decl_specifiers(state);
13501 type = declarator(state, base_type, &ident, 0);
13502 type->type = attributes_opt(state, type->type);
13503 if (global && ident && (peek(state) == TOK_LBRACE)) {
13505 type->type_ident = ident;
13506 state->function = ident->name;
13507 def = function_definition(state, type);
13508 symbol(state, ident, &ident->sym_ident, def, type);
13509 state->function = 0;
13513 flatten(state, first, do_decl(state, type, ident));
13514 /* type or variable definition */
13517 if (peek(state) == TOK_EQ) {
13519 error(state, 0, "cannot assign to a type");
13521 eat(state, TOK_EQ);
13522 flatten(state, first,
13524 ident->sym_ident->def,
13525 initializer(state, type)));
13527 arrays_complete(state, type);
13528 if (peek(state) == TOK_COMMA) {
13529 eat(state, TOK_COMMA);
13531 type = declarator(state, base_type, &ident, 0);
13532 flatten(state, first, do_decl(state, type, ident));
13536 eat(state, TOK_SEMI);
13540 static void decls(struct compile_state *state)
13542 struct triple *list;
13544 list = label(state);
13547 if (tok == TOK_EOF) {
13550 if (tok == TOK_SPACE) {
13551 eat(state, TOK_SPACE);
13554 if (list->next != list) {
13555 error(state, 0, "global variables not supported");
13561 * Function inlining
13563 struct triple_reg_set {
13564 struct triple_reg_set *next;
13565 struct triple *member;
13566 struct triple *new;
13569 struct block *block;
13570 struct triple_reg_set *in;
13571 struct triple_reg_set *out;
13574 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13575 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13576 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13577 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13578 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13579 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13581 static void print_block(
13582 struct compile_state *state, struct block *block, void *arg);
13583 static int do_triple_set(struct triple_reg_set **head,
13584 struct triple *member, struct triple *new_member);
13585 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13586 static struct reg_block *compute_variable_lifetimes(
13587 struct compile_state *state, struct basic_blocks *bb);
13588 static void free_variable_lifetimes(struct compile_state *state,
13589 struct basic_blocks *bb, struct reg_block *blocks);
13590 #if DEBUG_EXPLICIT_CLOSURES
13591 static void print_live_variables(struct compile_state *state,
13592 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13596 static struct triple *call(struct compile_state *state,
13597 struct triple *retvar, struct triple *ret_addr,
13598 struct triple *targ, struct triple *ret)
13600 struct triple *call;
13602 if (!retvar || !is_lvalue(state, retvar)) {
13603 internal_error(state, 0, "writing to a non lvalue?");
13605 write_compatible(state, retvar->type, &void_ptr_type);
13607 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13608 TARG(call, 0) = targ;
13609 MISC(call, 0) = ret;
13610 if (!targ || (targ->op != OP_LABEL)) {
13611 internal_error(state, 0, "call not to a label");
13613 if (!ret || (ret->op != OP_RET)) {
13614 internal_error(state, 0, "call not matched with return");
13619 static void walk_functions(struct compile_state *state,
13620 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13623 struct triple *func, *first;
13624 func = first = state->functions;
13626 cb(state, func, arg);
13628 } while(func != first);
13631 static void reverse_walk_functions(struct compile_state *state,
13632 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13635 struct triple *func, *first;
13636 func = first = state->functions;
13639 cb(state, func, arg);
13640 } while(func != first);
13644 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13646 struct triple *ptr, *first;
13647 if (func->u.cval == 0) {
13650 ptr = first = RHS(func, 0);
13652 if (ptr->op == OP_FCALL) {
13653 struct triple *called_func;
13654 called_func = MISC(ptr, 0);
13655 /* Mark the called function as used */
13656 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13657 called_func->u.cval++;
13659 /* Remove the called function from the list */
13660 called_func->prev->next = called_func->next;
13661 called_func->next->prev = called_func->prev;
13663 /* Place the called function before me on the list */
13664 called_func->next = func;
13665 called_func->prev = func->prev;
13666 called_func->prev->next = called_func;
13667 called_func->next->prev = called_func;
13670 } while(ptr != first);
13671 func->id |= TRIPLE_FLAG_FLATTENED;
13674 static void mark_live_functions(struct compile_state *state)
13676 /* Ensure state->main_function is the last function in
13677 * the list of functions.
13679 if ((state->main_function->next != state->functions) ||
13680 (state->functions->prev != state->main_function)) {
13681 internal_error(state, 0,
13682 "state->main_function is not at the end of the function list ");
13684 state->main_function->u.cval = 1;
13685 reverse_walk_functions(state, mark_live, 0);
13688 static int local_triple(struct compile_state *state,
13689 struct triple *func, struct triple *ins)
13691 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13694 FILE *fp = state->errout;
13695 fprintf(fp, "global: ");
13696 display_triple(fp, ins);
13702 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13703 struct occurance *base_occurance)
13705 struct triple *nfunc;
13706 struct triple *nfirst, *ofirst;
13707 struct triple *new, *old;
13709 if (state->compiler->debug & DEBUG_INLINE) {
13710 FILE *fp = state->dbgout;
13713 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13714 display_func(state, fp, ofunc);
13715 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13718 /* Make a new copy of the old function */
13719 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13721 ofirst = old = RHS(ofunc, 0);
13723 struct triple *new;
13724 struct occurance *occurance;
13725 int old_lhs, old_rhs;
13726 old_lhs = old->lhs;
13727 old_rhs = old->rhs;
13728 occurance = inline_occurance(state, base_occurance, old->occurance);
13729 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13730 MISC(old, 0)->u.cval += 1;
13732 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13734 if (!triple_stores_block(state, new)) {
13735 memcpy(&new->u, &old->u, sizeof(new->u));
13738 RHS(nfunc, 0) = nfirst = new;
13741 insert_triple(state, nfirst, new);
13743 new->id |= TRIPLE_FLAG_FLATTENED;
13744 new->id |= old->id & TRIPLE_FLAG_COPY;
13746 /* During the copy remember new as user of old */
13747 use_triple(old, new);
13749 /* Remember which instructions are local */
13750 old->id |= TRIPLE_FLAG_LOCAL;
13752 } while(old != ofirst);
13754 /* Make a second pass to fix up any unresolved references */
13758 struct triple **oexpr, **nexpr;
13760 /* Lookup where the copy is, to join pointers */
13761 count = TRIPLE_SIZE(old);
13762 for(i = 0; i < count; i++) {
13763 oexpr = &old->param[i];
13764 nexpr = &new->param[i];
13765 if (*oexpr && !*nexpr) {
13766 if (!local_triple(state, ofunc, *oexpr)) {
13769 else if ((*oexpr)->use) {
13770 *nexpr = (*oexpr)->use->member;
13772 if (*nexpr == old) {
13773 internal_error(state, 0, "new == old?");
13775 use_triple(*nexpr, new);
13777 if (!*nexpr && *oexpr) {
13778 internal_error(state, 0, "Could not copy %d", i);
13783 } while((old != ofirst) && (new != nfirst));
13785 /* Make a third pass to cleanup the extra useses */
13789 unuse_triple(old, new);
13790 /* Forget which instructions are local */
13791 old->id &= ~TRIPLE_FLAG_LOCAL;
13794 } while ((old != ofirst) && (new != nfirst));
13798 static void expand_inline_call(
13799 struct compile_state *state, struct triple *me, struct triple *fcall)
13801 /* Inline the function call */
13802 struct type *ptype;
13803 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13804 struct triple *end, *nend;
13807 /* Find the triples */
13808 ofunc = MISC(fcall, 0);
13809 if (ofunc->op != OP_LIST) {
13810 internal_error(state, 0, "improper function");
13812 nfunc = copy_func(state, ofunc, fcall->occurance);
13813 /* Prepend the parameter reading into the new function list */
13814 ptype = nfunc->type->right;
13815 pvals = fcall->rhs;
13816 for(i = 0; i < pvals; i++) {
13817 struct type *atype;
13818 struct triple *arg, *param;
13820 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13821 atype = ptype->left;
13823 param = farg(state, nfunc, i);
13824 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13825 internal_error(state, fcall, "param %d type mismatch", i);
13827 arg = RHS(fcall, i);
13828 flatten(state, fcall, write_expr(state, param, arg));
13829 ptype = ptype->right;
13832 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13833 result = read_expr(state,
13834 deref_index(state, fresult(state, nfunc), 1));
13836 if (state->compiler->debug & DEBUG_INLINE) {
13837 FILE *fp = state->dbgout;
13840 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13841 display_func(state, fp, nfunc);
13842 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13846 * Get rid of the extra triples
13848 /* Remove the read of the return address */
13849 ins = RHS(nfunc, 0)->prev->prev;
13850 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13851 internal_error(state, ins, "Not return addres read?");
13853 release_triple(state, ins);
13854 /* Remove the return instruction */
13855 ins = RHS(nfunc, 0)->prev;
13856 if (ins->op != OP_RET) {
13857 internal_error(state, ins, "Not return?");
13859 release_triple(state, ins);
13860 /* Remove the retaddres variable */
13861 retvar = fretaddr(state, nfunc);
13862 if ((retvar->lhs != 1) ||
13863 (retvar->op != OP_ADECL) ||
13864 (retvar->next->op != OP_PIECE) ||
13865 (MISC(retvar->next, 0) != retvar)) {
13866 internal_error(state, retvar, "Not the return address?");
13868 release_triple(state, retvar->next);
13869 release_triple(state, retvar);
13871 /* Remove the label at the start of the function */
13872 ins = RHS(nfunc, 0);
13873 if (ins->op != OP_LABEL) {
13874 internal_error(state, ins, "Not label?");
13876 nfirst = ins->next;
13877 free_triple(state, ins);
13878 /* Release the new function header */
13880 free_triple(state, nfunc);
13882 /* Append the new function list onto the return list */
13884 nend = nfirst->prev;
13885 end->next = nfirst;
13886 nfirst->prev = end;
13887 nend->next = fcall;
13888 fcall->prev = nend;
13890 /* Now the result reading code */
13892 result = flatten(state, fcall, result);
13893 propogate_use(state, fcall, result);
13896 /* Release the original fcall instruction */
13897 release_triple(state, fcall);
13904 * Type of the result variable.
13908 * +----------+------------+
13910 * union of closures result_type
13912 * +------------------+---------------+
13914 * closure1 ... closuerN
13916 * +----+--+-+--------+-----+ +----+----+---+-----+
13917 * | | | | | | | | |
13918 * var1 var2 var3 ... varN result var1 var2 ... varN result
13920 * +--------+---------+
13922 * union of closures result_type
13924 * +-----+-------------------+
13926 * closure1 ... closureN
13928 * +-----+---+----+----+ +----+---+----+-----+
13930 * var1 var2 ... varN result var1 var2 ... varN result
13933 static int add_closure_type(struct compile_state *state,
13934 struct triple *func, struct type *closure_type)
13936 struct type *type, *ctype, **next;
13937 struct triple *var, *new_var;
13941 FILE *fp = state->errout;
13942 fprintf(fp, "original_type: ");
13943 name_of(fp, fresult(state, func)->type);
13946 /* find the original type */
13947 var = fresult(state, func);
13949 if (type->elements != 2) {
13950 internal_error(state, var, "bad return type");
13953 /* Find the complete closure type and update it */
13954 ctype = type->left->left;
13955 next = &ctype->left;
13956 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13957 next = &(*next)->right;
13959 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13960 ctype->elements += 1;
13963 fprintf(fp, "new_type: ");
13966 fprintf(fp, "ctype: %p %d bits: %d ",
13967 ctype, ctype->elements, reg_size_of(state, ctype));
13968 name_of(fp, ctype);
13972 /* Regenerate the variable with the new type definition */
13973 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13974 new_var->id |= TRIPLE_FLAG_FLATTENED;
13975 for(i = 0; i < new_var->lhs; i++) {
13976 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13979 /* Point everyone at the new variable */
13980 propogate_use(state, var, new_var);
13982 /* Release the original variable */
13983 for(i = 0; i < var->lhs; i++) {
13984 release_triple(state, LHS(var, i));
13986 release_triple(state, var);
13988 /* Return the index of the added closure type */
13989 return ctype->elements - 1;
13992 static struct triple *closure_expr(struct compile_state *state,
13993 struct triple *func, int closure_idx, int var_idx)
13995 return deref_index(state,
13997 deref_index(state, fresult(state, func), 0),
14003 static void insert_triple_set(
14004 struct triple_reg_set **head, struct triple *member)
14006 struct triple_reg_set *new;
14007 new = xcmalloc(sizeof(*new), "triple_set");
14008 new->member = member;
14014 static int ordered_triple_set(
14015 struct triple_reg_set **head, struct triple *member)
14017 struct triple_reg_set **ptr;
14022 if (member == (*ptr)->member) {
14025 /* keep the list ordered */
14026 if (member->id < (*ptr)->member->id) {
14029 ptr = &(*ptr)->next;
14031 insert_triple_set(ptr, member);
14036 static void free_closure_variables(struct compile_state *state,
14037 struct triple_reg_set **enclose)
14039 struct triple_reg_set *entry, *next;
14040 for(entry = *enclose; entry; entry = next) {
14041 next = entry->next;
14042 do_triple_unset(enclose, entry->member);
14046 static int lookup_closure_index(struct compile_state *state,
14047 struct triple *me, struct triple *val)
14049 struct triple *first, *ins, *next;
14050 first = RHS(me, 0);
14051 ins = next = first;
14053 struct triple *result;
14054 struct triple *index0, *index1, *index2, *read, *write;
14057 if (ins->op != OP_CALL) {
14060 /* I am at a previous call point examine it closely */
14061 if (ins->next->op != OP_LABEL) {
14062 internal_error(state, ins, "call not followed by label");
14064 /* Does this call does not enclose any variables? */
14065 if ((ins->next->next->op != OP_INDEX) ||
14066 (ins->next->next->u.cval != 0) ||
14067 (result = MISC(ins->next->next, 0)) ||
14068 (result->id & TRIPLE_FLAG_LOCAL)) {
14071 index0 = ins->next->next;
14073 * 0 index result < 0 >
14079 for(index0 = ins->next->next;
14080 (index0->op == OP_INDEX) &&
14081 (MISC(index0, 0) == result) &&
14082 (index0->u.cval == 0) ;
14083 index0 = write->next)
14085 index1 = index0->next;
14086 index2 = index1->next;
14087 read = index2->next;
14088 write = read->next;
14089 if ((index0->op != OP_INDEX) ||
14090 (index1->op != OP_INDEX) ||
14091 (index2->op != OP_INDEX) ||
14092 (read->op != OP_READ) ||
14093 (write->op != OP_WRITE) ||
14094 (MISC(index1, 0) != index0) ||
14095 (MISC(index2, 0) != index1) ||
14096 (RHS(read, 0) != index2) ||
14097 (RHS(write, 0) != read)) {
14098 internal_error(state, index0, "bad var read");
14100 if (MISC(write, 0) == val) {
14101 return index2->u.cval;
14104 } while(next != first);
14108 static inline int enclose_triple(struct triple *ins)
14110 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14113 static void compute_closure_variables(struct compile_state *state,
14114 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14116 struct triple_reg_set *set, *vars, **last_var;
14117 struct basic_blocks bb;
14118 struct reg_block *rb;
14119 struct block *block;
14120 struct triple *old_result, *first, *ins;
14122 unsigned long used_indicies;
14124 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14125 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14132 /* Find the basic blocks of this function */
14134 bb.first = RHS(me, 0);
14136 if (!triple_is_ret(state, bb.first->prev)) {
14139 old_result = fresult(state, me);
14141 analyze_basic_blocks(state, &bb);
14143 /* Find which variables are currently alive in a given block */
14144 rb = compute_variable_lifetimes(state, &bb);
14146 /* Find the variables that are currently alive */
14147 block = block_of_triple(state, fcall);
14148 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14149 internal_error(state, fcall, "No reg block? block: %p", block);
14152 #if DEBUG_EXPLICIT_CLOSURES
14153 print_live_variables(state, &bb, rb, state->dbgout);
14154 fflush(state->dbgout);
14157 /* Count the number of triples in the function */
14158 first = RHS(me, 0);
14164 } while(ins != first);
14166 /* Allocate some memory to temorary hold the id info */
14167 info = xcmalloc(sizeof(*info) * (count +1), "info");
14169 /* Mark the local function */
14170 first = RHS(me, 0);
14174 info[idx].id = ins->id;
14175 ins->id = TRIPLE_FLAG_LOCAL | idx;
14178 } while(ins != first);
14181 * Build the list of variables to enclose.
14183 * A target it to put the same variable in the
14184 * same slot for ever call of a given function.
14185 * After coloring this removes all of the variable
14186 * manipulation code.
14188 * The list of variables to enclose is built ordered
14189 * program order because except in corner cases this
14190 * gives me the stability of assignment I need.
14192 * To gurantee that stability I lookup the variables
14193 * to see where they have been used before and
14194 * I build my final list with the assigned indicies.
14197 if (enclose_triple(old_result)) {
14198 ordered_triple_set(&vars, old_result);
14200 for(set = rb[block->vertex].out; set; set = set->next) {
14201 if (!enclose_triple(set->member)) {
14204 if ((set->member == fcall) || (set->member == old_result)) {
14207 if (!local_triple(state, me, set->member)) {
14208 internal_error(state, set->member, "not local?");
14210 ordered_triple_set(&vars, set->member);
14213 /* Lookup the current indicies of the live varialbe */
14216 for(set = vars; set ; set = set->next) {
14217 struct triple *ins;
14220 index = lookup_closure_index(state, me, ins);
14221 info[ID_BITS(ins->id)].index = index;
14225 if (index >= MAX_INDICIES) {
14226 internal_error(state, ins, "index unexpectedly large");
14228 if (used_indicies & (1 << index)) {
14229 internal_error(state, ins, "index previously used?");
14231 /* Remember which indicies have been used */
14232 used_indicies |= (1 << index);
14233 if (index > max_index) {
14238 /* Walk through the live variables and make certain
14239 * everything is assigned an index.
14241 for(set = vars; set; set = set->next) {
14242 struct triple *ins;
14245 index = info[ID_BITS(ins->id)].index;
14249 /* Find the lowest unused index value */
14250 for(index = 0; index < MAX_INDICIES; index++) {
14251 if (!(used_indicies & (1 << index))) {
14255 if (index == MAX_INDICIES) {
14256 internal_error(state, ins, "no free indicies?");
14258 info[ID_BITS(ins->id)].index = index;
14259 /* Remember which indicies have been used */
14260 used_indicies |= (1 << index);
14261 if (index > max_index) {
14266 /* Build the return list of variables with positions matching
14270 last_var = enclose;
14271 for(i = 0; i <= max_index; i++) {
14272 struct triple *var;
14274 if (used_indicies & (1 << i)) {
14275 for(set = vars; set; set = set->next) {
14277 index = info[ID_BITS(set->member->id)].index;
14284 internal_error(state, me, "missing variable");
14287 insert_triple_set(last_var, var);
14288 last_var = &(*last_var)->next;
14291 #if DEBUG_EXPLICIT_CLOSURES
14292 /* Print out the variables to be enclosed */
14293 loc(state->dbgout, state, fcall);
14294 fprintf(state->dbgout, "Alive: \n");
14295 for(set = *enclose; set; set = set->next) {
14296 display_triple(state->dbgout, set->member);
14298 fflush(state->dbgout);
14301 /* Clear the marks */
14304 ins->id = info[ID_BITS(ins->id)].id;
14306 } while(ins != first);
14308 /* Release the ordered list of live variables */
14309 free_closure_variables(state, &vars);
14311 /* Release the storage of the old ids */
14314 /* Release the variable lifetime information */
14315 free_variable_lifetimes(state, &bb, rb);
14317 /* Release the basic blocks of this function */
14318 free_basic_blocks(state, &bb);
14321 static void expand_function_call(
14322 struct compile_state *state, struct triple *me, struct triple *fcall)
14324 /* Generate an ordinary function call */
14325 struct type *closure_type, **closure_next;
14326 struct triple *func, *func_first, *func_last, *retvar;
14327 struct triple *first;
14328 struct type *ptype, *rtype;
14329 struct triple *jmp;
14330 struct triple *ret_addr, *ret_loc, *ret_set;
14331 struct triple_reg_set *enclose, *set;
14332 int closure_idx, pvals, i;
14334 #if DEBUG_EXPLICIT_CLOSURES
14335 FILE *fp = state->dbgout;
14336 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14337 display_func(state, fp, MISC(fcall, 0));
14338 display_func(state, fp, me);
14339 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14342 /* Find the triples */
14343 func = MISC(fcall, 0);
14344 func_first = RHS(func, 0);
14345 retvar = fretaddr(state, func);
14346 func_last = func_first->prev;
14347 first = fcall->next;
14349 /* Find what I need to enclose */
14350 compute_closure_variables(state, me, fcall, &enclose);
14352 /* Compute the closure type */
14353 closure_type = new_type(TYPE_TUPLE, 0, 0);
14354 closure_type->elements = 0;
14355 closure_next = &closure_type->left;
14356 for(set = enclose; set ; set = set->next) {
14360 type = set->member->type;
14362 if (!*closure_next) {
14363 *closure_next = type;
14365 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14367 closure_next = &(*closure_next)->right;
14369 closure_type->elements += 1;
14371 if (closure_type->elements == 0) {
14372 closure_type->type = TYPE_VOID;
14376 #if DEBUG_EXPLICIT_CLOSURES
14377 fprintf(state->dbgout, "closure type: ");
14378 name_of(state->dbgout, closure_type);
14379 fprintf(state->dbgout, "\n");
14382 /* Update the called functions closure variable */
14383 closure_idx = add_closure_type(state, func, closure_type);
14385 /* Generate some needed triples */
14386 ret_loc = label(state);
14387 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14389 /* Pass the parameters to the new function */
14390 ptype = func->type->right;
14391 pvals = fcall->rhs;
14392 for(i = 0; i < pvals; i++) {
14393 struct type *atype;
14394 struct triple *arg, *param;
14396 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14397 atype = ptype->left;
14399 param = farg(state, func, i);
14400 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14401 internal_error(state, fcall, "param type mismatch");
14403 arg = RHS(fcall, i);
14404 flatten(state, first, write_expr(state, param, arg));
14405 ptype = ptype->right;
14407 rtype = func->type->left;
14409 /* Thread the triples together */
14410 ret_loc = flatten(state, first, ret_loc);
14412 /* Save the active variables in the result variable */
14413 for(i = 0, set = enclose; set ; set = set->next, i++) {
14414 if (!set->member) {
14417 flatten(state, ret_loc,
14419 closure_expr(state, func, closure_idx, i),
14420 read_expr(state, set->member)));
14423 /* Initialize the return value */
14424 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14425 flatten(state, ret_loc,
14427 deref_index(state, fresult(state, func), 1),
14428 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14431 ret_addr = flatten(state, ret_loc, ret_addr);
14432 ret_set = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14433 jmp = flatten(state, ret_loc,
14434 call(state, retvar, ret_addr, func_first, func_last));
14436 /* Find the result */
14437 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14438 struct triple * result;
14439 result = flatten(state, first,
14441 deref_index(state, fresult(state, func), 1)));
14443 propogate_use(state, fcall, result);
14446 /* Release the original fcall instruction */
14447 release_triple(state, fcall);
14449 /* Restore the active variables from the result variable */
14450 for(i = 0, set = enclose; set ; set = set->next, i++) {
14451 struct triple_set *use, *next;
14452 struct triple *new;
14453 struct basic_blocks bb;
14454 if (!set->member || (set->member == fcall)) {
14457 /* Generate an expression for the value */
14458 new = flatten(state, first,
14460 closure_expr(state, func, closure_idx, i)));
14463 /* If the original is an lvalue restore the preserved value */
14464 if (is_lvalue(state, set->member)) {
14465 flatten(state, first,
14466 write_expr(state, set->member, new));
14470 * If the original is a value update the dominated uses.
14473 /* Analyze the basic blocks so I can see who dominates whom */
14475 bb.first = RHS(me, 0);
14476 if (!triple_is_ret(state, bb.first->prev)) {
14479 analyze_basic_blocks(state, &bb);
14482 #if DEBUG_EXPLICIT_CLOSURES
14483 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14486 /* If fcall dominates the use update the expression */
14487 for(use = set->member->use; use; use = next) {
14488 /* Replace use modifies the use chain and
14489 * removes use, so I must take a copy of the
14490 * next entry early.
14493 if (!tdominates(state, fcall, use->member)) {
14496 replace_use(state, set->member, new, use->member);
14499 /* Release the basic blocks, the instructions will be
14500 * different next time, and flatten/insert_triple does
14501 * not update the block values so I can't cache the analysis.
14503 free_basic_blocks(state, &bb);
14506 /* Release the closure variable list */
14507 free_closure_variables(state, &enclose);
14509 if (state->compiler->debug & DEBUG_INLINE) {
14510 FILE *fp = state->dbgout;
14513 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14514 display_func(state, fp, func);
14515 display_func(state, fp, me);
14516 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14522 static int do_inline(struct compile_state *state, struct triple *func)
14527 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14529 case COMPILER_INLINE_ALWAYS:
14531 if (func->type->type & ATTRIB_NOINLINE) {
14532 error(state, func, "noinline with always_inline compiler option");
14535 case COMPILER_INLINE_NEVER:
14537 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14538 error(state, func, "always_inline with noinline compiler option");
14541 case COMPILER_INLINE_DEFAULTON:
14542 switch(func->type->type & STOR_MASK) {
14543 case STOR_STATIC | STOR_INLINE:
14544 case STOR_LOCAL | STOR_INLINE:
14545 case STOR_EXTERN | STOR_INLINE:
14553 case COMPILER_INLINE_DEFAULTOFF:
14554 switch(func->type->type & STOR_MASK) {
14555 case STOR_STATIC | STOR_INLINE:
14556 case STOR_LOCAL | STOR_INLINE:
14557 case STOR_EXTERN | STOR_INLINE:
14565 case COMPILER_INLINE_NOPENALTY:
14566 switch(func->type->type & STOR_MASK) {
14567 case STOR_STATIC | STOR_INLINE:
14568 case STOR_LOCAL | STOR_INLINE:
14569 case STOR_EXTERN | STOR_INLINE:
14573 do_inline = (func->u.cval == 1);
14579 internal_error(state, 0, "Unimplemented inline policy");
14582 /* Force inlining */
14583 if (func->type->type & ATTRIB_NOINLINE) {
14586 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14592 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14594 struct triple *first, *ptr, *next;
14595 /* If the function is not used don't bother */
14596 if (me->u.cval <= 0) {
14599 if (state->compiler->debug & DEBUG_CALLS2) {
14600 FILE *fp = state->dbgout;
14601 fprintf(fp, "in: %s\n",
14602 me->type->type_ident->name);
14605 first = RHS(me, 0);
14606 ptr = next = first;
14608 struct triple *func, *prev;
14612 if (ptr->op != OP_FCALL) {
14615 func = MISC(ptr, 0);
14616 /* See if the function should be inlined */
14617 if (!do_inline(state, func)) {
14618 /* Put a label after the fcall */
14619 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14622 if (state->compiler->debug & DEBUG_CALLS) {
14623 FILE *fp = state->dbgout;
14624 if (state->compiler->debug & DEBUG_CALLS2) {
14625 loc(fp, state, ptr);
14627 fprintf(fp, "inlining %s\n",
14628 func->type->type_ident->name);
14632 /* Update the function use counts */
14635 /* Replace the fcall with the called function */
14636 expand_inline_call(state, me, ptr);
14639 } while (next != first);
14641 ptr = next = first;
14643 struct triple *prev, *func;
14647 if (ptr->op != OP_FCALL) {
14650 func = MISC(ptr, 0);
14651 if (state->compiler->debug & DEBUG_CALLS) {
14652 FILE *fp = state->dbgout;
14653 if (state->compiler->debug & DEBUG_CALLS2) {
14654 loc(fp, state, ptr);
14656 fprintf(fp, "calling %s\n",
14657 func->type->type_ident->name);
14660 /* Replace the fcall with the instruction sequence
14661 * needed to make the call.
14663 expand_function_call(state, me, ptr);
14665 } while(next != first);
14668 static void inline_functions(struct compile_state *state, struct triple *func)
14670 inline_function(state, func, 0);
14671 reverse_walk_functions(state, inline_function, 0);
14674 static void insert_function(struct compile_state *state,
14675 struct triple *func, void *arg)
14677 struct triple *first, *end, *ffirst, *fend;
14679 if (state->compiler->debug & DEBUG_INLINE) {
14680 FILE *fp = state->errout;
14681 fprintf(fp, "%s func count: %d\n",
14682 func->type->type_ident->name, func->u.cval);
14684 if (func->u.cval == 0) {
14688 /* Find the end points of the lists */
14691 ffirst = RHS(func, 0);
14692 fend = ffirst->prev;
14694 /* splice the lists together */
14695 end->next = ffirst;
14696 ffirst->prev = end;
14697 fend->next = first;
14698 first->prev = fend;
14701 struct triple *input_asm(struct compile_state *state)
14703 struct asm_info *info;
14704 struct triple *def;
14707 info = xcmalloc(sizeof(*info), "asm_info");
14710 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14711 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14713 def = new_triple(state, OP_ASM, &void_type, out, 0);
14714 def->u.ainfo = info;
14715 def->id |= TRIPLE_FLAG_VOLATILE;
14717 for(i = 0; i < out; i++) {
14718 struct triple *piece;
14719 piece = triple(state, OP_PIECE, &int_type, def, 0);
14721 LHS(def, i) = piece;
14727 struct triple *output_asm(struct compile_state *state)
14729 struct asm_info *info;
14730 struct triple *def;
14733 info = xcmalloc(sizeof(*info), "asm_info");
14736 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14737 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14739 def = new_triple(state, OP_ASM, &void_type, 0, in);
14740 def->u.ainfo = info;
14741 def->id |= TRIPLE_FLAG_VOLATILE;
14746 static void join_functions(struct compile_state *state)
14748 struct triple *jmp, *start, *end, *call, *in, *out, *func;
14749 struct file_state file;
14750 struct type *pnext, *param;
14751 struct type *result_type, *args_type;
14754 /* Be clear the functions have not been joined yet */
14755 state->functions_joined = 0;
14757 /* Dummy file state to get debug handing right */
14758 memset(&file, 0, sizeof(file));
14759 file.basename = "";
14761 file.report_line = 0;
14762 file.report_name = file.basename;
14763 file.prev = state->file;
14764 state->file = &file;
14765 state->function = "";
14767 if (!state->main_function) {
14768 error(state, 0, "No functions to compile\n");
14771 /* The type of arguments */
14772 args_type = state->main_function->type->right;
14773 /* The return type without any specifiers */
14774 result_type = clone_type(0, state->main_function->type->left);
14777 /* Verify the external arguments */
14778 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14779 error(state, state->main_function,
14780 "Too many external input arguments");
14782 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14783 error(state, state->main_function,
14784 "Too many external output arguments");
14787 /* Lay down the basic program structure */
14788 end = label(state);
14789 start = label(state);
14790 start = flatten(state, state->first, start);
14791 end = flatten(state, state->first, end);
14792 in = input_asm(state);
14793 out = output_asm(state);
14794 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14795 MISC(call, 0) = state->main_function;
14796 in = flatten(state, state->first, in);
14797 call = flatten(state, state->first, call);
14798 out = flatten(state, state->first, out);
14801 /* Read the external input arguments */
14804 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14805 struct triple *expr;
14808 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14809 pnext = param->right;
14810 param = param->left;
14812 if (registers_of(state, param) != 1) {
14813 error(state, state->main_function,
14814 "Arg: %d %s requires multiple registers",
14815 idx + 1, param->field_ident->name);
14817 expr = read_expr(state, LHS(in, idx));
14818 RHS(call, idx) = expr;
14819 expr = flatten(state, call, expr);
14820 use_triple(expr, call);
14826 /* Write the external output arguments */
14827 pnext = result_type;
14828 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14829 pnext = result_type->left;
14831 for(idx = 0; idx < out->rhs; idx++) {
14832 struct triple *expr;
14835 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14836 pnext = param->right;
14837 param = param->left;
14839 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14843 if (registers_of(state, param) != 1) {
14844 error(state, state->main_function,
14845 "Result: %d %s requires multiple registers",
14846 idx, param->field_ident->name);
14848 expr = read_expr(state, call);
14849 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14850 expr = deref_field(state, expr, param->field_ident);
14853 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14855 flatten(state, out, expr);
14856 RHS(out, idx) = expr;
14857 use_triple(expr, out);
14860 /* Allocate a dummy containing function */
14861 func = triple(state, OP_LIST,
14862 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14863 func->type->type_ident = lookup(state, "", 0);
14864 RHS(func, 0) = state->first;
14867 /* See which functions are called, and how often */
14868 mark_live_functions(state);
14869 inline_functions(state, func);
14870 walk_functions(state, insert_function, end);
14872 if (start->next != end) {
14873 jmp = flatten(state, start, branch(state, end, 0));
14876 /* OK now the functions have been joined. */
14877 state->functions_joined = 1;
14879 /* Done now cleanup */
14880 state->file = file.prev;
14881 state->function = 0;
14885 * Data structurs for optimation.
14889 static int do_use_block(
14890 struct block *used, struct block_set **head, struct block *user,
14893 struct block_set **ptr, *new;
14900 if ((*ptr)->member == user) {
14903 ptr = &(*ptr)->next;
14905 new = xcmalloc(sizeof(*new), "block_set");
14906 new->member = user;
14917 static int do_unuse_block(
14918 struct block *used, struct block_set **head, struct block *unuser)
14920 struct block_set *use, **ptr;
14926 if (use->member == unuser) {
14928 memset(use, -1, sizeof(*use));
14939 static void use_block(struct block *used, struct block *user)
14942 /* Append new to the head of the list, print_block
14945 count = do_use_block(used, &used->use, user, 1);
14946 used->users += count;
14948 static void unuse_block(struct block *used, struct block *unuser)
14951 count = do_unuse_block(used, &used->use, unuser);
14952 used->users -= count;
14955 static void add_block_edge(struct block *block, struct block *edge, int front)
14958 count = do_use_block(block, &block->edges, edge, front);
14959 block->edge_count += count;
14962 static void remove_block_edge(struct block *block, struct block *edge)
14965 count = do_unuse_block(block, &block->edges, edge);
14966 block->edge_count -= count;
14969 static void idom_block(struct block *idom, struct block *user)
14971 do_use_block(idom, &idom->idominates, user, 0);
14974 static void unidom_block(struct block *idom, struct block *unuser)
14976 do_unuse_block(idom, &idom->idominates, unuser);
14979 static void domf_block(struct block *block, struct block *domf)
14981 do_use_block(block, &block->domfrontier, domf, 0);
14984 static void undomf_block(struct block *block, struct block *undomf)
14986 do_unuse_block(block, &block->domfrontier, undomf);
14989 static void ipdom_block(struct block *ipdom, struct block *user)
14991 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14994 static void unipdom_block(struct block *ipdom, struct block *unuser)
14996 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14999 static void ipdomf_block(struct block *block, struct block *ipdomf)
15001 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
15004 static void unipdomf_block(struct block *block, struct block *unipdomf)
15006 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
15009 static int walk_triples(
15010 struct compile_state *state,
15011 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
15014 struct triple *ptr;
15016 ptr = state->first;
15018 result = cb(state, ptr, arg);
15019 if (ptr->next->prev != ptr) {
15020 internal_error(state, ptr->next, "bad prev");
15023 } while((result == 0) && (ptr != state->first));
15027 #define PRINT_LIST 1
15028 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15033 if (op == OP_LIST) {
15038 if ((op == OP_LABEL) && (ins->use)) {
15039 fprintf(fp, "\n%p:\n", ins);
15041 display_triple(fp, ins);
15043 if (triple_is_branch(state, ins) && ins->use &&
15044 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15045 internal_error(state, ins, "branch used?");
15047 if (triple_is_branch(state, ins)) {
15053 static void print_triples(struct compile_state *state)
15055 if (state->compiler->debug & DEBUG_TRIPLES) {
15056 FILE *fp = state->dbgout;
15057 fprintf(fp, "--------------- triples ---------------\n");
15058 walk_triples(state, do_print_triple, fp);
15064 struct block *block;
15066 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15068 struct block_set *edge;
15069 if (!block || (cf[block->vertex].block == block)) {
15072 cf[block->vertex].block = block;
15073 for(edge = block->edges; edge; edge = edge->next) {
15074 find_cf_blocks(cf, edge->member);
15078 static void print_control_flow(struct compile_state *state,
15079 FILE *fp, struct basic_blocks *bb)
15081 struct cf_block *cf;
15083 fprintf(fp, "\ncontrol flow\n");
15084 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15085 find_cf_blocks(cf, bb->first_block);
15087 for(i = 1; i <= bb->last_vertex; i++) {
15088 struct block *block;
15089 struct block_set *edge;
15090 block = cf[i].block;
15093 fprintf(fp, "(%p) %d:", block, block->vertex);
15094 for(edge = block->edges; edge; edge = edge->next) {
15095 fprintf(fp, " %d", edge->member->vertex);
15103 static void free_basic_block(struct compile_state *state, struct block *block)
15105 struct block_set *edge, *entry;
15106 struct block *child;
15110 if (block->vertex == -1) {
15113 block->vertex = -1;
15114 for(edge = block->edges; edge; edge = edge->next) {
15115 if (edge->member) {
15116 unuse_block(edge->member, block);
15120 unidom_block(block->idom, block);
15123 if (block->ipdom) {
15124 unipdom_block(block->ipdom, block);
15127 while((entry = block->use)) {
15128 child = entry->member;
15129 unuse_block(block, child);
15130 if (child && (child->vertex != -1)) {
15131 for(edge = child->edges; edge; edge = edge->next) {
15136 while((entry = block->idominates)) {
15137 child = entry->member;
15138 unidom_block(block, child);
15139 if (child && (child->vertex != -1)) {
15143 while((entry = block->domfrontier)) {
15144 child = entry->member;
15145 undomf_block(block, child);
15147 while((entry = block->ipdominates)) {
15148 child = entry->member;
15149 unipdom_block(block, child);
15150 if (child && (child->vertex != -1)) {
15154 while((entry = block->ipdomfrontier)) {
15155 child = entry->member;
15156 unipdomf_block(block, child);
15158 if (block->users != 0) {
15159 internal_error(state, 0, "block still has users");
15161 while((edge = block->edges)) {
15162 child = edge->member;
15163 remove_block_edge(block, child);
15165 if (child && (child->vertex != -1)) {
15166 free_basic_block(state, child);
15169 memset(block, -1, sizeof(*block));
15175 static void free_basic_blocks(struct compile_state *state,
15176 struct basic_blocks *bb)
15178 struct triple *first, *ins;
15179 free_basic_block(state, bb->first_block);
15180 bb->last_vertex = 0;
15181 bb->first_block = bb->last_block = 0;
15185 if (triple_stores_block(state, ins)) {
15189 } while(ins != first);
15193 static struct block *basic_block(struct compile_state *state,
15194 struct basic_blocks *bb, struct triple *first)
15196 struct block *block;
15197 struct triple *ptr;
15198 if (!triple_is_label(state, first)) {
15199 internal_error(state, first, "block does not start with a label");
15201 /* See if this basic block has already been setup */
15202 if (first->u.block != 0) {
15203 return first->u.block;
15205 /* Allocate another basic block structure */
15206 bb->last_vertex += 1;
15207 block = xcmalloc(sizeof(*block), "block");
15208 block->first = block->last = first;
15209 block->vertex = bb->last_vertex;
15212 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15216 /* If ptr->u is not used remember where the baic block is */
15217 if (triple_stores_block(state, ptr)) {
15218 ptr->u.block = block;
15220 if (triple_is_branch(state, ptr)) {
15224 } while (ptr != bb->first);
15225 if ((ptr == bb->first) ||
15226 ((ptr->next == bb->first) && (
15227 triple_is_end(state, ptr) ||
15228 triple_is_ret(state, ptr))))
15230 /* The block has no outflowing edges */
15232 else if (triple_is_label(state, ptr)) {
15233 struct block *next;
15234 next = basic_block(state, bb, ptr);
15235 add_block_edge(block, next, 0);
15236 use_block(next, block);
15238 else if (triple_is_branch(state, ptr)) {
15239 struct triple **expr, *first;
15240 struct block *child;
15241 /* Find the branch targets.
15242 * I special case the first branch as that magically
15243 * avoids some difficult cases for the register allocator.
15245 expr = triple_edge_targ(state, ptr, 0);
15247 internal_error(state, ptr, "branch without targets");
15250 expr = triple_edge_targ(state, ptr, expr);
15251 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15252 if (!*expr) continue;
15253 child = basic_block(state, bb, *expr);
15254 use_block(child, block);
15255 add_block_edge(block, child, 0);
15258 child = basic_block(state, bb, first);
15259 use_block(child, block);
15260 add_block_edge(block, child, 1);
15262 /* Be certain the return block of a call is
15263 * in a basic block. When it is not find
15264 * start of the block, insert a label if
15265 * necessary and build the basic block.
15266 * Then add a fake edge from the start block
15267 * to the return block of the function.
15269 if (state->functions_joined && triple_is_call(state, ptr)
15270 && !block_of_triple(state, MISC(ptr, 0))) {
15271 struct block *tail;
15272 struct triple *start;
15273 start = triple_to_block_start(state, MISC(ptr, 0));
15274 if (!triple_is_label(state, start)) {
15275 start = pre_triple(state,
15276 start, OP_LABEL, &void_type, 0, 0);
15278 tail = basic_block(state, bb, start);
15279 add_block_edge(child, tail, 0);
15280 use_block(tail, child);
15285 internal_error(state, 0, "Bad basic block split");
15289 struct block_set *edge;
15290 FILE *fp = state->errout;
15291 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15292 block, block->vertex,
15293 block->first, block->last);
15294 for(edge = block->edges; edge; edge = edge->next) {
15295 fprintf(fp, " %10p [%2d]",
15296 edge->member ? edge->member->first : 0,
15297 edge->member ? edge->member->vertex : -1);
15306 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15307 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15310 struct triple *ptr, *first;
15311 struct block *last_block;
15316 if (triple_stores_block(state, ptr)) {
15317 struct block *block;
15318 block = ptr->u.block;
15319 if (block && (block != last_block)) {
15320 cb(state, block, arg);
15322 last_block = block;
15325 } while(ptr != first);
15328 static void print_block(
15329 struct compile_state *state, struct block *block, void *arg)
15331 struct block_set *user, *edge;
15332 struct triple *ptr;
15335 fprintf(fp, "\nblock: %p (%d) ",
15339 for(edge = block->edges; edge; edge = edge->next) {
15340 fprintf(fp, " %p<-%p",
15342 (edge->member && edge->member->use)?
15343 edge->member->use->member : 0);
15346 if (block->first->op == OP_LABEL) {
15347 fprintf(fp, "%p:\n", block->first);
15349 for(ptr = block->first; ; ) {
15350 display_triple(fp, ptr);
15351 if (ptr == block->last)
15354 if (ptr == block->first) {
15355 internal_error(state, 0, "missing block last?");
15358 fprintf(fp, "users %d: ", block->users);
15359 for(user = block->use; user; user = user->next) {
15360 fprintf(fp, "%p (%d) ",
15362 user->member->vertex);
15364 fprintf(fp,"\n\n");
15368 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15370 fprintf(fp, "--------------- blocks ---------------\n");
15371 walk_blocks(state, &state->bb, print_block, fp);
15373 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15375 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15376 fprintf(fp, "After %s\n", func);
15377 romcc_print_blocks(state, fp);
15378 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15379 print_dominators(state, fp, &state->bb);
15380 print_dominance_frontiers(state, fp, &state->bb);
15382 print_control_flow(state, fp, &state->bb);
15386 static void prune_nonblock_triples(struct compile_state *state,
15387 struct basic_blocks *bb)
15389 struct block *block;
15390 struct triple *first, *ins, *next;
15391 /* Delete the triples not in a basic block */
15397 if (ins->op == OP_LABEL) {
15398 block = ins->u.block;
15401 struct triple_set *use;
15402 for(use = ins->use; use; use = use->next) {
15403 struct block *block;
15404 block = block_of_triple(state, use->member);
15406 internal_error(state, ins, "pruning used ins?");
15409 release_triple(state, ins);
15411 if (block && block->last == ins) {
15415 } while(ins != first);
15418 static void setup_basic_blocks(struct compile_state *state,
15419 struct basic_blocks *bb)
15421 if (!triple_stores_block(state, bb->first)) {
15422 internal_error(state, 0, "ins will not store block?");
15424 /* Initialize the state */
15425 bb->first_block = bb->last_block = 0;
15426 bb->last_vertex = 0;
15427 free_basic_blocks(state, bb);
15429 /* Find the basic blocks */
15430 bb->first_block = basic_block(state, bb, bb->first);
15432 /* Be certain the last instruction of a function, or the
15433 * entire program is in a basic block. When it is not find
15434 * the start of the block, insert a label if necessary and build
15435 * basic block. Then add a fake edge from the start block
15436 * to the final block.
15438 if (!block_of_triple(state, bb->first->prev)) {
15439 struct triple *start;
15440 struct block *tail;
15441 start = triple_to_block_start(state, bb->first->prev);
15442 if (!triple_is_label(state, start)) {
15443 start = pre_triple(state,
15444 start, OP_LABEL, &void_type, 0, 0);
15446 tail = basic_block(state, bb, start);
15447 add_block_edge(bb->first_block, tail, 0);
15448 use_block(tail, bb->first_block);
15451 /* Find the last basic block.
15453 bb->last_block = block_of_triple(state, bb->first->prev);
15455 /* Delete the triples not in a basic block */
15456 prune_nonblock_triples(state, bb);
15459 /* If we are debugging print what I have just done */
15460 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15461 print_blocks(state, state->dbgout);
15462 print_control_flow(state, bb);
15468 struct sdom_block {
15469 struct block *block;
15470 struct sdom_block *sdominates;
15471 struct sdom_block *sdom_next;
15472 struct sdom_block *sdom;
15473 struct sdom_block *label;
15474 struct sdom_block *parent;
15475 struct sdom_block *ancestor;
15480 static void unsdom_block(struct sdom_block *block)
15482 struct sdom_block **ptr;
15483 if (!block->sdom_next) {
15486 ptr = &block->sdom->sdominates;
15488 if ((*ptr) == block) {
15489 *ptr = block->sdom_next;
15492 ptr = &(*ptr)->sdom_next;
15496 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15498 unsdom_block(block);
15499 block->sdom = sdom;
15500 block->sdom_next = sdom->sdominates;
15501 sdom->sdominates = block;
15506 static int initialize_sdblock(struct sdom_block *sd,
15507 struct block *parent, struct block *block, int vertex)
15509 struct block_set *edge;
15510 if (!block || (sd[block->vertex].block == block)) {
15514 /* Renumber the blocks in a convinient fashion */
15515 block->vertex = vertex;
15516 sd[vertex].block = block;
15517 sd[vertex].sdom = &sd[vertex];
15518 sd[vertex].label = &sd[vertex];
15519 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15520 sd[vertex].ancestor = 0;
15521 sd[vertex].vertex = vertex;
15522 for(edge = block->edges; edge; edge = edge->next) {
15523 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15528 static int initialize_spdblock(
15529 struct compile_state *state, struct sdom_block *sd,
15530 struct block *parent, struct block *block, int vertex)
15532 struct block_set *user;
15533 if (!block || (sd[block->vertex].block == block)) {
15537 /* Renumber the blocks in a convinient fashion */
15538 block->vertex = vertex;
15539 sd[vertex].block = block;
15540 sd[vertex].sdom = &sd[vertex];
15541 sd[vertex].label = &sd[vertex];
15542 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15543 sd[vertex].ancestor = 0;
15544 sd[vertex].vertex = vertex;
15545 for(user = block->use; user; user = user->next) {
15546 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15551 static int setup_spdblocks(struct compile_state *state,
15552 struct basic_blocks *bb, struct sdom_block *sd)
15554 struct block *block;
15556 /* Setup as many sdpblocks as possible without using fake edges */
15557 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15559 /* Walk through the graph and find unconnected blocks. Add a
15560 * fake edge from the unconnected blocks to the end of the
15563 block = bb->first_block->last->next->u.block;
15564 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15565 if (sd[block->vertex].block == block) {
15568 #if DEBUG_SDP_BLOCKS
15570 FILE *fp = state->errout;
15571 fprintf(fp, "Adding %d\n", vertex +1);
15574 add_block_edge(block, bb->last_block, 0);
15575 use_block(bb->last_block, block);
15577 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15582 static void compress_ancestors(struct sdom_block *v)
15584 /* This procedure assumes ancestor(v) != 0 */
15585 /* if (ancestor(ancestor(v)) != 0) {
15586 * compress(ancestor(ancestor(v)));
15587 * if (semi(label(ancestor(v))) < semi(label(v))) {
15588 * label(v) = label(ancestor(v));
15590 * ancestor(v) = ancestor(ancestor(v));
15593 if (!v->ancestor) {
15596 if (v->ancestor->ancestor) {
15597 compress_ancestors(v->ancestor->ancestor);
15598 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15599 v->label = v->ancestor->label;
15601 v->ancestor = v->ancestor->ancestor;
15605 static void compute_sdom(struct compile_state *state,
15606 struct basic_blocks *bb, struct sdom_block *sd)
15610 * for each v <= pred(w) {
15612 * if (semi[u] < semi[w] {
15613 * semi[w] = semi[u];
15616 * add w to bucket(vertex(semi[w]));
15617 * LINK(parent(w), w);
15620 * for each v <= bucket(parent(w)) {
15621 * delete v from bucket(parent(w));
15623 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15626 for(i = bb->last_vertex; i >= 2; i--) {
15627 struct sdom_block *v, *parent, *next;
15628 struct block_set *user;
15629 struct block *block;
15630 block = sd[i].block;
15631 parent = sd[i].parent;
15633 for(user = block->use; user; user = user->next) {
15634 struct sdom_block *v, *u;
15635 v = &sd[user->member->vertex];
15636 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15637 if (u->sdom->vertex < sd[i].sdom->vertex) {
15638 sd[i].sdom = u->sdom;
15641 sdom_block(sd[i].sdom, &sd[i]);
15642 sd[i].ancestor = parent;
15644 for(v = parent->sdominates; v; v = next) {
15645 struct sdom_block *u;
15646 next = v->sdom_next;
15648 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15649 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15650 u->block : parent->block;
15655 static void compute_spdom(struct compile_state *state,
15656 struct basic_blocks *bb, struct sdom_block *sd)
15660 * for each v <= pred(w) {
15662 * if (semi[u] < semi[w] {
15663 * semi[w] = semi[u];
15666 * add w to bucket(vertex(semi[w]));
15667 * LINK(parent(w), w);
15670 * for each v <= bucket(parent(w)) {
15671 * delete v from bucket(parent(w));
15673 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15676 for(i = bb->last_vertex; i >= 2; i--) {
15677 struct sdom_block *u, *v, *parent, *next;
15678 struct block_set *edge;
15679 struct block *block;
15680 block = sd[i].block;
15681 parent = sd[i].parent;
15683 for(edge = block->edges; edge; edge = edge->next) {
15684 v = &sd[edge->member->vertex];
15685 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15686 if (u->sdom->vertex < sd[i].sdom->vertex) {
15687 sd[i].sdom = u->sdom;
15690 sdom_block(sd[i].sdom, &sd[i]);
15691 sd[i].ancestor = parent;
15693 for(v = parent->sdominates; v; v = next) {
15694 struct sdom_block *u;
15695 next = v->sdom_next;
15697 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15698 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15699 u->block : parent->block;
15704 static void compute_idom(struct compile_state *state,
15705 struct basic_blocks *bb, struct sdom_block *sd)
15708 for(i = 2; i <= bb->last_vertex; i++) {
15709 struct block *block;
15710 block = sd[i].block;
15711 if (block->idom->vertex != sd[i].sdom->vertex) {
15712 block->idom = block->idom->idom;
15714 idom_block(block->idom, block);
15716 sd[1].block->idom = 0;
15719 static void compute_ipdom(struct compile_state *state,
15720 struct basic_blocks *bb, struct sdom_block *sd)
15723 for(i = 2; i <= bb->last_vertex; i++) {
15724 struct block *block;
15725 block = sd[i].block;
15726 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15727 block->ipdom = block->ipdom->ipdom;
15729 ipdom_block(block->ipdom, block);
15731 sd[1].block->ipdom = 0;
15735 * Every vertex of a flowgraph G = (V, E, r) except r has
15736 * a unique immediate dominator.
15737 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15738 * rooted at r, called the dominator tree of G, such that
15739 * v dominates w if and only if v is a proper ancestor of w in
15740 * the dominator tree.
15743 * If v and w are vertices of G such that v <= w,
15744 * than any path from v to w must contain a common ancestor
15747 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15748 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15749 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15751 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15752 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15755 * Let w != r and let u be a vertex for which sdom(u) is
15756 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15757 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15759 /* Lemma 5: Let vertices v,w satisfy v -> w.
15760 * Then v -> idom(w) or idom(w) -> idom(v)
15763 static void find_immediate_dominators(struct compile_state *state,
15764 struct basic_blocks *bb)
15766 struct sdom_block *sd;
15767 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15768 * vi > w for (1 <= i <= k - 1}
15771 * For any vertex w != r.
15773 * {v|(v,w) <= E and v < w } U
15774 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15777 * Let w != r and let u be a vertex for which sdom(u) is
15778 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15780 * { sdom(w) if sdom(w) = sdom(u),
15782 * { idom(u) otherwise
15784 /* The algorithm consists of the following 4 steps.
15785 * Step 1. Carry out a depth-first search of the problem graph.
15786 * Number the vertices from 1 to N as they are reached during
15787 * the search. Initialize the variables used in succeeding steps.
15788 * Step 2. Compute the semidominators of all vertices by applying
15789 * theorem 4. Carry out the computation vertex by vertex in
15790 * decreasing order by number.
15791 * Step 3. Implicitly define the immediate dominator of each vertex
15792 * by applying Corollary 1.
15793 * Step 4. Explicitly define the immediate dominator of each vertex,
15794 * carrying out the computation vertex by vertex in increasing order
15797 /* Step 1 initialize the basic block information */
15798 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15799 initialize_sdblock(sd, 0, bb->first_block, 0);
15805 /* Step 2 compute the semidominators */
15806 /* Step 3 implicitly define the immediate dominator of each vertex */
15807 compute_sdom(state, bb, sd);
15808 /* Step 4 explicitly define the immediate dominator of each vertex */
15809 compute_idom(state, bb, sd);
15813 static void find_post_dominators(struct compile_state *state,
15814 struct basic_blocks *bb)
15816 struct sdom_block *sd;
15818 /* Step 1 initialize the basic block information */
15819 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15821 vertex = setup_spdblocks(state, bb, sd);
15822 if (vertex != bb->last_vertex) {
15823 internal_error(state, 0, "missing %d blocks",
15824 bb->last_vertex - vertex);
15827 /* Step 2 compute the semidominators */
15828 /* Step 3 implicitly define the immediate dominator of each vertex */
15829 compute_spdom(state, bb, sd);
15830 /* Step 4 explicitly define the immediate dominator of each vertex */
15831 compute_ipdom(state, bb, sd);
15837 static void find_block_domf(struct compile_state *state, struct block *block)
15839 struct block *child;
15840 struct block_set *user, *edge;
15841 if (block->domfrontier != 0) {
15842 internal_error(state, block->first, "domfrontier present?");
15844 for(user = block->idominates; user; user = user->next) {
15845 child = user->member;
15846 if (child->idom != block) {
15847 internal_error(state, block->first, "bad idom");
15849 find_block_domf(state, child);
15851 for(edge = block->edges; edge; edge = edge->next) {
15852 if (edge->member->idom != block) {
15853 domf_block(block, edge->member);
15856 for(user = block->idominates; user; user = user->next) {
15857 struct block_set *frontier;
15858 child = user->member;
15859 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15860 if (frontier->member->idom != block) {
15861 domf_block(block, frontier->member);
15867 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15869 struct block *child;
15870 struct block_set *user;
15871 if (block->ipdomfrontier != 0) {
15872 internal_error(state, block->first, "ipdomfrontier present?");
15874 for(user = block->ipdominates; user; user = user->next) {
15875 child = user->member;
15876 if (child->ipdom != block) {
15877 internal_error(state, block->first, "bad ipdom");
15879 find_block_ipdomf(state, child);
15881 for(user = block->use; user; user = user->next) {
15882 if (user->member->ipdom != block) {
15883 ipdomf_block(block, user->member);
15886 for(user = block->ipdominates; user; user = user->next) {
15887 struct block_set *frontier;
15888 child = user->member;
15889 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15890 if (frontier->member->ipdom != block) {
15891 ipdomf_block(block, frontier->member);
15897 static void print_dominated(
15898 struct compile_state *state, struct block *block, void *arg)
15900 struct block_set *user;
15903 fprintf(fp, "%d:", block->vertex);
15904 for(user = block->idominates; user; user = user->next) {
15905 fprintf(fp, " %d", user->member->vertex);
15906 if (user->member->idom != block) {
15907 internal_error(state, user->member->first, "bad idom");
15913 static void print_dominated2(
15914 struct compile_state *state, FILE *fp, int depth, struct block *block)
15916 struct block_set *user;
15917 struct triple *ins;
15918 struct occurance *ptr, *ptr2;
15919 const char *filename1, *filename2;
15920 int equal_filenames;
15922 for(i = 0; i < depth; i++) {
15925 fprintf(fp, "%3d: %p (%p - %p) @",
15926 block->vertex, block, block->first, block->last);
15927 ins = block->first;
15928 while(ins != block->last && (ins->occurance->line == 0)) {
15931 ptr = ins->occurance;
15932 ptr2 = block->last->occurance;
15933 filename1 = ptr->filename? ptr->filename : "";
15934 filename2 = ptr2->filename? ptr2->filename : "";
15935 equal_filenames = (strcmp(filename1, filename2) == 0);
15936 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15937 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15938 } else if (equal_filenames) {
15939 fprintf(fp, " %s:(%d - %d)",
15940 ptr->filename, ptr->line, ptr2->line);
15942 fprintf(fp, " (%s:%d - %s:%d)",
15943 ptr->filename, ptr->line,
15944 ptr2->filename, ptr2->line);
15947 for(user = block->idominates; user; user = user->next) {
15948 print_dominated2(state, fp, depth + 1, user->member);
15952 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15954 fprintf(fp, "\ndominates\n");
15955 walk_blocks(state, bb, print_dominated, fp);
15956 fprintf(fp, "dominates\n");
15957 print_dominated2(state, fp, 0, bb->first_block);
15961 static int print_frontiers(
15962 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15964 struct block_set *user, *edge;
15966 if (!block || (block->vertex != vertex + 1)) {
15971 fprintf(fp, "%d:", block->vertex);
15972 for(user = block->domfrontier; user; user = user->next) {
15973 fprintf(fp, " %d", user->member->vertex);
15977 for(edge = block->edges; edge; edge = edge->next) {
15978 vertex = print_frontiers(state, fp, edge->member, vertex);
15982 static void print_dominance_frontiers(struct compile_state *state,
15983 FILE *fp, struct basic_blocks *bb)
15985 fprintf(fp, "\ndominance frontiers\n");
15986 print_frontiers(state, fp, bb->first_block, 0);
15990 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15992 /* Find the immediate dominators */
15993 find_immediate_dominators(state, bb);
15994 /* Find the dominance frontiers */
15995 find_block_domf(state, bb->first_block);
15996 /* If debuging print the print what I have just found */
15997 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15998 print_dominators(state, state->dbgout, bb);
15999 print_dominance_frontiers(state, state->dbgout, bb);
16000 print_control_flow(state, state->dbgout, bb);
16005 static void print_ipdominated(
16006 struct compile_state *state, struct block *block, void *arg)
16008 struct block_set *user;
16011 fprintf(fp, "%d:", block->vertex);
16012 for(user = block->ipdominates; user; user = user->next) {
16013 fprintf(fp, " %d", user->member->vertex);
16014 if (user->member->ipdom != block) {
16015 internal_error(state, user->member->first, "bad ipdom");
16021 static void print_ipdominators(struct compile_state *state, FILE *fp,
16022 struct basic_blocks *bb)
16024 fprintf(fp, "\nipdominates\n");
16025 walk_blocks(state, bb, print_ipdominated, fp);
16028 static int print_pfrontiers(
16029 struct compile_state *state, FILE *fp, struct block *block, int vertex)
16031 struct block_set *user;
16033 if (!block || (block->vertex != vertex + 1)) {
16038 fprintf(fp, "%d:", block->vertex);
16039 for(user = block->ipdomfrontier; user; user = user->next) {
16040 fprintf(fp, " %d", user->member->vertex);
16043 for(user = block->use; user; user = user->next) {
16044 vertex = print_pfrontiers(state, fp, user->member, vertex);
16048 static void print_ipdominance_frontiers(struct compile_state *state,
16049 FILE *fp, struct basic_blocks *bb)
16051 fprintf(fp, "\nipdominance frontiers\n");
16052 print_pfrontiers(state, fp, bb->last_block, 0);
16056 static void analyze_ipdominators(struct compile_state *state,
16057 struct basic_blocks *bb)
16059 /* Find the post dominators */
16060 find_post_dominators(state, bb);
16061 /* Find the control dependencies (post dominance frontiers) */
16062 find_block_ipdomf(state, bb->last_block);
16063 /* If debuging print the print what I have just found */
16064 if (state->compiler->debug & DEBUG_RDOMINATORS) {
16065 print_ipdominators(state, state->dbgout, bb);
16066 print_ipdominance_frontiers(state, state->dbgout, bb);
16067 print_control_flow(state, state->dbgout, bb);
16071 static int bdominates(struct compile_state *state,
16072 struct block *dom, struct block *sub)
16074 while(sub && (sub != dom)) {
16080 static int tdominates(struct compile_state *state,
16081 struct triple *dom, struct triple *sub)
16083 struct block *bdom, *bsub;
16085 bdom = block_of_triple(state, dom);
16086 bsub = block_of_triple(state, sub);
16087 if (bdom != bsub) {
16088 result = bdominates(state, bdom, bsub);
16091 struct triple *ins;
16092 if (!bdom || !bsub) {
16093 internal_error(state, dom, "huh?");
16096 while((ins != bsub->first) && (ins != dom)) {
16099 result = (ins == dom);
16104 static void analyze_basic_blocks(
16105 struct compile_state *state, struct basic_blocks *bb)
16107 setup_basic_blocks(state, bb);
16108 analyze_idominators(state, bb);
16109 analyze_ipdominators(state, bb);
16112 static void insert_phi_operations(struct compile_state *state)
16115 struct triple *first;
16116 int *has_already, *work;
16117 struct block *work_list, **work_list_tail;
16119 struct triple *var, *vnext;
16121 size = sizeof(int) * (state->bb.last_vertex + 1);
16122 has_already = xcmalloc(size, "has_already");
16123 work = xcmalloc(size, "work");
16126 first = state->first;
16127 for(var = first->next; var != first ; var = vnext) {
16128 struct block *block;
16129 struct triple_set *user, *unext;
16132 if (!triple_is_auto_var(state, var) || !var->use) {
16138 work_list_tail = &work_list;
16139 for(user = var->use; user; user = unext) {
16140 unext = user->next;
16141 if (MISC(var, 0) == user->member) {
16144 if (user->member->op == OP_READ) {
16147 if (user->member->op != OP_WRITE) {
16148 internal_error(state, user->member,
16149 "bad variable access");
16151 block = user->member->u.block;
16153 warning(state, user->member, "dead code");
16154 release_triple(state, user->member);
16157 if (work[block->vertex] >= iter) {
16160 work[block->vertex] = iter;
16161 *work_list_tail = block;
16162 block->work_next = 0;
16163 work_list_tail = &block->work_next;
16165 for(block = work_list; block; block = block->work_next) {
16166 struct block_set *df;
16167 for(df = block->domfrontier; df; df = df->next) {
16168 struct triple *phi;
16169 struct block *front;
16171 front = df->member;
16173 if (has_already[front->vertex] >= iter) {
16176 /* Count how many edges flow into this block */
16177 in_edges = front->users;
16178 /* Insert a phi function for this variable */
16179 get_occurance(var->occurance);
16180 phi = alloc_triple(
16181 state, OP_PHI, var->type, -1, in_edges,
16183 phi->u.block = front;
16184 MISC(phi, 0) = var;
16185 use_triple(var, phi);
16187 if (phi->rhs != in_edges) {
16188 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16189 phi->rhs, in_edges);
16192 /* Insert the phi functions immediately after the label */
16193 insert_triple(state, front->first->next, phi);
16194 if (front->first == front->last) {
16195 front->last = front->first->next;
16197 has_already[front->vertex] = iter;
16198 transform_to_arch_instruction(state, phi);
16200 /* If necessary plan to visit the basic block */
16201 if (work[front->vertex] >= iter) {
16204 work[front->vertex] = iter;
16205 *work_list_tail = front;
16206 front->work_next = 0;
16207 work_list_tail = &front->work_next;
16211 xfree(has_already);
16217 struct triple_set *top;
16221 static int count_auto_vars(struct compile_state *state)
16223 struct triple *first, *ins;
16225 first = state->first;
16228 if (triple_is_auto_var(state, ins)) {
16232 } while(ins != first);
16236 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16238 struct triple *first, *ins;
16240 first = state->first;
16243 if (triple_is_auto_var(state, ins)) {
16245 stacks[auto_vars].orig_id = ins->id;
16246 ins->id = auto_vars;
16249 } while(ins != first);
16252 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16254 struct triple *first, *ins;
16255 first = state->first;
16258 if (triple_is_auto_var(state, ins)) {
16259 ins->id = stacks[ins->id].orig_id;
16262 } while(ins != first);
16265 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16267 struct triple_set *head;
16268 struct triple *top_val;
16270 head = stacks[var->id].top;
16272 top_val = head->member;
16277 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16279 struct triple_set *new;
16280 /* Append new to the head of the list,
16281 * it's the only sensible behavoir for a stack.
16283 new = xcmalloc(sizeof(*new), "triple_set");
16285 new->next = stacks[var->id].top;
16286 stacks[var->id].top = new;
16289 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16291 struct triple_set *set, **ptr;
16292 ptr = &stacks[var->id].top;
16295 if (set->member == oldval) {
16298 /* Only free one occurance from the stack */
16311 static void fixup_block_phi_variables(
16312 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16314 struct block_set *set;
16315 struct triple *ptr;
16317 if (!parent || !block)
16319 /* Find the edge I am coming in on */
16321 for(set = block->use; set; set = set->next, edge++) {
16322 if (set->member == parent) {
16327 internal_error(state, 0, "phi input is not on a control predecessor");
16329 for(ptr = block->first; ; ptr = ptr->next) {
16330 if (ptr->op == OP_PHI) {
16331 struct triple *var, *val, **slot;
16332 var = MISC(ptr, 0);
16334 internal_error(state, ptr, "no var???");
16336 /* Find the current value of the variable */
16337 val = peek_triple(stacks, var);
16338 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16339 internal_error(state, val, "bad value in phi");
16341 if (edge >= ptr->rhs) {
16342 internal_error(state, ptr, "edges > phi rhs");
16344 slot = &RHS(ptr, edge);
16345 if ((*slot != 0) && (*slot != val)) {
16346 internal_error(state, ptr, "phi already bound on this edge");
16349 use_triple(val, ptr);
16351 if (ptr == block->last) {
16358 static void rename_block_variables(
16359 struct compile_state *state, struct stack *stacks, struct block *block)
16361 struct block_set *user, *edge;
16362 struct triple *ptr, *next, *last;
16366 last = block->first;
16368 for(ptr = block->first; !done; ptr = next) {
16370 if (ptr == block->last) {
16374 if (ptr->op == OP_READ) {
16375 struct triple *var, *val;
16377 if (!triple_is_auto_var(state, var)) {
16378 internal_error(state, ptr, "read of non auto var!");
16380 unuse_triple(var, ptr);
16381 /* Find the current value of the variable */
16382 val = peek_triple(stacks, var);
16384 /* Let the optimizer at variables that are not initially
16385 * set. But give it a bogus value so things seem to
16386 * work by accident. This is useful for bitfields because
16387 * setting them always involves a read-modify-write.
16389 if (TYPE_ARITHMETIC(ptr->type->type)) {
16390 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16391 val->u.cval = 0xdeadbeaf;
16393 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16397 error(state, ptr, "variable used without being set");
16399 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16400 internal_error(state, val, "bad value in read");
16402 propogate_use(state, ptr, val);
16403 release_triple(state, ptr);
16407 if (ptr->op == OP_WRITE) {
16408 struct triple *var, *val, *tval;
16409 var = MISC(ptr, 0);
16410 if (!triple_is_auto_var(state, var)) {
16411 internal_error(state, ptr, "write to non auto var!");
16413 tval = val = RHS(ptr, 0);
16414 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16415 triple_is_auto_var(state, val)) {
16416 internal_error(state, ptr, "bad value in write");
16418 /* Insert a cast if the types differ */
16419 if (!is_subset_type(ptr->type, val->type)) {
16420 if (val->op == OP_INTCONST) {
16421 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16422 tval->u.cval = val->u.cval;
16425 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16426 use_triple(val, tval);
16428 transform_to_arch_instruction(state, tval);
16429 unuse_triple(val, ptr);
16430 RHS(ptr, 0) = tval;
16431 use_triple(tval, ptr);
16433 propogate_use(state, ptr, tval);
16434 unuse_triple(var, ptr);
16435 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16436 push_triple(stacks, var, tval);
16438 if (ptr->op == OP_PHI) {
16439 struct triple *var;
16440 var = MISC(ptr, 0);
16441 if (!triple_is_auto_var(state, var)) {
16442 internal_error(state, ptr, "phi references non auto var!");
16444 /* Push OP_PHI onto a stack of variable uses */
16445 push_triple(stacks, var, ptr);
16449 block->last = last;
16451 /* Fixup PHI functions in the cf successors */
16452 for(edge = block->edges; edge; edge = edge->next) {
16453 fixup_block_phi_variables(state, stacks, block, edge->member);
16455 /* rename variables in the dominated nodes */
16456 for(user = block->idominates; user; user = user->next) {
16457 rename_block_variables(state, stacks, user->member);
16459 /* pop the renamed variable stack */
16460 last = block->first;
16462 for(ptr = block->first; !done ; ptr = next) {
16464 if (ptr == block->last) {
16467 if (ptr->op == OP_WRITE) {
16468 struct triple *var;
16469 var = MISC(ptr, 0);
16470 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16471 pop_triple(stacks, var, RHS(ptr, 0));
16472 release_triple(state, ptr);
16475 if (ptr->op == OP_PHI) {
16476 struct triple *var;
16477 var = MISC(ptr, 0);
16478 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16479 pop_triple(stacks, var, ptr);
16483 block->last = last;
16486 static void rename_variables(struct compile_state *state)
16488 struct stack *stacks;
16491 /* Allocate stacks for the Variables */
16492 auto_vars = count_auto_vars(state);
16493 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16495 /* Give each auto_var a stack */
16496 number_auto_vars(state, stacks);
16498 /* Rename the variables */
16499 rename_block_variables(state, stacks, state->bb.first_block);
16501 /* Remove the stacks from the auto_vars */
16502 restore_auto_vars(state, stacks);
16506 static void prune_block_variables(struct compile_state *state,
16507 struct block *block)
16509 struct block_set *user;
16510 struct triple *next, *ptr;
16514 for(ptr = block->first; !done; ptr = next) {
16515 /* Be extremely careful I am deleting the list
16516 * as I walk trhough it.
16519 if (ptr == block->last) {
16522 if (triple_is_auto_var(state, ptr)) {
16523 struct triple_set *user, *next;
16524 for(user = ptr->use; user; user = next) {
16525 struct triple *use;
16527 use = user->member;
16528 if (MISC(ptr, 0) == user->member) {
16531 if (use->op != OP_PHI) {
16532 internal_error(state, use, "decl still used");
16534 if (MISC(use, 0) != ptr) {
16535 internal_error(state, use, "bad phi use of decl");
16537 unuse_triple(ptr, use);
16540 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16541 /* Delete the adecl */
16542 release_triple(state, MISC(ptr, 0));
16543 /* And the piece */
16544 release_triple(state, ptr);
16549 for(user = block->idominates; user; user = user->next) {
16550 prune_block_variables(state, user->member);
16554 struct phi_triple {
16555 struct triple *phi;
16560 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16562 struct triple **slot;
16564 if (live[phi->id].alive) {
16567 live[phi->id].alive = 1;
16569 slot = &RHS(phi, 0);
16570 for(i = 0; i < zrhs; i++) {
16571 struct triple *used;
16573 if (used && (used->op == OP_PHI)) {
16574 keep_phi(state, live, used);
16579 static void prune_unused_phis(struct compile_state *state)
16581 struct triple *first, *phi;
16582 struct phi_triple *live;
16585 /* Find the first instruction */
16586 first = state->first;
16588 /* Count how many phi functions I need to process */
16590 for(phi = first->next; phi != first; phi = phi->next) {
16591 if (phi->op == OP_PHI) {
16596 /* Mark them all dead */
16597 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16599 for(phi = first->next; phi != first; phi = phi->next) {
16600 if (phi->op != OP_PHI) {
16603 live[phis].alive = 0;
16604 live[phis].orig_id = phi->id;
16605 live[phis].phi = phi;
16610 /* Mark phis alive that are used by non phis */
16611 for(i = 0; i < phis; i++) {
16612 struct triple_set *set;
16613 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16614 if (set->member->op != OP_PHI) {
16615 keep_phi(state, live, live[i].phi);
16621 /* Delete the extraneous phis */
16622 for(i = 0; i < phis; i++) {
16623 struct triple **slot;
16625 if (!live[i].alive) {
16626 release_triple(state, live[i].phi);
16630 slot = &RHS(phi, 0);
16632 for(j = 0; j < zrhs; j++) {
16634 struct triple *unknown;
16635 get_occurance(phi->occurance);
16636 unknown = flatten(state, state->global_pool,
16637 alloc_triple(state, OP_UNKNOWNVAL,
16638 phi->type, 0, 0, phi->occurance));
16640 use_triple(unknown, phi);
16641 transform_to_arch_instruction(state, unknown);
16643 warning(state, phi, "variable not set at index %d on all paths to use", j);
16651 static void transform_to_ssa_form(struct compile_state *state)
16653 insert_phi_operations(state);
16654 rename_variables(state);
16656 prune_block_variables(state, state->bb.first_block);
16657 prune_unused_phis(state);
16659 print_blocks(state, __func__, state->dbgout);
16663 static void clear_vertex(
16664 struct compile_state *state, struct block *block, void *arg)
16666 /* Clear the current blocks vertex and the vertex of all
16667 * of the current blocks neighbors in case there are malformed
16668 * blocks with now instructions at this point.
16670 struct block_set *user, *edge;
16672 for(edge = block->edges; edge; edge = edge->next) {
16673 edge->member->vertex = 0;
16675 for(user = block->use; user; user = user->next) {
16676 user->member->vertex = 0;
16680 static void mark_live_block(
16681 struct compile_state *state, struct block *block, int *next_vertex)
16683 /* See if this is a block that has not been marked */
16684 if (block->vertex != 0) {
16687 block->vertex = *next_vertex;
16689 if (triple_is_branch(state, block->last)) {
16690 struct triple **targ;
16691 targ = triple_edge_targ(state, block->last, 0);
16692 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16696 if (!triple_stores_block(state, *targ)) {
16697 internal_error(state, 0, "bad targ");
16699 mark_live_block(state, (*targ)->u.block, next_vertex);
16701 /* Ensure the last block of a function remains alive */
16702 if (triple_is_call(state, block->last)) {
16703 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16706 else if (block->last->next != state->first) {
16707 struct triple *ins;
16708 ins = block->last->next;
16709 if (!triple_stores_block(state, ins)) {
16710 internal_error(state, 0, "bad block start");
16712 mark_live_block(state, ins->u.block, next_vertex);
16716 static void transform_from_ssa_form(struct compile_state *state)
16718 /* To get out of ssa form we insert moves on the incoming
16719 * edges to blocks containting phi functions.
16721 struct triple *first;
16722 struct triple *phi, *var, *next;
16725 /* Walk the control flow to see which blocks remain alive */
16726 walk_blocks(state, &state->bb, clear_vertex, 0);
16728 mark_live_block(state, state->bb.first_block, &next_vertex);
16730 /* Walk all of the operations to find the phi functions */
16731 first = state->first;
16732 for(phi = first->next; phi != first ; phi = next) {
16733 struct block_set *set;
16734 struct block *block;
16735 struct triple **slot;
16736 struct triple *var;
16737 struct triple_set *use, *use_next;
16738 int edge, writers, readers;
16740 if (phi->op != OP_PHI) {
16744 block = phi->u.block;
16745 slot = &RHS(phi, 0);
16747 /* If this phi is in a dead block just forget it */
16748 if (block->vertex == 0) {
16749 release_triple(state, phi);
16753 /* Forget uses from code in dead blocks */
16754 for(use = phi->use; use; use = use_next) {
16755 struct block *ublock;
16756 struct triple **expr;
16757 use_next = use->next;
16758 ublock = block_of_triple(state, use->member);
16759 if ((use->member == phi) || (ublock->vertex != 0)) {
16762 expr = triple_rhs(state, use->member, 0);
16763 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16764 if (*expr == phi) {
16768 unuse_triple(phi, use->member);
16770 /* A variable to replace the phi function */
16771 if (registers_of(state, phi->type) != 1) {
16772 internal_error(state, phi, "phi->type does not fit in a single register!");
16774 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16775 var = var->next; /* point at the var */
16777 /* Replaces use of phi with var */
16778 propogate_use(state, phi, var);
16780 /* Count the readers */
16782 for(use = var->use; use; use = use->next) {
16783 if (use->member != MISC(var, 0)) {
16788 /* Walk all of the incoming edges/blocks and insert moves.
16791 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16792 struct block *eblock, *vblock;
16793 struct triple *move;
16794 struct triple *val, *base;
16795 eblock = set->member;
16798 unuse_triple(val, phi);
16799 vblock = block_of_triple(state, val);
16801 /* If we don't have a value that belongs in an OP_WRITE
16804 if (!val || (val == &unknown_triple) || (val == phi)
16805 || (vblock && (vblock->vertex == 0))) {
16808 /* If the value should never occur error */
16810 internal_error(state, val, "no vblock?");
16814 /* If the value occurs in a dead block see if a replacement
16815 * block can be found.
16817 while(eblock && (eblock->vertex == 0)) {
16818 eblock = eblock->idom;
16820 /* If not continue on with the next value. */
16821 if (!eblock || (eblock->vertex == 0)) {
16825 /* If we have an empty incoming block ignore it. */
16826 if (!eblock->first) {
16827 internal_error(state, 0, "empty block?");
16830 /* Make certain the write is placed in the edge block... */
16831 /* Walk through the edge block backwards to find an
16832 * appropriate location for the OP_WRITE.
16834 for(base = eblock->last; base != eblock->first; base = base->prev) {
16835 struct triple **expr;
16836 if (base->op == OP_PIECE) {
16837 base = MISC(base, 0);
16839 if ((base == var) || (base == val)) {
16842 expr = triple_lhs(state, base, 0);
16843 for(; expr; expr = triple_lhs(state, base, expr)) {
16844 if ((*expr) == val) {
16848 expr = triple_rhs(state, base, 0);
16849 for(; expr; expr = triple_rhs(state, base, expr)) {
16850 if ((*expr) == var) {
16856 if (triple_is_branch(state, base)) {
16857 internal_error(state, base,
16858 "Could not insert write to phi");
16860 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16861 use_triple(val, move);
16862 use_triple(var, move);
16865 if (!writers && readers) {
16866 internal_error(state, var, "no value written to in use phi?");
16868 /* If var is not used free it */
16870 release_triple(state, MISC(var, 0));
16871 release_triple(state, var);
16873 /* Release the phi function */
16874 release_triple(state, phi);
16877 /* Walk all of the operations to find the adecls */
16878 for(var = first->next; var != first ; var = var->next) {
16879 struct triple_set *use, *use_next;
16880 if (!triple_is_auto_var(state, var)) {
16884 /* Walk through all of the rhs uses of var and
16885 * replace them with read of var.
16887 for(use = var->use; use; use = use_next) {
16888 struct triple *read, *user;
16889 struct triple **slot;
16891 use_next = use->next;
16892 user = use->member;
16894 /* Generate a read of var */
16895 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16896 use_triple(var, read);
16898 /* Find the rhs uses and see if they need to be replaced */
16901 slot = &RHS(user, 0);
16902 for(i = 0; i < zrhs; i++) {
16903 if (slot[i] == var) {
16908 /* If we did use it cleanup the uses */
16910 unuse_triple(var, user);
16911 use_triple(read, user);
16913 /* If we didn't use it release the extra triple */
16915 release_triple(state, read);
16921 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16922 FILE *fp = state->dbgout; \
16923 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16926 static void rebuild_ssa_form(struct compile_state *state)
16929 transform_from_ssa_form(state);
16931 state->bb.first = state->first;
16932 free_basic_blocks(state, &state->bb);
16933 analyze_basic_blocks(state, &state->bb);
16935 insert_phi_operations(state);
16937 rename_variables(state);
16940 prune_block_variables(state, state->bb.first_block);
16942 prune_unused_phis(state);
16948 * Register conflict resolution
16949 * =========================================================
16952 static struct reg_info find_def_color(
16953 struct compile_state *state, struct triple *def)
16955 struct triple_set *set;
16956 struct reg_info info;
16957 info.reg = REG_UNSET;
16959 if (!triple_is_def(state, def)) {
16962 info = arch_reg_lhs(state, def, 0);
16963 if (info.reg >= MAX_REGISTERS) {
16964 info.reg = REG_UNSET;
16966 for(set = def->use; set; set = set->next) {
16967 struct reg_info tinfo;
16969 i = find_rhs_use(state, set->member, def);
16973 tinfo = arch_reg_rhs(state, set->member, i);
16974 if (tinfo.reg >= MAX_REGISTERS) {
16975 tinfo.reg = REG_UNSET;
16977 if ((tinfo.reg != REG_UNSET) &&
16978 (info.reg != REG_UNSET) &&
16979 (tinfo.reg != info.reg)) {
16980 internal_error(state, def, "register conflict");
16982 if ((info.regcm & tinfo.regcm) == 0) {
16983 internal_error(state, def, "regcm conflict %x & %x == 0",
16984 info.regcm, tinfo.regcm);
16986 if (info.reg == REG_UNSET) {
16987 info.reg = tinfo.reg;
16989 info.regcm &= tinfo.regcm;
16991 if (info.reg >= MAX_REGISTERS) {
16992 internal_error(state, def, "register out of range");
16997 static struct reg_info find_lhs_pre_color(
16998 struct compile_state *state, struct triple *ins, int index)
17000 struct reg_info info;
17004 if (!zlhs && triple_is_def(state, ins)) {
17007 if (index >= zlhs) {
17008 internal_error(state, ins, "Bad lhs %d", index);
17010 info = arch_reg_lhs(state, ins, index);
17011 for(i = 0; i < zrhs; i++) {
17012 struct reg_info rinfo;
17013 rinfo = arch_reg_rhs(state, ins, i);
17014 if ((info.reg == rinfo.reg) &&
17015 (rinfo.reg >= MAX_REGISTERS)) {
17016 struct reg_info tinfo;
17017 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
17018 info.reg = tinfo.reg;
17019 info.regcm &= tinfo.regcm;
17023 if (info.reg >= MAX_REGISTERS) {
17024 info.reg = REG_UNSET;
17029 static struct reg_info find_rhs_post_color(
17030 struct compile_state *state, struct triple *ins, int index);
17032 static struct reg_info find_lhs_post_color(
17033 struct compile_state *state, struct triple *ins, int index)
17035 struct triple_set *set;
17036 struct reg_info info;
17037 struct triple *lhs;
17038 #if DEBUG_TRIPLE_COLOR
17039 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17042 if ((index == 0) && triple_is_def(state, ins)) {
17045 else if (index < ins->lhs) {
17046 lhs = LHS(ins, index);
17049 internal_error(state, ins, "Bad lhs %d", index);
17052 info = arch_reg_lhs(state, ins, index);
17053 if (info.reg >= MAX_REGISTERS) {
17054 info.reg = REG_UNSET;
17056 for(set = lhs->use; set; set = set->next) {
17057 struct reg_info rinfo;
17058 struct triple *user;
17060 user = set->member;
17062 for(i = 0; i < zrhs; i++) {
17063 if (RHS(user, i) != lhs) {
17066 rinfo = find_rhs_post_color(state, user, i);
17067 if ((info.reg != REG_UNSET) &&
17068 (rinfo.reg != REG_UNSET) &&
17069 (info.reg != rinfo.reg)) {
17070 internal_error(state, ins, "register conflict");
17072 if ((info.regcm & rinfo.regcm) == 0) {
17073 internal_error(state, ins, "regcm conflict %x & %x == 0",
17074 info.regcm, rinfo.regcm);
17076 if (info.reg == REG_UNSET) {
17077 info.reg = rinfo.reg;
17079 info.regcm &= rinfo.regcm;
17082 #if DEBUG_TRIPLE_COLOR
17083 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17084 ins, index, info.reg, info.regcm);
17089 static struct reg_info find_rhs_post_color(
17090 struct compile_state *state, struct triple *ins, int index)
17092 struct reg_info info, rinfo;
17094 #if DEBUG_TRIPLE_COLOR
17095 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17098 rinfo = arch_reg_rhs(state, ins, index);
17100 if (!zlhs && triple_is_def(state, ins)) {
17104 if (info.reg >= MAX_REGISTERS) {
17105 info.reg = REG_UNSET;
17107 for(i = 0; i < zlhs; i++) {
17108 struct reg_info linfo;
17109 linfo = arch_reg_lhs(state, ins, i);
17110 if ((linfo.reg == rinfo.reg) &&
17111 (linfo.reg >= MAX_REGISTERS)) {
17112 struct reg_info tinfo;
17113 tinfo = find_lhs_post_color(state, ins, i);
17114 if (tinfo.reg >= MAX_REGISTERS) {
17115 tinfo.reg = REG_UNSET;
17117 info.regcm &= linfo.regcm;
17118 info.regcm &= tinfo.regcm;
17119 if (info.reg != REG_UNSET) {
17120 internal_error(state, ins, "register conflict");
17122 if (info.regcm == 0) {
17123 internal_error(state, ins, "regcm conflict");
17125 info.reg = tinfo.reg;
17128 #if DEBUG_TRIPLE_COLOR
17129 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17130 ins, index, info.reg, info.regcm);
17135 static struct reg_info find_lhs_color(
17136 struct compile_state *state, struct triple *ins, int index)
17138 struct reg_info pre, post, info;
17139 #if DEBUG_TRIPLE_COLOR
17140 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17143 pre = find_lhs_pre_color(state, ins, index);
17144 post = find_lhs_post_color(state, ins, index);
17145 if ((pre.reg != post.reg) &&
17146 (pre.reg != REG_UNSET) &&
17147 (post.reg != REG_UNSET)) {
17148 internal_error(state, ins, "register conflict");
17150 info.regcm = pre.regcm & post.regcm;
17151 info.reg = pre.reg;
17152 if (info.reg == REG_UNSET) {
17153 info.reg = post.reg;
17155 #if DEBUG_TRIPLE_COLOR
17156 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17157 ins, index, info.reg, info.regcm,
17158 pre.reg, pre.regcm, post.reg, post.regcm);
17163 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17165 struct triple_set *entry, *next;
17166 struct triple *out;
17167 struct reg_info info, rinfo;
17169 info = arch_reg_lhs(state, ins, 0);
17170 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17171 use_triple(RHS(out, 0), out);
17172 /* Get the users of ins to use out instead */
17173 for(entry = ins->use; entry; entry = next) {
17175 next = entry->next;
17176 if (entry->member == out) {
17179 i = find_rhs_use(state, entry->member, ins);
17183 rinfo = arch_reg_rhs(state, entry->member, i);
17184 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17187 replace_rhs_use(state, ins, out, entry->member);
17189 transform_to_arch_instruction(state, out);
17193 static struct triple *typed_pre_copy(
17194 struct compile_state *state, struct type *type, struct triple *ins, int index)
17196 /* Carefully insert enough operations so that I can
17197 * enter any operation with a GPR32.
17200 struct triple **expr;
17202 struct reg_info info;
17204 if (ins->op == OP_PHI) {
17205 internal_error(state, ins, "pre_copy on a phi?");
17207 classes = arch_type_to_regcm(state, type);
17208 info = arch_reg_rhs(state, ins, index);
17209 expr = &RHS(ins, index);
17210 if ((info.regcm & classes) == 0) {
17211 FILE *fp = state->errout;
17212 fprintf(fp, "src_type: ");
17213 name_of(fp, ins->type);
17214 fprintf(fp, "\ndst_type: ");
17217 internal_error(state, ins, "pre_copy with no register classes");
17220 if (!equiv_types(type, (*expr)->type)) {
17223 in = pre_triple(state, ins, op, type, *expr, 0);
17224 unuse_triple(*expr, ins);
17226 use_triple(RHS(in, 0), in);
17227 use_triple(in, ins);
17228 transform_to_arch_instruction(state, in);
17232 static struct triple *pre_copy(
17233 struct compile_state *state, struct triple *ins, int index)
17235 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17239 static void insert_copies_to_phi(struct compile_state *state)
17241 /* To get out of ssa form we insert moves on the incoming
17242 * edges to blocks containting phi functions.
17244 struct triple *first;
17245 struct triple *phi;
17247 /* Walk all of the operations to find the phi functions */
17248 first = state->first;
17249 for(phi = first->next; phi != first ; phi = phi->next) {
17250 struct block_set *set;
17251 struct block *block;
17252 struct triple **slot, *copy;
17254 if (phi->op != OP_PHI) {
17257 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17258 block = phi->u.block;
17259 slot = &RHS(phi, 0);
17260 /* Phi's that feed into mandatory live range joins
17261 * cause nasty complications. Insert a copy of
17262 * the phi value so I never have to deal with
17263 * that in the rest of the code.
17265 copy = post_copy(state, phi);
17266 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17267 /* Walk all of the incoming edges/blocks and insert moves.
17269 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17270 struct block *eblock;
17271 struct triple *move;
17272 struct triple *val;
17273 struct triple *ptr;
17274 eblock = set->member;
17281 get_occurance(val->occurance);
17282 move = build_triple(state, OP_COPY, val->type, val, 0,
17284 move->u.block = eblock;
17285 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17286 use_triple(val, move);
17289 unuse_triple(val, phi);
17290 use_triple(move, phi);
17292 /* Walk up the dominator tree until I have found the appropriate block */
17293 while(eblock && !tdominates(state, val, eblock->last)) {
17294 eblock = eblock->idom;
17297 internal_error(state, phi, "Cannot find block dominated by %p",
17301 /* Walk through the block backwards to find
17302 * an appropriate location for the OP_COPY.
17304 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17305 struct triple **expr;
17306 if (ptr->op == OP_PIECE) {
17307 ptr = MISC(ptr, 0);
17309 if ((ptr == phi) || (ptr == val)) {
17312 expr = triple_lhs(state, ptr, 0);
17313 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17314 if ((*expr) == val) {
17318 expr = triple_rhs(state, ptr, 0);
17319 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17320 if ((*expr) == phi) {
17326 if (triple_is_branch(state, ptr)) {
17327 internal_error(state, ptr,
17328 "Could not insert write to phi");
17330 insert_triple(state, after_lhs(state, ptr), move);
17331 if (eblock->last == after_lhs(state, ptr)->prev) {
17332 eblock->last = move;
17334 transform_to_arch_instruction(state, move);
17337 print_blocks(state, __func__, state->dbgout);
17340 struct triple_reg_set;
17344 static int do_triple_set(struct triple_reg_set **head,
17345 struct triple *member, struct triple *new_member)
17347 struct triple_reg_set **ptr, *new;
17352 if ((*ptr)->member == member) {
17355 ptr = &(*ptr)->next;
17357 new = xcmalloc(sizeof(*new), "triple_set");
17358 new->member = member;
17359 new->new = new_member;
17365 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17367 struct triple_reg_set *entry, **ptr;
17371 if (entry->member == member) {
17372 *ptr = entry->next;
17377 ptr = &entry->next;
17382 static int in_triple(struct reg_block *rb, struct triple *in)
17384 return do_triple_set(&rb->in, in, 0);
17387 #if DEBUG_ROMCC_WARNING
17388 static void unin_triple(struct reg_block *rb, struct triple *unin)
17390 do_triple_unset(&rb->in, unin);
17394 static int out_triple(struct reg_block *rb, struct triple *out)
17396 return do_triple_set(&rb->out, out, 0);
17398 #if DEBUG_ROMCC_WARNING
17399 static void unout_triple(struct reg_block *rb, struct triple *unout)
17401 do_triple_unset(&rb->out, unout);
17405 static int initialize_regblock(struct reg_block *blocks,
17406 struct block *block, int vertex)
17408 struct block_set *user;
17409 if (!block || (blocks[block->vertex].block == block)) {
17413 /* Renumber the blocks in a convinient fashion */
17414 block->vertex = vertex;
17415 blocks[vertex].block = block;
17416 blocks[vertex].vertex = vertex;
17417 for(user = block->use; user; user = user->next) {
17418 vertex = initialize_regblock(blocks, user->member, vertex);
17423 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17425 /* Part to piece is a best attempt and it cannot be correct all by
17426 * itself. If various values are read as different sizes in different
17427 * parts of the code this function cannot work. Or rather it cannot
17428 * work in conjunction with compute_variable_liftimes. As the
17429 * analysis will get confused.
17431 struct triple *base;
17433 if (!is_lvalue(state, ins)) {
17438 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17439 base = MISC(ins, 0);
17442 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17445 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17448 internal_error(state, ins, "unhandled part");
17454 if (reg > base->lhs) {
17455 internal_error(state, base, "part out of range?");
17457 ins = LHS(base, reg);
17462 static int this_def(struct compile_state *state,
17463 struct triple *ins, struct triple *other)
17465 if (ins == other) {
17468 if (ins->op == OP_WRITE) {
17469 ins = part_to_piece(state, MISC(ins, 0));
17471 return ins == other;
17474 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17475 struct reg_block *rb, struct block *suc)
17477 /* Read the conditional input set of a successor block
17478 * (i.e. the input to the phi nodes) and place it in the
17479 * current blocks output set.
17481 struct block_set *set;
17482 struct triple *ptr;
17486 /* Find the edge I am coming in on */
17487 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17488 if (set->member == rb->block) {
17493 internal_error(state, 0, "Not coming on a control edge?");
17495 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17496 struct triple **slot, *expr, *ptr2;
17497 int out_change, done2;
17498 done = (ptr == suc->last);
17499 if (ptr->op != OP_PHI) {
17502 slot = &RHS(ptr, 0);
17504 out_change = out_triple(rb, expr);
17508 /* If we don't define the variable also plast it
17509 * in the current blocks input set.
17511 ptr2 = rb->block->first;
17512 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17513 if (this_def(state, ptr2, expr)) {
17516 done2 = (ptr2 == rb->block->last);
17521 change |= in_triple(rb, expr);
17526 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17527 struct reg_block *rb, struct block *suc)
17529 struct triple_reg_set *in_set;
17532 /* Read the input set of a successor block
17533 * and place it in the current blocks output set.
17535 in_set = blocks[suc->vertex].in;
17536 for(; in_set; in_set = in_set->next) {
17537 int out_change, done;
17538 struct triple *first, *last, *ptr;
17539 out_change = out_triple(rb, in_set->member);
17543 /* If we don't define the variable also place it
17544 * in the current blocks input set.
17546 first = rb->block->first;
17547 last = rb->block->last;
17549 for(ptr = first; !done; ptr = ptr->next) {
17550 if (this_def(state, ptr, in_set->member)) {
17553 done = (ptr == last);
17558 change |= in_triple(rb, in_set->member);
17560 change |= phi_in(state, blocks, rb, suc);
17564 static int use_in(struct compile_state *state, struct reg_block *rb)
17566 /* Find the variables we use but don't define and add
17567 * it to the current blocks input set.
17569 #if DEBUG_ROMCC_WARNINGS
17570 #warning "FIXME is this O(N^2) algorithm bad?"
17572 struct block *block;
17573 struct triple *ptr;
17578 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17579 struct triple **expr;
17580 done = (ptr == block->first);
17581 /* The variable a phi function uses depends on the
17582 * control flow, and is handled in phi_in, not
17585 if (ptr->op == OP_PHI) {
17588 expr = triple_rhs(state, ptr, 0);
17589 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17590 struct triple *rhs, *test;
17592 rhs = part_to_piece(state, *expr);
17597 /* See if rhs is defined in this block.
17598 * A write counts as a definition.
17600 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17601 tdone = (test == block->first);
17602 if (this_def(state, test, rhs)) {
17607 /* If I still have a valid rhs add it to in */
17608 change |= in_triple(rb, rhs);
17614 static struct reg_block *compute_variable_lifetimes(
17615 struct compile_state *state, struct basic_blocks *bb)
17617 struct reg_block *blocks;
17620 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17621 initialize_regblock(blocks, bb->last_block, 0);
17625 for(i = 1; i <= bb->last_vertex; i++) {
17626 struct block_set *edge;
17627 struct reg_block *rb;
17629 /* Add the all successor's input set to in */
17630 for(edge = rb->block->edges; edge; edge = edge->next) {
17631 change |= reg_in(state, blocks, rb, edge->member);
17633 /* Add use to in... */
17634 change |= use_in(state, rb);
17640 static void free_variable_lifetimes(struct compile_state *state,
17641 struct basic_blocks *bb, struct reg_block *blocks)
17644 /* free in_set && out_set on each block */
17645 for(i = 1; i <= bb->last_vertex; i++) {
17646 struct triple_reg_set *entry, *next;
17647 struct reg_block *rb;
17649 for(entry = rb->in; entry ; entry = next) {
17650 next = entry->next;
17651 do_triple_unset(&rb->in, entry->member);
17653 for(entry = rb->out; entry; entry = next) {
17654 next = entry->next;
17655 do_triple_unset(&rb->out, entry->member);
17662 typedef void (*wvl_cb_t)(
17663 struct compile_state *state,
17664 struct reg_block *blocks, struct triple_reg_set *live,
17665 struct reg_block *rb, struct triple *ins, void *arg);
17667 static void walk_variable_lifetimes(struct compile_state *state,
17668 struct basic_blocks *bb, struct reg_block *blocks,
17669 wvl_cb_t cb, void *arg)
17673 for(i = 1; i <= state->bb.last_vertex; i++) {
17674 struct triple_reg_set *live;
17675 struct triple_reg_set *entry, *next;
17676 struct triple *ptr, *prev;
17677 struct reg_block *rb;
17678 struct block *block;
17681 /* Get the blocks */
17685 /* Copy out into live */
17687 for(entry = rb->out; entry; entry = next) {
17688 next = entry->next;
17689 do_triple_set(&live, entry->member, entry->new);
17691 /* Walk through the basic block calculating live */
17692 for(done = 0, ptr = block->last; !done; ptr = prev) {
17693 struct triple **expr;
17696 done = (ptr == block->first);
17698 /* Ensure the current definition is in live */
17699 if (triple_is_def(state, ptr)) {
17700 do_triple_set(&live, ptr, 0);
17703 /* Inform the callback function of what is
17706 cb(state, blocks, live, rb, ptr, arg);
17708 /* Remove the current definition from live */
17709 do_triple_unset(&live, ptr);
17711 /* Add the current uses to live.
17713 * It is safe to skip phi functions because they do
17714 * not have any block local uses, and the block
17715 * output sets already properly account for what
17716 * control flow depedent uses phi functions do have.
17718 if (ptr->op == OP_PHI) {
17721 expr = triple_rhs(state, ptr, 0);
17722 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17723 /* If the triple is not a definition skip it. */
17724 if (!*expr || !triple_is_def(state, *expr)) {
17727 do_triple_set(&live, *expr, 0);
17731 for(entry = live; entry; entry = next) {
17732 next = entry->next;
17733 do_triple_unset(&live, entry->member);
17738 struct print_live_variable_info {
17739 struct reg_block *rb;
17742 #if DEBUG_EXPLICIT_CLOSURES
17743 static void print_live_variables_block(
17744 struct compile_state *state, struct block *block, void *arg)
17747 struct print_live_variable_info *info = arg;
17748 struct block_set *edge;
17749 FILE *fp = info->fp;
17750 struct reg_block *rb;
17751 struct triple *ptr;
17754 rb = &info->rb[block->vertex];
17756 fprintf(fp, "\nblock: %p (%d),",
17757 block, block->vertex);
17758 for(edge = block->edges; edge; edge = edge->next) {
17759 fprintf(fp, " %p<-%p",
17761 edge->member && edge->member->use?edge->member->use->member : 0);
17765 struct triple_reg_set *in_set;
17766 fprintf(fp, " in:");
17767 for(in_set = rb->in; in_set; in_set = in_set->next) {
17768 fprintf(fp, " %-10p", in_set->member);
17773 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17774 done = (ptr == block->last);
17775 if (ptr->op == OP_PHI) {
17782 for(edge = 0; edge < block->users; edge++) {
17783 fprintf(fp, " in(%d):", edge);
17784 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17785 struct triple **slot;
17786 done = (ptr == block->last);
17787 if (ptr->op != OP_PHI) {
17790 slot = &RHS(ptr, 0);
17791 fprintf(fp, " %-10p", slot[edge]);
17796 if (block->first->op == OP_LABEL) {
17797 fprintf(fp, "%p:\n", block->first);
17799 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17800 done = (ptr == block->last);
17801 display_triple(fp, ptr);
17804 struct triple_reg_set *out_set;
17805 fprintf(fp, " out:");
17806 for(out_set = rb->out; out_set; out_set = out_set->next) {
17807 fprintf(fp, " %-10p", out_set->member);
17814 static void print_live_variables(struct compile_state *state,
17815 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17817 struct print_live_variable_info info;
17820 fprintf(fp, "\nlive variables by block\n");
17821 walk_blocks(state, bb, print_live_variables_block, &info);
17826 static int count_triples(struct compile_state *state)
17828 struct triple *first, *ins;
17830 first = state->first;
17835 } while (ins != first);
17840 struct dead_triple {
17841 struct triple *triple;
17842 struct dead_triple *work_next;
17843 struct block *block;
17846 #define TRIPLE_FLAG_ALIVE 1
17847 #define TRIPLE_FLAG_FREE 1
17850 static void print_dead_triples(struct compile_state *state,
17851 struct dead_triple *dtriple)
17853 struct triple *first, *ins;
17854 struct dead_triple *dt;
17856 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17859 fp = state->dbgout;
17860 fprintf(fp, "--------------- dtriples ---------------\n");
17861 first = state->first;
17864 dt = &dtriple[ins->id];
17865 if ((ins->op == OP_LABEL) && (ins->use)) {
17866 fprintf(fp, "\n%p:\n", ins);
17869 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17870 display_triple(fp, ins);
17871 if (triple_is_branch(state, ins)) {
17875 } while(ins != first);
17880 static void awaken(
17881 struct compile_state *state,
17882 struct dead_triple *dtriple, struct triple **expr,
17883 struct dead_triple ***work_list_tail)
17885 struct triple *triple;
17886 struct dead_triple *dt;
17894 if (triple->id <= 0) {
17895 internal_error(state, triple, "bad triple id: %d",
17898 if (triple->op == OP_NOOP) {
17899 internal_error(state, triple, "awakening noop?");
17902 dt = &dtriple[triple->id];
17903 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17904 dt->flags |= TRIPLE_FLAG_ALIVE;
17905 if (!dt->work_next) {
17906 **work_list_tail = dt;
17907 *work_list_tail = &dt->work_next;
17912 static void eliminate_inefectual_code(struct compile_state *state)
17914 struct block *block;
17915 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17917 struct triple *first, *final, *ins;
17919 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17923 /* Setup the work list */
17925 work_list_tail = &work_list;
17927 first = state->first;
17928 final = state->first->prev;
17930 /* Count how many triples I have */
17931 triples = count_triples(state);
17933 /* Now put then in an array and mark all of the triples dead */
17934 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17940 dtriple[i].triple = ins;
17941 dtriple[i].block = block_of_triple(state, ins);
17942 dtriple[i].flags = 0;
17943 dtriple[i].old_id = ins->id;
17945 /* See if it is an operation we always keep */
17946 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17947 awaken(state, dtriple, &ins, &work_list_tail);
17951 } while(ins != first);
17953 struct block *block;
17954 struct dead_triple *dt;
17955 struct block_set *user;
17956 struct triple **expr;
17958 work_list = dt->work_next;
17960 work_list_tail = &work_list;
17962 /* Make certain the block the current instruction is in lives */
17963 block = block_of_triple(state, dt->triple);
17964 awaken(state, dtriple, &block->first, &work_list_tail);
17965 if (triple_is_branch(state, block->last)) {
17966 awaken(state, dtriple, &block->last, &work_list_tail);
17968 awaken(state, dtriple, &block->last->next, &work_list_tail);
17971 /* Wake up the data depencencies of this triple */
17974 expr = triple_rhs(state, dt->triple, expr);
17975 awaken(state, dtriple, expr, &work_list_tail);
17978 expr = triple_lhs(state, dt->triple, expr);
17979 awaken(state, dtriple, expr, &work_list_tail);
17982 expr = triple_misc(state, dt->triple, expr);
17983 awaken(state, dtriple, expr, &work_list_tail);
17985 /* Wake up the forward control dependencies */
17987 expr = triple_targ(state, dt->triple, expr);
17988 awaken(state, dtriple, expr, &work_list_tail);
17990 /* Wake up the reverse control dependencies of this triple */
17991 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17992 struct triple *last;
17993 last = user->member->last;
17994 while((last->op == OP_NOOP) && (last != user->member->first)) {
17995 #if DEBUG_ROMCC_WARNINGS
17996 #warning "Should we bring the awakening noops back?"
17998 // internal_warning(state, last, "awakening noop?");
18001 awaken(state, dtriple, &last, &work_list_tail);
18004 print_dead_triples(state, dtriple);
18005 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
18006 if ((dt->triple->op == OP_NOOP) &&
18007 (dt->flags & TRIPLE_FLAG_ALIVE)) {
18008 internal_error(state, dt->triple, "noop effective?");
18010 dt->triple->id = dt->old_id; /* Restore the color */
18011 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
18012 release_triple(state, dt->triple);
18017 rebuild_ssa_form(state);
18019 print_blocks(state, __func__, state->dbgout);
18023 static void insert_mandatory_copies(struct compile_state *state)
18025 struct triple *ins, *first;
18027 /* The object is with a minimum of inserted copies,
18028 * to resolve in fundamental register conflicts between
18029 * register value producers and consumers.
18030 * Theoretically we may be greater than minimal when we
18031 * are inserting copies before instructions but that
18032 * case should be rare.
18034 first = state->first;
18037 struct triple_set *entry, *next;
18038 struct triple *tmp;
18039 struct reg_info info;
18040 unsigned reg, regcm;
18041 int do_post_copy, do_pre_copy;
18043 if (!triple_is_def(state, ins)) {
18046 /* Find the architecture specific color information */
18047 info = find_lhs_pre_color(state, ins, 0);
18048 if (info.reg >= MAX_REGISTERS) {
18049 info.reg = REG_UNSET;
18053 regcm = arch_type_to_regcm(state, ins->type);
18054 do_post_copy = do_pre_copy = 0;
18056 /* Walk through the uses of ins and check for conflicts */
18057 for(entry = ins->use; entry; entry = next) {
18058 struct reg_info rinfo;
18060 next = entry->next;
18061 i = find_rhs_use(state, entry->member, ins);
18066 /* Find the users color requirements */
18067 rinfo = arch_reg_rhs(state, entry->member, i);
18068 if (rinfo.reg >= MAX_REGISTERS) {
18069 rinfo.reg = REG_UNSET;
18072 /* See if I need a pre_copy */
18073 if (rinfo.reg != REG_UNSET) {
18074 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18079 regcm &= rinfo.regcm;
18080 regcm = arch_regcm_normalize(state, regcm);
18084 /* Always use pre_copies for constants.
18085 * They do not take up any registers until a
18086 * copy places them in one.
18088 if ((info.reg == REG_UNNEEDED) &&
18089 (rinfo.reg != REG_UNNEEDED)) {
18095 (((info.reg != REG_UNSET) &&
18096 (reg != REG_UNSET) &&
18097 (info.reg != reg)) ||
18098 ((info.regcm & regcm) == 0));
18101 regcm = info.regcm;
18102 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18103 for(entry = ins->use; entry; entry = next) {
18104 struct reg_info rinfo;
18106 next = entry->next;
18107 i = find_rhs_use(state, entry->member, ins);
18112 /* Find the users color requirements */
18113 rinfo = arch_reg_rhs(state, entry->member, i);
18114 if (rinfo.reg >= MAX_REGISTERS) {
18115 rinfo.reg = REG_UNSET;
18118 /* Now see if it is time to do the pre_copy */
18119 if (rinfo.reg != REG_UNSET) {
18120 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18121 ((regcm & rinfo.regcm) == 0) ||
18122 /* Don't let a mandatory coalesce sneak
18123 * into a operation that is marked to prevent
18126 ((reg != REG_UNNEEDED) &&
18127 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18128 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18131 struct triple *user;
18132 user = entry->member;
18133 if (RHS(user, i) != ins) {
18134 internal_error(state, user, "bad rhs");
18136 tmp = pre_copy(state, user, i);
18137 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18145 if ((regcm & rinfo.regcm) == 0) {
18147 struct triple *user;
18148 user = entry->member;
18149 if (RHS(user, i) != ins) {
18150 internal_error(state, user, "bad rhs");
18152 tmp = pre_copy(state, user, i);
18153 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18159 regcm &= rinfo.regcm;
18162 if (do_post_copy) {
18163 struct reg_info pre, post;
18164 tmp = post_copy(state, ins);
18165 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18166 pre = arch_reg_lhs(state, ins, 0);
18167 post = arch_reg_lhs(state, tmp, 0);
18168 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18169 internal_error(state, tmp, "useless copy");
18174 } while(ins != first);
18176 print_blocks(state, __func__, state->dbgout);
18180 struct live_range_edge;
18181 struct live_range_def;
18182 struct live_range {
18183 struct live_range_edge *edges;
18184 struct live_range_def *defs;
18185 /* Note. The list pointed to by defs is kept in order.
18186 * That is baring splits in the flow control
18187 * defs dominates defs->next wich dominates defs->next->next
18194 struct live_range *group_next, **group_prev;
18197 struct live_range_edge {
18198 struct live_range_edge *next;
18199 struct live_range *node;
18202 struct live_range_def {
18203 struct live_range_def *next;
18204 struct live_range_def *prev;
18205 struct live_range *lr;
18206 struct triple *def;
18210 #define LRE_HASH_SIZE 2048
18212 struct lre_hash *next;
18213 struct live_range *left;
18214 struct live_range *right;
18219 struct lre_hash *hash[LRE_HASH_SIZE];
18220 struct reg_block *blocks;
18221 struct live_range_def *lrd;
18222 struct live_range *lr;
18223 struct live_range *low, **low_tail;
18224 struct live_range *high, **high_tail;
18227 int passes, max_passes;
18231 struct print_interference_block_info {
18232 struct reg_state *rstate;
18236 static void print_interference_block(
18237 struct compile_state *state, struct block *block, void *arg)
18240 struct print_interference_block_info *info = arg;
18241 struct reg_state *rstate = info->rstate;
18242 struct block_set *edge;
18243 FILE *fp = info->fp;
18244 struct reg_block *rb;
18245 struct triple *ptr;
18248 rb = &rstate->blocks[block->vertex];
18250 fprintf(fp, "\nblock: %p (%d),",
18251 block, block->vertex);
18252 for(edge = block->edges; edge; edge = edge->next) {
18253 fprintf(fp, " %p<-%p",
18255 edge->member && edge->member->use?edge->member->use->member : 0);
18259 struct triple_reg_set *in_set;
18260 fprintf(fp, " in:");
18261 for(in_set = rb->in; in_set; in_set = in_set->next) {
18262 fprintf(fp, " %-10p", in_set->member);
18267 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18268 done = (ptr == block->last);
18269 if (ptr->op == OP_PHI) {
18276 for(edge = 0; edge < block->users; edge++) {
18277 fprintf(fp, " in(%d):", edge);
18278 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18279 struct triple **slot;
18280 done = (ptr == block->last);
18281 if (ptr->op != OP_PHI) {
18284 slot = &RHS(ptr, 0);
18285 fprintf(fp, " %-10p", slot[edge]);
18290 if (block->first->op == OP_LABEL) {
18291 fprintf(fp, "%p:\n", block->first);
18293 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18294 struct live_range *lr;
18298 done = (ptr == block->last);
18299 lr = rstate->lrd[ptr->id].lr;
18302 ptr->id = rstate->lrd[id].orig_id;
18303 SET_REG(ptr->id, lr->color);
18304 display_triple(fp, ptr);
18307 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18308 internal_error(state, ptr, "lr has no defs!");
18310 if (info->need_edges) {
18312 struct live_range_def *lrd;
18313 fprintf(fp, " range:");
18316 fprintf(fp, " %-10p", lrd->def);
18318 } while(lrd != lr->defs);
18321 if (lr->edges > 0) {
18322 struct live_range_edge *edge;
18323 fprintf(fp, " edges:");
18324 for(edge = lr->edges; edge; edge = edge->next) {
18325 struct live_range_def *lrd;
18326 lrd = edge->node->defs;
18328 fprintf(fp, " %-10p", lrd->def);
18330 } while(lrd != edge->node->defs);
18336 /* Do a bunch of sanity checks */
18337 valid_ins(state, ptr);
18338 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18339 internal_error(state, ptr, "Invalid triple id: %d",
18344 struct triple_reg_set *out_set;
18345 fprintf(fp, " out:");
18346 for(out_set = rb->out; out_set; out_set = out_set->next) {
18347 fprintf(fp, " %-10p", out_set->member);
18354 static void print_interference_blocks(
18355 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18357 struct print_interference_block_info info;
18358 info.rstate = rstate;
18360 info.need_edges = need_edges;
18361 fprintf(fp, "\nlive variables by block\n");
18362 walk_blocks(state, &state->bb, print_interference_block, &info);
18366 static unsigned regc_max_size(struct compile_state *state, int classes)
18371 for(i = 0; i < MAX_REGC; i++) {
18372 if (classes & (1 << i)) {
18374 size = arch_regc_size(state, i);
18375 if (size > max_size) {
18383 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18385 unsigned equivs[MAX_REG_EQUIVS];
18387 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18388 internal_error(state, 0, "invalid register");
18390 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18391 internal_error(state, 0, "invalid register");
18393 arch_reg_equivs(state, equivs, reg1);
18394 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18395 if (equivs[i] == reg2) {
18402 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18404 unsigned equivs[MAX_REG_EQUIVS];
18406 if (reg == REG_UNNEEDED) {
18409 arch_reg_equivs(state, equivs, reg);
18410 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18411 used[equivs[i]] = 1;
18416 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18418 unsigned equivs[MAX_REG_EQUIVS];
18420 if (reg == REG_UNNEEDED) {
18423 arch_reg_equivs(state, equivs, reg);
18424 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18425 used[equivs[i]] += 1;
18430 static unsigned int hash_live_edge(
18431 struct live_range *left, struct live_range *right)
18433 unsigned int hash, val;
18434 unsigned long lval, rval;
18435 lval = ((unsigned long)left)/sizeof(struct live_range);
18436 rval = ((unsigned long)right)/sizeof(struct live_range);
18441 hash = (hash *263) + val;
18446 hash = (hash *263) + val;
18448 hash = hash & (LRE_HASH_SIZE - 1);
18452 static struct lre_hash **lre_probe(struct reg_state *rstate,
18453 struct live_range *left, struct live_range *right)
18455 struct lre_hash **ptr;
18456 unsigned int index;
18457 /* Ensure left <= right */
18458 if (left > right) {
18459 struct live_range *tmp;
18464 index = hash_live_edge(left, right);
18466 ptr = &rstate->hash[index];
18468 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18471 ptr = &(*ptr)->next;
18476 static int interfere(struct reg_state *rstate,
18477 struct live_range *left, struct live_range *right)
18479 struct lre_hash **ptr;
18480 ptr = lre_probe(rstate, left, right);
18481 return ptr && *ptr;
18484 static void add_live_edge(struct reg_state *rstate,
18485 struct live_range *left, struct live_range *right)
18487 /* FIXME the memory allocation overhead is noticeable here... */
18488 struct lre_hash **ptr, *new_hash;
18489 struct live_range_edge *edge;
18491 if (left == right) {
18494 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18497 /* Ensure left <= right */
18498 if (left > right) {
18499 struct live_range *tmp;
18504 ptr = lre_probe(rstate, left, right);
18509 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18512 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18513 new_hash->next = *ptr;
18514 new_hash->left = left;
18515 new_hash->right = right;
18518 edge = xmalloc(sizeof(*edge), "live_range_edge");
18519 edge->next = left->edges;
18520 edge->node = right;
18521 left->edges = edge;
18524 edge = xmalloc(sizeof(*edge), "live_range_edge");
18525 edge->next = right->edges;
18527 right->edges = edge;
18528 right->degree += 1;
18531 static void remove_live_edge(struct reg_state *rstate,
18532 struct live_range *left, struct live_range *right)
18534 struct live_range_edge *edge, **ptr;
18535 struct lre_hash **hptr, *entry;
18536 hptr = lre_probe(rstate, left, right);
18537 if (!hptr || !*hptr) {
18541 *hptr = entry->next;
18544 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18546 if (edge->node == right) {
18548 memset(edge, 0, sizeof(*edge));
18554 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18556 if (edge->node == left) {
18558 memset(edge, 0, sizeof(*edge));
18566 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18568 struct live_range_edge *edge, *next;
18569 for(edge = range->edges; edge; edge = next) {
18571 remove_live_edge(rstate, range, edge->node);
18575 static void transfer_live_edges(struct reg_state *rstate,
18576 struct live_range *dest, struct live_range *src)
18578 struct live_range_edge *edge, *next;
18579 for(edge = src->edges; edge; edge = next) {
18580 struct live_range *other;
18582 other = edge->node;
18583 remove_live_edge(rstate, src, other);
18584 add_live_edge(rstate, dest, other);
18589 /* Interference graph...
18591 * new(n) --- Return a graph with n nodes but no edges.
18592 * add(g,x,y) --- Return a graph including g with an between x and y
18593 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18594 * x and y in the graph g
18595 * degree(g, x) --- Return the degree of the node x in the graph g
18596 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18598 * Implement with a hash table && a set of adjcency vectors.
18599 * The hash table supports constant time implementations of add and interfere.
18600 * The adjacency vectors support an efficient implementation of neighbors.
18604 * +---------------------------------------------------+
18605 * | +--------------+ |
18607 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18609 * -- In simplify implment optimistic coloring... (No backtracking)
18610 * -- Implement Rematerialization it is the only form of spilling we can perform
18611 * Essentially this means dropping a constant from a register because
18612 * we can regenerate it later.
18614 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18615 * coalesce at phi points...
18616 * --- Bias coloring if at all possible do the coalesing a compile time.
18621 #if DEBUG_ROMCC_WARNING
18622 static void different_colored(
18623 struct compile_state *state, struct reg_state *rstate,
18624 struct triple *parent, struct triple *ins)
18626 struct live_range *lr;
18627 struct triple **expr;
18628 lr = rstate->lrd[ins->id].lr;
18629 expr = triple_rhs(state, ins, 0);
18630 for(;expr; expr = triple_rhs(state, ins, expr)) {
18631 struct live_range *lr2;
18632 if (!*expr || (*expr == parent) || (*expr == ins)) {
18635 lr2 = rstate->lrd[(*expr)->id].lr;
18636 if (lr->color == lr2->color) {
18637 internal_error(state, ins, "live range too big");
18643 static struct live_range *coalesce_ranges(
18644 struct compile_state *state, struct reg_state *rstate,
18645 struct live_range *lr1, struct live_range *lr2)
18647 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18653 if (!lr1->defs || !lr2->defs) {
18654 internal_error(state, 0,
18655 "cannot coalese dead live ranges");
18657 if ((lr1->color == REG_UNNEEDED) ||
18658 (lr2->color == REG_UNNEEDED)) {
18659 internal_error(state, 0,
18660 "cannot coalesce live ranges without a possible color");
18662 if ((lr1->color != lr2->color) &&
18663 (lr1->color != REG_UNSET) &&
18664 (lr2->color != REG_UNSET)) {
18665 internal_error(state, lr1->defs->def,
18666 "cannot coalesce live ranges of different colors");
18668 color = lr1->color;
18669 if (color == REG_UNSET) {
18670 color = lr2->color;
18672 classes = lr1->classes & lr2->classes;
18674 internal_error(state, lr1->defs->def,
18675 "cannot coalesce live ranges with dissimilar register classes");
18677 if (state->compiler->debug & DEBUG_COALESCING) {
18678 FILE *fp = state->errout;
18679 fprintf(fp, "coalescing:");
18682 fprintf(fp, " %p", lrd->def);
18684 } while(lrd != lr1->defs);
18688 fprintf(fp, " %p", lrd->def);
18690 } while(lrd != lr2->defs);
18693 /* If there is a clear dominate live range put it in lr1,
18694 * For purposes of this test phi functions are
18695 * considered dominated by the definitions that feed into
18698 if ((lr1->defs->prev->def->op == OP_PHI) ||
18699 ((lr2->defs->prev->def->op != OP_PHI) &&
18700 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18701 struct live_range *tmp;
18707 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18708 fprintf(state->errout, "lr1 post\n");
18710 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18711 fprintf(state->errout, "lr1 pre\n");
18713 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18714 fprintf(state->errout, "lr2 post\n");
18716 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18717 fprintf(state->errout, "lr2 pre\n");
18721 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18728 /* Append lr2 onto lr1 */
18729 #if DEBUG_ROMCC_WARNINGS
18730 #warning "FIXME should this be a merge instead of a splice?"
18732 /* This FIXME item applies to the correctness of live_range_end
18733 * and to the necessity of making multiple passes of coalesce_live_ranges.
18734 * A failure to find some coalesce opportunities in coaleace_live_ranges
18735 * does not impact the correct of the compiler just the efficiency with
18736 * which registers are allocated.
18739 mid1 = lr1->defs->prev;
18741 end = lr2->defs->prev;
18749 /* Fixup the live range in the added live range defs */
18754 } while(lrd != head);
18756 /* Mark lr2 as free. */
18758 lr2->color = REG_UNNEEDED;
18762 internal_error(state, 0, "lr1->defs == 0 ?");
18765 lr1->color = color;
18766 lr1->classes = classes;
18768 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18769 transfer_live_edges(rstate, lr1, lr2);
18774 static struct live_range_def *live_range_head(
18775 struct compile_state *state, struct live_range *lr,
18776 struct live_range_def *last)
18778 struct live_range_def *result;
18783 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18784 result = last->next;
18789 static struct live_range_def *live_range_end(
18790 struct compile_state *state, struct live_range *lr,
18791 struct live_range_def *last)
18793 struct live_range_def *result;
18796 result = lr->defs->prev;
18798 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18799 result = last->prev;
18805 static void initialize_live_ranges(
18806 struct compile_state *state, struct reg_state *rstate)
18808 struct triple *ins, *first;
18809 size_t count, size;
18812 first = state->first;
18813 /* First count how many instructions I have.
18815 count = count_triples(state);
18816 /* Potentially I need one live range definitions for each
18819 rstate->defs = count;
18820 /* Potentially I need one live range for each instruction
18821 * plus an extra for the dummy live range.
18823 rstate->ranges = count + 1;
18824 size = sizeof(rstate->lrd[0]) * rstate->defs;
18825 rstate->lrd = xcmalloc(size, "live_range_def");
18826 size = sizeof(rstate->lr[0]) * rstate->ranges;
18827 rstate->lr = xcmalloc(size, "live_range");
18829 /* Setup the dummy live range */
18830 rstate->lr[0].classes = 0;
18831 rstate->lr[0].color = REG_UNSET;
18832 rstate->lr[0].defs = 0;
18836 /* If the triple is a variable give it a live range */
18837 if (triple_is_def(state, ins)) {
18838 struct reg_info info;
18839 /* Find the architecture specific color information */
18840 info = find_def_color(state, ins);
18842 rstate->lr[i].defs = &rstate->lrd[j];
18843 rstate->lr[i].color = info.reg;
18844 rstate->lr[i].classes = info.regcm;
18845 rstate->lr[i].degree = 0;
18846 rstate->lrd[j].lr = &rstate->lr[i];
18848 /* Otherwise give the triple the dummy live range. */
18850 rstate->lrd[j].lr = &rstate->lr[0];
18853 /* Initalize the live_range_def */
18854 rstate->lrd[j].next = &rstate->lrd[j];
18855 rstate->lrd[j].prev = &rstate->lrd[j];
18856 rstate->lrd[j].def = ins;
18857 rstate->lrd[j].orig_id = ins->id;
18862 } while(ins != first);
18863 rstate->ranges = i;
18865 /* Make a second pass to handle achitecture specific register
18870 int zlhs, zrhs, i, j;
18871 if (ins->id > rstate->defs) {
18872 internal_error(state, ins, "bad id");
18875 /* Walk through the template of ins and coalesce live ranges */
18877 if ((zlhs == 0) && triple_is_def(state, ins)) {
18882 if (state->compiler->debug & DEBUG_COALESCING2) {
18883 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18887 for(i = 0; i < zlhs; i++) {
18888 struct reg_info linfo;
18889 struct live_range_def *lhs;
18890 linfo = arch_reg_lhs(state, ins, i);
18891 if (linfo.reg < MAX_REGISTERS) {
18894 if (triple_is_def(state, ins)) {
18895 lhs = &rstate->lrd[ins->id];
18897 lhs = &rstate->lrd[LHS(ins, i)->id];
18900 if (state->compiler->debug & DEBUG_COALESCING2) {
18901 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18902 i, lhs, linfo.reg);
18905 for(j = 0; j < zrhs; j++) {
18906 struct reg_info rinfo;
18907 struct live_range_def *rhs;
18908 rinfo = arch_reg_rhs(state, ins, j);
18909 if (rinfo.reg < MAX_REGISTERS) {
18912 rhs = &rstate->lrd[RHS(ins, j)->id];
18914 if (state->compiler->debug & DEBUG_COALESCING2) {
18915 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18916 j, rhs, rinfo.reg);
18919 if (rinfo.reg == linfo.reg) {
18920 coalesce_ranges(state, rstate,
18926 } while(ins != first);
18929 static void graph_ins(
18930 struct compile_state *state,
18931 struct reg_block *blocks, struct triple_reg_set *live,
18932 struct reg_block *rb, struct triple *ins, void *arg)
18934 struct reg_state *rstate = arg;
18935 struct live_range *def;
18936 struct triple_reg_set *entry;
18938 /* If the triple is not a definition
18939 * we do not have a definition to add to
18940 * the interference graph.
18942 if (!triple_is_def(state, ins)) {
18945 def = rstate->lrd[ins->id].lr;
18947 /* Create an edge between ins and everything that is
18948 * alive, unless the live_range cannot share
18949 * a physical register with ins.
18951 for(entry = live; entry; entry = entry->next) {
18952 struct live_range *lr;
18953 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18954 internal_error(state, 0, "bad entry?");
18956 lr = rstate->lrd[entry->member->id].lr;
18960 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18963 add_live_edge(rstate, def, lr);
18968 #if DEBUG_CONSISTENCY > 1
18969 static struct live_range *get_verify_live_range(
18970 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18972 struct live_range *lr;
18973 struct live_range_def *lrd;
18975 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18976 internal_error(state, ins, "bad ins?");
18978 lr = rstate->lrd[ins->id].lr;
18982 if (lrd->def == ins) {
18986 } while(lrd != lr->defs);
18988 internal_error(state, ins, "ins not in live range");
18993 static void verify_graph_ins(
18994 struct compile_state *state,
18995 struct reg_block *blocks, struct triple_reg_set *live,
18996 struct reg_block *rb, struct triple *ins, void *arg)
18998 struct reg_state *rstate = arg;
18999 struct triple_reg_set *entry1, *entry2;
19002 /* Compare live against edges and make certain the code is working */
19003 for(entry1 = live; entry1; entry1 = entry1->next) {
19004 struct live_range *lr1;
19005 lr1 = get_verify_live_range(state, rstate, entry1->member);
19006 for(entry2 = live; entry2; entry2 = entry2->next) {
19007 struct live_range *lr2;
19008 struct live_range_edge *edge2;
19011 if (entry2 == entry1) {
19014 lr2 = get_verify_live_range(state, rstate, entry2->member);
19016 internal_error(state, entry2->member,
19017 "live range with 2 values simultaneously alive");
19019 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19022 if (!interfere(rstate, lr1, lr2)) {
19023 internal_error(state, entry2->member,
19024 "edges don't interfere?");
19029 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19031 if (edge2->node == lr1) {
19035 if (lr2_degree != lr2->degree) {
19036 internal_error(state, entry2->member,
19037 "computed degree: %d does not match reported degree: %d\n",
19038 lr2_degree, lr2->degree);
19041 internal_error(state, entry2->member, "missing edge");
19049 static void print_interference_ins(
19050 struct compile_state *state,
19051 struct reg_block *blocks, struct triple_reg_set *live,
19052 struct reg_block *rb, struct triple *ins, void *arg)
19054 struct reg_state *rstate = arg;
19055 struct live_range *lr;
19057 FILE *fp = state->dbgout;
19059 lr = rstate->lrd[ins->id].lr;
19061 ins->id = rstate->lrd[id].orig_id;
19062 SET_REG(ins->id, lr->color);
19063 display_triple(state->dbgout, ins);
19067 struct live_range_def *lrd;
19068 fprintf(fp, " range:");
19071 fprintf(fp, " %-10p", lrd->def);
19073 } while(lrd != lr->defs);
19077 struct triple_reg_set *entry;
19078 fprintf(fp, " live:");
19079 for(entry = live; entry; entry = entry->next) {
19080 fprintf(fp, " %-10p", entry->member);
19085 struct live_range_edge *entry;
19086 fprintf(fp, " edges:");
19087 for(entry = lr->edges; entry; entry = entry->next) {
19088 struct live_range_def *lrd;
19089 lrd = entry->node->defs;
19091 fprintf(fp, " %-10p", lrd->def);
19093 } while(lrd != entry->node->defs);
19098 if (triple_is_branch(state, ins)) {
19104 static int coalesce_live_ranges(
19105 struct compile_state *state, struct reg_state *rstate)
19107 /* At the point where a value is moved from one
19108 * register to another that value requires two
19109 * registers, thus increasing register pressure.
19110 * Live range coaleescing reduces the register
19111 * pressure by keeping a value in one register
19114 * In the case of a phi function all paths leading
19115 * into it must be allocated to the same register
19116 * otherwise the phi function may not be removed.
19118 * Forcing a value to stay in a single register
19119 * for an extended period of time does have
19120 * limitations when applied to non homogenous
19123 * The two cases I have identified are:
19124 * 1) Two forced register assignments may
19126 * 2) Registers may go unused because they
19127 * are only good for storing the value
19128 * and not manipulating it.
19130 * Because of this I need to split live ranges,
19131 * even outside of the context of coalesced live
19132 * ranges. The need to split live ranges does
19133 * impose some constraints on live range coalescing.
19135 * - Live ranges may not be coalesced across phi
19136 * functions. This creates a 2 headed live
19137 * range that cannot be sanely split.
19139 * - phi functions (coalesced in initialize_live_ranges)
19140 * are handled as pre split live ranges so we will
19141 * never attempt to split them.
19147 for(i = 0; i <= rstate->ranges; i++) {
19148 struct live_range *lr1;
19149 struct live_range_def *lrd1;
19150 lr1 = &rstate->lr[i];
19154 lrd1 = live_range_end(state, lr1, 0);
19155 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19156 struct triple_set *set;
19157 if (lrd1->def->op != OP_COPY) {
19160 /* Skip copies that are the result of a live range split. */
19161 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19164 for(set = lrd1->def->use; set; set = set->next) {
19165 struct live_range_def *lrd2;
19166 struct live_range *lr2, *res;
19168 lrd2 = &rstate->lrd[set->member->id];
19170 /* Don't coalesce with instructions
19171 * that are the result of a live range
19174 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19177 lr2 = rstate->lrd[set->member->id].lr;
19181 if ((lr1->color != lr2->color) &&
19182 (lr1->color != REG_UNSET) &&
19183 (lr2->color != REG_UNSET)) {
19186 if ((lr1->classes & lr2->classes) == 0) {
19190 if (interfere(rstate, lr1, lr2)) {
19194 res = coalesce_ranges(state, rstate, lr1, lr2);
19208 static void fix_coalesce_conflicts(struct compile_state *state,
19209 struct reg_block *blocks, struct triple_reg_set *live,
19210 struct reg_block *rb, struct triple *ins, void *arg)
19212 int *conflicts = arg;
19213 int zlhs, zrhs, i, j;
19215 /* See if we have a mandatory coalesce operation between
19216 * a lhs and a rhs value. If so and the rhs value is also
19217 * alive then this triple needs to be pre copied. Otherwise
19218 * we would have two definitions in the same live range simultaneously
19222 if ((zlhs == 0) && triple_is_def(state, ins)) {
19226 for(i = 0; i < zlhs; i++) {
19227 struct reg_info linfo;
19228 linfo = arch_reg_lhs(state, ins, i);
19229 if (linfo.reg < MAX_REGISTERS) {
19232 for(j = 0; j < zrhs; j++) {
19233 struct reg_info rinfo;
19234 struct triple *rhs;
19235 struct triple_reg_set *set;
19238 rinfo = arch_reg_rhs(state, ins, j);
19239 if (rinfo.reg != linfo.reg) {
19243 for(set = live; set && !found; set = set->next) {
19244 if (set->member == rhs) {
19249 struct triple *copy;
19250 copy = pre_copy(state, ins, j);
19251 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19259 static int correct_coalesce_conflicts(
19260 struct compile_state *state, struct reg_block *blocks)
19264 walk_variable_lifetimes(state, &state->bb, blocks,
19265 fix_coalesce_conflicts, &conflicts);
19269 static void replace_set_use(struct compile_state *state,
19270 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19272 struct triple_reg_set *set;
19273 for(set = head; set; set = set->next) {
19274 if (set->member == orig) {
19280 static void replace_block_use(struct compile_state *state,
19281 struct reg_block *blocks, struct triple *orig, struct triple *new)
19284 #if DEBUG_ROMCC_WARNINGS
19285 #warning "WISHLIST visit just those blocks that need it *"
19287 for(i = 1; i <= state->bb.last_vertex; i++) {
19288 struct reg_block *rb;
19290 replace_set_use(state, rb->in, orig, new);
19291 replace_set_use(state, rb->out, orig, new);
19295 static void color_instructions(struct compile_state *state)
19297 struct triple *ins, *first;
19298 first = state->first;
19301 if (triple_is_def(state, ins)) {
19302 struct reg_info info;
19303 info = find_lhs_color(state, ins, 0);
19304 if (info.reg >= MAX_REGISTERS) {
19305 info.reg = REG_UNSET;
19307 SET_INFO(ins->id, info);
19310 } while(ins != first);
19313 static struct reg_info read_lhs_color(
19314 struct compile_state *state, struct triple *ins, int index)
19316 struct reg_info info;
19317 if ((index == 0) && triple_is_def(state, ins)) {
19318 info.reg = ID_REG(ins->id);
19319 info.regcm = ID_REGCM(ins->id);
19321 else if (index < ins->lhs) {
19322 info = read_lhs_color(state, LHS(ins, index), 0);
19325 internal_error(state, ins, "Bad lhs %d", index);
19326 info.reg = REG_UNSET;
19332 static struct triple *resolve_tangle(
19333 struct compile_state *state, struct triple *tangle)
19335 struct reg_info info, uinfo;
19336 struct triple_set *set, *next;
19337 struct triple *copy;
19339 #if DEBUG_ROMCC_WARNINGS
19340 #warning "WISHLIST recalculate all affected instructions colors"
19342 info = find_lhs_color(state, tangle, 0);
19343 for(set = tangle->use; set; set = next) {
19344 struct triple *user;
19347 user = set->member;
19349 for(i = 0; i < zrhs; i++) {
19350 if (RHS(user, i) != tangle) {
19353 uinfo = find_rhs_post_color(state, user, i);
19354 if (uinfo.reg == info.reg) {
19355 copy = pre_copy(state, user, i);
19356 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19357 SET_INFO(copy->id, uinfo);
19362 uinfo = find_lhs_pre_color(state, tangle, 0);
19363 if (uinfo.reg == info.reg) {
19364 struct reg_info linfo;
19365 copy = post_copy(state, tangle);
19366 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19367 linfo = find_lhs_color(state, copy, 0);
19368 SET_INFO(copy->id, linfo);
19370 info = find_lhs_color(state, tangle, 0);
19371 SET_INFO(tangle->id, info);
19377 static void fix_tangles(struct compile_state *state,
19378 struct reg_block *blocks, struct triple_reg_set *live,
19379 struct reg_block *rb, struct triple *ins, void *arg)
19381 int *tangles = arg;
19382 struct triple *tangle;
19384 char used[MAX_REGISTERS];
19385 struct triple_reg_set *set;
19388 /* Find out which registers have multiple uses at this point */
19389 memset(used, 0, sizeof(used));
19390 for(set = live; set; set = set->next) {
19391 struct reg_info info;
19392 info = read_lhs_color(state, set->member, 0);
19393 if (info.reg == REG_UNSET) {
19396 reg_inc_used(state, used, info.reg);
19399 /* Now find the least dominated definition of a register in
19400 * conflict I have seen so far.
19402 for(set = live; set; set = set->next) {
19403 struct reg_info info;
19404 info = read_lhs_color(state, set->member, 0);
19405 if (used[info.reg] < 2) {
19408 /* Changing copies that feed into phi functions
19411 if (set->member->use &&
19412 (set->member->use->member->op == OP_PHI)) {
19415 if (!tangle || tdominates(state, set->member, tangle)) {
19416 tangle = set->member;
19419 /* If I have found a tangle resolve it */
19421 struct triple *post_copy;
19423 post_copy = resolve_tangle(state, tangle);
19425 replace_block_use(state, blocks, tangle, post_copy);
19427 if (post_copy && (tangle != ins)) {
19428 replace_set_use(state, live, tangle, post_copy);
19435 static int correct_tangles(
19436 struct compile_state *state, struct reg_block *blocks)
19440 color_instructions(state);
19441 walk_variable_lifetimes(state, &state->bb, blocks,
19442 fix_tangles, &tangles);
19447 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19448 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19450 struct triple *find_constrained_def(
19451 struct compile_state *state, struct live_range *range, struct triple *constrained)
19453 struct live_range_def *lrd, *lrd_next;
19454 lrd_next = range->defs;
19456 struct reg_info info;
19460 lrd_next = lrd->next;
19462 regcm = arch_type_to_regcm(state, lrd->def->type);
19463 info = find_lhs_color(state, lrd->def, 0);
19464 regcm = arch_regcm_reg_normalize(state, regcm);
19465 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19466 /* If the 2 register class masks are equal then
19467 * the current register class is not constrained.
19469 if (regcm == info.regcm) {
19473 /* If there is just one use.
19474 * That use cannot accept a larger register class.
19475 * There are no intervening definitions except
19476 * definitions that feed into that use.
19477 * Then a triple is not constrained.
19478 * FIXME handle this case!
19480 #if DEBUG_ROMCC_WARNINGS
19481 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19485 /* Of the constrained live ranges deal with the
19486 * least dominated one first.
19488 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19489 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19490 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19492 if (!constrained ||
19493 tdominates(state, lrd->def, constrained))
19495 constrained = lrd->def;
19497 } while(lrd_next != range->defs);
19498 return constrained;
19501 static int split_constrained_ranges(
19502 struct compile_state *state, struct reg_state *rstate,
19503 struct live_range *range)
19505 /* Walk through the edges in conflict and our current live
19506 * range, and find definitions that are more severly constrained
19507 * than they type of data they contain require.
19509 * Then pick one of those ranges and relax the constraints.
19511 struct live_range_edge *edge;
19512 struct triple *constrained;
19515 for(edge = range->edges; edge; edge = edge->next) {
19516 constrained = find_constrained_def(state, edge->node, constrained);
19518 #if DEBUG_ROMCC_WARNINGS
19519 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19521 if (!constrained) {
19522 constrained = find_constrained_def(state, range, constrained);
19525 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19526 fprintf(state->errout, "constrained: ");
19527 display_triple(state->errout, constrained);
19530 ids_from_rstate(state, rstate);
19531 cleanup_rstate(state, rstate);
19532 resolve_tangle(state, constrained);
19534 return !!constrained;
19537 static int split_ranges(
19538 struct compile_state *state, struct reg_state *rstate,
19539 char *used, struct live_range *range)
19542 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19543 fprintf(state->errout, "split_ranges %d %s %p\n",
19544 rstate->passes, tops(range->defs->def->op), range->defs->def);
19546 if ((range->color == REG_UNNEEDED) ||
19547 (rstate->passes >= rstate->max_passes)) {
19550 split = split_constrained_ranges(state, rstate, range);
19552 /* Ideally I would split the live range that will not be used
19553 * for the longest period of time in hopes that this will
19554 * (a) allow me to spill a register or
19555 * (b) allow me to place a value in another register.
19557 * So far I don't have a test case for this, the resolving
19558 * of mandatory constraints has solved all of my
19559 * know issues. So I have choosen not to write any
19560 * code until I cat get a better feel for cases where
19561 * it would be useful to have.
19564 #if DEBUG_ROMCC_WARNINGS
19565 #warning "WISHLIST implement live range splitting..."
19568 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19569 FILE *fp = state->errout;
19570 print_interference_blocks(state, rstate, fp, 0);
19571 print_dominators(state, fp, &state->bb);
19576 static FILE *cgdebug_fp(struct compile_state *state)
19580 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19581 fp = state->errout;
19583 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19584 fp = state->dbgout;
19589 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19592 fp = cgdebug_fp(state);
19595 va_start(args, fmt);
19596 vfprintf(fp, fmt, args);
19601 static void cgdebug_flush(struct compile_state *state)
19604 fp = cgdebug_fp(state);
19610 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19613 fp = cgdebug_fp(state);
19615 loc(fp, state, ins);
19619 static int select_free_color(struct compile_state *state,
19620 struct reg_state *rstate, struct live_range *range)
19622 struct triple_set *entry;
19623 struct live_range_def *lrd;
19624 struct live_range_def *phi;
19625 struct live_range_edge *edge;
19626 char used[MAX_REGISTERS];
19627 struct triple **expr;
19629 /* Instead of doing just the trivial color select here I try
19630 * a few extra things because a good color selection will help reduce
19634 /* Find the registers currently in use */
19635 memset(used, 0, sizeof(used));
19636 for(edge = range->edges; edge; edge = edge->next) {
19637 if (edge->node->color == REG_UNSET) {
19640 reg_fill_used(state, used, edge->node->color);
19643 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19646 for(edge = range->edges; edge; edge = edge->next) {
19649 cgdebug_printf(state, "\n%s edges: %d",
19650 tops(range->defs->def->op), i);
19651 cgdebug_loc(state, range->defs->def);
19652 cgdebug_printf(state, "\n");
19653 for(i = 0; i < MAX_REGISTERS; i++) {
19655 cgdebug_printf(state, "used: %s\n",
19661 /* If a color is already assigned see if it will work */
19662 if (range->color != REG_UNSET) {
19663 struct live_range_def *lrd;
19664 if (!used[range->color]) {
19667 for(edge = range->edges; edge; edge = edge->next) {
19668 if (edge->node->color != range->color) {
19671 warning(state, edge->node->defs->def, "edge: ");
19672 lrd = edge->node->defs;
19674 warning(state, lrd->def, " %p %s",
19675 lrd->def, tops(lrd->def->op));
19677 } while(lrd != edge->node->defs);
19680 warning(state, range->defs->def, "def: ");
19682 warning(state, lrd->def, " %p %s",
19683 lrd->def, tops(lrd->def->op));
19685 } while(lrd != range->defs);
19686 internal_error(state, range->defs->def,
19687 "live range with already used color %s",
19688 arch_reg_str(range->color));
19691 /* If I feed into an expression reuse it's color.
19692 * This should help remove copies in the case of 2 register instructions
19693 * and phi functions.
19696 lrd = live_range_end(state, range, 0);
19697 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19698 entry = lrd->def->use;
19699 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19700 struct live_range_def *insd;
19702 insd = &rstate->lrd[entry->member->id];
19703 if (insd->lr->defs == 0) {
19706 if (!phi && (insd->def->op == OP_PHI) &&
19707 !interfere(rstate, range, insd->lr)) {
19710 if (insd->lr->color == REG_UNSET) {
19713 regcm = insd->lr->classes;
19714 if (((regcm & range->classes) == 0) ||
19715 (used[insd->lr->color])) {
19718 if (interfere(rstate, range, insd->lr)) {
19721 range->color = insd->lr->color;
19724 /* If I feed into a phi function reuse it's color or the color
19725 * of something else that feeds into the phi function.
19728 if (phi->lr->color != REG_UNSET) {
19729 if (used[phi->lr->color]) {
19730 range->color = phi->lr->color;
19734 expr = triple_rhs(state, phi->def, 0);
19735 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19736 struct live_range *lr;
19741 lr = rstate->lrd[(*expr)->id].lr;
19742 if (lr->color == REG_UNSET) {
19745 regcm = lr->classes;
19746 if (((regcm & range->classes) == 0) ||
19747 (used[lr->color])) {
19750 if (interfere(rstate, range, lr)) {
19753 range->color = lr->color;
19757 /* If I don't interfere with a rhs node reuse it's color */
19758 lrd = live_range_head(state, range, 0);
19759 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19760 expr = triple_rhs(state, lrd->def, 0);
19761 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19762 struct live_range *lr;
19767 lr = rstate->lrd[(*expr)->id].lr;
19768 if (lr->color == REG_UNSET) {
19771 regcm = lr->classes;
19772 if (((regcm & range->classes) == 0) ||
19773 (used[lr->color])) {
19776 if (interfere(rstate, range, lr)) {
19779 range->color = lr->color;
19783 /* If I have not opportunitically picked a useful color
19784 * pick the first color that is free.
19786 if (range->color == REG_UNSET) {
19788 arch_select_free_register(state, used, range->classes);
19790 if (range->color == REG_UNSET) {
19791 struct live_range_def *lrd;
19793 if (split_ranges(state, rstate, used, range)) {
19796 for(edge = range->edges; edge; edge = edge->next) {
19797 warning(state, edge->node->defs->def, "edge reg %s",
19798 arch_reg_str(edge->node->color));
19799 lrd = edge->node->defs;
19801 warning(state, lrd->def, " %s %p",
19802 tops(lrd->def->op), lrd->def);
19804 } while(lrd != edge->node->defs);
19806 warning(state, range->defs->def, "range: ");
19809 warning(state, lrd->def, " %s %p",
19810 tops(lrd->def->op), lrd->def);
19812 } while(lrd != range->defs);
19814 warning(state, range->defs->def, "classes: %x",
19816 for(i = 0; i < MAX_REGISTERS; i++) {
19818 warning(state, range->defs->def, "used: %s",
19822 error(state, range->defs->def, "too few registers");
19824 range->classes &= arch_reg_regcm(state, range->color);
19825 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19826 internal_error(state, range->defs->def, "select_free_color did not?");
19831 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19834 struct live_range_edge *edge;
19835 struct live_range *range;
19837 cgdebug_printf(state, "Lo: ");
19838 range = rstate->low;
19839 if (*range->group_prev != range) {
19840 internal_error(state, 0, "lo: *prev != range?");
19842 *range->group_prev = range->group_next;
19843 if (range->group_next) {
19844 range->group_next->group_prev = range->group_prev;
19846 if (&range->group_next == rstate->low_tail) {
19847 rstate->low_tail = range->group_prev;
19849 if (rstate->low == range) {
19850 internal_error(state, 0, "low: next != prev?");
19853 else if (rstate->high) {
19854 cgdebug_printf(state, "Hi: ");
19855 range = rstate->high;
19856 if (*range->group_prev != range) {
19857 internal_error(state, 0, "hi: *prev != range?");
19859 *range->group_prev = range->group_next;
19860 if (range->group_next) {
19861 range->group_next->group_prev = range->group_prev;
19863 if (&range->group_next == rstate->high_tail) {
19864 rstate->high_tail = range->group_prev;
19866 if (rstate->high == range) {
19867 internal_error(state, 0, "high: next != prev?");
19873 cgdebug_printf(state, " %d\n", range - rstate->lr);
19874 range->group_prev = 0;
19875 for(edge = range->edges; edge; edge = edge->next) {
19876 struct live_range *node;
19878 /* Move nodes from the high to the low list */
19879 if (node->group_prev && (node->color == REG_UNSET) &&
19880 (node->degree == regc_max_size(state, node->classes))) {
19881 if (*node->group_prev != node) {
19882 internal_error(state, 0, "move: *prev != node?");
19884 *node->group_prev = node->group_next;
19885 if (node->group_next) {
19886 node->group_next->group_prev = node->group_prev;
19888 if (&node->group_next == rstate->high_tail) {
19889 rstate->high_tail = node->group_prev;
19891 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19892 node->group_prev = rstate->low_tail;
19893 node->group_next = 0;
19894 *rstate->low_tail = node;
19895 rstate->low_tail = &node->group_next;
19896 if (*node->group_prev != node) {
19897 internal_error(state, 0, "move2: *prev != node?");
19902 colored = color_graph(state, rstate);
19904 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19905 cgdebug_loc(state, range->defs->def);
19906 cgdebug_flush(state);
19907 colored = select_free_color(state, rstate, range);
19909 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19915 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19917 struct live_range *lr;
19918 struct live_range_edge *edge;
19919 struct triple *ins, *first;
19920 char used[MAX_REGISTERS];
19921 first = state->first;
19924 if (triple_is_def(state, ins)) {
19925 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19926 internal_error(state, ins,
19927 "triple without a live range def");
19929 lr = rstate->lrd[ins->id].lr;
19930 if (lr->color == REG_UNSET) {
19931 internal_error(state, ins,
19932 "triple without a color");
19934 /* Find the registers used by the edges */
19935 memset(used, 0, sizeof(used));
19936 for(edge = lr->edges; edge; edge = edge->next) {
19937 if (edge->node->color == REG_UNSET) {
19938 internal_error(state, 0,
19939 "live range without a color");
19941 reg_fill_used(state, used, edge->node->color);
19943 if (used[lr->color]) {
19944 internal_error(state, ins,
19945 "triple with already used color");
19949 } while(ins != first);
19952 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19954 struct live_range_def *lrd;
19955 struct live_range *lr;
19956 struct triple *first, *ins;
19957 first = state->first;
19960 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19961 internal_error(state, ins,
19962 "triple without a live range");
19964 lrd = &rstate->lrd[ins->id];
19966 ins->id = lrd->orig_id;
19967 SET_REG(ins->id, lr->color);
19969 } while (ins != first);
19972 static struct live_range *merge_sort_lr(
19973 struct live_range *first, struct live_range *last)
19975 struct live_range *mid, *join, **join_tail, *pick;
19977 size = (last - first) + 1;
19979 mid = first + size/2;
19980 first = merge_sort_lr(first, mid -1);
19981 mid = merge_sort_lr(mid, last);
19985 /* merge the two lists */
19986 while(first && mid) {
19987 if ((first->degree < mid->degree) ||
19988 ((first->degree == mid->degree) &&
19989 (first->length < mid->length))) {
19991 first = first->group_next;
19993 first->group_prev = 0;
19998 mid = mid->group_next;
20000 mid->group_prev = 0;
20003 pick->group_next = 0;
20004 pick->group_prev = join_tail;
20006 join_tail = &pick->group_next;
20008 /* Splice the remaining list */
20009 pick = (first)? first : mid;
20012 pick->group_prev = join_tail;
20016 if (!first->defs) {
20024 static void ids_from_rstate(struct compile_state *state,
20025 struct reg_state *rstate)
20027 struct triple *ins, *first;
20028 if (!rstate->defs) {
20031 /* Display the graph if desired */
20032 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20033 FILE *fp = state->dbgout;
20034 print_interference_blocks(state, rstate, fp, 0);
20035 print_control_flow(state, fp, &state->bb);
20038 first = state->first;
20042 struct live_range_def *lrd;
20043 lrd = &rstate->lrd[ins->id];
20044 ins->id = lrd->orig_id;
20047 } while(ins != first);
20050 static void cleanup_live_edges(struct reg_state *rstate)
20053 /* Free the edges on each node */
20054 for(i = 1; i <= rstate->ranges; i++) {
20055 remove_live_edges(rstate, &rstate->lr[i]);
20059 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20061 cleanup_live_edges(rstate);
20062 xfree(rstate->lrd);
20065 /* Free the variable lifetime information */
20066 if (rstate->blocks) {
20067 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20070 rstate->ranges = 0;
20073 rstate->blocks = 0;
20076 static void verify_consistency(struct compile_state *state);
20077 static void allocate_registers(struct compile_state *state)
20079 struct reg_state rstate;
20082 /* Clear out the reg_state */
20083 memset(&rstate, 0, sizeof(rstate));
20084 rstate.max_passes = state->compiler->max_allocation_passes;
20087 struct live_range **point, **next;
20092 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20093 FILE *fp = state->errout;
20094 fprintf(fp, "pass: %d\n", rstate.passes);
20099 ids_from_rstate(state, &rstate);
20101 /* Cleanup the temporary data structures */
20102 cleanup_rstate(state, &rstate);
20104 /* Compute the variable lifetimes */
20105 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20107 /* Fix invalid mandatory live range coalesce conflicts */
20108 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20110 /* Fix two simultaneous uses of the same register.
20111 * In a few pathlogical cases a partial untangle moves
20112 * the tangle to a part of the graph we won't revisit.
20113 * So we keep looping until we have no more tangle fixes
20117 tangles = correct_tangles(state, rstate.blocks);
20121 print_blocks(state, "resolve_tangles", state->dbgout);
20122 verify_consistency(state);
20124 /* Allocate and initialize the live ranges */
20125 initialize_live_ranges(state, &rstate);
20127 /* Note currently doing coalescing in a loop appears to
20128 * buys me nothing. The code is left this way in case
20129 * there is some value in it. Or if a future bugfix
20130 * yields some benefit.
20133 if (state->compiler->debug & DEBUG_COALESCING) {
20134 fprintf(state->errout, "coalescing\n");
20137 /* Remove any previous live edge calculations */
20138 cleanup_live_edges(&rstate);
20140 /* Compute the interference graph */
20141 walk_variable_lifetimes(
20142 state, &state->bb, rstate.blocks,
20143 graph_ins, &rstate);
20145 /* Display the interference graph if desired */
20146 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20147 print_interference_blocks(state, &rstate, state->dbgout, 1);
20148 fprintf(state->dbgout, "\nlive variables by instruction\n");
20149 walk_variable_lifetimes(
20150 state, &state->bb, rstate.blocks,
20151 print_interference_ins, &rstate);
20154 coalesced = coalesce_live_ranges(state, &rstate);
20156 if (state->compiler->debug & DEBUG_COALESCING) {
20157 fprintf(state->errout, "coalesced: %d\n", coalesced);
20159 } while(coalesced);
20161 #if DEBUG_CONSISTENCY > 1
20163 fprintf(state->errout, "verify_graph_ins...\n");
20165 /* Verify the interference graph */
20166 walk_variable_lifetimes(
20167 state, &state->bb, rstate.blocks,
20168 verify_graph_ins, &rstate);
20170 fprintf(state->errout, "verify_graph_ins done\n");
20174 /* Build the groups low and high. But with the nodes
20175 * first sorted by degree order.
20177 rstate.low_tail = &rstate.low;
20178 rstate.high_tail = &rstate.high;
20179 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20181 rstate.high->group_prev = &rstate.high;
20183 for(point = &rstate.high; *point; point = &(*point)->group_next)
20185 rstate.high_tail = point;
20186 /* Walk through the high list and move everything that needs
20189 for(point = &rstate.high; *point; point = next) {
20190 struct live_range *range;
20191 next = &(*point)->group_next;
20194 /* If it has a low degree or it already has a color
20195 * place the node in low.
20197 if ((range->degree < regc_max_size(state, range->classes)) ||
20198 (range->color != REG_UNSET)) {
20199 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20200 range - rstate.lr, range->degree,
20201 (range->color != REG_UNSET) ? " (colored)": "");
20202 *range->group_prev = range->group_next;
20203 if (range->group_next) {
20204 range->group_next->group_prev = range->group_prev;
20206 if (&range->group_next == rstate.high_tail) {
20207 rstate.high_tail = range->group_prev;
20209 range->group_prev = rstate.low_tail;
20210 range->group_next = 0;
20211 *rstate.low_tail = range;
20212 rstate.low_tail = &range->group_next;
20216 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20217 range - rstate.lr, range->degree,
20218 (range->color != REG_UNSET) ? " (colored)": "");
20221 /* Color the live_ranges */
20222 colored = color_graph(state, &rstate);
20224 } while (!colored);
20226 /* Verify the graph was properly colored */
20227 verify_colors(state, &rstate);
20229 /* Move the colors from the graph to the triples */
20230 color_triples(state, &rstate);
20232 /* Cleanup the temporary data structures */
20233 cleanup_rstate(state, &rstate);
20235 /* Display the new graph */
20236 print_blocks(state, __func__, state->dbgout);
20239 /* Sparce Conditional Constant Propogation
20240 * =========================================
20244 struct lattice_node {
20246 struct triple *def;
20247 struct ssa_edge *out;
20248 struct flow_block *fblock;
20249 struct triple *val;
20250 /* lattice high val == def
20251 * lattice const is_const(val)
20252 * lattice low other
20256 struct lattice_node *src;
20257 struct lattice_node *dst;
20258 struct ssa_edge *work_next;
20259 struct ssa_edge *work_prev;
20260 struct ssa_edge *out_next;
20263 struct flow_block *src;
20264 struct flow_block *dst;
20265 struct flow_edge *work_next;
20266 struct flow_edge *work_prev;
20267 struct flow_edge *in_next;
20268 struct flow_edge *out_next;
20271 #define MAX_FLOW_BLOCK_EDGES 3
20272 struct flow_block {
20273 struct block *block;
20274 struct flow_edge *in;
20275 struct flow_edge *out;
20276 struct flow_edge *edges;
20281 struct lattice_node *lattice;
20282 struct ssa_edge *ssa_edges;
20283 struct flow_block *flow_blocks;
20284 struct flow_edge *flow_work_list;
20285 struct ssa_edge *ssa_work_list;
20289 static int is_scc_const(struct compile_state *state, struct triple *ins)
20291 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20294 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20296 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20299 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20301 return is_scc_const(state, lnode->val);
20304 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20306 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20309 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20310 struct flow_edge *fedge)
20312 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20313 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20315 fedge->src->block?fedge->src->block->last->id: 0,
20316 fedge->dst->block?fedge->dst->block->first->id: 0);
20318 if ((fedge == scc->flow_work_list) ||
20319 (fedge->work_next != fedge) ||
20320 (fedge->work_prev != fedge)) {
20322 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20323 fprintf(state->errout, "dupped fedge: %p\n",
20328 if (!scc->flow_work_list) {
20329 scc->flow_work_list = fedge;
20330 fedge->work_next = fedge->work_prev = fedge;
20333 struct flow_edge *ftail;
20334 ftail = scc->flow_work_list->work_prev;
20335 fedge->work_next = ftail->work_next;
20336 fedge->work_prev = ftail;
20337 fedge->work_next->work_prev = fedge;
20338 fedge->work_prev->work_next = fedge;
20342 static struct flow_edge *scc_next_fedge(
20343 struct compile_state *state, struct scc_state *scc)
20345 struct flow_edge *fedge;
20346 fedge = scc->flow_work_list;
20348 fedge->work_next->work_prev = fedge->work_prev;
20349 fedge->work_prev->work_next = fedge->work_next;
20350 if (fedge->work_next != fedge) {
20351 scc->flow_work_list = fedge->work_next;
20353 scc->flow_work_list = 0;
20355 fedge->work_next = fedge->work_prev = fedge;
20360 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20361 struct ssa_edge *sedge)
20363 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20364 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20365 (long)(sedge - scc->ssa_edges),
20366 sedge->src->def->id,
20367 sedge->dst->def->id);
20369 if ((sedge == scc->ssa_work_list) ||
20370 (sedge->work_next != sedge) ||
20371 (sedge->work_prev != sedge)) {
20373 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20374 fprintf(state->errout, "dupped sedge: %5ld\n",
20375 (long)(sedge - scc->ssa_edges));
20379 if (!scc->ssa_work_list) {
20380 scc->ssa_work_list = sedge;
20381 sedge->work_next = sedge->work_prev = sedge;
20384 struct ssa_edge *stail;
20385 stail = scc->ssa_work_list->work_prev;
20386 sedge->work_next = stail->work_next;
20387 sedge->work_prev = stail;
20388 sedge->work_next->work_prev = sedge;
20389 sedge->work_prev->work_next = sedge;
20393 static struct ssa_edge *scc_next_sedge(
20394 struct compile_state *state, struct scc_state *scc)
20396 struct ssa_edge *sedge;
20397 sedge = scc->ssa_work_list;
20399 sedge->work_next->work_prev = sedge->work_prev;
20400 sedge->work_prev->work_next = sedge->work_next;
20401 if (sedge->work_next != sedge) {
20402 scc->ssa_work_list = sedge->work_next;
20404 scc->ssa_work_list = 0;
20406 sedge->work_next = sedge->work_prev = sedge;
20411 static void initialize_scc_state(
20412 struct compile_state *state, struct scc_state *scc)
20414 int ins_count, ssa_edge_count;
20415 int ins_index, ssa_edge_index, fblock_index;
20416 struct triple *first, *ins;
20417 struct block *block;
20418 struct flow_block *fblock;
20420 memset(scc, 0, sizeof(*scc));
20422 /* Inialize pass zero find out how much memory we need */
20423 first = state->first;
20425 ins_count = ssa_edge_count = 0;
20427 struct triple_set *edge;
20429 for(edge = ins->use; edge; edge = edge->next) {
20433 } while(ins != first);
20434 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20435 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20436 ins_count, ssa_edge_count, state->bb.last_vertex);
20438 scc->ins_count = ins_count;
20440 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20442 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20444 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20447 /* Initialize pass one collect up the nodes */
20450 ins_index = ssa_edge_index = fblock_index = 0;
20453 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20454 block = ins->u.block;
20456 internal_error(state, ins, "label without block");
20459 block->vertex = fblock_index;
20460 fblock = &scc->flow_blocks[fblock_index];
20461 fblock->block = block;
20462 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20466 struct lattice_node *lnode;
20468 lnode = &scc->lattice[ins_index];
20471 lnode->fblock = fblock;
20472 lnode->val = ins; /* LATTICE HIGH */
20473 if (lnode->val->op == OP_UNKNOWNVAL) {
20474 lnode->val = 0; /* LATTICE LOW by definition */
20476 lnode->old_id = ins->id;
20477 ins->id = ins_index;
20480 } while(ins != first);
20481 /* Initialize pass two collect up the edges */
20487 struct triple_set *edge;
20488 struct ssa_edge **stail;
20489 struct lattice_node *lnode;
20490 lnode = &scc->lattice[ins->id];
20492 stail = &lnode->out;
20493 for(edge = ins->use; edge; edge = edge->next) {
20494 struct ssa_edge *sedge;
20495 ssa_edge_index += 1;
20496 sedge = &scc->ssa_edges[ssa_edge_index];
20498 stail = &sedge->out_next;
20499 sedge->src = lnode;
20500 sedge->dst = &scc->lattice[edge->member->id];
20501 sedge->work_next = sedge->work_prev = sedge;
20502 sedge->out_next = 0;
20505 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20506 struct flow_edge *fedge, **ftail;
20507 struct block_set *bedge;
20508 block = ins->u.block;
20509 fblock = &scc->flow_blocks[block->vertex];
20512 ftail = &fblock->out;
20514 fedge = fblock->edges;
20515 bedge = block->edges;
20516 for(; bedge; bedge = bedge->next, fedge++) {
20517 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20518 if (fedge->dst->block != bedge->member) {
20519 internal_error(state, 0, "block mismatch");
20522 ftail = &fedge->out_next;
20523 fedge->out_next = 0;
20525 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20526 fedge->src = fblock;
20527 fedge->work_next = fedge->work_prev = fedge;
20528 fedge->executable = 0;
20532 } while (ins != first);
20537 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20538 struct flow_edge **ftail;
20539 struct block_set *bedge;
20540 block = ins->u.block;
20541 fblock = &scc->flow_blocks[block->vertex];
20542 ftail = &fblock->in;
20543 for(bedge = block->use; bedge; bedge = bedge->next) {
20544 struct block *src_block;
20545 struct flow_block *sfblock;
20546 struct flow_edge *sfedge;
20547 src_block = bedge->member;
20548 sfblock = &scc->flow_blocks[src_block->vertex];
20549 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20550 if (sfedge->dst == fblock) {
20555 internal_error(state, 0, "edge mismatch");
20558 ftail = &sfedge->in_next;
20559 sfedge->in_next = 0;
20563 } while(ins != first);
20564 /* Setup a dummy block 0 as a node above the start node */
20566 struct flow_block *fblock, *dst;
20567 struct flow_edge *fedge;
20568 fblock = &scc->flow_blocks[0];
20570 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20572 fblock->out = fblock->edges;
20573 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20574 fedge = fblock->edges;
20575 fedge->src = fblock;
20577 fedge->work_next = fedge;
20578 fedge->work_prev = fedge;
20579 fedge->in_next = fedge->dst->in;
20580 fedge->out_next = 0;
20581 fedge->executable = 0;
20582 fedge->dst->in = fedge;
20584 /* Initialize the work lists */
20585 scc->flow_work_list = 0;
20586 scc->ssa_work_list = 0;
20587 scc_add_fedge(state, scc, fedge);
20589 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20590 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20591 ins_index, ssa_edge_index, fblock_index);
20596 static void free_scc_state(
20597 struct compile_state *state, struct scc_state *scc)
20600 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20601 struct flow_block *fblock;
20602 fblock = &scc->flow_blocks[i];
20603 if (fblock->edges) {
20604 xfree(fblock->edges);
20608 xfree(scc->flow_blocks);
20609 xfree(scc->ssa_edges);
20610 xfree(scc->lattice);
20614 static struct lattice_node *triple_to_lattice(
20615 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20617 if (ins->id <= 0) {
20618 internal_error(state, ins, "bad id");
20620 return &scc->lattice[ins->id];
20623 static struct triple *preserve_lval(
20624 struct compile_state *state, struct lattice_node *lnode)
20626 struct triple *old;
20627 /* Preserve the original value */
20629 old = dup_triple(state, lnode->val);
20630 if (lnode->val != lnode->def) {
20640 static int lval_changed(struct compile_state *state,
20641 struct triple *old, struct lattice_node *lnode)
20644 /* See if the lattice value has changed */
20646 if (!old && !lnode->val) {
20650 lnode->val && old &&
20651 (memcmp(lnode->val->param, old->param,
20652 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20653 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20663 static void scc_debug_lnode(
20664 struct compile_state *state, struct scc_state *scc,
20665 struct lattice_node *lnode, int changed)
20667 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20668 display_triple_changes(state->errout, lnode->val, lnode->def);
20670 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20671 FILE *fp = state->errout;
20672 struct triple *val, **expr;
20673 val = lnode->val? lnode->val : lnode->def;
20674 fprintf(fp, "%p %s %3d %10s (",
20676 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20678 tops(lnode->def->op));
20679 expr = triple_rhs(state, lnode->def, 0);
20680 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20682 fprintf(fp, " %d", (*expr)->id);
20685 if (val->op == OP_INTCONST) {
20686 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20688 fprintf(fp, " ) -> %s %s\n",
20689 (is_lattice_hi(state, lnode)? "hi":
20690 is_lattice_const(state, lnode)? "const" : "lo"),
20691 changed? "changed" : ""
20696 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20697 struct lattice_node *lnode)
20700 struct triple *old, *scratch;
20701 struct triple **dexpr, **vexpr;
20704 /* Store the original value */
20705 old = preserve_lval(state, lnode);
20707 /* Reinitialize the value */
20708 lnode->val = scratch = dup_triple(state, lnode->def);
20709 scratch->id = lnode->old_id;
20710 scratch->next = scratch;
20711 scratch->prev = scratch;
20714 count = TRIPLE_SIZE(scratch);
20715 for(i = 0; i < count; i++) {
20716 dexpr = &lnode->def->param[i];
20717 vexpr = &scratch->param[i];
20719 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20720 (i >= TRIPLE_TARG_OFF(scratch))) &&
20722 struct lattice_node *tmp;
20723 tmp = triple_to_lattice(state, scc, *dexpr);
20724 *vexpr = (tmp->val)? tmp->val : tmp->def;
20727 if (triple_is_branch(state, scratch)) {
20728 scratch->next = lnode->def->next;
20730 /* Recompute the value */
20731 #if DEBUG_ROMCC_WARNINGS
20732 #warning "FIXME see if simplify does anything bad"
20734 /* So far it looks like only the strength reduction
20735 * optimization are things I need to worry about.
20737 simplify(state, scratch);
20738 /* Cleanup my value */
20739 if (scratch->use) {
20740 internal_error(state, lnode->def, "scratch used?");
20742 if ((scratch->prev != scratch) ||
20743 ((scratch->next != scratch) &&
20744 (!triple_is_branch(state, lnode->def) ||
20745 (scratch->next != lnode->def->next)))) {
20746 internal_error(state, lnode->def, "scratch in list?");
20748 /* undo any uses... */
20749 count = TRIPLE_SIZE(scratch);
20750 for(i = 0; i < count; i++) {
20751 vexpr = &scratch->param[i];
20753 unuse_triple(*vexpr, scratch);
20756 if (lnode->val->op == OP_UNKNOWNVAL) {
20757 lnode->val = 0; /* Lattice low by definition */
20759 /* Find the case when I am lattice high */
20761 (lnode->val->op == lnode->def->op) &&
20762 (memcmp(lnode->val->param, lnode->def->param,
20763 count * sizeof(lnode->val->param[0])) == 0) &&
20764 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20765 lnode->val = lnode->def;
20767 /* Only allow lattice high when all of my inputs
20768 * are also lattice high. Occassionally I can
20769 * have constants with a lattice low input, so
20770 * I do not need to check that case.
20772 if (is_lattice_hi(state, lnode)) {
20773 struct lattice_node *tmp;
20775 rhs = lnode->val->rhs;
20776 for(i = 0; i < rhs; i++) {
20777 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20778 if (!is_lattice_hi(state, tmp)) {
20784 /* Find the cases that are always lattice lo */
20786 triple_is_def(state, lnode->val) &&
20787 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20790 /* See if the lattice value has changed */
20791 changed = lval_changed(state, old, lnode);
20792 /* See if this value should not change */
20793 if ((lnode->val != lnode->def) &&
20794 (( !triple_is_def(state, lnode->def) &&
20795 !triple_is_cbranch(state, lnode->def)) ||
20796 (lnode->def->op == OP_PIECE))) {
20797 #if DEBUG_ROMCC_WARNINGS
20798 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20801 internal_warning(state, lnode->def, "non def changes value?");
20806 /* See if we need to free the scratch value */
20807 if (lnode->val != scratch) {
20815 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20816 struct lattice_node *lnode)
20818 struct lattice_node *cond;
20819 struct flow_edge *left, *right;
20822 /* Update the branch value */
20823 changed = compute_lnode_val(state, scc, lnode);
20824 scc_debug_lnode(state, scc, lnode, changed);
20826 /* This only applies to conditional branches */
20827 if (!triple_is_cbranch(state, lnode->def)) {
20828 internal_error(state, lnode->def, "not a conditional branch");
20831 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20832 struct flow_edge *fedge;
20833 FILE *fp = state->errout;
20834 fprintf(fp, "%s: %d (",
20835 tops(lnode->def->op),
20838 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20839 fprintf(fp, " %d", fedge->dst->block->vertex);
20842 if (lnode->def->rhs > 0) {
20843 fprintf(fp, " <- %d",
20844 RHS(lnode->def, 0)->id);
20848 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20849 for(left = cond->fblock->out; left; left = left->out_next) {
20850 if (left->dst->block->first == lnode->def->next) {
20855 internal_error(state, lnode->def, "Cannot find left branch edge");
20857 for(right = cond->fblock->out; right; right = right->out_next) {
20858 if (right->dst->block->first == TARG(lnode->def, 0)) {
20863 internal_error(state, lnode->def, "Cannot find right branch edge");
20865 /* I should only come here if the controlling expressions value
20866 * has changed, which means it must be either a constant or lo.
20868 if (is_lattice_hi(state, cond)) {
20869 internal_error(state, cond->def, "condition high?");
20872 if (is_lattice_lo(state, cond)) {
20873 scc_add_fedge(state, scc, left);
20874 scc_add_fedge(state, scc, right);
20876 else if (cond->val->u.cval) {
20877 scc_add_fedge(state, scc, right);
20879 scc_add_fedge(state, scc, left);
20885 static void scc_add_sedge_dst(struct compile_state *state,
20886 struct scc_state *scc, struct ssa_edge *sedge)
20888 if (triple_is_cbranch(state, sedge->dst->def)) {
20889 scc_visit_cbranch(state, scc, sedge->dst);
20891 else if (triple_is_def(state, sedge->dst->def)) {
20892 scc_add_sedge(state, scc, sedge);
20896 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20897 struct lattice_node *lnode)
20899 struct lattice_node *tmp;
20900 struct triple **slot, *old;
20901 struct flow_edge *fedge;
20904 if (lnode->def->op != OP_PHI) {
20905 internal_error(state, lnode->def, "not phi");
20907 /* Store the original value */
20908 old = preserve_lval(state, lnode);
20910 /* default to lattice high */
20911 lnode->val = lnode->def;
20912 slot = &RHS(lnode->def, 0);
20914 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20915 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20916 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20918 fedge->dst->block->vertex,
20922 if (!fedge->executable) {
20925 if (!slot[index]) {
20926 internal_error(state, lnode->def, "no phi value");
20928 tmp = triple_to_lattice(state, scc, slot[index]);
20929 /* meet(X, lattice low) = lattice low */
20930 if (is_lattice_lo(state, tmp)) {
20933 /* meet(X, lattice high) = X */
20934 else if (is_lattice_hi(state, tmp)) {
20935 lnode->val = lnode->val;
20937 /* meet(lattice high, X) = X */
20938 else if (is_lattice_hi(state, lnode)) {
20939 lnode->val = dup_triple(state, tmp->val);
20940 /* Only change the type if necessary */
20941 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20942 lnode->val->type = lnode->def->type;
20945 /* meet(const, const) = const or lattice low */
20946 else if (!constants_equal(state, lnode->val, tmp->val)) {
20950 /* meet(lattice low, X) = lattice low */
20951 if (is_lattice_lo(state, lnode)) {
20956 changed = lval_changed(state, old, lnode);
20957 scc_debug_lnode(state, scc, lnode, changed);
20959 /* If the lattice value has changed update the work lists. */
20961 struct ssa_edge *sedge;
20962 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20963 scc_add_sedge_dst(state, scc, sedge);
20969 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20970 struct lattice_node *lnode)
20974 if (!triple_is_def(state, lnode->def)) {
20975 internal_warning(state, lnode->def, "not visiting an expression?");
20977 changed = compute_lnode_val(state, scc, lnode);
20978 scc_debug_lnode(state, scc, lnode, changed);
20981 struct ssa_edge *sedge;
20982 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20983 scc_add_sedge_dst(state, scc, sedge);
20988 static void scc_writeback_values(
20989 struct compile_state *state, struct scc_state *scc)
20991 struct triple *first, *ins;
20992 first = state->first;
20995 struct lattice_node *lnode;
20996 lnode = triple_to_lattice(state, scc, ins);
20997 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20998 if (is_lattice_hi(state, lnode) &&
20999 (lnode->val->op != OP_NOOP))
21001 struct flow_edge *fedge;
21004 for(fedge = lnode->fblock->in;
21005 !executable && fedge; fedge = fedge->in_next) {
21006 executable |= fedge->executable;
21009 internal_warning(state, lnode->def,
21010 "lattice node %d %s->%s still high?",
21012 tops(lnode->def->op),
21013 tops(lnode->val->op));
21019 ins->id = lnode->old_id;
21020 if (lnode->val && (lnode->val != ins)) {
21021 /* See if it something I know how to write back */
21022 switch(lnode->val->op) {
21024 mkconst(state, ins, lnode->val->u.cval);
21027 mkaddr_const(state, ins,
21028 MISC(lnode->val, 0), lnode->val->u.cval);
21031 /* By default don't copy the changes,
21032 * recompute them in place instead.
21034 simplify(state, ins);
21037 if (is_const(lnode->val) &&
21038 !constants_equal(state, lnode->val, ins)) {
21039 internal_error(state, 0, "constants not equal");
21041 /* Free the lattice nodes */
21046 } while(ins != first);
21049 static void scc_transform(struct compile_state *state)
21051 struct scc_state scc;
21052 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21056 initialize_scc_state(state, &scc);
21058 while(scc.flow_work_list || scc.ssa_work_list) {
21059 struct flow_edge *fedge;
21060 struct ssa_edge *sedge;
21061 struct flow_edge *fptr;
21062 while((fedge = scc_next_fedge(state, &scc))) {
21063 struct block *block;
21064 struct triple *ptr;
21065 struct flow_block *fblock;
21068 if (fedge->executable) {
21072 internal_error(state, 0, "fedge without dst");
21075 internal_error(state, 0, "fedge without src");
21077 fedge->executable = 1;
21078 fblock = fedge->dst;
21079 block = fblock->block;
21081 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21082 if (fptr->executable) {
21087 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21088 fprintf(state->errout, "vertex: %d reps: %d\n",
21089 block->vertex, reps);
21093 for(ptr = block->first; !done; ptr = ptr->next) {
21094 struct lattice_node *lnode;
21095 done = (ptr == block->last);
21096 lnode = &scc.lattice[ptr->id];
21097 if (ptr->op == OP_PHI) {
21098 scc_visit_phi(state, &scc, lnode);
21100 else if ((reps == 1) && triple_is_def(state, ptr))
21102 scc_visit_expr(state, &scc, lnode);
21105 /* Add unconditional branch edges */
21106 if (!triple_is_cbranch(state, fblock->block->last)) {
21107 struct flow_edge *out;
21108 for(out = fblock->out; out; out = out->out_next) {
21109 scc_add_fedge(state, &scc, out);
21113 while((sedge = scc_next_sedge(state, &scc))) {
21114 struct lattice_node *lnode;
21115 struct flow_block *fblock;
21116 lnode = sedge->dst;
21117 fblock = lnode->fblock;
21119 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21120 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21121 (unsigned long)sedge - (unsigned long)scc.ssa_edges,
21122 sedge->src->def->id,
21123 sedge->dst->def->id);
21126 if (lnode->def->op == OP_PHI) {
21127 scc_visit_phi(state, &scc, lnode);
21130 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21131 if (fptr->executable) {
21136 scc_visit_expr(state, &scc, lnode);
21142 scc_writeback_values(state, &scc);
21143 free_scc_state(state, &scc);
21144 rebuild_ssa_form(state);
21146 print_blocks(state, __func__, state->dbgout);
21150 static void transform_to_arch_instructions(struct compile_state *state)
21152 struct triple *ins, *first;
21153 first = state->first;
21156 ins = transform_to_arch_instruction(state, ins);
21157 } while(ins != first);
21159 print_blocks(state, __func__, state->dbgout);
21162 #if DEBUG_CONSISTENCY
21163 static void verify_uses(struct compile_state *state)
21165 struct triple *first, *ins;
21166 struct triple_set *set;
21167 first = state->first;
21170 struct triple **expr;
21171 expr = triple_rhs(state, ins, 0);
21172 for(; expr; expr = triple_rhs(state, ins, expr)) {
21173 struct triple *rhs;
21175 for(set = rhs?rhs->use:0; set; set = set->next) {
21176 if (set->member == ins) {
21181 internal_error(state, ins, "rhs not used");
21184 expr = triple_lhs(state, ins, 0);
21185 for(; expr; expr = triple_lhs(state, ins, expr)) {
21186 struct triple *lhs;
21188 for(set = lhs?lhs->use:0; set; set = set->next) {
21189 if (set->member == ins) {
21194 internal_error(state, ins, "lhs not used");
21197 expr = triple_misc(state, ins, 0);
21198 if (ins->op != OP_PHI) {
21199 for(; expr; expr = triple_targ(state, ins, expr)) {
21200 struct triple *misc;
21202 for(set = misc?misc->use:0; set; set = set->next) {
21203 if (set->member == ins) {
21208 internal_error(state, ins, "misc not used");
21212 if (!triple_is_ret(state, ins)) {
21213 expr = triple_targ(state, ins, 0);
21214 for(; expr; expr = triple_targ(state, ins, expr)) {
21215 struct triple *targ;
21217 for(set = targ?targ->use:0; set; set = set->next) {
21218 if (set->member == ins) {
21223 internal_error(state, ins, "targ not used");
21228 } while(ins != first);
21231 static void verify_blocks_present(struct compile_state *state)
21233 struct triple *first, *ins;
21234 if (!state->bb.first_block) {
21237 first = state->first;
21240 valid_ins(state, ins);
21241 if (triple_stores_block(state, ins)) {
21242 if (!ins->u.block) {
21243 internal_error(state, ins,
21244 "%p not in a block?", ins);
21248 } while(ins != first);
21253 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21255 struct block_set *bedge;
21256 struct block *targ;
21257 targ = block_of_triple(state, edge);
21258 for(bedge = block->edges; bedge; bedge = bedge->next) {
21259 if (bedge->member == targ) {
21266 static void verify_blocks(struct compile_state *state)
21268 struct triple *ins;
21269 struct block *block;
21271 block = state->bb.first_block;
21278 struct block_set *user, *edge;
21280 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21281 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21282 internal_error(state, ins, "inconsitent block specified");
21284 valid_ins(state, ins);
21287 for(user = block->use; user; user = user->next) {
21289 if (!user->member->first) {
21290 internal_error(state, block->first, "user is empty");
21292 if ((block == state->bb.last_block) &&
21293 (user->member == state->bb.first_block)) {
21296 for(edge = user->member->edges; edge; edge = edge->next) {
21297 if (edge->member == block) {
21302 internal_error(state, user->member->first,
21303 "user does not use block");
21306 if (triple_is_branch(state, block->last)) {
21307 struct triple **expr;
21308 expr = triple_edge_targ(state, block->last, 0);
21309 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21310 if (*expr && !edge_present(state, block, *expr)) {
21311 internal_error(state, block->last, "no edge to targ");
21315 if (!triple_is_ubranch(state, block->last) &&
21316 (block != state->bb.last_block) &&
21317 !edge_present(state, block, block->last->next)) {
21318 internal_error(state, block->last, "no edge to block->last->next");
21320 for(edge = block->edges; edge; edge = edge->next) {
21321 for(user = edge->member->use; user; user = user->next) {
21322 if (user->member == block) {
21326 if (!user || user->member != block) {
21327 internal_error(state, block->first,
21328 "block does not use edge");
21330 if (!edge->member->first) {
21331 internal_error(state, block->first, "edge block is empty");
21334 if (block->users != users) {
21335 internal_error(state, block->first,
21336 "computed users %d != stored users %d",
21337 users, block->users);
21339 if (!triple_stores_block(state, block->last->next)) {
21340 internal_error(state, block->last->next,
21341 "cannot find next block");
21343 block = block->last->next->u.block;
21345 internal_error(state, block->last->next,
21348 } while(block != state->bb.first_block);
21349 if (blocks != state->bb.last_vertex) {
21350 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21351 blocks, state->bb.last_vertex);
21355 static void verify_domination(struct compile_state *state)
21357 struct triple *first, *ins;
21358 struct triple_set *set;
21359 if (!state->bb.first_block) {
21363 first = state->first;
21366 for(set = ins->use; set; set = set->next) {
21367 struct triple **slot;
21368 struct triple *use_point;
21371 zrhs = set->member->rhs;
21372 slot = &RHS(set->member, 0);
21373 /* See if the use is on the right hand side */
21374 for(i = 0; i < zrhs; i++) {
21375 if (slot[i] == ins) {
21380 use_point = set->member;
21381 if (set->member->op == OP_PHI) {
21382 struct block_set *bset;
21384 bset = set->member->u.block->use;
21385 for(edge = 0; bset && (edge < i); edge++) {
21389 internal_error(state, set->member,
21390 "no edge for phi rhs %d", i);
21392 use_point = bset->member->last;
21396 !tdominates(state, ins, use_point)) {
21397 if (is_const(ins)) {
21398 internal_warning(state, ins,
21399 "non dominated rhs use point %p?", use_point);
21402 internal_error(state, ins,
21403 "non dominated rhs use point %p?", use_point);
21408 } while(ins != first);
21411 static void verify_rhs(struct compile_state *state)
21413 struct triple *first, *ins;
21414 first = state->first;
21417 struct triple **slot;
21420 slot = &RHS(ins, 0);
21421 for(i = 0; i < zrhs; i++) {
21422 if (slot[i] == 0) {
21423 internal_error(state, ins,
21424 "missing rhs %d on %s",
21427 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21428 internal_error(state, ins,
21429 "ins == rhs[%d] on %s",
21434 } while(ins != first);
21437 static void verify_piece(struct compile_state *state)
21439 struct triple *first, *ins;
21440 first = state->first;
21443 struct triple *ptr;
21446 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21447 if (ptr != LHS(ins, i)) {
21448 internal_error(state, ins, "malformed lhs on %s",
21451 if (ptr->op != OP_PIECE) {
21452 internal_error(state, ins, "bad lhs op %s at %d on %s",
21453 tops(ptr->op), i, tops(ins->op));
21455 if (ptr->u.cval != i) {
21456 internal_error(state, ins, "bad u.cval of %d %d expected",
21461 } while(ins != first);
21464 static void verify_ins_colors(struct compile_state *state)
21466 struct triple *first, *ins;
21468 first = state->first;
21472 } while(ins != first);
21475 static void verify_unknown(struct compile_state *state)
21477 struct triple *first, *ins;
21478 if ( (unknown_triple.next != &unknown_triple) ||
21479 (unknown_triple.prev != &unknown_triple) ||
21481 (unknown_triple.use != 0) ||
21483 (unknown_triple.op != OP_UNKNOWNVAL) ||
21484 (unknown_triple.lhs != 0) ||
21485 (unknown_triple.rhs != 0) ||
21486 (unknown_triple.misc != 0) ||
21487 (unknown_triple.targ != 0) ||
21488 (unknown_triple.template_id != 0) ||
21489 (unknown_triple.id != -1) ||
21490 (unknown_triple.type != &unknown_type) ||
21491 (unknown_triple.occurance != &dummy_occurance) ||
21492 (unknown_triple.param[0] != 0) ||
21493 (unknown_triple.param[1] != 0)) {
21494 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21496 if ( (dummy_occurance.count != 2) ||
21497 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21498 (strcmp(dummy_occurance.function, "") != 0) ||
21499 (dummy_occurance.col != 0) ||
21500 (dummy_occurance.parent != 0)) {
21501 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21503 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21504 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21506 first = state->first;
21510 if (ins == &unknown_triple) {
21511 internal_error(state, ins, "unknown triple in list");
21513 params = TRIPLE_SIZE(ins);
21514 for(i = 0; i < params; i++) {
21515 if (ins->param[i] == &unknown_triple) {
21516 internal_error(state, ins, "unknown triple used!");
21520 } while(ins != first);
21523 static void verify_types(struct compile_state *state)
21525 struct triple *first, *ins;
21526 first = state->first;
21529 struct type *invalid;
21530 invalid = invalid_type(state, ins->type);
21532 FILE *fp = state->errout;
21533 fprintf(fp, "type: ");
21534 name_of(fp, ins->type);
21536 fprintf(fp, "invalid type: ");
21537 name_of(fp, invalid);
21539 internal_error(state, ins, "invalid ins type");
21541 } while(ins != first);
21544 static void verify_copy(struct compile_state *state)
21546 struct triple *first, *ins, *next;
21547 first = state->first;
21548 next = ins = first;
21552 if (ins->op != OP_COPY) {
21555 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21556 FILE *fp = state->errout;
21557 fprintf(fp, "src type: ");
21558 name_of(fp, RHS(ins, 0)->type);
21560 fprintf(fp, "dst type: ");
21561 name_of(fp, ins->type);
21563 internal_error(state, ins, "type mismatch in copy");
21565 } while(next != first);
21568 static void verify_consistency(struct compile_state *state)
21570 verify_unknown(state);
21571 verify_uses(state);
21572 verify_blocks_present(state);
21573 verify_blocks(state);
21574 verify_domination(state);
21576 verify_piece(state);
21577 verify_ins_colors(state);
21578 verify_types(state);
21579 verify_copy(state);
21580 if (state->compiler->debug & DEBUG_VERIFICATION) {
21581 fprintf(state->dbgout, "consistency verified\n");
21585 static void verify_consistency(struct compile_state *state) {}
21586 #endif /* DEBUG_CONSISTENCY */
21588 static void optimize(struct compile_state *state)
21590 /* Join all of the functions into one giant function */
21591 join_functions(state);
21593 /* Dump what the instruction graph intially looks like */
21594 print_triples(state);
21596 /* Replace structures with simpler data types */
21597 decompose_compound_types(state);
21598 print_triples(state);
21600 verify_consistency(state);
21601 /* Analyze the intermediate code */
21602 state->bb.first = state->first;
21603 analyze_basic_blocks(state, &state->bb);
21605 /* Transform the code to ssa form. */
21607 * The transformation to ssa form puts a phi function
21608 * on each of edge of a dominance frontier where that
21609 * phi function might be needed. At -O2 if we don't
21610 * eleminate the excess phi functions we can get an
21611 * exponential code size growth. So I kill the extra
21612 * phi functions early and I kill them often.
21614 transform_to_ssa_form(state);
21615 verify_consistency(state);
21617 /* Remove dead code */
21618 eliminate_inefectual_code(state);
21619 verify_consistency(state);
21621 /* Do strength reduction and simple constant optimizations */
21622 simplify_all(state);
21623 verify_consistency(state);
21624 /* Propogate constants throughout the code */
21625 scc_transform(state);
21626 verify_consistency(state);
21627 #if DEBUG_ROMCC_WARNINGS
21628 #warning "WISHLIST implement single use constants (least possible register pressure)"
21629 #warning "WISHLIST implement induction variable elimination"
21631 /* Select architecture instructions and an initial partial
21632 * coloring based on architecture constraints.
21634 transform_to_arch_instructions(state);
21635 verify_consistency(state);
21637 /* Remove dead code */
21638 eliminate_inefectual_code(state);
21639 verify_consistency(state);
21641 /* Color all of the variables to see if they will fit in registers */
21642 insert_copies_to_phi(state);
21643 verify_consistency(state);
21645 insert_mandatory_copies(state);
21646 verify_consistency(state);
21648 allocate_registers(state);
21649 verify_consistency(state);
21651 /* Remove the optimization information.
21652 * This is more to check for memory consistency than to free memory.
21654 free_basic_blocks(state, &state->bb);
21657 static void print_op_asm(struct compile_state *state,
21658 struct triple *ins, FILE *fp)
21660 struct asm_info *info;
21662 unsigned lhs, rhs, i;
21663 info = ins->u.ainfo;
21666 /* Don't count the clobbers in lhs */
21667 for(i = 0; i < lhs; i++) {
21668 if (LHS(ins, i)->type == &void_type) {
21673 fprintf(fp, "#ASM\n");
21675 for(ptr = info->str; *ptr; ptr++) {
21677 unsigned long param;
21678 struct triple *piece;
21688 param = strtoul(ptr, &next, 10);
21690 error(state, ins, "Invalid asm template");
21692 if (param >= (lhs + rhs)) {
21693 error(state, ins, "Invalid param %%%u in asm template",
21696 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21698 arch_reg_str(ID_REG(piece->id)));
21701 fprintf(fp, "\n#NOT ASM\n");
21705 /* Only use the low x86 byte registers. This allows me
21706 * allocate the entire register when a byte register is used.
21708 #define X86_4_8BIT_GPRS 1
21711 #define X86_MMX_REGS (1<<0)
21712 #define X86_XMM_REGS (1<<1)
21713 #define X86_NOOP_COPY (1<<2)
21715 /* The x86 register classes */
21716 #define REGC_FLAGS 0
21717 #define REGC_GPR8 1
21718 #define REGC_GPR16 2
21719 #define REGC_GPR32 3
21720 #define REGC_DIVIDEND64 4
21721 #define REGC_DIVIDEND32 5
21724 #define REGC_GPR32_8 8
21725 #define REGC_GPR16_8 9
21726 #define REGC_GPR8_LO 10
21727 #define REGC_IMM32 11
21728 #define REGC_IMM16 12
21729 #define REGC_IMM8 13
21730 #define LAST_REGC REGC_IMM8
21731 #if LAST_REGC >= MAX_REGC
21732 #error "MAX_REGC is to low"
21735 /* Register class masks */
21736 #define REGCM_FLAGS (1 << REGC_FLAGS)
21737 #define REGCM_GPR8 (1 << REGC_GPR8)
21738 #define REGCM_GPR16 (1 << REGC_GPR16)
21739 #define REGCM_GPR32 (1 << REGC_GPR32)
21740 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21741 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21742 #define REGCM_MMX (1 << REGC_MMX)
21743 #define REGCM_XMM (1 << REGC_XMM)
21744 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21745 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21746 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21747 #define REGCM_IMM32 (1 << REGC_IMM32)
21748 #define REGCM_IMM16 (1 << REGC_IMM16)
21749 #define REGCM_IMM8 (1 << REGC_IMM8)
21750 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21751 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21753 /* The x86 registers */
21754 #define REG_EFLAGS 2
21755 #define REGC_FLAGS_FIRST REG_EFLAGS
21756 #define REGC_FLAGS_LAST REG_EFLAGS
21765 #define REGC_GPR8_LO_FIRST REG_AL
21766 #define REGC_GPR8_LO_LAST REG_DL
21767 #define REGC_GPR8_FIRST REG_AL
21768 #define REGC_GPR8_LAST REG_DH
21777 #define REGC_GPR16_FIRST REG_AX
21778 #define REGC_GPR16_LAST REG_SP
21787 #define REGC_GPR32_FIRST REG_EAX
21788 #define REGC_GPR32_LAST REG_ESP
21789 #define REG_EDXEAX 27
21790 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21791 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21792 #define REG_DXAX 28
21793 #define REGC_DIVIDEND32_FIRST REG_DXAX
21794 #define REGC_DIVIDEND32_LAST REG_DXAX
21795 #define REG_MMX0 29
21796 #define REG_MMX1 30
21797 #define REG_MMX2 31
21798 #define REG_MMX3 32
21799 #define REG_MMX4 33
21800 #define REG_MMX5 34
21801 #define REG_MMX6 35
21802 #define REG_MMX7 36
21803 #define REGC_MMX_FIRST REG_MMX0
21804 #define REGC_MMX_LAST REG_MMX7
21805 #define REG_XMM0 37
21806 #define REG_XMM1 38
21807 #define REG_XMM2 39
21808 #define REG_XMM3 40
21809 #define REG_XMM4 41
21810 #define REG_XMM5 42
21811 #define REG_XMM6 43
21812 #define REG_XMM7 44
21813 #define REGC_XMM_FIRST REG_XMM0
21814 #define REGC_XMM_LAST REG_XMM7
21816 #if DEBUG_ROMCC_WARNINGS
21817 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21820 #define LAST_REG REG_XMM7
21822 #define REGC_GPR32_8_FIRST REG_EAX
21823 #define REGC_GPR32_8_LAST REG_EDX
21824 #define REGC_GPR16_8_FIRST REG_AX
21825 #define REGC_GPR16_8_LAST REG_DX
21827 #define REGC_IMM8_FIRST -1
21828 #define REGC_IMM8_LAST -1
21829 #define REGC_IMM16_FIRST -2
21830 #define REGC_IMM16_LAST -1
21831 #define REGC_IMM32_FIRST -4
21832 #define REGC_IMM32_LAST -1
21834 #if LAST_REG >= MAX_REGISTERS
21835 #error "MAX_REGISTERS to low"
21839 static unsigned regc_size[LAST_REGC +1] = {
21840 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21841 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21842 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21843 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21844 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21845 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21846 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21847 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21848 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21849 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21850 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21856 static const struct {
21858 } regcm_bound[LAST_REGC + 1] = {
21859 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21860 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21861 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21862 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21863 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21864 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21865 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21866 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21867 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21868 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21869 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21870 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21871 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21872 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21875 #if ARCH_INPUT_REGS != 4
21876 #error ARCH_INPUT_REGS size mismatch
21878 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21879 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21880 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21881 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21882 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21885 #if ARCH_OUTPUT_REGS != 4
21886 #error ARCH_INPUT_REGS size mismatch
21888 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21889 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21890 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21891 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21892 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21895 static void init_arch_state(struct arch_state *arch)
21897 memset(arch, 0, sizeof(*arch));
21898 arch->features = 0;
21901 static const struct compiler_flag arch_flags[] = {
21902 { "mmx", X86_MMX_REGS },
21903 { "sse", X86_XMM_REGS },
21904 { "noop-copy", X86_NOOP_COPY },
21907 static const struct compiler_flag arch_cpus[] = {
21909 { "p2", X86_MMX_REGS },
21910 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21911 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21912 { "k7", X86_MMX_REGS },
21913 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21914 { "c3", X86_MMX_REGS },
21915 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21918 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21925 if (strncmp(flag, "no-", 3) == 0) {
21929 if (act && strncmp(flag, "cpu=", 4) == 0) {
21931 result = set_flag(arch_cpus, &arch->features, 1, flag);
21934 result = set_flag(arch_flags, &arch->features, act, flag);
21939 static void arch_usage(FILE *fp)
21941 flag_usage(fp, arch_flags, "-m", "-mno-");
21942 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21945 static unsigned arch_regc_size(struct compile_state *state, int class)
21947 if ((class < 0) || (class > LAST_REGC)) {
21950 return regc_size[class];
21953 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21955 /* See if two register classes may have overlapping registers */
21956 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21957 REGCM_GPR32_8 | REGCM_GPR32 |
21958 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21960 /* Special case for the immediates */
21961 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21962 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21963 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21964 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21967 return (regcm1 & regcm2) ||
21968 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21971 static void arch_reg_equivs(
21972 struct compile_state *state, unsigned *equiv, int reg)
21974 if ((reg < 0) || (reg > LAST_REG)) {
21975 internal_error(state, 0, "invalid register");
21980 #if X86_4_8BIT_GPRS
21984 *equiv++ = REG_EAX;
21985 *equiv++ = REG_DXAX;
21986 *equiv++ = REG_EDXEAX;
21989 #if X86_4_8BIT_GPRS
21993 *equiv++ = REG_EAX;
21994 *equiv++ = REG_DXAX;
21995 *equiv++ = REG_EDXEAX;
21998 #if X86_4_8BIT_GPRS
22002 *equiv++ = REG_EBX;
22006 #if X86_4_8BIT_GPRS
22010 *equiv++ = REG_EBX;
22013 #if X86_4_8BIT_GPRS
22017 *equiv++ = REG_ECX;
22021 #if X86_4_8BIT_GPRS
22025 *equiv++ = REG_ECX;
22028 #if X86_4_8BIT_GPRS
22032 *equiv++ = REG_EDX;
22033 *equiv++ = REG_DXAX;
22034 *equiv++ = REG_EDXEAX;
22037 #if X86_4_8BIT_GPRS
22041 *equiv++ = REG_EDX;
22042 *equiv++ = REG_DXAX;
22043 *equiv++ = REG_EDXEAX;
22048 *equiv++ = REG_EAX;
22049 *equiv++ = REG_DXAX;
22050 *equiv++ = REG_EDXEAX;
22055 *equiv++ = REG_EBX;
22060 *equiv++ = REG_ECX;
22065 *equiv++ = REG_EDX;
22066 *equiv++ = REG_DXAX;
22067 *equiv++ = REG_EDXEAX;
22070 *equiv++ = REG_ESI;
22073 *equiv++ = REG_EDI;
22076 *equiv++ = REG_EBP;
22079 *equiv++ = REG_ESP;
22085 *equiv++ = REG_DXAX;
22086 *equiv++ = REG_EDXEAX;
22102 *equiv++ = REG_DXAX;
22103 *equiv++ = REG_EDXEAX;
22124 *equiv++ = REG_EAX;
22125 *equiv++ = REG_EDX;
22126 *equiv++ = REG_EDXEAX;
22135 *equiv++ = REG_EAX;
22136 *equiv++ = REG_EDX;
22137 *equiv++ = REG_DXAX;
22140 *equiv++ = REG_UNSET;
22143 static unsigned arch_avail_mask(struct compile_state *state)
22145 unsigned avail_mask;
22146 /* REGCM_GPR8 is not available */
22147 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22148 REGCM_GPR32 | REGCM_GPR32_8 |
22149 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22150 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22151 if (state->arch->features & X86_MMX_REGS) {
22152 avail_mask |= REGCM_MMX;
22154 if (state->arch->features & X86_XMM_REGS) {
22155 avail_mask |= REGCM_XMM;
22160 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22162 unsigned mask, result;
22166 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22167 if ((result & mask) == 0) {
22170 if (class > LAST_REGC) {
22173 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22174 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22175 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22176 result |= (1 << class2);
22180 result &= arch_avail_mask(state);
22184 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22186 /* Like arch_regcm_normalize except immediate register classes are excluded */
22187 regcm = arch_regcm_normalize(state, regcm);
22188 /* Remove the immediate register classes */
22189 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22194 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22199 for(class = 0; class <= LAST_REGC; class++) {
22200 if ((reg >= regcm_bound[class].first) &&
22201 (reg <= regcm_bound[class].last)) {
22202 mask |= (1 << class);
22206 internal_error(state, 0, "reg %d not in any class", reg);
22211 static struct reg_info arch_reg_constraint(
22212 struct compile_state *state, struct type *type, const char *constraint)
22214 static const struct {
22218 } constraints[] = {
22219 { 'r', REGCM_GPR32, REG_UNSET },
22220 { 'g', REGCM_GPR32, REG_UNSET },
22221 { 'p', REGCM_GPR32, REG_UNSET },
22222 { 'q', REGCM_GPR8_LO, REG_UNSET },
22223 { 'Q', REGCM_GPR32_8, REG_UNSET },
22224 { 'x', REGCM_XMM, REG_UNSET },
22225 { 'y', REGCM_MMX, REG_UNSET },
22226 { 'a', REGCM_GPR32, REG_EAX },
22227 { 'b', REGCM_GPR32, REG_EBX },
22228 { 'c', REGCM_GPR32, REG_ECX },
22229 { 'd', REGCM_GPR32, REG_EDX },
22230 { 'D', REGCM_GPR32, REG_EDI },
22231 { 'S', REGCM_GPR32, REG_ESI },
22232 { '\0', 0, REG_UNSET },
22234 unsigned int regcm;
22235 unsigned int mask, reg;
22236 struct reg_info result;
22238 regcm = arch_type_to_regcm(state, type);
22241 for(ptr = constraint; *ptr; ptr++) {
22246 for(i = 0; constraints[i].class != '\0'; i++) {
22247 if (constraints[i].class == *ptr) {
22251 if (constraints[i].class == '\0') {
22252 error(state, 0, "invalid register constraint ``%c''", *ptr);
22255 if ((constraints[i].mask & regcm) == 0) {
22256 error(state, 0, "invalid register class %c specified",
22259 mask |= constraints[i].mask;
22260 if (constraints[i].reg != REG_UNSET) {
22261 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22262 error(state, 0, "Only one register may be specified");
22264 reg = constraints[i].reg;
22268 result.regcm = mask;
22272 static struct reg_info arch_reg_clobber(
22273 struct compile_state *state, const char *clobber)
22275 struct reg_info result;
22276 if (strcmp(clobber, "memory") == 0) {
22277 result.reg = REG_UNSET;
22280 else if (strcmp(clobber, "eax") == 0) {
22281 result.reg = REG_EAX;
22282 result.regcm = REGCM_GPR32;
22284 else if (strcmp(clobber, "ebx") == 0) {
22285 result.reg = REG_EBX;
22286 result.regcm = REGCM_GPR32;
22288 else if (strcmp(clobber, "ecx") == 0) {
22289 result.reg = REG_ECX;
22290 result.regcm = REGCM_GPR32;
22292 else if (strcmp(clobber, "edx") == 0) {
22293 result.reg = REG_EDX;
22294 result.regcm = REGCM_GPR32;
22296 else if (strcmp(clobber, "esi") == 0) {
22297 result.reg = REG_ESI;
22298 result.regcm = REGCM_GPR32;
22300 else if (strcmp(clobber, "edi") == 0) {
22301 result.reg = REG_EDI;
22302 result.regcm = REGCM_GPR32;
22304 else if (strcmp(clobber, "ebp") == 0) {
22305 result.reg = REG_EBP;
22306 result.regcm = REGCM_GPR32;
22308 else if (strcmp(clobber, "esp") == 0) {
22309 result.reg = REG_ESP;
22310 result.regcm = REGCM_GPR32;
22312 else if (strcmp(clobber, "cc") == 0) {
22313 result.reg = REG_EFLAGS;
22314 result.regcm = REGCM_FLAGS;
22316 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22317 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22318 result.reg = REG_XMM0 + octdigval(clobber[3]);
22319 result.regcm = REGCM_XMM;
22321 else if ((strncmp(clobber, "mm", 2) == 0) &&
22322 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22323 result.reg = REG_MMX0 + octdigval(clobber[3]);
22324 result.regcm = REGCM_MMX;
22327 error(state, 0, "unknown register name `%s' in asm",
22329 result.reg = REG_UNSET;
22335 static int do_select_reg(struct compile_state *state,
22336 char *used, int reg, unsigned classes)
22342 mask = arch_reg_regcm(state, reg);
22343 return (classes & mask) ? reg : REG_UNSET;
22346 static int arch_select_free_register(
22347 struct compile_state *state, char *used, int classes)
22349 /* Live ranges with the most neighbors are colored first.
22351 * Generally it does not matter which colors are given
22352 * as the register allocator attempts to color live ranges
22353 * in an order where you are guaranteed not to run out of colors.
22355 * Occasionally the register allocator cannot find an order
22356 * of register selection that will find a free color. To
22357 * increase the odds the register allocator will work when
22358 * it guesses first give out registers from register classes
22359 * least likely to run out of registers.
22364 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22365 reg = do_select_reg(state, used, i, classes);
22367 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22368 reg = do_select_reg(state, used, i, classes);
22370 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22371 reg = do_select_reg(state, used, i, classes);
22373 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22374 reg = do_select_reg(state, used, i, classes);
22376 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22377 reg = do_select_reg(state, used, i, classes);
22379 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22380 reg = do_select_reg(state, used, i, classes);
22382 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22383 reg = do_select_reg(state, used, i, classes);
22385 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22386 reg = do_select_reg(state, used, i, classes);
22388 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22389 reg = do_select_reg(state, used, i, classes);
22395 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22398 #if DEBUG_ROMCC_WARNINGS
22399 #warning "FIXME force types smaller (if legal) before I get here"
22403 switch(type->type & TYPE_MASK) {
22410 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22411 REGCM_GPR16 | REGCM_GPR16_8 |
22412 REGCM_GPR32 | REGCM_GPR32_8 |
22413 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22414 REGCM_MMX | REGCM_XMM |
22415 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22419 mask = REGCM_GPR16 | REGCM_GPR16_8 |
22420 REGCM_GPR32 | REGCM_GPR32_8 |
22421 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22422 REGCM_MMX | REGCM_XMM |
22423 REGCM_IMM32 | REGCM_IMM16;
22431 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22432 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22433 REGCM_MMX | REGCM_XMM |
22438 mask = arch_type_to_regcm(state, type->left);
22441 mask = arch_type_to_regcm(state, type->left) &
22442 arch_type_to_regcm(state, type->right);
22444 case TYPE_BITFIELD:
22445 mask = arch_type_to_regcm(state, type->left);
22448 fprintf(state->errout, "type: ");
22449 name_of(state->errout, type);
22450 fprintf(state->errout, "\n");
22451 internal_error(state, 0, "no register class for type");
22454 mask = arch_regcm_normalize(state, mask);
22458 static int is_imm32(struct triple *imm)
22460 // second condition commented out to prevent compiler warning:
22461 // imm->u.cval is always 32bit unsigned, so the comparison is
22463 return ((imm->op == OP_INTCONST) /* && (imm->u.cval <= 0xffffffffUL) */ ) ||
22464 (imm->op == OP_ADDRCONST);
22467 static int is_imm16(struct triple *imm)
22469 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22471 static int is_imm8(struct triple *imm)
22473 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22476 static int get_imm32(struct triple *ins, struct triple **expr)
22478 struct triple *imm;
22480 while(imm->op == OP_COPY) {
22483 if (!is_imm32(imm)) {
22486 unuse_triple(*expr, ins);
22487 use_triple(imm, ins);
22492 static int get_imm8(struct triple *ins, struct triple **expr)
22494 struct triple *imm;
22496 while(imm->op == OP_COPY) {
22499 if (!is_imm8(imm)) {
22502 unuse_triple(*expr, ins);
22503 use_triple(imm, ins);
22508 #define TEMPLATE_NOP 0
22509 #define TEMPLATE_INTCONST8 1
22510 #define TEMPLATE_INTCONST32 2
22511 #define TEMPLATE_UNKNOWNVAL 3
22512 #define TEMPLATE_COPY8_REG 5
22513 #define TEMPLATE_COPY16_REG 6
22514 #define TEMPLATE_COPY32_REG 7
22515 #define TEMPLATE_COPY_IMM8 8
22516 #define TEMPLATE_COPY_IMM16 9
22517 #define TEMPLATE_COPY_IMM32 10
22518 #define TEMPLATE_PHI8 11
22519 #define TEMPLATE_PHI16 12
22520 #define TEMPLATE_PHI32 13
22521 #define TEMPLATE_STORE8 14
22522 #define TEMPLATE_STORE16 15
22523 #define TEMPLATE_STORE32 16
22524 #define TEMPLATE_LOAD8 17
22525 #define TEMPLATE_LOAD16 18
22526 #define TEMPLATE_LOAD32 19
22527 #define TEMPLATE_BINARY8_REG 20
22528 #define TEMPLATE_BINARY16_REG 21
22529 #define TEMPLATE_BINARY32_REG 22
22530 #define TEMPLATE_BINARY8_IMM 23
22531 #define TEMPLATE_BINARY16_IMM 24
22532 #define TEMPLATE_BINARY32_IMM 25
22533 #define TEMPLATE_SL8_CL 26
22534 #define TEMPLATE_SL16_CL 27
22535 #define TEMPLATE_SL32_CL 28
22536 #define TEMPLATE_SL8_IMM 29
22537 #define TEMPLATE_SL16_IMM 30
22538 #define TEMPLATE_SL32_IMM 31
22539 #define TEMPLATE_UNARY8 32
22540 #define TEMPLATE_UNARY16 33
22541 #define TEMPLATE_UNARY32 34
22542 #define TEMPLATE_CMP8_REG 35
22543 #define TEMPLATE_CMP16_REG 36
22544 #define TEMPLATE_CMP32_REG 37
22545 #define TEMPLATE_CMP8_IMM 38
22546 #define TEMPLATE_CMP16_IMM 39
22547 #define TEMPLATE_CMP32_IMM 40
22548 #define TEMPLATE_TEST8 41
22549 #define TEMPLATE_TEST16 42
22550 #define TEMPLATE_TEST32 43
22551 #define TEMPLATE_SET 44
22552 #define TEMPLATE_JMP 45
22553 #define TEMPLATE_RET 46
22554 #define TEMPLATE_INB_DX 47
22555 #define TEMPLATE_INB_IMM 48
22556 #define TEMPLATE_INW_DX 49
22557 #define TEMPLATE_INW_IMM 50
22558 #define TEMPLATE_INL_DX 51
22559 #define TEMPLATE_INL_IMM 52
22560 #define TEMPLATE_OUTB_DX 53
22561 #define TEMPLATE_OUTB_IMM 54
22562 #define TEMPLATE_OUTW_DX 55
22563 #define TEMPLATE_OUTW_IMM 56
22564 #define TEMPLATE_OUTL_DX 57
22565 #define TEMPLATE_OUTL_IMM 58
22566 #define TEMPLATE_BSF 59
22567 #define TEMPLATE_RDMSR 60
22568 #define TEMPLATE_WRMSR 61
22569 #define TEMPLATE_UMUL8 62
22570 #define TEMPLATE_UMUL16 63
22571 #define TEMPLATE_UMUL32 64
22572 #define TEMPLATE_DIV8 65
22573 #define TEMPLATE_DIV16 66
22574 #define TEMPLATE_DIV32 67
22575 #define LAST_TEMPLATE TEMPLATE_DIV32
22576 #if LAST_TEMPLATE >= MAX_TEMPLATES
22577 #error "MAX_TEMPLATES to low"
22580 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22581 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22582 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22585 static struct ins_template templates[] = {
22588 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22589 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22590 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22591 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22592 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22593 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22594 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22595 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22596 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22597 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22598 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22599 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22600 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22601 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22602 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22603 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22604 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22605 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22606 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22607 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22608 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22609 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22610 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22611 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22612 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22613 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22614 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22615 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22616 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22617 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22618 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22619 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22620 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22621 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22622 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22623 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22624 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22625 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22626 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22627 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22628 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22629 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22630 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22631 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22632 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22633 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22634 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22635 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22636 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22637 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22638 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22639 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22640 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22641 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22642 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22643 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22644 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22645 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22646 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22647 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22648 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22649 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22650 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22651 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22654 [TEMPLATE_INTCONST8] = {
22655 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22657 [TEMPLATE_INTCONST32] = {
22658 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22660 [TEMPLATE_UNKNOWNVAL] = {
22661 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22663 [TEMPLATE_COPY8_REG] = {
22664 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22665 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22667 [TEMPLATE_COPY16_REG] = {
22668 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22669 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22671 [TEMPLATE_COPY32_REG] = {
22672 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22673 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22675 [TEMPLATE_COPY_IMM8] = {
22676 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22677 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22679 [TEMPLATE_COPY_IMM16] = {
22680 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22681 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22683 [TEMPLATE_COPY_IMM32] = {
22684 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22685 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22687 [TEMPLATE_PHI8] = {
22688 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22689 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22691 [TEMPLATE_PHI16] = {
22692 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22693 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22695 [TEMPLATE_PHI32] = {
22696 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22697 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22699 [TEMPLATE_STORE8] = {
22701 [0] = { REG_UNSET, REGCM_GPR32 },
22702 [1] = { REG_UNSET, REGCM_GPR8_LO },
22705 [TEMPLATE_STORE16] = {
22707 [0] = { REG_UNSET, REGCM_GPR32 },
22708 [1] = { REG_UNSET, REGCM_GPR16 },
22711 [TEMPLATE_STORE32] = {
22713 [0] = { REG_UNSET, REGCM_GPR32 },
22714 [1] = { REG_UNSET, REGCM_GPR32 },
22717 [TEMPLATE_LOAD8] = {
22718 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22719 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22721 [TEMPLATE_LOAD16] = {
22722 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22723 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22725 [TEMPLATE_LOAD32] = {
22726 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22727 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22729 [TEMPLATE_BINARY8_REG] = {
22730 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22732 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22733 [1] = { REG_UNSET, REGCM_GPR8_LO },
22736 [TEMPLATE_BINARY16_REG] = {
22737 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22739 [0] = { REG_VIRT0, REGCM_GPR16 },
22740 [1] = { REG_UNSET, REGCM_GPR16 },
22743 [TEMPLATE_BINARY32_REG] = {
22744 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22746 [0] = { REG_VIRT0, REGCM_GPR32 },
22747 [1] = { REG_UNSET, REGCM_GPR32 },
22750 [TEMPLATE_BINARY8_IMM] = {
22751 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22753 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22754 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22757 [TEMPLATE_BINARY16_IMM] = {
22758 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22760 [0] = { REG_VIRT0, REGCM_GPR16 },
22761 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22764 [TEMPLATE_BINARY32_IMM] = {
22765 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22767 [0] = { REG_VIRT0, REGCM_GPR32 },
22768 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22771 [TEMPLATE_SL8_CL] = {
22772 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22774 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22775 [1] = { REG_CL, REGCM_GPR8_LO },
22778 [TEMPLATE_SL16_CL] = {
22779 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22781 [0] = { REG_VIRT0, REGCM_GPR16 },
22782 [1] = { REG_CL, REGCM_GPR8_LO },
22785 [TEMPLATE_SL32_CL] = {
22786 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22788 [0] = { REG_VIRT0, REGCM_GPR32 },
22789 [1] = { REG_CL, REGCM_GPR8_LO },
22792 [TEMPLATE_SL8_IMM] = {
22793 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22795 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22796 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22799 [TEMPLATE_SL16_IMM] = {
22800 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22802 [0] = { REG_VIRT0, REGCM_GPR16 },
22803 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22806 [TEMPLATE_SL32_IMM] = {
22807 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22809 [0] = { REG_VIRT0, REGCM_GPR32 },
22810 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22813 [TEMPLATE_UNARY8] = {
22814 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22815 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22817 [TEMPLATE_UNARY16] = {
22818 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22819 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22821 [TEMPLATE_UNARY32] = {
22822 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22823 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22825 [TEMPLATE_CMP8_REG] = {
22826 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22828 [0] = { REG_UNSET, REGCM_GPR8_LO },
22829 [1] = { REG_UNSET, REGCM_GPR8_LO },
22832 [TEMPLATE_CMP16_REG] = {
22833 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22835 [0] = { REG_UNSET, REGCM_GPR16 },
22836 [1] = { REG_UNSET, REGCM_GPR16 },
22839 [TEMPLATE_CMP32_REG] = {
22840 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22842 [0] = { REG_UNSET, REGCM_GPR32 },
22843 [1] = { REG_UNSET, REGCM_GPR32 },
22846 [TEMPLATE_CMP8_IMM] = {
22847 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22849 [0] = { REG_UNSET, REGCM_GPR8_LO },
22850 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22853 [TEMPLATE_CMP16_IMM] = {
22854 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22856 [0] = { REG_UNSET, REGCM_GPR16 },
22857 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22860 [TEMPLATE_CMP32_IMM] = {
22861 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22863 [0] = { REG_UNSET, REGCM_GPR32 },
22864 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22867 [TEMPLATE_TEST8] = {
22868 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22869 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22871 [TEMPLATE_TEST16] = {
22872 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22873 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22875 [TEMPLATE_TEST32] = {
22876 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22877 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22880 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22881 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22884 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22887 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22889 [TEMPLATE_INB_DX] = {
22890 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22891 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22893 [TEMPLATE_INB_IMM] = {
22894 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22895 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22897 [TEMPLATE_INW_DX] = {
22898 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22899 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22901 [TEMPLATE_INW_IMM] = {
22902 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22903 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22905 [TEMPLATE_INL_DX] = {
22906 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22907 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22909 [TEMPLATE_INL_IMM] = {
22910 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22911 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22913 [TEMPLATE_OUTB_DX] = {
22915 [0] = { REG_AL, REGCM_GPR8_LO },
22916 [1] = { REG_DX, REGCM_GPR16 },
22919 [TEMPLATE_OUTB_IMM] = {
22921 [0] = { REG_AL, REGCM_GPR8_LO },
22922 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22925 [TEMPLATE_OUTW_DX] = {
22927 [0] = { REG_AX, REGCM_GPR16 },
22928 [1] = { REG_DX, REGCM_GPR16 },
22931 [TEMPLATE_OUTW_IMM] = {
22933 [0] = { REG_AX, REGCM_GPR16 },
22934 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22937 [TEMPLATE_OUTL_DX] = {
22939 [0] = { REG_EAX, REGCM_GPR32 },
22940 [1] = { REG_DX, REGCM_GPR16 },
22943 [TEMPLATE_OUTL_IMM] = {
22945 [0] = { REG_EAX, REGCM_GPR32 },
22946 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22950 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22951 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22953 [TEMPLATE_RDMSR] = {
22955 [0] = { REG_EAX, REGCM_GPR32 },
22956 [1] = { REG_EDX, REGCM_GPR32 },
22958 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22960 [TEMPLATE_WRMSR] = {
22962 [0] = { REG_ECX, REGCM_GPR32 },
22963 [1] = { REG_EAX, REGCM_GPR32 },
22964 [2] = { REG_EDX, REGCM_GPR32 },
22967 [TEMPLATE_UMUL8] = {
22968 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22970 [0] = { REG_AL, REGCM_GPR8_LO },
22971 [1] = { REG_UNSET, REGCM_GPR8_LO },
22974 [TEMPLATE_UMUL16] = {
22975 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22977 [0] = { REG_AX, REGCM_GPR16 },
22978 [1] = { REG_UNSET, REGCM_GPR16 },
22981 [TEMPLATE_UMUL32] = {
22982 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22984 [0] = { REG_EAX, REGCM_GPR32 },
22985 [1] = { REG_UNSET, REGCM_GPR32 },
22988 [TEMPLATE_DIV8] = {
22990 [0] = { REG_AL, REGCM_GPR8_LO },
22991 [1] = { REG_AH, REGCM_GPR8 },
22994 [0] = { REG_AX, REGCM_GPR16 },
22995 [1] = { REG_UNSET, REGCM_GPR8_LO },
22998 [TEMPLATE_DIV16] = {
23000 [0] = { REG_AX, REGCM_GPR16 },
23001 [1] = { REG_DX, REGCM_GPR16 },
23004 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
23005 [1] = { REG_UNSET, REGCM_GPR16 },
23008 [TEMPLATE_DIV32] = {
23010 [0] = { REG_EAX, REGCM_GPR32 },
23011 [1] = { REG_EDX, REGCM_GPR32 },
23014 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
23015 [1] = { REG_UNSET, REGCM_GPR32 },
23020 static void fixup_branch(struct compile_state *state,
23021 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23022 struct triple *left, struct triple *right)
23024 struct triple *test;
23026 internal_error(state, branch, "no branch test?");
23028 test = pre_triple(state, branch,
23029 cmp_op, cmp_type, left, right);
23030 test->template_id = TEMPLATE_TEST32;
23031 if (cmp_op == OP_CMP) {
23032 test->template_id = TEMPLATE_CMP32_REG;
23033 if (get_imm32(test, &RHS(test, 1))) {
23034 test->template_id = TEMPLATE_CMP32_IMM;
23037 use_triple(RHS(test, 0), test);
23038 use_triple(RHS(test, 1), test);
23039 unuse_triple(RHS(branch, 0), branch);
23040 RHS(branch, 0) = test;
23041 branch->op = jmp_op;
23042 branch->template_id = TEMPLATE_JMP;
23043 use_triple(RHS(branch, 0), branch);
23046 static void fixup_branches(struct compile_state *state,
23047 struct triple *cmp, struct triple *use, int jmp_op)
23049 struct triple_set *entry, *next;
23050 for(entry = use->use; entry; entry = next) {
23051 next = entry->next;
23052 if (entry->member->op == OP_COPY) {
23053 fixup_branches(state, cmp, entry->member, jmp_op);
23055 else if (entry->member->op == OP_CBRANCH) {
23056 struct triple *branch;
23057 struct triple *left, *right;
23059 left = RHS(cmp, 0);
23060 if (cmp->rhs > 1) {
23061 right = RHS(cmp, 1);
23063 branch = entry->member;
23064 fixup_branch(state, branch, jmp_op,
23065 cmp->op, cmp->type, left, right);
23070 static void bool_cmp(struct compile_state *state,
23071 struct triple *ins, int cmp_op, int jmp_op, int set_op)
23073 struct triple_set *entry, *next;
23074 struct triple *set, *convert;
23076 /* Put a barrier up before the cmp which preceeds the
23077 * copy instruction. If a set actually occurs this gives
23078 * us a chance to move variables in registers out of the way.
23081 /* Modify the comparison operator */
23083 ins->template_id = TEMPLATE_TEST32;
23084 if (cmp_op == OP_CMP) {
23085 ins->template_id = TEMPLATE_CMP32_REG;
23086 if (get_imm32(ins, &RHS(ins, 1))) {
23087 ins->template_id = TEMPLATE_CMP32_IMM;
23090 /* Generate the instruction sequence that will transform the
23091 * result of the comparison into a logical value.
23093 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23094 use_triple(ins, set);
23095 set->template_id = TEMPLATE_SET;
23098 if (!equiv_types(ins->type, set->type)) {
23099 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23100 use_triple(set, convert);
23101 convert->template_id = TEMPLATE_COPY32_REG;
23104 for(entry = ins->use; entry; entry = next) {
23105 next = entry->next;
23106 if (entry->member == set) {
23109 replace_rhs_use(state, ins, convert, entry->member);
23111 fixup_branches(state, ins, convert, jmp_op);
23114 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23116 struct ins_template *template;
23117 struct reg_info result;
23119 if (ins->op == OP_PIECE) {
23120 index = ins->u.cval;
23121 ins = MISC(ins, 0);
23124 if (triple_is_def(state, ins)) {
23127 if (index >= zlhs) {
23128 internal_error(state, ins, "index %d out of range for %s",
23129 index, tops(ins->op));
23133 template = &ins->u.ainfo->tmpl;
23136 if (ins->template_id > LAST_TEMPLATE) {
23137 internal_error(state, ins, "bad template number %d",
23140 template = &templates[ins->template_id];
23143 result = template->lhs[index];
23144 result.regcm = arch_regcm_normalize(state, result.regcm);
23145 if (result.reg != REG_UNNEEDED) {
23146 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23148 if (result.regcm == 0) {
23149 internal_error(state, ins, "lhs %d regcm == 0", index);
23154 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23156 struct reg_info result;
23157 struct ins_template *template;
23158 if ((index > ins->rhs) ||
23159 (ins->op == OP_PIECE)) {
23160 internal_error(state, ins, "index %d out of range for %s\n",
23161 index, tops(ins->op));
23165 template = &ins->u.ainfo->tmpl;
23171 if (ins->template_id > LAST_TEMPLATE) {
23172 internal_error(state, ins, "bad template number %d",
23175 template = &templates[ins->template_id];
23178 result = template->rhs[index];
23179 result.regcm = arch_regcm_normalize(state, result.regcm);
23180 if (result.regcm == 0) {
23181 internal_error(state, ins, "rhs %d regcm == 0", index);
23186 static struct triple *mod_div(struct compile_state *state,
23187 struct triple *ins, int div_op, int index)
23189 struct triple *div, *piece0, *piece1;
23191 /* Generate the appropriate division instruction */
23192 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23193 RHS(div, 0) = RHS(ins, 0);
23194 RHS(div, 1) = RHS(ins, 1);
23195 piece0 = LHS(div, 0);
23196 piece1 = LHS(div, 1);
23197 div->template_id = TEMPLATE_DIV32;
23198 use_triple(RHS(div, 0), div);
23199 use_triple(RHS(div, 1), div);
23200 use_triple(LHS(div, 0), div);
23201 use_triple(LHS(div, 1), div);
23203 /* Replate uses of ins with the appropriate piece of the div */
23204 propogate_use(state, ins, LHS(div, index));
23205 release_triple(state, ins);
23207 /* Return the address of the next instruction */
23208 return piece1->next;
23211 static int noop_adecl(struct triple *adecl)
23213 struct triple_set *use;
23214 /* It's a noop if it doesn't specify stoorage */
23215 if (adecl->lhs == 0) {
23218 /* Is the adecl used? If not it's a noop */
23219 for(use = adecl->use; use ; use = use->next) {
23220 if ((use->member->op != OP_PIECE) ||
23221 (MISC(use->member, 0) != adecl)) {
23228 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23230 struct triple *mask, *nmask, *shift;
23231 struct triple *val, *val_mask, *val_shift;
23232 struct triple *targ, *targ_mask;
23233 struct triple *new;
23234 ulong_t the_mask, the_nmask;
23236 targ = RHS(ins, 0);
23239 /* Get constant for the mask value */
23241 the_mask <<= ins->u.bitfield.size;
23243 the_mask <<= ins->u.bitfield.offset;
23244 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23245 mask->u.cval = the_mask;
23247 /* Get the inverted mask value */
23248 the_nmask = ~the_mask;
23249 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23250 nmask->u.cval = the_nmask;
23252 /* Get constant for the shift value */
23253 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23254 shift->u.cval = ins->u.bitfield.offset;
23256 /* Shift and mask the source value */
23258 if (shift->u.cval != 0) {
23259 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23260 use_triple(val, val_shift);
23261 use_triple(shift, val_shift);
23263 val_mask = val_shift;
23264 if (is_signed(val->type)) {
23265 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23266 use_triple(val_shift, val_mask);
23267 use_triple(mask, val_mask);
23270 /* Mask the target value */
23271 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23272 use_triple(targ, targ_mask);
23273 use_triple(nmask, targ_mask);
23275 /* Now combined them together */
23276 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23277 use_triple(targ_mask, new);
23278 use_triple(val_mask, new);
23280 /* Move all of the users over to the new expression */
23281 propogate_use(state, ins, new);
23283 /* Delete the original triple */
23284 release_triple(state, ins);
23286 /* Restart the transformation at mask */
23290 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23292 struct triple *mask, *shift;
23293 struct triple *val, *val_mask, *val_shift;
23298 /* Get constant for the mask value */
23300 the_mask <<= ins->u.bitfield.size;
23302 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23303 mask->u.cval = the_mask;
23305 /* Get constant for the right shift value */
23306 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23307 shift->u.cval = ins->u.bitfield.offset;
23309 /* Shift arithmetic right, to correct the sign */
23311 if (shift->u.cval != 0) {
23313 if (ins->op == OP_SEXTRACT) {
23318 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23319 use_triple(val, val_shift);
23320 use_triple(shift, val_shift);
23323 /* Finally mask the value */
23324 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23325 use_triple(val_shift, val_mask);
23326 use_triple(mask, val_mask);
23328 /* Move all of the users over to the new expression */
23329 propogate_use(state, ins, val_mask);
23331 /* Release the original instruction */
23332 release_triple(state, ins);
23338 static struct triple *transform_to_arch_instruction(
23339 struct compile_state *state, struct triple *ins)
23341 /* Transform from generic 3 address instructions
23342 * to archtecture specific instructions.
23343 * And apply architecture specific constraints to instructions.
23344 * Copies are inserted to preserve the register flexibility
23345 * of 3 address instructions.
23347 struct triple *next, *value;
23352 ins->template_id = TEMPLATE_INTCONST32;
23353 if (ins->u.cval < 256) {
23354 ins->template_id = TEMPLATE_INTCONST8;
23358 ins->template_id = TEMPLATE_INTCONST32;
23360 case OP_UNKNOWNVAL:
23361 ins->template_id = TEMPLATE_UNKNOWNVAL;
23367 ins->template_id = TEMPLATE_NOP;
23371 size = size_of(state, ins->type);
23372 value = RHS(ins, 0);
23373 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23374 ins->template_id = TEMPLATE_COPY_IMM8;
23376 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23377 ins->template_id = TEMPLATE_COPY_IMM16;
23379 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23380 ins->template_id = TEMPLATE_COPY_IMM32;
23382 else if (is_const(value)) {
23383 internal_error(state, ins, "bad constant passed to copy");
23385 else if (size <= SIZEOF_I8) {
23386 ins->template_id = TEMPLATE_COPY8_REG;
23388 else if (size <= SIZEOF_I16) {
23389 ins->template_id = TEMPLATE_COPY16_REG;
23391 else if (size <= SIZEOF_I32) {
23392 ins->template_id = TEMPLATE_COPY32_REG;
23395 internal_error(state, ins, "bad type passed to copy");
23399 size = size_of(state, ins->type);
23400 if (size <= SIZEOF_I8) {
23401 ins->template_id = TEMPLATE_PHI8;
23403 else if (size <= SIZEOF_I16) {
23404 ins->template_id = TEMPLATE_PHI16;
23406 else if (size <= SIZEOF_I32) {
23407 ins->template_id = TEMPLATE_PHI32;
23410 internal_error(state, ins, "bad type passed to phi");
23414 /* Adecls should always be treated as dead code and
23415 * removed. If we are not optimizing they may linger.
23417 if (!noop_adecl(ins)) {
23418 internal_error(state, ins, "adecl remains?");
23420 ins->template_id = TEMPLATE_NOP;
23421 next = after_lhs(state, ins);
23424 switch(ins->type->type & TYPE_MASK) {
23425 case TYPE_CHAR: case TYPE_UCHAR:
23426 ins->template_id = TEMPLATE_STORE8;
23428 case TYPE_SHORT: case TYPE_USHORT:
23429 ins->template_id = TEMPLATE_STORE16;
23431 case TYPE_INT: case TYPE_UINT:
23432 case TYPE_LONG: case TYPE_ULONG:
23434 ins->template_id = TEMPLATE_STORE32;
23437 internal_error(state, ins, "unknown type in store");
23442 switch(ins->type->type & TYPE_MASK) {
23443 case TYPE_CHAR: case TYPE_UCHAR:
23444 case TYPE_SHORT: case TYPE_USHORT:
23445 case TYPE_INT: case TYPE_UINT:
23446 case TYPE_LONG: case TYPE_ULONG:
23450 internal_error(state, ins, "unknown type in load");
23453 ins->template_id = TEMPLATE_LOAD32;
23461 ins->template_id = TEMPLATE_BINARY32_REG;
23462 if (get_imm32(ins, &RHS(ins, 1))) {
23463 ins->template_id = TEMPLATE_BINARY32_IMM;
23468 ins->template_id = TEMPLATE_DIV32;
23469 next = after_lhs(state, ins);
23472 ins->template_id = TEMPLATE_UMUL32;
23475 next = mod_div(state, ins, OP_UDIVT, 0);
23478 next = mod_div(state, ins, OP_SDIVT, 0);
23481 next = mod_div(state, ins, OP_UDIVT, 1);
23484 next = mod_div(state, ins, OP_SDIVT, 1);
23489 ins->template_id = TEMPLATE_SL32_CL;
23490 if (get_imm8(ins, &RHS(ins, 1))) {
23491 ins->template_id = TEMPLATE_SL32_IMM;
23492 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23493 typed_pre_copy(state, &uchar_type, ins, 1);
23498 ins->template_id = TEMPLATE_UNARY32;
23501 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23504 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23507 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23510 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23513 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23516 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23519 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23522 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23525 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23528 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23531 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23534 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23538 ins->template_id = TEMPLATE_NOP;
23541 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23542 RHS(ins, 0)->type, RHS(ins, 0), 0);
23545 ins->template_id = TEMPLATE_NOP;
23548 ins->template_id = TEMPLATE_RET;
23554 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23555 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23556 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23558 if (get_imm8(ins, &RHS(ins, 0))) {
23559 ins->template_id += 1;
23566 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23567 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23568 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23570 if (get_imm8(ins, &RHS(ins, 1))) {
23571 ins->template_id += 1;
23576 ins->template_id = TEMPLATE_BSF;
23579 ins->template_id = TEMPLATE_RDMSR;
23580 next = after_lhs(state, ins);
23583 ins->template_id = TEMPLATE_WRMSR;
23586 ins->template_id = TEMPLATE_NOP;
23589 ins->template_id = TEMPLATE_NOP;
23590 next = after_lhs(state, ins);
23592 /* Already transformed instructions */
23594 ins->template_id = TEMPLATE_TEST32;
23597 ins->template_id = TEMPLATE_CMP32_REG;
23598 if (get_imm32(ins, &RHS(ins, 1))) {
23599 ins->template_id = TEMPLATE_CMP32_IMM;
23603 ins->template_id = TEMPLATE_NOP;
23605 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23606 case OP_JMP_SLESS: case OP_JMP_ULESS:
23607 case OP_JMP_SMORE: case OP_JMP_UMORE:
23608 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23609 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23610 ins->template_id = TEMPLATE_JMP;
23612 case OP_SET_EQ: case OP_SET_NOTEQ:
23613 case OP_SET_SLESS: case OP_SET_ULESS:
23614 case OP_SET_SMORE: case OP_SET_UMORE:
23615 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23616 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23617 ins->template_id = TEMPLATE_SET;
23620 next = x86_deposit(state, ins);
23624 next = x86_extract(state, ins);
23626 /* Unhandled instructions */
23629 internal_error(state, ins, "unhandled ins: %d %s",
23630 ins->op, tops(ins->op));
23636 static long next_label(struct compile_state *state)
23638 static long label_counter = 1000;
23639 return ++label_counter;
23641 static void generate_local_labels(struct compile_state *state)
23643 struct triple *first, *label;
23644 first = state->first;
23647 if ((label->op == OP_LABEL) ||
23648 (label->op == OP_SDECL)) {
23650 label->u.cval = next_label(state);
23656 label = label->next;
23657 } while(label != first);
23660 static int check_reg(struct compile_state *state,
23661 struct triple *triple, int classes)
23665 reg = ID_REG(triple->id);
23666 if (reg == REG_UNSET) {
23667 internal_error(state, triple, "register not set");
23669 mask = arch_reg_regcm(state, reg);
23670 if (!(classes & mask)) {
23671 internal_error(state, triple, "reg %d in wrong class",
23679 #error "Registers have renumberd fix arch_reg_str"
23681 static const char *arch_regs[] = {
23685 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23686 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23687 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23690 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23691 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23692 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23694 static const char *arch_reg_str(int reg)
23696 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23699 return arch_regs[reg];
23702 static const char *reg(struct compile_state *state, struct triple *triple,
23706 reg = check_reg(state, triple, classes);
23707 return arch_reg_str(reg);
23710 static int arch_reg_size(int reg)
23714 if (reg == REG_EFLAGS) {
23717 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23720 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23723 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23726 else if (reg == REG_EDXEAX) {
23729 else if (reg == REG_DXAX) {
23732 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23735 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23741 static int reg_size(struct compile_state *state, struct triple *ins)
23744 reg = ID_REG(ins->id);
23745 if (reg == REG_UNSET) {
23746 internal_error(state, ins, "register not set");
23748 return arch_reg_size(reg);
23753 const char *type_suffix(struct compile_state *state, struct type *type)
23755 const char *suffix;
23756 switch(size_of(state, type)) {
23757 case SIZEOF_I8: suffix = "b"; break;
23758 case SIZEOF_I16: suffix = "w"; break;
23759 case SIZEOF_I32: suffix = "l"; break;
23761 internal_error(state, 0, "unknown suffix");
23768 static void print_const_val(
23769 struct compile_state *state, struct triple *ins, FILE *fp)
23773 fprintf(fp, " $%ld ",
23774 (long)(ins->u.cval));
23777 if ((MISC(ins, 0)->op != OP_SDECL) &&
23778 (MISC(ins, 0)->op != OP_LABEL))
23780 internal_error(state, ins, "bad base for addrconst");
23782 if (MISC(ins, 0)->u.cval <= 0) {
23783 internal_error(state, ins, "unlabeled constant");
23785 fprintf(fp, " $L%s%lu+%lu ",
23786 state->compiler->label_prefix,
23787 (unsigned long)(MISC(ins, 0)->u.cval),
23788 (unsigned long)(ins->u.cval));
23791 internal_error(state, ins, "unknown constant type");
23796 static void print_const(struct compile_state *state,
23797 struct triple *ins, FILE *fp)
23801 switch(ins->type->type & TYPE_MASK) {
23804 fprintf(fp, ".byte 0x%02lx\n",
23805 (unsigned long)(ins->u.cval));
23809 fprintf(fp, ".short 0x%04lx\n",
23810 (unsigned long)(ins->u.cval));
23817 fprintf(fp, ".int %lu\n",
23818 (unsigned long)(ins->u.cval));
23821 fprintf(state->errout, "type: ");
23822 name_of(state->errout, ins->type);
23823 fprintf(state->errout, "\n");
23824 internal_error(state, ins, "Unknown constant type. Val: %lu",
23825 (unsigned long)(ins->u.cval));
23830 if ((MISC(ins, 0)->op != OP_SDECL) &&
23831 (MISC(ins, 0)->op != OP_LABEL)) {
23832 internal_error(state, ins, "bad base for addrconst");
23834 if (MISC(ins, 0)->u.cval <= 0) {
23835 internal_error(state, ins, "unlabeled constant");
23837 fprintf(fp, ".int L%s%lu+%lu\n",
23838 state->compiler->label_prefix,
23839 (unsigned long)(MISC(ins, 0)->u.cval),
23840 (unsigned long)(ins->u.cval));
23844 unsigned char *blob;
23846 size = size_of_in_bytes(state, ins->type);
23847 blob = ins->u.blob;
23848 for(i = 0; i < size; i++) {
23849 fprintf(fp, ".byte 0x%02x\n",
23855 internal_error(state, ins, "Unknown constant type");
23860 #define TEXT_SECTION ".rom.text"
23861 #define DATA_SECTION ".rom.data"
23863 static long get_const_pool_ref(
23864 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23868 ref = next_label(state);
23869 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23870 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23871 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23872 print_const(state, ins, fp);
23873 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23875 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23877 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23881 static long get_mask_pool_ref(
23882 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23885 if (mask == 0xff) {
23888 else if (mask == 0xffff) {
23893 internal_error(state, ins, "unhandled mask value");
23898 static void print_binary_op(struct compile_state *state,
23899 const char *op, struct triple *ins, FILE *fp)
23902 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23903 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23904 internal_error(state, ins, "invalid register assignment");
23906 if (is_const(RHS(ins, 1))) {
23907 fprintf(fp, "\t%s ", op);
23908 print_const_val(state, RHS(ins, 1), fp);
23909 fprintf(fp, ", %s\n",
23910 reg(state, RHS(ins, 0), mask));
23913 unsigned lmask, rmask;
23915 lreg = check_reg(state, RHS(ins, 0), mask);
23916 rreg = check_reg(state, RHS(ins, 1), mask);
23917 lmask = arch_reg_regcm(state, lreg);
23918 rmask = arch_reg_regcm(state, rreg);
23919 mask = lmask & rmask;
23920 fprintf(fp, "\t%s %s, %s\n",
23922 reg(state, RHS(ins, 1), mask),
23923 reg(state, RHS(ins, 0), mask));
23926 static void print_unary_op(struct compile_state *state,
23927 const char *op, struct triple *ins, FILE *fp)
23930 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23931 fprintf(fp, "\t%s %s\n",
23933 reg(state, RHS(ins, 0), mask));
23936 static void print_op_shift(struct compile_state *state,
23937 const char *op, struct triple *ins, FILE *fp)
23940 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23941 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23942 internal_error(state, ins, "invalid register assignment");
23944 if (is_const(RHS(ins, 1))) {
23945 fprintf(fp, "\t%s ", op);
23946 print_const_val(state, RHS(ins, 1), fp);
23947 fprintf(fp, ", %s\n",
23948 reg(state, RHS(ins, 0), mask));
23951 fprintf(fp, "\t%s %s, %s\n",
23953 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23954 reg(state, RHS(ins, 0), mask));
23958 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23965 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23966 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23967 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23969 internal_error(state, ins, "not an in operation");
23973 dreg = check_reg(state, ins, mask);
23974 if (!reg_is_reg(state, dreg, REG_EAX)) {
23975 internal_error(state, ins, "dst != %%eax");
23977 if (is_const(RHS(ins, 0))) {
23978 fprintf(fp, "\t%s ", op);
23979 print_const_val(state, RHS(ins, 0), fp);
23980 fprintf(fp, ", %s\n",
23981 reg(state, ins, mask));
23985 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23986 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23987 internal_error(state, ins, "src != %%dx");
23989 fprintf(fp, "\t%s %s, %s\n",
23991 reg(state, RHS(ins, 0), REGCM_GPR16),
23992 reg(state, ins, mask));
23996 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
24003 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
24004 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
24005 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
24007 internal_error(state, ins, "not an out operation");
24011 lreg = check_reg(state, RHS(ins, 0), mask);
24012 if (!reg_is_reg(state, lreg, REG_EAX)) {
24013 internal_error(state, ins, "src != %%eax");
24015 if (is_const(RHS(ins, 1))) {
24016 fprintf(fp, "\t%s %s,",
24017 op, reg(state, RHS(ins, 0), mask));
24018 print_const_val(state, RHS(ins, 1), fp);
24023 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24024 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24025 internal_error(state, ins, "dst != %%dx");
24027 fprintf(fp, "\t%s %s, %s\n",
24029 reg(state, RHS(ins, 0), mask),
24030 reg(state, RHS(ins, 1), REGCM_GPR16));
24034 static void print_op_move(struct compile_state *state,
24035 struct triple *ins, FILE *fp)
24037 /* op_move is complex because there are many types
24038 * of registers we can move between.
24039 * Because OP_COPY will be introduced in arbitrary locations
24040 * OP_COPY must not affect flags.
24041 * OP_CONVERT can change the flags and it is the only operation
24042 * where it is expected the types in the registers can change.
24044 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24045 struct triple *dst, *src;
24046 if (state->arch->features & X86_NOOP_COPY) {
24049 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24054 internal_error(state, ins, "unknown move operation");
24057 if (reg_size(state, dst) < size_of(state, dst->type)) {
24058 internal_error(state, ins, "Invalid destination register");
24060 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24061 fprintf(state->errout, "src type: ");
24062 name_of(state->errout, src->type);
24063 fprintf(state->errout, "\n");
24064 fprintf(state->errout, "dst type: ");
24065 name_of(state->errout, dst->type);
24066 fprintf(state->errout, "\n");
24067 internal_error(state, ins, "Type mismatch for OP_COPY");
24070 if (!is_const(src)) {
24071 int src_reg, dst_reg;
24072 int src_regcm, dst_regcm;
24073 src_reg = ID_REG(src->id);
24074 dst_reg = ID_REG(dst->id);
24075 src_regcm = arch_reg_regcm(state, src_reg);
24076 dst_regcm = arch_reg_regcm(state, dst_reg);
24077 /* If the class is the same just move the register */
24078 if (src_regcm & dst_regcm &
24079 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24080 if ((src_reg != dst_reg) || !omit_copy) {
24081 fprintf(fp, "\tmov %s, %s\n",
24082 reg(state, src, src_regcm),
24083 reg(state, dst, dst_regcm));
24086 /* Move 32bit to 16bit */
24087 else if ((src_regcm & REGCM_GPR32) &&
24088 (dst_regcm & REGCM_GPR16)) {
24089 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24090 if ((src_reg != dst_reg) || !omit_copy) {
24091 fprintf(fp, "\tmovw %s, %s\n",
24092 arch_reg_str(src_reg),
24093 arch_reg_str(dst_reg));
24096 /* Move from 32bit gprs to 16bit gprs */
24097 else if ((src_regcm & REGCM_GPR32) &&
24098 (dst_regcm & REGCM_GPR16)) {
24099 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24100 if ((src_reg != dst_reg) || !omit_copy) {
24101 fprintf(fp, "\tmov %s, %s\n",
24102 arch_reg_str(src_reg),
24103 arch_reg_str(dst_reg));
24106 /* Move 32bit to 8bit */
24107 else if ((src_regcm & REGCM_GPR32_8) &&
24108 (dst_regcm & REGCM_GPR8_LO))
24110 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24111 if ((src_reg != dst_reg) || !omit_copy) {
24112 fprintf(fp, "\tmovb %s, %s\n",
24113 arch_reg_str(src_reg),
24114 arch_reg_str(dst_reg));
24117 /* Move 16bit to 8bit */
24118 else if ((src_regcm & REGCM_GPR16_8) &&
24119 (dst_regcm & REGCM_GPR8_LO))
24121 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24122 if ((src_reg != dst_reg) || !omit_copy) {
24123 fprintf(fp, "\tmovb %s, %s\n",
24124 arch_reg_str(src_reg),
24125 arch_reg_str(dst_reg));
24128 /* Move 8/16bit to 16/32bit */
24129 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24130 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24132 op = is_signed(src->type)? "movsx": "movzx";
24133 fprintf(fp, "\t%s %s, %s\n",
24135 reg(state, src, src_regcm),
24136 reg(state, dst, dst_regcm));
24138 /* Move between sse registers */
24139 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24140 if ((src_reg != dst_reg) || !omit_copy) {
24141 fprintf(fp, "\tmovdqa %s, %s\n",
24142 reg(state, src, src_regcm),
24143 reg(state, dst, dst_regcm));
24146 /* Move between mmx registers */
24147 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24148 if ((src_reg != dst_reg) || !omit_copy) {
24149 fprintf(fp, "\tmovq %s, %s\n",
24150 reg(state, src, src_regcm),
24151 reg(state, dst, dst_regcm));
24154 /* Move from sse to mmx registers */
24155 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24156 fprintf(fp, "\tmovdq2q %s, %s\n",
24157 reg(state, src, src_regcm),
24158 reg(state, dst, dst_regcm));
24160 /* Move from mmx to sse registers */
24161 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24162 fprintf(fp, "\tmovq2dq %s, %s\n",
24163 reg(state, src, src_regcm),
24164 reg(state, dst, dst_regcm));
24166 /* Move between 32bit gprs & mmx/sse registers */
24167 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24168 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24169 fprintf(fp, "\tmovd %s, %s\n",
24170 reg(state, src, src_regcm),
24171 reg(state, dst, dst_regcm));
24173 /* Move from 16bit gprs & mmx/sse registers */
24174 else if ((src_regcm & REGCM_GPR16) &&
24175 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24178 op = is_signed(src->type)? "movsx":"movzx";
24179 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24180 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24182 arch_reg_str(src_reg),
24183 arch_reg_str(mid_reg),
24184 arch_reg_str(mid_reg),
24185 arch_reg_str(dst_reg));
24187 /* Move from mmx/sse registers to 16bit gprs */
24188 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24189 (dst_regcm & REGCM_GPR16)) {
24190 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24191 fprintf(fp, "\tmovd %s, %s\n",
24192 arch_reg_str(src_reg),
24193 arch_reg_str(dst_reg));
24195 /* Move from gpr to 64bit dividend */
24196 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24197 (dst_regcm & REGCM_DIVIDEND64)) {
24198 const char *extend;
24199 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24200 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24201 arch_reg_str(src_reg),
24204 /* Move from 64bit gpr to gpr */
24205 else if ((src_regcm & REGCM_DIVIDEND64) &&
24206 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24207 if (dst_regcm & REGCM_GPR32) {
24210 else if (dst_regcm & REGCM_GPR16) {
24213 else if (dst_regcm & REGCM_GPR8_LO) {
24216 fprintf(fp, "\tmov %s, %s\n",
24217 arch_reg_str(src_reg),
24218 arch_reg_str(dst_reg));
24220 /* Move from mmx/sse registers to 64bit gpr */
24221 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24222 (dst_regcm & REGCM_DIVIDEND64)) {
24223 const char *extend;
24224 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24225 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24226 arch_reg_str(src_reg),
24229 /* Move from 64bit gpr to mmx/sse register */
24230 else if ((src_regcm & REGCM_DIVIDEND64) &&
24231 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24232 fprintf(fp, "\tmovd %%eax, %s\n",
24233 arch_reg_str(dst_reg));
24235 #if X86_4_8BIT_GPRS
24236 /* Move from 8bit gprs to mmx/sse registers */
24237 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24238 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24241 op = is_signed(src->type)? "movsx":"movzx";
24242 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24243 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24245 reg(state, src, src_regcm),
24246 arch_reg_str(mid_reg),
24247 arch_reg_str(mid_reg),
24248 reg(state, dst, dst_regcm));
24250 /* Move from mmx/sse registers and 8bit gprs */
24251 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24252 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24254 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24255 fprintf(fp, "\tmovd %s, %s\n",
24256 reg(state, src, src_regcm),
24257 arch_reg_str(mid_reg));
24259 /* Move from 32bit gprs to 8bit gprs */
24260 else if ((src_regcm & REGCM_GPR32) &&
24261 (dst_regcm & REGCM_GPR8_LO)) {
24262 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24263 if ((src_reg != dst_reg) || !omit_copy) {
24264 fprintf(fp, "\tmov %s, %s\n",
24265 arch_reg_str(src_reg),
24266 arch_reg_str(dst_reg));
24269 /* Move from 16bit gprs to 8bit gprs */
24270 else if ((src_regcm & REGCM_GPR16) &&
24271 (dst_regcm & REGCM_GPR8_LO)) {
24272 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24273 if ((src_reg != dst_reg) || !omit_copy) {
24274 fprintf(fp, "\tmov %s, %s\n",
24275 arch_reg_str(src_reg),
24276 arch_reg_str(dst_reg));
24279 #endif /* X86_4_8BIT_GPRS */
24280 /* Move from %eax:%edx to %eax:%edx */
24281 else if ((src_regcm & REGCM_DIVIDEND64) &&
24282 (dst_regcm & REGCM_DIVIDEND64) &&
24283 (src_reg == dst_reg)) {
24285 fprintf(fp, "\t/*mov %s, %s*/\n",
24286 arch_reg_str(src_reg),
24287 arch_reg_str(dst_reg));
24291 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24292 internal_error(state, ins, "attempt to copy from %%eflags!");
24294 internal_error(state, ins, "unknown copy type");
24301 dst_size = size_of(state, dst->type);
24302 dst_reg = ID_REG(dst->id);
24303 dst_regcm = arch_reg_regcm(state, dst_reg);
24304 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24305 fprintf(fp, "\tmov ");
24306 print_const_val(state, src, fp);
24307 fprintf(fp, ", %s\n",
24308 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24310 else if (dst_regcm & REGCM_DIVIDEND64) {
24311 if (dst_size > SIZEOF_I32) {
24312 internal_error(state, ins, "%dbit constant...", dst_size);
24314 fprintf(fp, "\tmov $0, %%edx\n");
24315 fprintf(fp, "\tmov ");
24316 print_const_val(state, src, fp);
24317 fprintf(fp, ", %%eax\n");
24319 else if (dst_regcm & REGCM_DIVIDEND32) {
24320 if (dst_size > SIZEOF_I16) {
24321 internal_error(state, ins, "%dbit constant...", dst_size);
24323 fprintf(fp, "\tmov $0, %%dx\n");
24324 fprintf(fp, "\tmov ");
24325 print_const_val(state, src, fp);
24326 fprintf(fp, ", %%ax");
24328 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24330 if (dst_size > SIZEOF_I32) {
24331 internal_error(state, ins, "%d bit constant...", dst_size);
24333 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24334 fprintf(fp, "\tmovd L%s%lu, %s\n",
24335 state->compiler->label_prefix, ref,
24336 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24339 internal_error(state, ins, "unknown copy immediate type");
24342 /* Leave now if this is not a type conversion */
24343 if (ins->op != OP_CONVERT) {
24346 /* Now make certain I have not logically overflowed the destination */
24347 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24348 (size_of(state, dst->type) < reg_size(state, dst)))
24350 unsigned long mask;
24353 if (size_of(state, dst->type) >= 32) {
24354 fprintf(state->errout, "dst type: ");
24355 name_of(state->errout, dst->type);
24356 fprintf(state->errout, "\n");
24357 internal_error(state, dst, "unhandled dst type size");
24360 mask <<= size_of(state, dst->type);
24363 dst_reg = ID_REG(dst->id);
24364 dst_regcm = arch_reg_regcm(state, dst_reg);
24366 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24367 fprintf(fp, "\tand $0x%lx, %s\n",
24368 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24370 else if (dst_regcm & REGCM_MMX) {
24372 ref = get_mask_pool_ref(state, dst, mask, fp);
24373 fprintf(fp, "\tpand L%s%lu, %s\n",
24374 state->compiler->label_prefix, ref,
24375 reg(state, dst, REGCM_MMX));
24377 else if (dst_regcm & REGCM_XMM) {
24379 ref = get_mask_pool_ref(state, dst, mask, fp);
24380 fprintf(fp, "\tpand L%s%lu, %s\n",
24381 state->compiler->label_prefix, ref,
24382 reg(state, dst, REGCM_XMM));
24385 fprintf(state->errout, "dst type: ");
24386 name_of(state->errout, dst->type);
24387 fprintf(state->errout, "\n");
24388 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24389 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24392 /* Make certain I am properly sign extended */
24393 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24394 (is_signed(src->type)))
24396 int bits, reg_bits, shift_bits;
24400 bits = size_of(state, src->type);
24401 reg_bits = reg_size(state, dst);
24402 if (reg_bits > 32) {
24405 shift_bits = reg_bits - size_of(state, src->type);
24406 dst_reg = ID_REG(dst->id);
24407 dst_regcm = arch_reg_regcm(state, dst_reg);
24409 if (shift_bits < 0) {
24410 internal_error(state, dst, "negative shift?");
24413 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24414 fprintf(fp, "\tshl $%d, %s\n",
24416 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24417 fprintf(fp, "\tsar $%d, %s\n",
24419 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24421 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24422 fprintf(fp, "\tpslld $%d, %s\n",
24424 reg(state, dst, REGCM_MMX | REGCM_XMM));
24425 fprintf(fp, "\tpsrad $%d, %s\n",
24427 reg(state, dst, REGCM_MMX | REGCM_XMM));
24430 fprintf(state->errout, "dst type: ");
24431 name_of(state->errout, dst->type);
24432 fprintf(state->errout, "\n");
24433 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24434 internal_error(state, dst, "failed to signed extend value");
24439 static void print_op_load(struct compile_state *state,
24440 struct triple *ins, FILE *fp)
24442 struct triple *dst, *src;
24446 if (is_const(src) || is_const(dst)) {
24447 internal_error(state, ins, "unknown load operation");
24449 switch(ins->type->type & TYPE_MASK) {
24450 case TYPE_CHAR: op = "movsbl"; break;
24451 case TYPE_UCHAR: op = "movzbl"; break;
24452 case TYPE_SHORT: op = "movswl"; break;
24453 case TYPE_USHORT: op = "movzwl"; break;
24454 case TYPE_INT: case TYPE_UINT:
24455 case TYPE_LONG: case TYPE_ULONG:
24460 internal_error(state, ins, "unknown type in load");
24461 op = "<invalid opcode>";
24464 fprintf(fp, "\t%s (%s), %s\n",
24466 reg(state, src, REGCM_GPR32),
24467 reg(state, dst, REGCM_GPR32));
24471 static void print_op_store(struct compile_state *state,
24472 struct triple *ins, FILE *fp)
24474 struct triple *dst, *src;
24477 if (is_const(src) && (src->op == OP_INTCONST)) {
24479 value = (long_t)(src->u.cval);
24480 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24481 type_suffix(state, src->type),
24483 reg(state, dst, REGCM_GPR32));
24485 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24486 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24487 type_suffix(state, src->type),
24488 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24489 (unsigned long)(dst->u.cval));
24492 if (is_const(src) || is_const(dst)) {
24493 internal_error(state, ins, "unknown store operation");
24495 fprintf(fp, "\tmov%s %s, (%s)\n",
24496 type_suffix(state, src->type),
24497 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24498 reg(state, dst, REGCM_GPR32));
24504 static void print_op_smul(struct compile_state *state,
24505 struct triple *ins, FILE *fp)
24507 if (!is_const(RHS(ins, 1))) {
24508 fprintf(fp, "\timul %s, %s\n",
24509 reg(state, RHS(ins, 1), REGCM_GPR32),
24510 reg(state, RHS(ins, 0), REGCM_GPR32));
24513 fprintf(fp, "\timul ");
24514 print_const_val(state, RHS(ins, 1), fp);
24515 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24519 static void print_op_cmp(struct compile_state *state,
24520 struct triple *ins, FILE *fp)
24524 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24525 dreg = check_reg(state, ins, REGCM_FLAGS);
24526 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24527 internal_error(state, ins, "bad dest register for cmp");
24529 if (is_const(RHS(ins, 1))) {
24530 fprintf(fp, "\tcmp ");
24531 print_const_val(state, RHS(ins, 1), fp);
24532 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24535 unsigned lmask, rmask;
24537 lreg = check_reg(state, RHS(ins, 0), mask);
24538 rreg = check_reg(state, RHS(ins, 1), mask);
24539 lmask = arch_reg_regcm(state, lreg);
24540 rmask = arch_reg_regcm(state, rreg);
24541 mask = lmask & rmask;
24542 fprintf(fp, "\tcmp %s, %s\n",
24543 reg(state, RHS(ins, 1), mask),
24544 reg(state, RHS(ins, 0), mask));
24548 static void print_op_test(struct compile_state *state,
24549 struct triple *ins, FILE *fp)
24552 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24553 fprintf(fp, "\ttest %s, %s\n",
24554 reg(state, RHS(ins, 0), mask),
24555 reg(state, RHS(ins, 0), mask));
24558 static void print_op_branch(struct compile_state *state,
24559 struct triple *branch, FILE *fp)
24561 const char *bop = "j";
24562 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24563 if (branch->rhs != 0) {
24564 internal_error(state, branch, "jmp with condition?");
24569 struct triple *ptr;
24570 if (branch->rhs != 1) {
24571 internal_error(state, branch, "jmpcc without condition?");
24573 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24574 if ((RHS(branch, 0)->op != OP_CMP) &&
24575 (RHS(branch, 0)->op != OP_TEST)) {
24576 internal_error(state, branch, "bad branch test");
24578 #if DEBUG_ROMCC_WARNINGS
24579 #warning "FIXME I have observed instructions between the test and branch instructions"
24581 ptr = RHS(branch, 0);
24582 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24583 if (ptr->op != OP_COPY) {
24584 internal_error(state, branch, "branch does not follow test");
24587 switch(branch->op) {
24588 case OP_JMP_EQ: bop = "jz"; break;
24589 case OP_JMP_NOTEQ: bop = "jnz"; break;
24590 case OP_JMP_SLESS: bop = "jl"; break;
24591 case OP_JMP_ULESS: bop = "jb"; break;
24592 case OP_JMP_SMORE: bop = "jg"; break;
24593 case OP_JMP_UMORE: bop = "ja"; break;
24594 case OP_JMP_SLESSEQ: bop = "jle"; break;
24595 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24596 case OP_JMP_SMOREEQ: bop = "jge"; break;
24597 case OP_JMP_UMOREEQ: bop = "jae"; break;
24599 internal_error(state, branch, "Invalid branch op");
24605 if (branch->op == OP_CALL) {
24606 fprintf(fp, "\t/* call */\n");
24609 fprintf(fp, "\t%s L%s%lu\n",
24611 state->compiler->label_prefix,
24612 (unsigned long)(TARG(branch, 0)->u.cval));
24615 static void print_op_ret(struct compile_state *state,
24616 struct triple *branch, FILE *fp)
24618 fprintf(fp, "\tjmp *%s\n",
24619 reg(state, RHS(branch, 0), REGCM_GPR32));
24622 static void print_op_set(struct compile_state *state,
24623 struct triple *set, FILE *fp)
24625 const char *sop = "set";
24626 if (set->rhs != 1) {
24627 internal_error(state, set, "setcc without condition?");
24629 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24630 if ((RHS(set, 0)->op != OP_CMP) &&
24631 (RHS(set, 0)->op != OP_TEST)) {
24632 internal_error(state, set, "bad set test");
24634 if (RHS(set, 0)->next != set) {
24635 internal_error(state, set, "set does not follow test");
24638 case OP_SET_EQ: sop = "setz"; break;
24639 case OP_SET_NOTEQ: sop = "setnz"; break;
24640 case OP_SET_SLESS: sop = "setl"; break;
24641 case OP_SET_ULESS: sop = "setb"; break;
24642 case OP_SET_SMORE: sop = "setg"; break;
24643 case OP_SET_UMORE: sop = "seta"; break;
24644 case OP_SET_SLESSEQ: sop = "setle"; break;
24645 case OP_SET_ULESSEQ: sop = "setbe"; break;
24646 case OP_SET_SMOREEQ: sop = "setge"; break;
24647 case OP_SET_UMOREEQ: sop = "setae"; break;
24649 internal_error(state, set, "Invalid set op");
24652 fprintf(fp, "\t%s %s\n",
24653 sop, reg(state, set, REGCM_GPR8_LO));
24656 static void print_op_bit_scan(struct compile_state *state,
24657 struct triple *ins, FILE *fp)
24661 case OP_BSF: op = "bsf"; break;
24662 case OP_BSR: op = "bsr"; break;
24664 internal_error(state, ins, "unknown bit scan");
24674 reg(state, RHS(ins, 0), REGCM_GPR32),
24675 reg(state, ins, REGCM_GPR32),
24676 reg(state, ins, REGCM_GPR32));
24680 static void print_sdecl(struct compile_state *state,
24681 struct triple *ins, FILE *fp)
24683 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24684 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24685 fprintf(fp, "L%s%lu:\n",
24686 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24687 print_const(state, MISC(ins, 0), fp);
24688 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24692 static void print_instruction(struct compile_state *state,
24693 struct triple *ins, FILE *fp)
24695 /* Assumption: after I have exted the register allocator
24696 * everything is in a valid register.
24700 print_op_asm(state, ins, fp);
24702 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24703 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24704 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24705 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24706 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24707 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24708 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24709 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24710 case OP_POS: break;
24711 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24712 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24717 /* Don't generate anything here for constants */
24719 /* Don't generate anything for variable declarations. */
24721 case OP_UNKNOWNVAL:
24722 fprintf(fp, " /* unknown %s */\n",
24723 reg(state, ins, REGCM_ALL));
24726 print_sdecl(state, ins, fp);
24730 print_op_move(state, ins, fp);
24733 print_op_load(state, ins, fp);
24736 print_op_store(state, ins, fp);
24739 print_op_smul(state, ins, fp);
24741 case OP_CMP: print_op_cmp(state, ins, fp); break;
24742 case OP_TEST: print_op_test(state, ins, fp); break;
24744 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24745 case OP_JMP_SLESS: case OP_JMP_ULESS:
24746 case OP_JMP_SMORE: case OP_JMP_UMORE:
24747 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24748 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24750 print_op_branch(state, ins, fp);
24753 print_op_ret(state, ins, fp);
24755 case OP_SET_EQ: case OP_SET_NOTEQ:
24756 case OP_SET_SLESS: case OP_SET_ULESS:
24757 case OP_SET_SMORE: case OP_SET_UMORE:
24758 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24759 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24760 print_op_set(state, ins, fp);
24762 case OP_INB: case OP_INW: case OP_INL:
24763 print_op_in(state, ins, fp);
24765 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24766 print_op_out(state, ins, fp);
24770 print_op_bit_scan(state, ins, fp);
24773 after_lhs(state, ins);
24774 fprintf(fp, "\trdmsr\n");
24777 fprintf(fp, "\twrmsr\n");
24780 fprintf(fp, "\thlt\n");
24783 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24786 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24789 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24795 fprintf(fp, "L%s%lu:\n",
24796 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24799 /* Ignore adecls with no registers error otherwise */
24800 if (!noop_adecl(ins)) {
24801 internal_error(state, ins, "adecl remains?");
24804 /* Ignore OP_PIECE */
24807 /* Operations that should never get here */
24808 case OP_SDIV: case OP_UDIV:
24809 case OP_SMOD: case OP_UMOD:
24810 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24811 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24812 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24814 internal_error(state, ins, "unknown op: %d %s",
24815 ins->op, tops(ins->op));
24820 static void print_instructions(struct compile_state *state)
24822 struct triple *first, *ins;
24823 int print_location;
24824 struct occurance *last_occurance;
24826 int max_inline_depth;
24827 max_inline_depth = 0;
24828 print_location = 1;
24829 last_occurance = 0;
24830 fp = state->output;
24831 /* Masks for common sizes */
24832 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24833 fprintf(fp, ".balign 16\n");
24834 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24835 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24836 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24837 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24838 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24839 first = state->first;
24842 if (print_location &&
24843 last_occurance != ins->occurance) {
24844 if (!ins->occurance->parent) {
24845 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24846 ins->occurance->function?ins->occurance->function:"(null)",
24847 ins->occurance->filename?ins->occurance->filename:"(null)",
24848 ins->occurance->line,
24849 ins->occurance->col);
24852 struct occurance *ptr;
24854 fprintf(fp, "\t/*\n");
24856 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24858 fprintf(fp, "\t * %s,%s:%d.%d\n",
24864 fprintf(fp, "\t */\n");
24865 if (inline_depth > max_inline_depth) {
24866 max_inline_depth = inline_depth;
24869 if (last_occurance) {
24870 put_occurance(last_occurance);
24872 get_occurance(ins->occurance);
24873 last_occurance = ins->occurance;
24876 print_instruction(state, ins, fp);
24878 } while(ins != first);
24879 if (print_location) {
24880 fprintf(fp, "/* max inline depth %d */\n",
24885 static void generate_code(struct compile_state *state)
24887 generate_local_labels(state);
24888 print_instructions(state);
24892 static void print_preprocessed_tokens(struct compile_state *state)
24897 const char *filename;
24898 fp = state->output;
24902 struct file_state *file;
24904 const char *token_str;
24906 if (tok == TOK_EOF) {
24909 tk = eat(state, tok);
24911 tk->ident ? tk->ident->name :
24912 tk->str_len ? tk->val.str :
24915 file = state->file;
24916 while(file->macro && file->prev) {
24919 if (!file->macro &&
24920 ((file->line != line) || (file->basename != filename)))
24923 if ((file->basename == filename) &&
24924 (line < file->line)) {
24925 while(line < file->line) {
24931 fprintf(fp, "\n#line %d \"%s\"\n",
24932 file->line, file->basename);
24935 filename = file->basename;
24936 col = get_col(file) - strlen(token_str);
24937 for(i = 0; i < col; i++) {
24942 fprintf(fp, "%s ", token_str);
24944 if (state->compiler->debug & DEBUG_TOKENS) {
24945 loc(state->dbgout, state, 0);
24946 fprintf(state->dbgout, "%s <- `%s'\n",
24947 tokens[tok], token_str);
24952 static void compile(const char *filename,
24953 struct compiler_state *compiler, struct arch_state *arch)
24956 struct compile_state state;
24957 struct triple *ptr;
24958 struct filelist *includes = include_filelist;
24959 memset(&state, 0, sizeof(state));
24960 state.compiler = compiler;
24963 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24964 memset(&state.token[i], 0, sizeof(state.token[i]));
24965 state.token[i].tok = -1;
24967 /* Remember the output descriptors */
24968 state.errout = stderr;
24969 state.dbgout = stdout;
24970 /* Remember the output filename */
24971 state.output = fopen(state.compiler->ofilename, "w");
24972 if (!state.output) {
24973 error(&state, 0, "Cannot open output file %s\n",
24974 state.compiler->ofilename);
24976 /* Make certain a good cleanup happens */
24977 exit_state = &state;
24978 atexit(exit_cleanup);
24980 /* Prep the preprocessor */
24981 state.if_depth = 0;
24982 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24983 /* register the C keywords */
24984 register_keywords(&state);
24985 /* register the keywords the macro preprocessor knows */
24986 register_macro_keywords(&state);
24987 /* generate some builtin macros */
24988 register_builtin_macros(&state);
24989 /* Memorize where some special keywords are. */
24990 state.i_switch = lookup(&state, "switch", 6);
24991 state.i_case = lookup(&state, "case", 4);
24992 state.i_continue = lookup(&state, "continue", 8);
24993 state.i_break = lookup(&state, "break", 5);
24994 state.i_default = lookup(&state, "default", 7);
24995 state.i_return = lookup(&state, "return", 6);
24996 /* Memorize where predefined macros are. */
24997 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24998 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24999 state.i___LINE__ = lookup(&state, "__LINE__", 8);
25000 /* Memorize where predefined identifiers are. */
25001 state.i___func__ = lookup(&state, "__func__", 8);
25002 /* Memorize where some attribute keywords are. */
25003 state.i_noinline = lookup(&state, "noinline", 8);
25004 state.i_always_inline = lookup(&state, "always_inline", 13);
25005 state.i_noreturn = lookup(&state, "noreturn", 8);
25007 /* Process the command line macros */
25008 process_cmdline_macros(&state);
25010 /* Allocate beginning bounding labels for the function list */
25011 state.first = label(&state);
25012 state.first->id |= TRIPLE_FLAG_VOLATILE;
25013 use_triple(state.first, state.first);
25014 ptr = label(&state);
25015 ptr->id |= TRIPLE_FLAG_VOLATILE;
25016 use_triple(ptr, ptr);
25017 flatten(&state, state.first, ptr);
25019 /* Allocate a label for the pool of global variables */
25020 state.global_pool = label(&state);
25021 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
25022 flatten(&state, state.first, state.global_pool);
25024 /* Enter the globl definition scope */
25025 start_scope(&state);
25026 register_builtins(&state);
25028 compile_file(&state, filename, 1);
25031 compile_file(&state, includes->filename, 1);
25032 includes=includes->next;
25035 /* Stop if all we want is preprocessor output */
25036 if (state.compiler->flags & COMPILER_PP_ONLY) {
25037 print_preprocessed_tokens(&state);
25043 /* Exit the global definition scope */
25046 /* Now that basic compilation has happened
25047 * optimize the intermediate code
25051 generate_code(&state);
25052 if (state.compiler->debug) {
25053 fprintf(state.errout, "done\n");
25058 static void version(FILE *fp)
25060 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25063 static void usage(void)
25068 "\nUsage: romcc [options] <source>.c\n"
25069 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25071 "-o <output file name>\n"
25072 "-f<option> Specify a generic compiler option\n"
25073 "-m<option> Specify a arch dependent option\n"
25074 "-- Specify this is the last option\n"
25075 "\nGeneric compiler options:\n"
25077 compiler_usage(fp);
25079 "\nArchitecture compiler options:\n"
25087 static void arg_error(char *fmt, ...)
25090 va_start(args, fmt);
25091 vfprintf(stderr, fmt, args);
25097 int main(int argc, char **argv)
25099 const char *filename;
25100 struct compiler_state compiler;
25101 struct arch_state arch;
25105 /* I don't want any surprises */
25106 setlocale(LC_ALL, "C");
25108 init_compiler_state(&compiler);
25109 init_arch_state(&arch);
25113 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25114 compiler.ofilename = argv[2];
25118 else if (!all_opts && argv[1][0] == '-') {
25121 if (strcmp(argv[1], "--") == 0) {
25125 else if (strncmp(argv[1], "-E", 2) == 0) {
25126 result = compiler_encode_flag(&compiler, argv[1]);
25128 else if (strncmp(argv[1], "-O", 2) == 0) {
25129 result = compiler_encode_flag(&compiler, argv[1]);
25131 else if (strncmp(argv[1], "-I", 2) == 0) {
25132 result = compiler_encode_flag(&compiler, argv[1]);
25134 else if (strncmp(argv[1], "-D", 2) == 0) {
25135 result = compiler_encode_flag(&compiler, argv[1]);
25137 else if (strncmp(argv[1], "-U", 2) == 0) {
25138 result = compiler_encode_flag(&compiler, argv[1]);
25140 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25141 result = compiler_encode_flag(&compiler, argv[1]+2);
25143 else if (strncmp(argv[1], "-f", 2) == 0) {
25144 result = compiler_encode_flag(&compiler, argv[1]+2);
25146 else if (strncmp(argv[1], "-m", 2) == 0) {
25147 result = arch_encode_flag(&arch, argv[1]+2);
25149 else if (strncmp(argv[1], "-include", 10) == 0) {
25150 struct filelist *old_head = include_filelist;
25151 include_filelist = malloc(sizeof(struct filelist));
25152 if (!include_filelist) {
25153 die("Out of memory.\n");
25157 include_filelist->filename = argv[1];
25158 include_filelist->next = old_head;
25162 arg_error("Invalid option specified: %s\n",
25170 arg_error("Only one filename may be specified\n");
25172 filename = argv[1];
25178 arg_error("No filename specified\n");
25180 compile(filename, &compiler, &arch);