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 /* Additional hash entries for predefined macros */
1087 struct hash_entry *i_defined;
1088 struct hash_entry *i___VA_ARGS__;
1089 struct hash_entry *i___FILE__;
1090 struct hash_entry *i___LINE__;
1091 /* Additional hash entries for predefined identifiers */
1092 struct hash_entry *i___func__;
1093 /* Additional hash entries for attributes */
1094 struct hash_entry *i_noinline;
1095 struct hash_entry *i_always_inline;
1097 unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1099 int eat_depth, eat_targ;
1100 struct file_state *macro_file;
1101 struct triple *functions;
1102 struct triple *main_function;
1103 struct triple *first;
1104 struct triple *global_pool;
1105 struct basic_blocks bb;
1106 int functions_joined;
1109 /* visibility global/local */
1110 /* static/auto duration */
1111 /* typedef, register, inline */
1112 #define STOR_SHIFT 0
1113 #define STOR_MASK 0x001f
1115 #define STOR_GLOBAL 0x0001
1117 #define STOR_PERM 0x0002
1118 /* Definition locality */
1119 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1120 /* Storage specifiers */
1121 #define STOR_AUTO 0x0000
1122 #define STOR_STATIC 0x0002
1123 #define STOR_LOCAL 0x0003
1124 #define STOR_EXTERN 0x0007
1125 #define STOR_INLINE 0x0008
1126 #define STOR_REGISTER 0x0010
1127 #define STOR_TYPEDEF 0x0018
1129 #define QUAL_SHIFT 5
1130 #define QUAL_MASK 0x00e0
1131 #define QUAL_NONE 0x0000
1132 #define QUAL_CONST 0x0020
1133 #define QUAL_VOLATILE 0x0040
1134 #define QUAL_RESTRICT 0x0080
1136 #define TYPE_SHIFT 8
1137 #define TYPE_MASK 0x1f00
1138 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1139 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1140 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1141 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1142 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1143 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1144 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1145 #define TYPE_DEFAULT 0x0000
1146 #define TYPE_VOID 0x0100
1147 #define TYPE_CHAR 0x0200
1148 #define TYPE_UCHAR 0x0300
1149 #define TYPE_SHORT 0x0400
1150 #define TYPE_USHORT 0x0500
1151 #define TYPE_INT 0x0600
1152 #define TYPE_UINT 0x0700
1153 #define TYPE_LONG 0x0800
1154 #define TYPE_ULONG 0x0900
1155 #define TYPE_LLONG 0x0a00 /* long long */
1156 #define TYPE_ULLONG 0x0b00
1157 #define TYPE_FLOAT 0x0c00
1158 #define TYPE_DOUBLE 0x0d00
1159 #define TYPE_LDOUBLE 0x0e00 /* long double */
1161 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1162 #define TYPE_ENUM 0x1600
1163 #define TYPE_LIST 0x1700
1164 /* TYPE_LIST is a basic building block when defining enumerations
1165 * type->field_ident holds the name of this enumeration entry.
1166 * type->right holds the entry in the list.
1169 #define TYPE_STRUCT 0x1000
1171 * type->left holds the link list of TYPE_PRODUCT entries that
1172 * make up the structure.
1173 * type->elements hold the length of the linked list
1175 #define TYPE_UNION 0x1100
1177 * type->left holds the link list of TYPE_OVERLAP entries that
1178 * make up the union.
1179 * type->elements hold the length of the linked list
1181 #define TYPE_POINTER 0x1200
1182 /* For TYPE_POINTER:
1183 * type->left holds the type pointed to.
1185 #define TYPE_FUNCTION 0x1300
1186 /* For TYPE_FUNCTION:
1187 * type->left holds the return type.
1188 * type->right holds the type of the arguments
1189 * type->elements holds the count of the arguments
1191 #define TYPE_PRODUCT 0x1400
1192 /* TYPE_PRODUCT is a basic building block when defining structures
1193 * type->left holds the type that appears first in memory.
1194 * type->right holds the type that appears next in memory.
1196 #define TYPE_OVERLAP 0x1500
1197 /* TYPE_OVERLAP is a basic building block when defining unions
1198 * type->left and type->right holds to types that overlap
1199 * each other in memory.
1201 #define TYPE_ARRAY 0x1800
1202 /* TYPE_ARRAY is a basic building block when definitng arrays.
1203 * type->left holds the type we are an array of.
1204 * type->elements holds the number of elements.
1206 #define TYPE_TUPLE 0x1900
1207 /* TYPE_TUPLE is a basic building block when defining
1208 * positionally reference type conglomerations. (i.e. closures)
1209 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1210 * except it has no field names.
1211 * type->left holds the liked list of TYPE_PRODUCT entries that
1212 * make up the closure type.
1213 * type->elements hold the number of elements in the closure.
1215 #define TYPE_JOIN 0x1a00
1216 /* TYPE_JOIN is a basic building block when defining
1217 * positionally reference type conglomerations. (i.e. closures)
1218 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1219 * except it has no field names.
1220 * type->left holds the liked list of TYPE_OVERLAP entries that
1221 * make up the closure type.
1222 * type->elements hold the number of elements in the closure.
1224 #define TYPE_BITFIELD 0x1b00
1225 /* TYPE_BITFIED is the type of a bitfield.
1226 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1227 * type->elements holds the number of bits in the bitfield.
1229 #define TYPE_UNKNOWN 0x1c00
1230 /* TYPE_UNKNOWN is the type of an unknown value.
1231 * Used on unknown consts and other places where I don't know the type.
1234 #define ATTRIB_SHIFT 16
1235 #define ATTRIB_MASK 0xffff0000
1236 #define ATTRIB_NOINLINE 0x00010000
1237 #define ATTRIB_ALWAYS_INLINE 0x00020000
1239 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1243 struct type *left, *right;
1245 struct hash_entry *field_ident;
1246 struct hash_entry *type_ident;
1249 #define TEMPLATE_BITS 7
1250 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1251 #define MAX_REG_EQUIVS 16
1253 #define MAX_REGISTERS 75
1254 #define REGISTER_BITS 7
1255 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1258 #define REG_UNNEEDED 2
1259 #define REG_VIRT0 (MAX_REGISTERS + 0)
1260 #define REG_VIRT1 (MAX_REGISTERS + 1)
1261 #define REG_VIRT2 (MAX_REGISTERS + 2)
1262 #define REG_VIRT3 (MAX_REGISTERS + 3)
1263 #define REG_VIRT4 (MAX_REGISTERS + 4)
1264 #define REG_VIRT5 (MAX_REGISTERS + 5)
1265 #define REG_VIRT6 (MAX_REGISTERS + 6)
1266 #define REG_VIRT7 (MAX_REGISTERS + 7)
1267 #define REG_VIRT8 (MAX_REGISTERS + 8)
1268 #define REG_VIRT9 (MAX_REGISTERS + 9)
1270 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1271 #error "MAX_VIRT_REGISTERS to small"
1273 #if (MAX_REGC + REGISTER_BITS) >= 26
1274 #error "Too many id bits used"
1277 /* Provision for 8 register classes */
1279 #define REGC_SHIFT REGISTER_BITS
1280 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1281 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1282 #define ID_REG(ID) ((ID) & REG_MASK)
1283 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1284 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1285 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1286 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1287 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1289 #define ARCH_INPUT_REGS 4
1290 #define ARCH_OUTPUT_REGS 4
1292 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1293 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1294 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1295 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1296 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1297 static void arch_reg_equivs(
1298 struct compile_state *state, unsigned *equiv, int reg);
1299 static int arch_select_free_register(
1300 struct compile_state *state, char *used, int classes);
1301 static unsigned arch_regc_size(struct compile_state *state, int class);
1302 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1303 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1304 static const char *arch_reg_str(int reg);
1305 static struct reg_info arch_reg_constraint(
1306 struct compile_state *state, struct type *type, const char *constraint);
1307 static struct reg_info arch_reg_clobber(
1308 struct compile_state *state, const char *clobber);
1309 static struct reg_info arch_reg_lhs(struct compile_state *state,
1310 struct triple *ins, int index);
1311 static struct reg_info arch_reg_rhs(struct compile_state *state,
1312 struct triple *ins, int index);
1313 static int arch_reg_size(int reg);
1314 static struct triple *transform_to_arch_instruction(
1315 struct compile_state *state, struct triple *ins);
1316 static struct triple *flatten(
1317 struct compile_state *state, struct triple *first, struct triple *ptr);
1318 static void print_dominators(struct compile_state *state,
1319 FILE *fp, struct basic_blocks *bb);
1320 static void print_dominance_frontiers(struct compile_state *state,
1321 FILE *fp, struct basic_blocks *bb);
1325 #define DEBUG_ABORT_ON_ERROR 0x00000001
1326 #define DEBUG_BASIC_BLOCKS 0x00000002
1327 #define DEBUG_FDOMINATORS 0x00000004
1328 #define DEBUG_RDOMINATORS 0x00000008
1329 #define DEBUG_TRIPLES 0x00000010
1330 #define DEBUG_INTERFERENCE 0x00000020
1331 #define DEBUG_SCC_TRANSFORM 0x00000040
1332 #define DEBUG_SCC_TRANSFORM2 0x00000080
1333 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1334 #define DEBUG_INLINE 0x00000200
1335 #define DEBUG_RANGE_CONFLICTS 0x00000400
1336 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1337 #define DEBUG_COLOR_GRAPH 0x00001000
1338 #define DEBUG_COLOR_GRAPH2 0x00002000
1339 #define DEBUG_COALESCING 0x00004000
1340 #define DEBUG_COALESCING2 0x00008000
1341 #define DEBUG_VERIFICATION 0x00010000
1342 #define DEBUG_CALLS 0x00020000
1343 #define DEBUG_CALLS2 0x00040000
1344 #define DEBUG_TOKENS 0x80000000
1346 #define DEBUG_DEFAULT ( \
1347 DEBUG_ABORT_ON_ERROR | \
1348 DEBUG_BASIC_BLOCKS | \
1349 DEBUG_FDOMINATORS | \
1350 DEBUG_RDOMINATORS | \
1354 #define DEBUG_ALL ( \
1355 DEBUG_ABORT_ON_ERROR | \
1356 DEBUG_BASIC_BLOCKS | \
1357 DEBUG_FDOMINATORS | \
1358 DEBUG_RDOMINATORS | \
1360 DEBUG_INTERFERENCE | \
1361 DEBUG_SCC_TRANSFORM | \
1362 DEBUG_SCC_TRANSFORM2 | \
1363 DEBUG_REBUILD_SSA_FORM | \
1365 DEBUG_RANGE_CONFLICTS | \
1366 DEBUG_RANGE_CONFLICTS2 | \
1367 DEBUG_COLOR_GRAPH | \
1368 DEBUG_COLOR_GRAPH2 | \
1369 DEBUG_COALESCING | \
1370 DEBUG_COALESCING2 | \
1371 DEBUG_VERIFICATION | \
1377 #define COMPILER_INLINE_MASK 0x00000007
1378 #define COMPILER_INLINE_ALWAYS 0x00000000
1379 #define COMPILER_INLINE_NEVER 0x00000001
1380 #define COMPILER_INLINE_DEFAULTON 0x00000002
1381 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1382 #define COMPILER_INLINE_NOPENALTY 0x00000004
1383 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1384 #define COMPILER_SIMPLIFY 0x00000010
1385 #define COMPILER_SCC_TRANSFORM 0x00000020
1386 #define COMPILER_SIMPLIFY_OP 0x00000040
1387 #define COMPILER_SIMPLIFY_PHI 0x00000080
1388 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1389 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1390 #define COMPILER_SIMPLIFY_COPY 0x00000400
1391 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1392 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1393 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1394 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1395 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1397 #define COMPILER_TRIGRAPHS 0x40000000
1398 #define COMPILER_PP_ONLY 0x80000000
1400 #define COMPILER_DEFAULT_FLAGS ( \
1401 COMPILER_TRIGRAPHS | \
1402 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1403 COMPILER_INLINE_DEFAULTON | \
1404 COMPILER_SIMPLIFY_OP | \
1405 COMPILER_SIMPLIFY_PHI | \
1406 COMPILER_SIMPLIFY_LABEL | \
1407 COMPILER_SIMPLIFY_BRANCH | \
1408 COMPILER_SIMPLIFY_COPY | \
1409 COMPILER_SIMPLIFY_ARITH | \
1410 COMPILER_SIMPLIFY_SHIFT | \
1411 COMPILER_SIMPLIFY_BITWISE | \
1412 COMPILER_SIMPLIFY_LOGICAL | \
1413 COMPILER_SIMPLIFY_BITFIELD | \
1416 #define GLOBAL_SCOPE_DEPTH 1
1417 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1419 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1423 static void init_compiler_state(struct compiler_state *compiler)
1425 memset(compiler, 0, sizeof(*compiler));
1426 compiler->label_prefix = "";
1427 compiler->ofilename = "auto.inc";
1428 compiler->flags = COMPILER_DEFAULT_FLAGS;
1429 compiler->debug = 0;
1430 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1431 compiler->include_path_count = 1;
1432 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1433 compiler->define_count = 1;
1434 compiler->defines = xcmalloc(sizeof(char *), "defines");
1435 compiler->undef_count = 1;
1436 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1439 struct compiler_flag {
1444 struct compiler_arg {
1447 struct compiler_flag flags[16];
1450 static int set_flag(
1451 const struct compiler_flag *ptr, unsigned long *flags,
1452 int act, const char *flag)
1455 for(; ptr->name; ptr++) {
1456 if (strcmp(ptr->name, flag) == 0) {
1462 *flags &= ~(ptr->flag);
1464 *flags |= ptr->flag;
1471 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1476 val = strchr(arg, '=');
1480 for(; ptr->name; ptr++) {
1481 if (strncmp(ptr->name, arg, len) == 0) {
1486 *flags &= ~ptr->mask;
1487 result = set_flag(&ptr->flags[0], flags, 1, val);
1494 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1495 const char *prefix, const char *invert_prefix)
1497 for(;ptr->name; ptr++) {
1498 fprintf(fp, "%s%s\n", prefix, ptr->name);
1499 if (invert_prefix) {
1500 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1505 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1508 for(;ptr->name; ptr++) {
1509 const struct compiler_flag *flag;
1510 for(flag = &ptr->flags[0]; flag->name; flag++) {
1511 fprintf(fp, "%s%s=%s\n",
1512 prefix, ptr->name, flag->name);
1517 static int append_string(size_t *max, const char ***vec, const char *str,
1522 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1523 (*vec)[count -1] = 0;
1524 (*vec)[count -2] = str;
1528 static void arg_error(char *fmt, ...);
1529 static const char *identifier(const char *str, const char *end);
1531 static int append_include_path(struct compiler_state *compiler, const char *str)
1534 if (!exists(str, ".")) {
1535 arg_error("Nonexistent include path: `%s'\n",
1538 result = append_string(&compiler->include_path_count,
1539 &compiler->include_paths, str, "include_paths");
1543 static int append_define(struct compiler_state *compiler, const char *str)
1545 const char *end, *rest;
1548 end = strchr(str, '=');
1550 end = str + strlen(str);
1552 rest = identifier(str, end);
1554 int len = end - str - 1;
1555 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1558 result = append_string(&compiler->define_count,
1559 &compiler->defines, str, "defines");
1563 static int append_undef(struct compiler_state *compiler, const char *str)
1565 const char *end, *rest;
1568 end = str + strlen(str);
1569 rest = identifier(str, end);
1571 int len = end - str - 1;
1572 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1575 result = append_string(&compiler->undef_count,
1576 &compiler->undefs, str, "undefs");
1580 static const struct compiler_flag romcc_flags[] = {
1581 { "trigraphs", COMPILER_TRIGRAPHS },
1582 { "pp-only", COMPILER_PP_ONLY },
1583 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1584 { "simplify", COMPILER_SIMPLIFY },
1585 { "scc-transform", COMPILER_SCC_TRANSFORM },
1586 { "simplify-op", COMPILER_SIMPLIFY_OP },
1587 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1588 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1589 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1590 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1591 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1592 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1593 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1594 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1595 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1598 static const struct compiler_arg romcc_args[] = {
1599 { "inline-policy", COMPILER_INLINE_MASK,
1601 { "always", COMPILER_INLINE_ALWAYS, },
1602 { "never", COMPILER_INLINE_NEVER, },
1603 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1604 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1605 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1611 static const struct compiler_flag romcc_opt_flags[] = {
1612 { "-O", COMPILER_SIMPLIFY },
1613 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1614 { "-E", COMPILER_PP_ONLY },
1617 static const struct compiler_flag romcc_debug_flags[] = {
1618 { "all", DEBUG_ALL },
1619 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1620 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1621 { "fdominators", DEBUG_FDOMINATORS },
1622 { "rdominators", DEBUG_RDOMINATORS },
1623 { "triples", DEBUG_TRIPLES },
1624 { "interference", DEBUG_INTERFERENCE },
1625 { "scc-transform", DEBUG_SCC_TRANSFORM },
1626 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1627 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1628 { "inline", DEBUG_INLINE },
1629 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1630 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1631 { "color-graph", DEBUG_COLOR_GRAPH },
1632 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1633 { "coalescing", DEBUG_COALESCING },
1634 { "coalescing2", DEBUG_COALESCING2 },
1635 { "verification", DEBUG_VERIFICATION },
1636 { "calls", DEBUG_CALLS },
1637 { "calls2", DEBUG_CALLS2 },
1638 { "tokens", DEBUG_TOKENS },
1642 static int compiler_encode_flag(
1643 struct compiler_state *compiler, const char *flag)
1650 if (strncmp(flag, "no-", 3) == 0) {
1654 if (strncmp(flag, "-O", 2) == 0) {
1655 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1657 else if (strncmp(flag, "-E", 2) == 0) {
1658 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1660 else if (strncmp(flag, "-I", 2) == 0) {
1661 result = append_include_path(compiler, flag + 2);
1663 else if (strncmp(flag, "-D", 2) == 0) {
1664 result = append_define(compiler, flag + 2);
1666 else if (strncmp(flag, "-U", 2) == 0) {
1667 result = append_undef(compiler, flag + 2);
1669 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1671 compiler->label_prefix = flag + 13;
1673 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1674 unsigned long max_passes;
1676 max_passes = strtoul(flag + 22, &end, 10);
1677 if (end[0] == '\0') {
1679 compiler->max_allocation_passes = max_passes;
1682 else if (act && strcmp(flag, "debug") == 0) {
1684 compiler->debug |= DEBUG_DEFAULT;
1686 else if (strncmp(flag, "debug-", 6) == 0) {
1688 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1691 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1693 result = set_arg(romcc_args, &compiler->flags, flag);
1699 static void compiler_usage(FILE *fp)
1701 flag_usage(fp, romcc_opt_flags, "", 0);
1702 flag_usage(fp, romcc_flags, "-f", "-fno-");
1703 arg_usage(fp, romcc_args, "-f");
1704 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1705 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1706 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1707 fprintf(fp, "-I<include path>\n");
1708 fprintf(fp, "-D<macro>[=defn]\n");
1709 fprintf(fp, "-U<macro>\n");
1712 static void do_cleanup(struct compile_state *state)
1714 if (state->output) {
1715 fclose(state->output);
1716 unlink(state->compiler->ofilename);
1719 if (state->dbgout) {
1720 fflush(state->dbgout);
1722 if (state->errout) {
1723 fflush(state->errout);
1727 static struct compile_state *exit_state;
1728 static void exit_cleanup(void)
1731 do_cleanup(exit_state);
1735 static int get_col(struct file_state *file)
1738 const char *ptr, *end;
1739 ptr = file->line_start;
1741 for(col = 0; ptr < end; ptr++) {
1746 col = (col & ~7) + 8;
1752 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1755 if (triple && triple->occurance) {
1756 struct occurance *spot;
1757 for(spot = triple->occurance; spot; spot = spot->parent) {
1758 fprintf(fp, "%s:%d.%d: ",
1759 spot->filename, spot->line, spot->col);
1766 col = get_col(state->file);
1767 fprintf(fp, "%s:%d.%d: ",
1768 state->file->report_name, state->file->report_line, col);
1771 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr,
1772 const char *fmt, ...)
1774 FILE *fp = state->errout;
1776 va_start(args, fmt);
1777 loc(fp, state, ptr);
1780 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1782 fprintf(fp, "Internal compiler error: ");
1783 vfprintf(fp, fmt, args);
1791 static void internal_warning(struct compile_state *state, struct triple *ptr,
1792 const char *fmt, ...)
1794 FILE *fp = state->errout;
1796 va_start(args, fmt);
1797 loc(fp, state, ptr);
1799 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1801 fprintf(fp, "Internal compiler warning: ");
1802 vfprintf(fp, fmt, args);
1809 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr,
1810 const char *fmt, ...)
1812 FILE *fp = state->errout;
1814 va_start(args, fmt);
1815 loc(fp, state, ptr);
1817 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1818 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1820 vfprintf(fp, fmt, args);
1824 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1830 static void warning(struct compile_state *state, struct triple *ptr,
1831 const char *fmt, ...)
1833 FILE *fp = state->errout;
1835 va_start(args, fmt);
1836 loc(fp, state, ptr);
1837 fprintf(fp, "warning: ");
1838 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1839 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1841 vfprintf(fp, fmt, args);
1846 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1848 static void valid_op(struct compile_state *state, int op)
1850 char *fmt = "invalid op: %d";
1852 internal_error(state, 0, fmt, op);
1855 internal_error(state, 0, fmt, op);
1859 static void valid_ins(struct compile_state *state, struct triple *ptr)
1861 valid_op(state, ptr->op);
1864 #if DEBUG_ROMCC_WARNING
1865 static void valid_param_count(struct compile_state *state, struct triple *ins)
1867 int lhs, rhs, misc, targ;
1868 valid_ins(state, ins);
1869 lhs = table_ops[ins->op].lhs;
1870 rhs = table_ops[ins->op].rhs;
1871 misc = table_ops[ins->op].misc;
1872 targ = table_ops[ins->op].targ;
1874 if ((lhs >= 0) && (ins->lhs != lhs)) {
1875 internal_error(state, ins, "Bad lhs count");
1877 if ((rhs >= 0) && (ins->rhs != rhs)) {
1878 internal_error(state, ins, "Bad rhs count");
1880 if ((misc >= 0) && (ins->misc != misc)) {
1881 internal_error(state, ins, "Bad misc count");
1883 if ((targ >= 0) && (ins->targ != targ)) {
1884 internal_error(state, ins, "Bad targ count");
1889 static struct type void_type;
1890 static struct type unknown_type;
1891 static void use_triple(struct triple *used, struct triple *user)
1893 struct triple_set **ptr, *new;
1900 if ((*ptr)->member == user) {
1903 ptr = &(*ptr)->next;
1905 /* Append new to the head of the list,
1906 * copy_func and rename_block_variables
1909 new = xcmalloc(sizeof(*new), "triple_set");
1911 new->next = used->use;
1915 static void unuse_triple(struct triple *used, struct triple *unuser)
1917 struct triple_set *use, **ptr;
1924 if (use->member == unuser) {
1934 static void put_occurance(struct occurance *occurance)
1937 occurance->count -= 1;
1938 if (occurance->count <= 0) {
1939 if (occurance->parent) {
1940 put_occurance(occurance->parent);
1947 static void get_occurance(struct occurance *occurance)
1950 occurance->count += 1;
1955 static struct occurance *new_occurance(struct compile_state *state)
1957 struct occurance *result, *last;
1958 const char *filename;
1959 const char *function;
1967 filename = state->file->report_name;
1968 line = state->file->report_line;
1969 col = get_col(state->file);
1971 if (state->function) {
1972 function = state->function;
1974 last = state->last_occurance;
1976 (last->col == col) &&
1977 (last->line == line) &&
1978 (last->function == function) &&
1979 ((last->filename == filename) ||
1980 (strcmp(last->filename, filename) == 0)))
1982 get_occurance(last);
1986 state->last_occurance = 0;
1987 put_occurance(last);
1989 result = xmalloc(sizeof(*result), "occurance");
1991 result->filename = filename;
1992 result->function = function;
1993 result->line = line;
1996 state->last_occurance = result;
2000 static struct occurance *inline_occurance(struct compile_state *state,
2001 struct occurance *base, struct occurance *top)
2003 struct occurance *result, *last;
2005 internal_error(state, 0, "inlining an already inlined function?");
2007 /* If I have a null base treat it that way */
2008 if ((base->parent == 0) &&
2010 (base->line == 0) &&
2011 (base->function[0] == '\0') &&
2012 (base->filename[0] == '\0')) {
2015 /* See if I can reuse the last occurance I had */
2016 last = state->last_occurance;
2018 (last->parent == base) &&
2019 (last->col == top->col) &&
2020 (last->line == top->line) &&
2021 (last->function == top->function) &&
2022 (last->filename == top->filename)) {
2023 get_occurance(last);
2026 /* I can't reuse the last occurance so free it */
2028 state->last_occurance = 0;
2029 put_occurance(last);
2031 /* Generate a new occurance structure */
2032 get_occurance(base);
2033 result = xmalloc(sizeof(*result), "occurance");
2035 result->filename = top->filename;
2036 result->function = top->function;
2037 result->line = top->line;
2038 result->col = top->col;
2039 result->parent = base;
2040 state->last_occurance = result;
2044 static struct occurance dummy_occurance = {
2046 .filename = __FILE__,
2053 /* The undef triple is used as a place holder when we are removing pointers
2054 * from a triple. Having allows certain sanity checks to pass even
2055 * when the original triple that was pointed to is gone.
2057 static struct triple unknown_triple = {
2058 .next = &unknown_triple,
2059 .prev = &unknown_triple,
2061 .op = OP_UNKNOWNVAL,
2066 .type = &unknown_type,
2067 .id = -1, /* An invalid id */
2068 .u = { .cval = 0, },
2069 .occurance = &dummy_occurance,
2070 .param = { [0] = 0, [1] = 0, },
2074 static size_t registers_of(struct compile_state *state, struct type *type);
2076 static struct triple *alloc_triple(struct compile_state *state,
2077 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2078 struct occurance *occurance)
2080 size_t size, extra_count, min_count;
2081 int lhs, rhs, misc, targ;
2082 struct triple *ret, dummy;
2084 dummy.occurance = occurance;
2085 valid_op(state, op);
2086 lhs = table_ops[op].lhs;
2087 rhs = table_ops[op].rhs;
2088 misc = table_ops[op].misc;
2089 targ = table_ops[op].targ;
2099 lhs = registers_of(state, type);
2102 lhs = registers_of(state, type);
2109 if ((rhs < 0) || (rhs > MAX_RHS)) {
2110 internal_error(state, &dummy, "bad rhs count %d", rhs);
2112 if ((lhs < 0) || (lhs > MAX_LHS)) {
2113 internal_error(state, &dummy, "bad lhs count %d", lhs);
2115 if ((misc < 0) || (misc > MAX_MISC)) {
2116 internal_error(state, &dummy, "bad misc count %d", misc);
2118 if ((targ < 0) || (targ > MAX_TARG)) {
2119 internal_error(state, &dummy, "bad targs count %d", targ);
2122 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2123 extra_count = lhs + rhs + misc + targ;
2124 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2126 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2127 ret = xcmalloc(size, "tripple");
2136 ret->occurance = occurance;
2137 /* A simple sanity check */
2138 if ((ret->op != op) ||
2139 (ret->lhs != lhs) ||
2140 (ret->rhs != rhs) ||
2141 (ret->misc != misc) ||
2142 (ret->targ != targ) ||
2143 (ret->type != type) ||
2144 (ret->next != ret) ||
2145 (ret->prev != ret) ||
2146 (ret->occurance != occurance)) {
2147 internal_error(state, ret, "huh?");
2152 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2155 int src_lhs, src_rhs, src_size;
2158 src_size = TRIPLE_SIZE(src);
2159 get_occurance(src->occurance);
2160 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2162 memcpy(dup, src, sizeof(*src));
2163 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2167 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2169 struct triple *copy;
2170 copy = dup_triple(state, src);
2172 copy->next = copy->prev = copy;
2176 static struct triple *new_triple(struct compile_state *state,
2177 int op, struct type *type, int lhs, int rhs)
2180 struct occurance *occurance;
2181 occurance = new_occurance(state);
2182 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2186 static struct triple *build_triple(struct compile_state *state,
2187 int op, struct type *type, struct triple *left, struct triple *right,
2188 struct occurance *occurance)
2192 ret = alloc_triple(state, op, type, -1, -1, occurance);
2193 count = TRIPLE_SIZE(ret);
2195 ret->param[0] = left;
2198 ret->param[1] = right;
2203 static struct triple *triple(struct compile_state *state,
2204 int op, struct type *type, struct triple *left, struct triple *right)
2208 ret = new_triple(state, op, type, -1, -1);
2209 count = TRIPLE_SIZE(ret);
2211 ret->param[0] = left;
2214 ret->param[1] = right;
2219 static struct triple *branch(struct compile_state *state,
2220 struct triple *targ, struct triple *test)
2224 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2227 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2229 TARG(ret, 0) = targ;
2230 /* record the branch target was used */
2231 if (!targ || (targ->op != OP_LABEL)) {
2232 internal_error(state, 0, "branch not to label");
2237 static int triple_is_label(struct compile_state *state, struct triple *ins);
2238 static int triple_is_call(struct compile_state *state, struct triple *ins);
2239 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2240 static void insert_triple(struct compile_state *state,
2241 struct triple *first, struct triple *ptr)
2244 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2245 internal_error(state, ptr, "expression already used");
2248 ptr->prev = first->prev;
2249 ptr->prev->next = ptr;
2250 ptr->next->prev = ptr;
2252 if (triple_is_cbranch(state, ptr->prev) ||
2253 triple_is_call(state, ptr->prev)) {
2254 unuse_triple(first, ptr->prev);
2255 use_triple(ptr, ptr->prev);
2260 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2262 /* This function is used to determine if u.block
2263 * is utilized to store the current block number.
2266 valid_ins(state, ins);
2267 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2268 return stores_block;
2271 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2272 static struct block *block_of_triple(struct compile_state *state,
2275 struct triple *first;
2276 if (!ins || ins == &unknown_triple) {
2279 first = state->first;
2280 while(ins != first && !triple_is_branch(state, ins->prev) &&
2281 !triple_stores_block(state, ins))
2283 if (ins == ins->prev) {
2284 internal_error(state, ins, "ins == ins->prev?");
2288 return triple_stores_block(state, ins)? ins->u.block: 0;
2291 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2292 static struct triple *pre_triple(struct compile_state *state,
2293 struct triple *base,
2294 int op, struct type *type, struct triple *left, struct triple *right)
2296 struct block *block;
2299 /* If I am an OP_PIECE jump to the real instruction */
2300 if (base->op == OP_PIECE) {
2301 base = MISC(base, 0);
2303 block = block_of_triple(state, base);
2304 get_occurance(base->occurance);
2305 ret = build_triple(state, op, type, left, right, base->occurance);
2306 generate_lhs_pieces(state, ret);
2307 if (triple_stores_block(state, ret)) {
2308 ret->u.block = block;
2310 insert_triple(state, base, ret);
2311 for(i = 0; i < ret->lhs; i++) {
2312 struct triple *piece;
2313 piece = LHS(ret, i);
2314 insert_triple(state, base, piece);
2315 use_triple(ret, piece);
2316 use_triple(piece, ret);
2318 if (block && (block->first == base)) {
2324 static struct triple *post_triple(struct compile_state *state,
2325 struct triple *base,
2326 int op, struct type *type, struct triple *left, struct triple *right)
2328 struct block *block;
2329 struct triple *ret, *next;
2331 /* If I am an OP_PIECE jump to the real instruction */
2332 if (base->op == OP_PIECE) {
2333 base = MISC(base, 0);
2335 /* If I have a left hand side skip over it */
2338 base = LHS(base, zlhs - 1);
2341 block = block_of_triple(state, base);
2342 get_occurance(base->occurance);
2343 ret = build_triple(state, op, type, left, right, base->occurance);
2344 generate_lhs_pieces(state, ret);
2345 if (triple_stores_block(state, ret)) {
2346 ret->u.block = block;
2349 insert_triple(state, next, ret);
2351 for(i = 0; i < zlhs; i++) {
2352 struct triple *piece;
2353 piece = LHS(ret, i);
2354 insert_triple(state, next, piece);
2355 use_triple(ret, piece);
2356 use_triple(piece, ret);
2358 if (block && (block->last == base)) {
2361 block->last = LHS(ret, zlhs - 1);
2367 static struct type *reg_type(
2368 struct compile_state *state, struct type *type, int reg);
2370 static void generate_lhs_piece(
2371 struct compile_state *state, struct triple *ins, int index)
2373 struct type *piece_type;
2374 struct triple *piece;
2375 get_occurance(ins->occurance);
2376 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2378 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2379 piece_type = piece_type->left;
2383 static void name_of(FILE *fp, struct type *type);
2384 FILE * fp = state->errout;
2385 fprintf(fp, "piece_type(%d): ", index);
2386 name_of(fp, piece_type);
2390 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2391 piece->u.cval = index;
2392 LHS(ins, piece->u.cval) = piece;
2393 MISC(piece, 0) = ins;
2396 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2400 for(i = 0; i < zlhs; i++) {
2401 generate_lhs_piece(state, ins, i);
2405 static struct triple *label(struct compile_state *state)
2407 /* Labels don't get a type */
2408 struct triple *result;
2409 result = triple(state, OP_LABEL, &void_type, 0, 0);
2413 static struct triple *mkprog(struct compile_state *state, ...)
2415 struct triple *prog, *head, *arg;
2419 head = label(state);
2420 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2421 RHS(prog, 0) = head;
2422 va_start(args, state);
2424 while((arg = va_arg(args, struct triple *)) != 0) {
2426 internal_error(state, 0, "too many arguments to mkprog");
2428 flatten(state, head, arg);
2431 prog->type = head->prev->type;
2434 static void name_of(FILE *fp, struct type *type);
2435 static void display_triple(FILE *fp, struct triple *ins)
2437 struct occurance *ptr;
2439 char pre, post, vol;
2440 pre = post = vol = ' ';
2442 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2445 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2448 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2451 reg = arch_reg_str(ID_REG(ins->id));
2454 fprintf(fp, "(%p) <nothing> ", ins);
2456 else if (ins->op == OP_INTCONST) {
2457 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2458 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2459 (unsigned long)(ins->u.cval));
2461 else if (ins->op == OP_ADDRCONST) {
2462 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2463 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2464 MISC(ins, 0), (unsigned long)(ins->u.cval));
2466 else if (ins->op == OP_INDEX) {
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 RHS(ins, 0), (unsigned long)(ins->u.cval));
2471 else if (ins->op == OP_PIECE) {
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 MISC(ins, 0), (unsigned long)(ins->u.cval));
2478 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2479 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2480 if (table_ops[ins->op].flags & BITFIELD) {
2481 fprintf(fp, " <%2d-%2d:%2d>",
2482 ins->u.bitfield.offset,
2483 ins->u.bitfield.offset + ins->u.bitfield.size,
2484 ins->u.bitfield.size);
2486 count = TRIPLE_SIZE(ins);
2487 for(i = 0; i < count; i++) {
2488 fprintf(fp, " %-10p", ins->param[i]);
2495 struct triple_set *user;
2496 #if DEBUG_DISPLAY_TYPES
2498 name_of(fp, ins->type);
2501 #if DEBUG_DISPLAY_USES
2503 for(user = ins->use; user; user = user->next) {
2504 fprintf(fp, " %-10p", user->member);
2509 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2510 fprintf(fp, " %s,%s:%d.%d",
2516 if (ins->op == OP_ASM) {
2517 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2524 static int equiv_types(struct type *left, struct type *right);
2525 static void display_triple_changes(
2526 FILE *fp, const struct triple *new, const struct triple *orig)
2529 int new_count, orig_count;
2530 new_count = TRIPLE_SIZE(new);
2531 orig_count = TRIPLE_SIZE(orig);
2532 if ((new->op != orig->op) ||
2533 (new_count != orig_count) ||
2534 (memcmp(orig->param, new->param,
2535 orig_count * sizeof(orig->param[0])) != 0) ||
2536 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2538 struct occurance *ptr;
2539 int i, min_count, indent;
2540 fprintf(fp, "(%p %p)", new, orig);
2541 if (orig->op == new->op) {
2542 fprintf(fp, " %-11s", tops(orig->op));
2544 fprintf(fp, " [%-10s %-10s]",
2545 tops(new->op), tops(orig->op));
2547 min_count = new_count;
2548 if (min_count > orig_count) {
2549 min_count = orig_count;
2551 for(indent = i = 0; i < min_count; i++) {
2552 if (orig->param[i] == new->param[i]) {
2553 fprintf(fp, " %-11p",
2557 fprintf(fp, " [%-10p %-10p]",
2563 for(; i < orig_count; i++) {
2564 fprintf(fp, " [%-9p]", orig->param[i]);
2567 for(; i < new_count; i++) {
2568 fprintf(fp, " [%-9p]", new->param[i]);
2571 if ((new->op == OP_INTCONST)||
2572 (new->op == OP_ADDRCONST)) {
2573 fprintf(fp, " <0x%08lx>",
2574 (unsigned long)(new->u.cval));
2577 for(;indent < 36; indent++) {
2581 #if DEBUG_DISPLAY_TYPES
2583 name_of(fp, new->type);
2584 if (!equiv_types(new->type, orig->type)) {
2585 fprintf(fp, " -- ");
2586 name_of(fp, orig->type);
2592 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2593 fprintf(fp, " %s,%s:%d.%d",
2605 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2607 /* Does the triple have no side effects.
2608 * I.e. Rexecuting the triple with the same arguments
2609 * gives the same value.
2612 valid_ins(state, ins);
2613 pure = PURE_BITS(table_ops[ins->op].flags);
2614 if ((pure != PURE) && (pure != IMPURE)) {
2615 internal_error(state, 0, "Purity of %s not known",
2618 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2621 static int triple_is_branch_type(struct compile_state *state,
2622 struct triple *ins, unsigned type)
2624 /* Is this one of the passed branch types? */
2625 valid_ins(state, ins);
2626 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2629 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2631 /* Is this triple a branch instruction? */
2632 valid_ins(state, ins);
2633 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2636 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2638 /* Is this triple a conditional branch instruction? */
2639 return triple_is_branch_type(state, ins, CBRANCH);
2642 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2644 /* Is this triple a unconditional branch instruction? */
2646 valid_ins(state, ins);
2647 type = BRANCH_BITS(table_ops[ins->op].flags);
2648 return (type != 0) && (type != CBRANCH);
2651 static int triple_is_call(struct compile_state *state, struct triple *ins)
2653 /* Is this triple a call instruction? */
2654 return triple_is_branch_type(state, ins, CALLBRANCH);
2657 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2659 /* Is this triple a return instruction? */
2660 return triple_is_branch_type(state, ins, RETBRANCH);
2663 #if DEBUG_ROMCC_WARNING
2664 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2666 /* Is this triple an unconditional branch and not a call or a
2668 return triple_is_branch_type(state, ins, UBRANCH);
2672 static int triple_is_end(struct compile_state *state, struct triple *ins)
2674 return triple_is_branch_type(state, ins, ENDBRANCH);
2677 static int triple_is_label(struct compile_state *state, struct triple *ins)
2679 valid_ins(state, ins);
2680 return (ins->op == OP_LABEL);
2683 static struct triple *triple_to_block_start(
2684 struct compile_state *state, struct triple *start)
2686 while(!triple_is_branch(state, start->prev) &&
2687 (!triple_is_label(state, start) || !start->use)) {
2688 start = start->prev;
2693 static int triple_is_def(struct compile_state *state, struct triple *ins)
2695 /* This function is used to determine which triples need
2699 valid_ins(state, ins);
2700 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2701 if (ins->lhs >= 1) {
2707 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2710 valid_ins(state, ins);
2711 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2712 return is_structural;
2715 static int triple_is_part(struct compile_state *state, struct triple *ins)
2718 valid_ins(state, ins);
2719 is_part = (table_ops[ins->op].flags & PART) == PART;
2723 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2725 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2728 static struct triple **triple_iter(struct compile_state *state,
2729 size_t count, struct triple **vector,
2730 struct triple *ins, struct triple **last)
2732 struct triple **ret;
2738 else if ((last >= vector) && (last < (vector + count - 1))) {
2746 static struct triple **triple_lhs(struct compile_state *state,
2747 struct triple *ins, struct triple **last)
2749 return triple_iter(state, ins->lhs, &LHS(ins,0),
2753 static struct triple **triple_rhs(struct compile_state *state,
2754 struct triple *ins, struct triple **last)
2756 return triple_iter(state, ins->rhs, &RHS(ins,0),
2760 static struct triple **triple_misc(struct compile_state *state,
2761 struct triple *ins, struct triple **last)
2763 return triple_iter(state, ins->misc, &MISC(ins,0),
2767 static struct triple **do_triple_targ(struct compile_state *state,
2768 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2771 struct triple **ret, **vector;
2776 if (triple_is_cbranch(state, ins)) {
2779 if (!call_edges && triple_is_call(state, ins)) {
2782 if (next_edges && triple_is_call(state, ins)) {
2785 vector = &TARG(ins, 0);
2786 if (!ret && next_is_targ) {
2789 } else if (last == &ins->next) {
2793 if (!ret && count) {
2797 else if ((last >= vector) && (last < (vector + count - 1))) {
2800 else if (last == vector + count - 1) {
2804 if (!ret && triple_is_ret(state, ins) && call_edges) {
2805 struct triple_set *use;
2806 for(use = ins->use; use; use = use->next) {
2807 if (!triple_is_call(state, use->member)) {
2811 ret = &use->member->next;
2814 else if (last == &use->member->next) {
2822 static struct triple **triple_targ(struct compile_state *state,
2823 struct triple *ins, struct triple **last)
2825 return do_triple_targ(state, ins, last, 1, 1);
2828 static struct triple **triple_edge_targ(struct compile_state *state,
2829 struct triple *ins, struct triple **last)
2831 return do_triple_targ(state, ins, last,
2832 state->functions_joined, !state->functions_joined);
2835 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2837 struct triple *next;
2841 for(i = 0; i < lhs; i++) {
2842 struct triple *piece;
2843 piece = LHS(ins, i);
2844 if (next != piece) {
2845 internal_error(state, ins, "malformed lhs on %s",
2848 if (next->op != OP_PIECE) {
2849 internal_error(state, ins, "bad lhs op %s at %d on %s",
2850 tops(next->op), i, tops(ins->op));
2852 if (next->u.cval != i) {
2853 internal_error(state, ins, "bad u.cval of %d %d expected",
2861 /* Function piece accessor functions */
2862 static struct triple *do_farg(struct compile_state *state,
2863 struct triple *func, unsigned index)
2866 struct triple *first, *arg;
2870 if((index < 0) || (index >= (ftype->elements + 2))) {
2871 internal_error(state, func, "bad argument index: %d", index);
2873 first = RHS(func, 0);
2875 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2878 if (arg->op != OP_ADECL) {
2879 internal_error(state, 0, "arg not adecl?");
2883 static struct triple *fresult(struct compile_state *state, struct triple *func)
2885 return do_farg(state, func, 0);
2887 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2889 return do_farg(state, func, 1);
2891 static struct triple *farg(struct compile_state *state,
2892 struct triple *func, unsigned index)
2894 return do_farg(state, func, index + 2);
2898 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2900 struct triple *first, *ins;
2901 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2902 first = ins = RHS(func, 0);
2904 if (triple_is_label(state, ins) && ins->use) {
2905 fprintf(fp, "%p:\n", ins);
2907 display_triple(fp, ins);
2909 if (triple_is_branch(state, ins)) {
2912 if (ins->next->prev != ins) {
2913 internal_error(state, ins->next, "bad prev");
2916 } while(ins != first);
2919 static void verify_use(struct compile_state *state,
2920 struct triple *user, struct triple *used)
2923 size = TRIPLE_SIZE(user);
2924 for(i = 0; i < size; i++) {
2925 if (user->param[i] == used) {
2929 if (triple_is_branch(state, user)) {
2930 if (user->next == used) {
2935 internal_error(state, user, "%s(%p) does not use %s(%p)",
2936 tops(user->op), user, tops(used->op), used);
2940 static int find_rhs_use(struct compile_state *state,
2941 struct triple *user, struct triple *used)
2943 struct triple **param;
2945 verify_use(state, user, used);
2947 #if DEBUG_ROMCC_WARNINGS
2948 #warning "AUDIT ME ->rhs"
2951 param = &RHS(user, 0);
2952 for(i = 0; i < size; i++) {
2953 if (param[i] == used) {
2960 static void free_triple(struct compile_state *state, struct triple *ptr)
2963 size = sizeof(*ptr) - sizeof(ptr->param) +
2964 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2965 ptr->prev->next = ptr->next;
2966 ptr->next->prev = ptr->prev;
2968 internal_error(state, ptr, "ptr->use != 0");
2970 put_occurance(ptr->occurance);
2971 memset(ptr, -1, size);
2975 static void release_triple(struct compile_state *state, struct triple *ptr)
2977 struct triple_set *set, *next;
2978 struct triple **expr;
2979 struct block *block;
2980 if (ptr == &unknown_triple) {
2983 valid_ins(state, ptr);
2984 /* Make certain the we are not the first or last element of a block */
2985 block = block_of_triple(state, ptr);
2987 if ((block->last == ptr) && (block->first == ptr)) {
2988 block->last = block->first = 0;
2990 else if (block->last == ptr) {
2991 block->last = ptr->prev;
2993 else if (block->first == ptr) {
2994 block->first = ptr->next;
2997 /* Remove ptr from use chains where it is the user */
2998 expr = triple_rhs(state, ptr, 0);
2999 for(; expr; expr = triple_rhs(state, ptr, expr)) {
3001 unuse_triple(*expr, ptr);
3004 expr = triple_lhs(state, ptr, 0);
3005 for(; expr; expr = triple_lhs(state, ptr, expr)) {
3007 unuse_triple(*expr, ptr);
3010 expr = triple_misc(state, ptr, 0);
3011 for(; expr; expr = triple_misc(state, ptr, expr)) {
3013 unuse_triple(*expr, ptr);
3016 expr = triple_targ(state, ptr, 0);
3017 for(; expr; expr = triple_targ(state, ptr, expr)) {
3019 unuse_triple(*expr, ptr);
3022 /* Reomve ptr from use chains where it is used */
3023 for(set = ptr->use; set; set = next) {
3025 valid_ins(state, set->member);
3026 expr = triple_rhs(state, set->member, 0);
3027 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3029 *expr = &unknown_triple;
3032 expr = triple_lhs(state, set->member, 0);
3033 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3035 *expr = &unknown_triple;
3038 expr = triple_misc(state, set->member, 0);
3039 for(; expr; expr = triple_misc(state, set->member, expr)) {
3041 *expr = &unknown_triple;
3044 expr = triple_targ(state, set->member, 0);
3045 for(; expr; expr = triple_targ(state, set->member, expr)) {
3047 *expr = &unknown_triple;
3050 unuse_triple(ptr, set->member);
3052 free_triple(state, ptr);
3055 static void print_triples(struct compile_state *state);
3056 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3058 #define TOK_UNKNOWN 0
3061 #define TOK_LBRACE 3
3062 #define TOK_RBRACE 4
3066 #define TOK_LBRACKET 8
3067 #define TOK_RBRACKET 9
3068 #define TOK_LPAREN 10
3069 #define TOK_RPAREN 11
3074 #define TOK_TIMESEQ 16
3075 #define TOK_DIVEQ 17
3076 #define TOK_MODEQ 18
3077 #define TOK_PLUSEQ 19
3078 #define TOK_MINUSEQ 20
3081 #define TOK_ANDEQ 23
3082 #define TOK_XOREQ 24
3085 #define TOK_NOTEQ 27
3086 #define TOK_QUEST 28
3087 #define TOK_LOGOR 29
3088 #define TOK_LOGAND 30
3092 #define TOK_LESSEQ 34
3093 #define TOK_MOREEQ 35
3097 #define TOK_MINUS 39
3100 #define TOK_PLUSPLUS 42
3101 #define TOK_MINUSMINUS 43
3103 #define TOK_ARROW 45
3105 #define TOK_TILDE 47
3106 #define TOK_LIT_STRING 48
3107 #define TOK_LIT_CHAR 49
3108 #define TOK_LIT_INT 50
3109 #define TOK_LIT_FLOAT 51
3110 #define TOK_MACRO 52
3111 #define TOK_CONCATENATE 53
3113 #define TOK_IDENT 54
3114 #define TOK_STRUCT_NAME 55
3115 #define TOK_ENUM_CONST 56
3116 #define TOK_TYPE_NAME 57
3119 #define TOK_BREAK 59
3122 #define TOK_CONST 62
3123 #define TOK_CONTINUE 63
3124 #define TOK_DEFAULT 64
3126 #define TOK_DOUBLE 66
3129 #define TOK_EXTERN 69
3130 #define TOK_FLOAT 70
3134 #define TOK_INLINE 74
3137 #define TOK_REGISTER 77
3138 #define TOK_RESTRICT 78
3139 #define TOK_RETURN 79
3140 #define TOK_SHORT 80
3141 #define TOK_SIGNED 81
3142 #define TOK_SIZEOF 82
3143 #define TOK_STATIC 83
3144 #define TOK_STRUCT 84
3145 #define TOK_SWITCH 85
3146 #define TOK_TYPEDEF 86
3147 #define TOK_UNION 87
3148 #define TOK_UNSIGNED 88
3150 #define TOK_VOLATILE 90
3151 #define TOK_WHILE 91
3153 #define TOK_ATTRIBUTE 93
3154 #define TOK_ALIGNOF 94
3155 #define TOK_FIRST_KEYWORD TOK_AUTO
3156 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3158 #define TOK_MDEFINE 100
3159 #define TOK_MDEFINED 101
3160 #define TOK_MUNDEF 102
3161 #define TOK_MINCLUDE 103
3162 #define TOK_MLINE 104
3163 #define TOK_MERROR 105
3164 #define TOK_MWARNING 106
3165 #define TOK_MPRAGMA 107
3166 #define TOK_MIFDEF 108
3167 #define TOK_MIFNDEF 109
3168 #define TOK_MELIF 110
3169 #define TOK_MENDIF 111
3171 #define TOK_FIRST_MACRO TOK_MDEFINE
3172 #define TOK_LAST_MACRO TOK_MENDIF
3175 #define TOK_MELSE 113
3176 #define TOK_MIDENT 114
3181 static const char *tokens[] = {
3182 [TOK_UNKNOWN ] = ":unknown:",
3183 [TOK_SPACE ] = ":space:",
3185 [TOK_LBRACE ] = "{",
3186 [TOK_RBRACE ] = "}",
3190 [TOK_LBRACKET ] = "[",
3191 [TOK_RBRACKET ] = "]",
3192 [TOK_LPAREN ] = "(",
3193 [TOK_RPAREN ] = ")",
3195 [TOK_DOTS ] = "...",
3198 [TOK_TIMESEQ ] = "*=",
3199 [TOK_DIVEQ ] = "/=",
3200 [TOK_MODEQ ] = "%=",
3201 [TOK_PLUSEQ ] = "+=",
3202 [TOK_MINUSEQ ] = "-=",
3203 [TOK_SLEQ ] = "<<=",
3204 [TOK_SREQ ] = ">>=",
3205 [TOK_ANDEQ ] = "&=",
3206 [TOK_XOREQ ] = "^=",
3209 [TOK_NOTEQ ] = "!=",
3211 [TOK_LOGOR ] = "||",
3212 [TOK_LOGAND ] = "&&",
3216 [TOK_LESSEQ ] = "<=",
3217 [TOK_MOREEQ ] = ">=",
3224 [TOK_PLUSPLUS ] = "++",
3225 [TOK_MINUSMINUS ] = "--",
3227 [TOK_ARROW ] = "->",
3230 [TOK_LIT_STRING ] = ":string:",
3231 [TOK_IDENT ] = ":ident:",
3232 [TOK_TYPE_NAME ] = ":typename:",
3233 [TOK_LIT_CHAR ] = ":char:",
3234 [TOK_LIT_INT ] = ":integer:",
3235 [TOK_LIT_FLOAT ] = ":float:",
3237 [TOK_CONCATENATE ] = "##",
3239 [TOK_AUTO ] = "auto",
3240 [TOK_BREAK ] = "break",
3241 [TOK_CASE ] = "case",
3242 [TOK_CHAR ] = "char",
3243 [TOK_CONST ] = "const",
3244 [TOK_CONTINUE ] = "continue",
3245 [TOK_DEFAULT ] = "default",
3247 [TOK_DOUBLE ] = "double",
3248 [TOK_ELSE ] = "else",
3249 [TOK_ENUM ] = "enum",
3250 [TOK_EXTERN ] = "extern",
3251 [TOK_FLOAT ] = "float",
3253 [TOK_GOTO ] = "goto",
3255 [TOK_INLINE ] = "inline",
3257 [TOK_LONG ] = "long",
3258 [TOK_REGISTER ] = "register",
3259 [TOK_RESTRICT ] = "restrict",
3260 [TOK_RETURN ] = "return",
3261 [TOK_SHORT ] = "short",
3262 [TOK_SIGNED ] = "signed",
3263 [TOK_SIZEOF ] = "sizeof",
3264 [TOK_STATIC ] = "static",
3265 [TOK_STRUCT ] = "struct",
3266 [TOK_SWITCH ] = "switch",
3267 [TOK_TYPEDEF ] = "typedef",
3268 [TOK_UNION ] = "union",
3269 [TOK_UNSIGNED ] = "unsigned",
3270 [TOK_VOID ] = "void",
3271 [TOK_VOLATILE ] = "volatile",
3272 [TOK_WHILE ] = "while",
3274 [TOK_ATTRIBUTE ] = "__attribute__",
3275 [TOK_ALIGNOF ] = "__alignof__",
3277 [TOK_MDEFINE ] = "#define",
3278 [TOK_MDEFINED ] = "#defined",
3279 [TOK_MUNDEF ] = "#undef",
3280 [TOK_MINCLUDE ] = "#include",
3281 [TOK_MLINE ] = "#line",
3282 [TOK_MERROR ] = "#error",
3283 [TOK_MWARNING ] = "#warning",
3284 [TOK_MPRAGMA ] = "#pragma",
3285 [TOK_MIFDEF ] = "#ifdef",
3286 [TOK_MIFNDEF ] = "#ifndef",
3287 [TOK_MELIF ] = "#elif",
3288 [TOK_MENDIF ] = "#endif",
3291 [TOK_MELSE ] = "#else",
3292 [TOK_MIDENT ] = "#:ident:",
3297 static unsigned int hash(const char *str, int str_len)
3301 end = str + str_len;
3303 for(; str < end; str++) {
3304 hash = (hash *263) + *str;
3306 hash = hash & (HASH_TABLE_SIZE -1);
3310 static struct hash_entry *lookup(
3311 struct compile_state *state, const char *name, int name_len)
3313 struct hash_entry *entry;
3315 index = hash(name, name_len);
3316 entry = state->hash_table[index];
3318 ((entry->name_len != name_len) ||
3319 (memcmp(entry->name, name, name_len) != 0))) {
3320 entry = entry->next;
3324 /* Get a private copy of the name */
3325 new_name = xmalloc(name_len + 1, "hash_name");
3326 memcpy(new_name, name, name_len);
3327 new_name[name_len] = '\0';
3329 /* Create a new hash entry */
3330 entry = xcmalloc(sizeof(*entry), "hash_entry");
3331 entry->next = state->hash_table[index];
3332 entry->name = new_name;
3333 entry->name_len = name_len;
3335 /* Place the new entry in the hash table */
3336 state->hash_table[index] = entry;
3341 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3343 struct hash_entry *entry;
3345 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3346 (entry->tok == TOK_ENUM_CONST) ||
3347 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3348 (entry->tok <= TOK_LAST_KEYWORD)))) {
3349 tk->tok = entry->tok;
3353 static void ident_to_macro(struct compile_state *state, struct token *tk)
3355 struct hash_entry *entry;
3359 if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3360 tk->tok = entry->tok;
3362 else if (entry->tok == TOK_IF) {
3365 else if (entry->tok == TOK_ELSE) {
3366 tk->tok = TOK_MELSE;
3369 tk->tok = TOK_MIDENT;
3373 static void hash_keyword(
3374 struct compile_state *state, const char *keyword, int tok)
3376 struct hash_entry *entry;
3377 entry = lookup(state, keyword, strlen(keyword));
3378 if (entry && entry->tok != TOK_UNKNOWN) {
3379 die("keyword %s already hashed", keyword);
3384 static void romcc_symbol(
3385 struct compile_state *state, struct hash_entry *ident,
3386 struct symbol **chain, struct triple *def, struct type *type, int depth)
3389 if (*chain && ((*chain)->scope_depth >= depth)) {
3390 error(state, 0, "%s already defined", ident->name);
3392 sym = xcmalloc(sizeof(*sym), "symbol");
3396 sym->scope_depth = depth;
3402 struct compile_state *state, struct hash_entry *ident,
3403 struct symbol **chain, struct triple *def, struct type *type)
3405 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3408 static void var_symbol(struct compile_state *state,
3409 struct hash_entry *ident, struct triple *def)
3411 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3412 internal_error(state, 0, "bad var type");
3414 symbol(state, ident, &ident->sym_ident, def, def->type);
3417 static void label_symbol(struct compile_state *state,
3418 struct hash_entry *ident, struct triple *label, int depth)
3420 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3423 static void start_scope(struct compile_state *state)
3425 state->scope_depth++;
3428 static void end_scope_syms(struct compile_state *state,
3429 struct symbol **chain, int depth)
3431 struct symbol *sym, *next;
3433 while(sym && (sym->scope_depth == depth)) {
3441 static void end_scope(struct compile_state *state)
3445 /* Walk through the hash table and remove all symbols
3446 * in the current scope.
3448 depth = state->scope_depth;
3449 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3450 struct hash_entry *entry;
3451 entry = state->hash_table[i];
3453 end_scope_syms(state, &entry->sym_label, depth);
3454 end_scope_syms(state, &entry->sym_tag, depth);
3455 end_scope_syms(state, &entry->sym_ident, depth);
3456 entry = entry->next;
3459 state->scope_depth = depth - 1;
3462 static void register_keywords(struct compile_state *state)
3464 hash_keyword(state, "auto", TOK_AUTO);
3465 hash_keyword(state, "break", TOK_BREAK);
3466 hash_keyword(state, "case", TOK_CASE);
3467 hash_keyword(state, "char", TOK_CHAR);
3468 hash_keyword(state, "const", TOK_CONST);
3469 hash_keyword(state, "continue", TOK_CONTINUE);
3470 hash_keyword(state, "default", TOK_DEFAULT);
3471 hash_keyword(state, "do", TOK_DO);
3472 hash_keyword(state, "double", TOK_DOUBLE);
3473 hash_keyword(state, "else", TOK_ELSE);
3474 hash_keyword(state, "enum", TOK_ENUM);
3475 hash_keyword(state, "extern", TOK_EXTERN);
3476 hash_keyword(state, "float", TOK_FLOAT);
3477 hash_keyword(state, "for", TOK_FOR);
3478 hash_keyword(state, "goto", TOK_GOTO);
3479 hash_keyword(state, "if", TOK_IF);
3480 hash_keyword(state, "inline", TOK_INLINE);
3481 hash_keyword(state, "int", TOK_INT);
3482 hash_keyword(state, "long", TOK_LONG);
3483 hash_keyword(state, "register", TOK_REGISTER);
3484 hash_keyword(state, "restrict", TOK_RESTRICT);
3485 hash_keyword(state, "return", TOK_RETURN);
3486 hash_keyword(state, "short", TOK_SHORT);
3487 hash_keyword(state, "signed", TOK_SIGNED);
3488 hash_keyword(state, "sizeof", TOK_SIZEOF);
3489 hash_keyword(state, "static", TOK_STATIC);
3490 hash_keyword(state, "struct", TOK_STRUCT);
3491 hash_keyword(state, "switch", TOK_SWITCH);
3492 hash_keyword(state, "typedef", TOK_TYPEDEF);
3493 hash_keyword(state, "union", TOK_UNION);
3494 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3495 hash_keyword(state, "void", TOK_VOID);
3496 hash_keyword(state, "volatile", TOK_VOLATILE);
3497 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3498 hash_keyword(state, "while", TOK_WHILE);
3499 hash_keyword(state, "asm", TOK_ASM);
3500 hash_keyword(state, "__asm__", TOK_ASM);
3501 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3502 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3505 static void register_macro_keywords(struct compile_state *state)
3507 hash_keyword(state, "define", TOK_MDEFINE);
3508 hash_keyword(state, "defined", TOK_MDEFINED);
3509 hash_keyword(state, "undef", TOK_MUNDEF);
3510 hash_keyword(state, "include", TOK_MINCLUDE);
3511 hash_keyword(state, "line", TOK_MLINE);
3512 hash_keyword(state, "error", TOK_MERROR);
3513 hash_keyword(state, "warning", TOK_MWARNING);
3514 hash_keyword(state, "pragma", TOK_MPRAGMA);
3515 hash_keyword(state, "ifdef", TOK_MIFDEF);
3516 hash_keyword(state, "ifndef", TOK_MIFNDEF);
3517 hash_keyword(state, "elif", TOK_MELIF);
3518 hash_keyword(state, "endif", TOK_MENDIF);
3522 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3524 if (ident->sym_define != 0) {
3525 struct macro *macro;
3526 struct macro_arg *arg, *anext;
3527 macro = ident->sym_define;
3528 ident->sym_define = 0;
3530 /* Free the macro arguments... */
3531 anext = macro->args;
3538 /* Free the macro buffer */
3541 /* Now free the macro itself */
3546 static void do_define_macro(struct compile_state *state,
3547 struct hash_entry *ident, const char *body,
3548 int argc, struct macro_arg *args)
3550 struct macro *macro;
3551 struct macro_arg *arg;
3554 /* Find the length of the body */
3555 body_len = strlen(body);
3556 macro = ident->sym_define;
3558 int identical_bodies, identical_args;
3559 struct macro_arg *oarg;
3560 /* Explicitly allow identical redfinitions of the same macro */
3562 (macro->buf_len == body_len) &&
3563 (memcmp(macro->buf, body, body_len) == 0);
3564 identical_args = macro->argc == argc;
3567 while(identical_args && arg) {
3568 identical_args = oarg->ident == arg->ident;
3572 if (identical_bodies && identical_args) {
3576 error(state, 0, "macro %s already defined\n", ident->name);
3579 fprintf(state->errout, "#define %s: `%*.*s'\n",
3580 ident->name, body_len, body_len, body);
3582 macro = xmalloc(sizeof(*macro), "macro");
3583 macro->ident = ident;
3585 macro->buf_len = body_len;
3589 ident->sym_define = macro;
3592 static void define_macro(
3593 struct compile_state *state,
3594 struct hash_entry *ident,
3595 const char *body, int body_len,
3596 int argc, struct macro_arg *args)
3599 buf = xmalloc(body_len + 1, "macro buf");
3600 memcpy(buf, body, body_len);
3601 buf[body_len] = '\0';
3602 do_define_macro(state, ident, buf, argc, args);
3605 static void register_builtin_macro(struct compile_state *state,
3606 const char *name, const char *value)
3608 struct hash_entry *ident;
3610 if (value[0] == '(') {
3611 internal_error(state, 0, "Builtin macros with arguments not supported");
3613 ident = lookup(state, name, strlen(name));
3614 define_macro(state, ident, value, strlen(value), -1, 0);
3617 static void register_builtin_macros(struct compile_state *state)
3624 tm = localtime(&now);
3626 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3627 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3628 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3629 register_builtin_macro(state, "__LINE__", "54321");
3631 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3632 sprintf(buf, "\"%s\"", scratch);
3633 register_builtin_macro(state, "__DATE__", buf);
3635 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3636 sprintf(buf, "\"%s\"", scratch);
3637 register_builtin_macro(state, "__TIME__", buf);
3639 /* I can't be a conforming implementation of C :( */
3640 register_builtin_macro(state, "__STDC__", "0");
3641 /* In particular I don't conform to C99 */
3642 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3646 static void process_cmdline_macros(struct compile_state *state)
3648 const char **macro, *name;
3649 struct hash_entry *ident;
3650 for(macro = state->compiler->defines; (name = *macro); macro++) {
3654 name_len = strlen(name);
3655 body = strchr(name, '=');
3659 name_len = body - name;
3662 ident = lookup(state, name, name_len);
3663 define_macro(state, ident, body, strlen(body), -1, 0);
3665 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3666 ident = lookup(state, name, strlen(name));
3667 undef_macro(state, ident);
3671 static int spacep(int c)
3686 static int digitp(int c)
3690 case '0': case '1': case '2': case '3': case '4':
3691 case '5': case '6': case '7': case '8': case '9':
3697 static int digval(int c)
3700 if ((c >= '0') && (c <= '9')) {
3706 static int hexdigitp(int c)
3710 case '0': case '1': case '2': case '3': case '4':
3711 case '5': case '6': case '7': case '8': case '9':
3712 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3713 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3719 static int hexdigval(int c)
3722 if ((c >= '0') && (c <= '9')) {
3725 else if ((c >= 'A') && (c <= 'F')) {
3726 val = 10 + (c - 'A');
3728 else if ((c >= 'a') && (c <= 'f')) {
3729 val = 10 + (c - 'a');
3734 static int octdigitp(int c)
3738 case '0': case '1': case '2': case '3':
3739 case '4': case '5': case '6': case '7':
3745 static int octdigval(int c)
3748 if ((c >= '0') && (c <= '7')) {
3754 static int letterp(int c)
3758 case 'a': case 'b': case 'c': case 'd': case 'e':
3759 case 'f': case 'g': case 'h': case 'i': case 'j':
3760 case 'k': case 'l': case 'm': case 'n': case 'o':
3761 case 'p': case 'q': case 'r': case 's': case 't':
3762 case 'u': case 'v': case 'w': case 'x': case 'y':
3764 case 'A': case 'B': case 'C': case 'D': case 'E':
3765 case 'F': case 'G': case 'H': case 'I': case 'J':
3766 case 'K': case 'L': case 'M': case 'N': case 'O':
3767 case 'P': case 'Q': case 'R': case 'S': case 'T':
3768 case 'U': case 'V': case 'W': case 'X': case 'Y':
3777 static const char *identifier(const char *str, const char *end)
3779 if (letterp(*str)) {
3780 for(; str < end; str++) {
3783 if (!letterp(c) && !digitp(c)) {
3791 static int char_value(struct compile_state *state,
3792 const signed char **strp, const signed char *end)
3794 const signed char *str;
3798 if ((c == '\\') && (str < end)) {
3800 case 'n': c = '\n'; str++; break;
3801 case 't': c = '\t'; str++; break;
3802 case 'v': c = '\v'; str++; break;
3803 case 'b': c = '\b'; str++; break;
3804 case 'r': c = '\r'; str++; break;
3805 case 'f': c = '\f'; str++; break;
3806 case 'a': c = '\a'; str++; break;
3807 case '\\': c = '\\'; str++; break;
3808 case '?': c = '?'; str++; break;
3809 case '\'': c = '\''; str++; break;
3810 case '"': c = '"'; str++; break;
3814 while((str < end) && hexdigitp(*str)) {
3816 c += hexdigval(*str);
3820 case '0': case '1': case '2': case '3':
3821 case '4': case '5': case '6': case '7':
3823 while((str < end) && octdigitp(*str)) {
3825 c += octdigval(*str);
3830 error(state, 0, "Invalid character constant");
3838 static const char *next_char(struct file_state *file, const char *pos, int index)
3840 const char *end = file->buf + file->size;
3842 /* Lookup the character */
3845 /* Is this a trigraph? */
3846 if (file->trigraphs &&
3847 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3850 case '=': c = '#'; break;
3851 case '/': c = '\\'; break;
3852 case '\'': c = '^'; break;
3853 case '(': c = '['; break;
3854 case ')': c = ']'; break;
3855 case '!': c = '!'; break;
3856 case '<': c = '{'; break;
3857 case '>': c = '}'; break;
3858 case '-': c = '~'; break;
3864 /* Is this an escaped newline? */
3865 if (file->join_lines &&
3866 (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3868 int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3869 /* At the start of a line just eat it */
3870 if (pos == file->pos) {
3872 file->report_line++;
3873 file->line_start = pos + size + 1 + cr_offset;
3875 pos += size + 1 + cr_offset;
3877 /* Do I need to ga any farther? */
3878 else if (index == 0) {
3881 /* Process a normal character */
3890 static int get_char(struct file_state *file, const char *pos)
3892 const char *end = file->buf + file->size;
3895 pos = next_char(file, pos, 0);
3897 /* Lookup the character */
3899 /* If it is a trigraph get the trigraph value */
3900 if (file->trigraphs &&
3901 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3904 case '=': c = '#'; break;
3905 case '/': c = '\\'; break;
3906 case '\'': c = '^'; break;
3907 case '(': c = '['; break;
3908 case ')': c = ']'; break;
3909 case '!': c = '!'; break;
3910 case '<': c = '{'; break;
3911 case '>': c = '}'; break;
3912 case '-': c = '~'; break;
3919 static void eat_chars(struct file_state *file, const char *targ)
3921 const char *pos = file->pos;
3923 /* Do we have a newline? */
3924 if (pos[0] == '\n') {
3926 file->report_line++;
3927 file->line_start = pos + 1;
3935 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3940 src = next_char(file, src, 1);
3946 static void char_strcpy(char *dest,
3947 struct file_state *file, const char *src, const char *end)
3951 c = get_char(file, src);
3952 src = next_char(file, src, 1);
3957 static char *char_strdup(struct file_state *file,
3958 const char *start, const char *end, const char *id)
3962 str_len = char_strlen(file, start, end);
3963 str = xcmalloc(str_len + 1, id);
3964 char_strcpy(str, file, start, end);
3965 str[str_len] = '\0';
3969 static const char *after_digits(struct file_state *file, const char *ptr)
3971 while(digitp(get_char(file, ptr))) {
3972 ptr = next_char(file, ptr, 1);
3977 static const char *after_octdigits(struct file_state *file, const char *ptr)
3979 while(octdigitp(get_char(file, ptr))) {
3980 ptr = next_char(file, ptr, 1);
3985 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3987 while(hexdigitp(get_char(file, ptr))) {
3988 ptr = next_char(file, ptr, 1);
3993 static const char *after_alnums(struct file_state *file, const char *ptr)
3996 c = get_char(file, ptr);
3997 while(letterp(c) || digitp(c)) {
3998 ptr = next_char(file, ptr, 1);
3999 c = get_char(file, ptr);
4004 static void save_string(struct file_state *file,
4005 struct token *tk, const char *start, const char *end, const char *id)
4009 /* Create a private copy of the string */
4010 str = char_strdup(file, start, end, id);
4012 /* Store the copy in the token */
4014 tk->str_len = strlen(str);
4017 static void raw_next_token(struct compile_state *state,
4018 struct file_state *file, struct token *tk)
4028 token = tokp = next_char(file, file->pos, 0);
4030 c = get_char(file, tokp);
4031 tokp = next_char(file, tokp, 1);
4033 c1 = get_char(file, tokp);
4034 c2 = get_char(file, next_char(file, tokp, 1));
4035 c3 = get_char(file, next_char(file, tokp, 2));
4037 /* The end of the file */
4042 else if (spacep(c)) {
4044 while (spacep(get_char(file, tokp))) {
4045 tokp = next_char(file, tokp, 1);
4049 else if ((c == '/') && (c1 == '/')) {
4051 tokp = next_char(file, tokp, 1);
4052 while((c = get_char(file, tokp)) != -1) {
4053 /* Advance to the next character only after we verify
4054 * the current character is not a newline.
4055 * EOL is special to the preprocessor so we don't
4056 * want to loose any.
4061 tokp = next_char(file, tokp, 1);
4065 else if ((c == '/') && (c1 == '*')) {
4066 tokp = next_char(file, tokp, 2);
4068 while((c1 = get_char(file, tokp)) != -1) {
4069 tokp = next_char(file, tokp, 1);
4070 if ((c == '*') && (c1 == '/')) {
4076 if (tok == TOK_UNKNOWN) {
4077 error(state, 0, "unterminated comment");
4080 /* string constants */
4081 else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4082 int wchar, multiline;
4088 tokp = next_char(file, tokp, 1);
4090 while((c = get_char(file, tokp)) != -1) {
4091 tokp = next_char(file, tokp, 1);
4095 else if (c == '\\') {
4096 tokp = next_char(file, tokp, 1);
4098 else if (c == '"') {
4099 tok = TOK_LIT_STRING;
4103 if (tok == TOK_UNKNOWN) {
4104 error(state, 0, "unterminated string constant");
4107 warning(state, 0, "multiline string constant");
4110 /* Save the string value */
4111 save_string(file, tk, token, tokp, "literal string");
4113 /* character constants */
4114 else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4115 int wchar, multiline;
4121 tokp = next_char(file, tokp, 1);
4123 while((c = get_char(file, tokp)) != -1) {
4124 tokp = next_char(file, tokp, 1);
4128 else if (c == '\\') {
4129 tokp = next_char(file, tokp, 1);
4131 else if (c == '\'') {
4136 if (tok == TOK_UNKNOWN) {
4137 error(state, 0, "unterminated character constant");
4140 warning(state, 0, "multiline character constant");
4143 /* Save the character value */
4144 save_string(file, tk, token, tokp, "literal character");
4146 /* integer and floating constants
4152 * Floating constants
4153 * {digits}.{digits}[Ee][+-]?{digits}
4155 * {digits}[Ee][+-]?{digits}
4156 * .{digits}[Ee][+-]?{digits}
4159 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4165 next = after_digits(file, tokp);
4170 cn = get_char(file, next);
4172 next = next_char(file, next, 1);
4173 next = after_digits(file, next);
4176 cn = get_char(file, next);
4177 if ((cn == 'e') || (cn == 'E')) {
4179 next = next_char(file, next, 1);
4180 cn = get_char(file, next);
4181 if ((cn == '+') || (cn == '-')) {
4182 next = next_char(file, next, 1);
4184 new = after_digits(file, next);
4185 is_float |= (new != next);
4189 tok = TOK_LIT_FLOAT;
4190 cn = get_char(file, next);
4191 if ((cn == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4192 next = next_char(file, next, 1);
4195 if (!is_float && digitp(c)) {
4197 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4198 next = next_char(file, tokp, 1);
4199 next = after_hexdigits(file, next);
4201 else if (c == '0') {
4202 next = after_octdigits(file, tokp);
4205 next = after_digits(file, tokp);
4207 /* crazy integer suffixes */
4208 cn = get_char(file, next);
4209 if ((cn == 'u') || (cn == 'U')) {
4210 next = next_char(file, next, 1);
4211 cn = get_char(file, next);
4212 if ((cn == 'l') || (cn == 'L')) {
4213 next = next_char(file, next, 1);
4214 cn = get_char(file, next);
4216 if ((cn == 'l') || (cn == 'L')) {
4217 next = next_char(file, next, 1);
4220 else if ((cn == 'l') || (cn == 'L')) {
4221 next = next_char(file, next, 1);
4222 cn = get_char(file, next);
4223 if ((cn == 'l') || (cn == 'L')) {
4224 next = next_char(file, next, 1);
4225 cn = get_char(file, next);
4227 if ((cn == 'u') || (cn == 'U')) {
4228 next = next_char(file, next, 1);
4234 /* Save the integer/floating point value */
4235 save_string(file, tk, token, tokp, "literal number");
4238 else if (letterp(c)) {
4241 /* Find and save the identifier string */
4242 tokp = after_alnums(file, tokp);
4243 save_string(file, tk, token, tokp, "identifier");
4245 /* Look up to see which identifier it is */
4246 tk->ident = lookup(state, tk->val.str, tk->str_len);
4248 /* Free the identifier string */
4252 /* See if this identifier can be macro expanded */
4253 tk->val.notmacro = 0;
4254 c = get_char(file, tokp);
4256 tokp = next_char(file, tokp, 1);
4257 tk->val.notmacro = 1;
4260 /* C99 alternate macro characters */
4261 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4263 tok = TOK_CONCATENATE;
4265 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4266 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4267 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4268 else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4269 else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4270 else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4271 else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4272 else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4273 else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4274 else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4275 else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4276 else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4277 else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4278 else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4279 else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4280 else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4281 else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4282 else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4283 else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4284 else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4285 else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4286 else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4287 else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4288 else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4289 else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4290 else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4291 else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4292 else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4293 else if (c == ';') { tok = TOK_SEMI; }
4294 else if (c == '{') { tok = TOK_LBRACE; }
4295 else if (c == '}') { tok = TOK_RBRACE; }
4296 else if (c == ',') { tok = TOK_COMMA; }
4297 else if (c == '=') { tok = TOK_EQ; }
4298 else if (c == ':') { tok = TOK_COLON; }
4299 else if (c == '[') { tok = TOK_LBRACKET; }
4300 else if (c == ']') { tok = TOK_RBRACKET; }
4301 else if (c == '(') { tok = TOK_LPAREN; }
4302 else if (c == ')') { tok = TOK_RPAREN; }
4303 else if (c == '*') { tok = TOK_STAR; }
4304 else if (c == '>') { tok = TOK_MORE; }
4305 else if (c == '<') { tok = TOK_LESS; }
4306 else if (c == '?') { tok = TOK_QUEST; }
4307 else if (c == '|') { tok = TOK_OR; }
4308 else if (c == '&') { tok = TOK_AND; }
4309 else if (c == '^') { tok = TOK_XOR; }
4310 else if (c == '+') { tok = TOK_PLUS; }
4311 else if (c == '-') { tok = TOK_MINUS; }
4312 else if (c == '/') { tok = TOK_DIV; }
4313 else if (c == '%') { tok = TOK_MOD; }
4314 else if (c == '!') { tok = TOK_BANG; }
4315 else if (c == '.') { tok = TOK_DOT; }
4316 else if (c == '~') { tok = TOK_TILDE; }
4317 else if (c == '#') { tok = TOK_MACRO; }
4318 else if (c == '\n') { tok = TOK_EOL; }
4320 tokp = next_char(file, tokp, eat);
4321 eat_chars(file, tokp);
4326 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4328 if (tk->tok != tok) {
4329 const char *name1, *name2;
4330 name1 = tokens[tk->tok];
4332 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4333 name2 = tk->ident->name;
4335 error(state, 0, "\tfound %s %s expected %s",
4336 name1, name2, tokens[tok]);
4340 struct macro_arg_value {
4341 struct hash_entry *ident;
4345 static struct macro_arg_value *read_macro_args(
4346 struct compile_state *state, struct macro *macro,
4347 struct file_state *file, struct token *tk)
4349 struct macro_arg_value *argv;
4350 struct macro_arg *arg;
4354 if (macro->argc == 0) {
4356 raw_next_token(state, file, tk);
4357 } while(tk->tok == TOK_SPACE);
4360 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4361 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4364 argv[i].ident = arg->ident;
4373 raw_next_token(state, file, tk);
4375 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4376 (argv[i].ident != state->i___VA_ARGS__))
4379 if (i >= macro->argc) {
4380 error(state, 0, "too many args to %s\n",
4381 macro->ident->name);
4386 if (tk->tok == TOK_LPAREN) {
4390 if (tk->tok == TOK_RPAREN) {
4391 if (paren_depth == 0) {
4396 if (tk->tok == TOK_EOF) {
4397 error(state, 0, "End of file encountered while parsing macro arguments");
4400 len = char_strlen(file, start, file->pos);
4401 argv[i].value = xrealloc(
4402 argv[i].value, argv[i].len + len, "macro args");
4403 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4406 if (i != macro->argc -1) {
4407 error(state, 0, "missing %s arg %d\n",
4408 macro->ident->name, i +2);
4414 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4417 for(i = 0; i < macro->argc; i++) {
4418 xfree(argv[i].value);
4428 static void grow_macro_buf(struct compile_state *state,
4429 const char *id, struct macro_buf *buf,
4432 if ((buf->pos + grow) >= buf->len) {
4433 buf->str = xrealloc(buf->str, buf->len + grow, id);
4438 static void append_macro_text(struct compile_state *state,
4439 const char *id, struct macro_buf *buf,
4440 const char *fstart, size_t flen)
4442 grow_macro_buf(state, id, buf, flen);
4443 memcpy(buf->str + buf->pos, fstart, flen);
4445 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4446 buf->pos, buf->pos, buf->str,
4447 flen, flen, buf->str + buf->pos);
4453 static void append_macro_chars(struct compile_state *state,
4454 const char *id, struct macro_buf *buf,
4455 struct file_state *file, const char *start, const char *end)
4458 flen = char_strlen(file, start, end);
4459 grow_macro_buf(state, id, buf, flen);
4460 char_strcpy(buf->str + buf->pos, file, start, end);
4462 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4463 buf->pos, buf->pos, buf->str,
4464 flen, flen, buf->str + buf->pos);
4469 static int compile_macro(struct compile_state *state,
4470 struct file_state **filep, struct token *tk);
4472 static void macro_expand_args(struct compile_state *state,
4473 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4477 for(i = 0; i < macro->argc; i++) {
4478 struct file_state fmacro, *file;
4479 struct macro_buf buf;
4482 fmacro.basename = argv[i].ident->name;
4483 fmacro.dirname = "";
4484 fmacro.buf = (char *)argv[i].value;
4485 fmacro.size = argv[i].len;
4486 fmacro.pos = fmacro.buf;
4488 fmacro.line_start = fmacro.buf;
4489 fmacro.report_line = 1;
4490 fmacro.report_name = fmacro.basename;
4491 fmacro.report_dir = fmacro.dirname;
4493 fmacro.trigraphs = 0;
4494 fmacro.join_lines = 0;
4496 buf.len = argv[i].len;
4497 buf.str = xmalloc(buf.len, argv[i].ident->name);
4502 raw_next_token(state, file, tk);
4504 /* If we have recursed into another macro body
4507 if (tk->tok == TOK_EOF) {
4508 struct file_state *old;
4514 /* old->basename is used keep it */
4515 xfree(old->dirname);
4520 else if (tk->ident && tk->ident->sym_define) {
4521 if (compile_macro(state, &file, tk)) {
4526 append_macro_chars(state, macro->ident->name, &buf,
4527 file, tk->pos, file->pos);
4530 xfree(argv[i].value);
4531 argv[i].value = buf.str;
4532 argv[i].len = buf.pos;
4537 static void expand_macro(struct compile_state *state,
4538 struct macro *macro, struct macro_buf *buf,
4539 struct macro_arg_value *argv, struct token *tk)
4541 struct file_state fmacro;
4542 const char space[] = " ";
4547 /* Place the macro body in a dummy file */
4549 fmacro.basename = macro->ident->name;
4550 fmacro.dirname = "";
4551 fmacro.buf = macro->buf;
4552 fmacro.size = macro->buf_len;
4553 fmacro.pos = fmacro.buf;
4555 fmacro.line_start = fmacro.buf;
4556 fmacro.report_line = 1;
4557 fmacro.report_name = fmacro.basename;
4558 fmacro.report_dir = fmacro.dirname;
4560 fmacro.trigraphs = 0;
4561 fmacro.join_lines = 0;
4563 /* Allocate a buffer to hold the macro expansion */
4564 buf->len = macro->buf_len + 3;
4565 buf->str = xmalloc(buf->len, macro->ident->name);
4568 fstart = fmacro.pos;
4569 raw_next_token(state, &fmacro, tk);
4570 while(tk->tok != TOK_EOF) {
4571 flen = fmacro.pos - fstart;
4574 for(i = 0; i < macro->argc; i++) {
4575 if (argv[i].ident == tk->ident) {
4579 if (i >= macro->argc) {
4582 /* Substitute macro parameter */
4583 fstart = argv[i].value;
4587 if (macro->argc < 0) {
4591 raw_next_token(state, &fmacro, tk);
4592 } while(tk->tok == TOK_SPACE);
4593 check_tok(state, tk, TOK_IDENT);
4594 for(i = 0; i < macro->argc; i++) {
4595 if (argv[i].ident == tk->ident) {
4599 if (i >= macro->argc) {
4600 error(state, 0, "parameter `%s' not found",
4603 /* Stringize token */
4604 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4605 for(j = 0; j < argv[i].len; j++) {
4606 char *str = argv[i].value + j;
4612 else if (*str == '"') {
4616 append_macro_text(state, macro->ident->name, buf, str, len);
4618 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4622 case TOK_CONCATENATE:
4623 /* Concatenate tokens */
4624 /* Delete the previous whitespace token */
4625 if (buf->str[buf->pos - 1] == ' ') {
4628 /* Skip the next sequence of whitspace tokens */
4630 fstart = fmacro.pos;
4631 raw_next_token(state, &fmacro, tk);
4632 } while(tk->tok == TOK_SPACE);
4633 /* Restart at the top of the loop.
4634 * I need to process the non white space token.
4639 /* Collapse multiple spaces into one */
4640 if (buf->str[buf->pos - 1] != ' ') {
4652 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4654 fstart = fmacro.pos;
4655 raw_next_token(state, &fmacro, tk);
4659 static void tag_macro_name(struct compile_state *state,
4660 struct macro *macro, struct macro_buf *buf,
4663 /* Guard all instances of the macro name in the replacement
4664 * text from further macro expansion.
4666 struct file_state fmacro;
4670 /* Put the old macro expansion buffer in a file */
4672 fmacro.basename = macro->ident->name;
4673 fmacro.dirname = "";
4674 fmacro.buf = buf->str;
4675 fmacro.size = buf->pos;
4676 fmacro.pos = fmacro.buf;
4678 fmacro.line_start = fmacro.buf;
4679 fmacro.report_line = 1;
4680 fmacro.report_name = fmacro.basename;
4681 fmacro.report_dir = fmacro.dirname;
4683 fmacro.trigraphs = 0;
4684 fmacro.join_lines = 0;
4686 /* Allocate a new macro expansion buffer */
4687 buf->len = macro->buf_len + 3;
4688 buf->str = xmalloc(buf->len, macro->ident->name);
4691 fstart = fmacro.pos;
4692 raw_next_token(state, &fmacro, tk);
4693 while(tk->tok != TOK_EOF) {
4694 flen = fmacro.pos - fstart;
4695 if ((tk->tok == TOK_IDENT) &&
4696 (tk->ident == macro->ident) &&
4697 (tk->val.notmacro == 0))
4699 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4704 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4706 fstart = fmacro.pos;
4707 raw_next_token(state, &fmacro, tk);
4712 static int compile_macro(struct compile_state *state,
4713 struct file_state **filep, struct token *tk)
4715 struct file_state *file;
4716 struct hash_entry *ident;
4717 struct macro *macro;
4718 struct macro_arg_value *argv;
4719 struct macro_buf buf;
4722 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4725 macro = ident->sym_define;
4727 /* If this token comes from a macro expansion ignore it */
4728 if (tk->val.notmacro) {
4731 /* If I am a function like macro and the identifier is not followed
4732 * by a left parenthesis, do nothing.
4734 if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4738 /* Read in the macro arguments */
4740 if (macro->argc >= 0) {
4741 raw_next_token(state, *filep, tk);
4742 check_tok(state, tk, TOK_LPAREN);
4744 argv = read_macro_args(state, macro, *filep, tk);
4746 check_tok(state, tk, TOK_RPAREN);
4748 /* Macro expand the macro arguments */
4749 macro_expand_args(state, macro, argv, tk);
4754 if (ident == state->i___FILE__) {
4755 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4756 buf.str = xmalloc(buf.len, ident->name);
4757 sprintf(buf.str, "\"%s\"", state->file->basename);
4758 buf.pos = strlen(buf.str);
4760 else if (ident == state->i___LINE__) {
4762 buf.str = xmalloc(buf.len, ident->name);
4763 sprintf(buf.str, "%d", state->file->line);
4764 buf.pos = strlen(buf.str);
4767 expand_macro(state, macro, &buf, argv, tk);
4769 /* Tag the macro name with a $ so it will no longer
4770 * be regonized as a canidate for macro expansion.
4772 tag_macro_name(state, macro, &buf, tk);
4775 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4776 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4779 free_macro_args(macro, argv);
4781 file = xmalloc(sizeof(*file), "file_state");
4782 file->prev = *filep;
4783 file->basename = xstrdup(ident->name);
4784 file->dirname = xstrdup("");
4785 file->buf = buf.str;
4786 file->size = buf.pos;
4787 file->pos = file->buf;
4789 file->line_start = file->pos;
4790 file->report_line = 1;
4791 file->report_name = file->basename;
4792 file->report_dir = file->dirname;
4794 file->trigraphs = 0;
4795 file->join_lines = 0;
4800 static void eat_tokens(struct compile_state *state, int targ_tok)
4802 if (state->eat_depth > 0) {
4803 internal_error(state, 0, "Already eating...");
4805 state->eat_depth = state->if_depth;
4806 state->eat_targ = targ_tok;
4808 static int if_eat(struct compile_state *state)
4810 return state->eat_depth > 0;
4812 static int if_value(struct compile_state *state)
4815 index = state->if_depth / CHAR_BIT;
4816 offset = state->if_depth % CHAR_BIT;
4817 return !!(state->if_bytes[index] & (1 << (offset)));
4819 static void set_if_value(struct compile_state *state, int value)
4822 index = state->if_depth / CHAR_BIT;
4823 offset = state->if_depth % CHAR_BIT;
4825 state->if_bytes[index] &= ~(1 << offset);
4827 state->if_bytes[index] |= (1 << offset);
4830 static void in_if(struct compile_state *state, const char *name)
4832 if (state->if_depth <= 0) {
4833 error(state, 0, "%s without #if", name);
4836 static void enter_if(struct compile_state *state)
4838 state->if_depth += 1;
4839 if (state->if_depth > MAX_PP_IF_DEPTH) {
4840 error(state, 0, "#if depth too great");
4843 static void reenter_if(struct compile_state *state, const char *name)
4846 if ((state->eat_depth == state->if_depth) &&
4847 (state->eat_targ == TOK_MELSE)) {
4848 state->eat_depth = 0;
4849 state->eat_targ = 0;
4852 static void enter_else(struct compile_state *state, const char *name)
4855 if ((state->eat_depth == state->if_depth) &&
4856 (state->eat_targ == TOK_MELSE)) {
4857 state->eat_depth = 0;
4858 state->eat_targ = 0;
4861 static void exit_if(struct compile_state *state, const char *name)
4864 if (state->eat_depth == state->if_depth) {
4865 state->eat_depth = 0;
4866 state->eat_targ = 0;
4868 state->if_depth -= 1;
4871 static void raw_token(struct compile_state *state, struct token *tk)
4873 struct file_state *file;
4877 raw_next_token(state, file, tk);
4881 /* Exit out of an include directive or macro call */
4882 if ((tk->tok == TOK_EOF) &&
4883 (file != state->macro_file) && file->prev)
4885 state->file = file->prev;
4886 /* file->basename is used keep it */
4887 xfree(file->dirname);
4891 raw_next_token(state, state->file, tk);
4897 static void pp_token(struct compile_state *state, struct token *tk)
4899 struct file_state *file;
4902 raw_token(state, tk);
4906 if (tk->tok == TOK_SPACE) {
4907 raw_token(state, tk);
4910 else if (tk->tok == TOK_IDENT) {
4911 if (state->token_base == 0) {
4912 ident_to_keyword(state, tk);
4914 ident_to_macro(state, tk);
4920 static void preprocess(struct compile_state *state, struct token *tk);
4922 static void token(struct compile_state *state, struct token *tk)
4925 pp_token(state, tk);
4928 /* Process a macro directive */
4929 if (tk->tok == TOK_MACRO) {
4930 /* Only match preprocessor directives at the start of a line */
4932 ptr = state->file->line_start;
4933 while((ptr < tk->pos)
4934 && spacep(get_char(state->file, ptr)))
4936 ptr = next_char(state->file, ptr, 1);
4938 if (ptr == tk->pos) {
4939 preprocess(state, tk);
4943 /* Expand a macro call */
4944 else if (tk->ident && tk->ident->sym_define) {
4945 rescan = compile_macro(state, &state->file, tk);
4947 pp_token(state, tk);
4950 /* Eat tokens disabled by the preprocessor
4951 * (Unless we are parsing a preprocessor directive
4953 else if (if_eat(state) && (state->token_base == 0)) {
4954 pp_token(state, tk);
4957 /* Make certain EOL only shows up in preprocessor directives */
4958 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4959 pp_token(state, tk);
4962 /* Error on unknown tokens */
4963 else if (tk->tok == TOK_UNKNOWN) {
4964 error(state, 0, "unknown token");
4970 static inline struct token *get_token(struct compile_state *state, int offset)
4973 index = state->token_base + offset;
4974 if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4975 internal_error(state, 0, "token array to small");
4977 return &state->token[index];
4980 static struct token *do_eat_token(struct compile_state *state, int tok)
4984 check_tok(state, get_token(state, 1), tok);
4986 /* Free the old token value */
4987 tk = get_token(state, 0);
4989 memset((void *)tk->val.str, -1, tk->str_len);
4992 /* Overwrite the old token with newer tokens */
4993 for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4994 state->token[i] = state->token[i + 1];
4996 /* Clear the last token */
4997 memset(&state->token[i], 0, sizeof(state->token[i]));
4998 state->token[i].tok = -1;
5000 /* Return the token */
5004 static int raw_peek(struct compile_state *state)
5007 tk1 = get_token(state, 1);
5008 if (tk1->tok == -1) {
5009 raw_token(state, tk1);
5014 static struct token *raw_eat(struct compile_state *state, int tok)
5017 return do_eat_token(state, tok);
5020 static int pp_peek(struct compile_state *state)
5023 tk1 = get_token(state, 1);
5024 if (tk1->tok == -1) {
5025 pp_token(state, tk1);
5030 static struct token *pp_eat(struct compile_state *state, int tok)
5033 return do_eat_token(state, tok);
5036 static int peek(struct compile_state *state)
5039 tk1 = get_token(state, 1);
5040 if (tk1->tok == -1) {
5046 static int peek2(struct compile_state *state)
5048 struct token *tk1, *tk2;
5049 tk1 = get_token(state, 1);
5050 tk2 = get_token(state, 2);
5051 if (tk1->tok == -1) {
5054 if (tk2->tok == -1) {
5060 static struct token *eat(struct compile_state *state, int tok)
5063 return do_eat_token(state, tok);
5066 static void compile_file(struct compile_state *state, const char *filename, int local)
5068 char cwd[MAX_CWD_SIZE];
5069 const char *subdir, *base;
5071 struct file_state *file;
5073 file = xmalloc(sizeof(*file), "file_state");
5075 base = strrchr(filename, '/');
5078 subdir_len = base - filename;
5085 basename = xmalloc(strlen(base) +1, "basename");
5086 strcpy(basename, base);
5087 file->basename = basename;
5089 if (getcwd(cwd, sizeof(cwd)) == 0) {
5090 die("cwd buffer to small");
5092 if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5093 file->dirname = xmalloc(subdir_len + 1, "dirname");
5094 memcpy(file->dirname, subdir, subdir_len);
5095 file->dirname[subdir_len] = '\0';
5101 /* Find the appropriate directory... */
5103 if (!state->file && exists(cwd, filename)) {
5106 if (local && state->file && exists(state->file->dirname, filename)) {
5107 dir = state->file->dirname;
5109 for(path = state->compiler->include_paths; !dir && *path; path++) {
5110 if (exists(*path, filename)) {
5115 error(state, 0, "Cannot open `%s'\n", filename);
5117 dirlen = strlen(dir);
5118 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5119 memcpy(file->dirname, dir, dirlen);
5120 file->dirname[dirlen] = '/';
5121 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5122 file->dirname[dirlen + 1 + subdir_len] = '\0';
5124 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5126 file->pos = file->buf;
5127 file->line_start = file->pos;
5130 file->report_line = 1;
5131 file->report_name = file->basename;
5132 file->report_dir = file->dirname;
5134 file->trigraphs = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5135 file->join_lines = 1;
5137 file->prev = state->file;
5141 static struct triple *constant_expr(struct compile_state *state);
5142 static void integral(struct compile_state *state, struct triple *def);
5144 static int mcexpr(struct compile_state *state)
5146 struct triple *cvalue;
5147 cvalue = constant_expr(state);
5148 integral(state, cvalue);
5149 if (cvalue->op != OP_INTCONST) {
5150 error(state, 0, "integer constant expected");
5152 return cvalue->u.cval != 0;
5155 static void preprocess(struct compile_state *state, struct token *current_token)
5157 /* Doing much more with the preprocessor would require
5158 * a parser and a major restructuring.
5159 * Postpone that for later.
5164 state->macro_file = state->file;
5166 old_token_base = state->token_base;
5167 state->token_base = current_token - state->token;
5169 tok = pp_peek(state);
5175 tk = pp_eat(state, TOK_LIT_INT);
5176 override_line = strtoul(tk->val.str, 0, 10);
5177 /* I have a preprocessor line marker parse it */
5178 if (pp_peek(state) == TOK_LIT_STRING) {
5179 const char *token, *base;
5181 int name_len, dir_len;
5182 tk = pp_eat(state, TOK_LIT_STRING);
5183 name = xmalloc(tk->str_len, "report_name");
5184 token = tk->val.str + 1;
5185 base = strrchr(token, '/');
5186 name_len = tk->str_len -2;
5188 dir_len = base - token;
5190 name_len -= base - token;
5195 memcpy(name, base, name_len);
5196 name[name_len] = '\0';
5197 dir = xmalloc(dir_len + 1, "report_dir");
5198 memcpy(dir, token, dir_len);
5199 dir[dir_len] = '\0';
5200 state->file->report_line = override_line - 1;
5201 state->file->report_name = name;
5202 state->file->report_dir = dir;
5203 state->file->macro = 0;
5210 pp_eat(state, TOK_MLINE);
5211 tk = eat(state, TOK_LIT_INT);
5212 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5213 if (pp_peek(state) == TOK_LIT_STRING) {
5214 const char *token, *base;
5216 int name_len, dir_len;
5217 tk = pp_eat(state, TOK_LIT_STRING);
5218 name = xmalloc(tk->str_len, "report_name");
5219 token = tk->val.str + 1;
5220 base = strrchr(token, '/');
5221 name_len = tk->str_len - 2;
5223 dir_len = base - token;
5225 name_len -= base - token;
5230 memcpy(name, base, name_len);
5231 name[name_len] = '\0';
5232 dir = xmalloc(dir_len + 1, "report_dir");
5233 memcpy(dir, token, dir_len);
5234 dir[dir_len] = '\0';
5235 state->file->report_name = name;
5236 state->file->report_dir = dir;
5237 state->file->macro = 0;
5243 struct hash_entry *ident;
5244 pp_eat(state, TOK_MUNDEF);
5245 if (if_eat(state)) /* quit early when #if'd out */
5248 ident = pp_eat(state, TOK_MIDENT)->ident;
5250 undef_macro(state, ident);
5254 pp_eat(state, TOK_MPRAGMA);
5255 if (if_eat(state)) /* quit early when #if'd out */
5257 warning(state, 0, "Ignoring pragma");
5260 pp_eat(state, TOK_MELIF);
5261 reenter_if(state, "#elif");
5262 if (if_eat(state)) /* quit early when #if'd out */
5264 /* If the #if was taken the #elif just disables the following code */
5265 if (if_value(state)) {
5266 eat_tokens(state, TOK_MENDIF);
5268 /* If the previous #if was not taken see if the #elif enables the
5272 set_if_value(state, mcexpr(state));
5273 if (!if_value(state)) {
5274 eat_tokens(state, TOK_MELSE);
5279 pp_eat(state, TOK_MIF);
5281 if (if_eat(state)) /* quit early when #if'd out */
5283 set_if_value(state, mcexpr(state));
5284 if (!if_value(state)) {
5285 eat_tokens(state, TOK_MELSE);
5290 struct hash_entry *ident;
5292 pp_eat(state, TOK_MIFNDEF);
5294 if (if_eat(state)) /* quit early when #if'd out */
5296 ident = pp_eat(state, TOK_MIDENT)->ident;
5297 set_if_value(state, ident->sym_define == 0);
5298 if (!if_value(state)) {
5299 eat_tokens(state, TOK_MELSE);
5305 struct hash_entry *ident;
5306 pp_eat(state, TOK_MIFDEF);
5308 if (if_eat(state)) /* quit early when #if'd out */
5310 ident = pp_eat(state, TOK_MIDENT)->ident;
5311 set_if_value(state, ident->sym_define != 0);
5312 if (!if_value(state)) {
5313 eat_tokens(state, TOK_MELSE);
5318 pp_eat(state, TOK_MELSE);
5319 enter_else(state, "#else");
5320 if (!if_eat(state) && if_value(state)) {
5321 eat_tokens(state, TOK_MENDIF);
5325 pp_eat(state, TOK_MENDIF);
5326 exit_if(state, "#endif");
5330 struct hash_entry *ident;
5331 struct macro_arg *args, **larg;
5332 const char *mstart, *mend;
5335 pp_eat(state, TOK_MDEFINE);
5336 if (if_eat(state)) /* quit early when #if'd out */
5338 ident = pp_eat(state, TOK_MIDENT)->ident;
5343 /* Parse macro parameters */
5344 if (raw_peek(state) == TOK_LPAREN) {
5345 raw_eat(state, TOK_LPAREN);
5349 struct macro_arg *narg, *arg;
5350 struct hash_entry *aident;
5353 tok = pp_peek(state);
5354 if (!args && (tok == TOK_RPAREN)) {
5357 else if (tok == TOK_DOTS) {
5358 pp_eat(state, TOK_DOTS);
5359 aident = state->i___VA_ARGS__;
5362 aident = pp_eat(state, TOK_MIDENT)->ident;
5365 narg = xcmalloc(sizeof(*arg), "macro arg");
5366 narg->ident = aident;
5368 /* Verify I don't have a duplicate identifier */
5369 for(arg = args; arg; arg = arg->next) {
5370 if (arg->ident == narg->ident) {
5371 error(state, 0, "Duplicate macro arg `%s'",
5375 /* Add the new argument to the end of the list */
5380 if ((aident == state->i___VA_ARGS__) ||
5381 (pp_peek(state) != TOK_COMMA)) {
5384 pp_eat(state, TOK_COMMA);
5386 pp_eat(state, TOK_RPAREN);
5388 /* Remove leading whitespace */
5389 while(raw_peek(state) == TOK_SPACE) {
5390 raw_eat(state, TOK_SPACE);
5393 /* Remember the start of the macro body */
5394 tok = raw_peek(state);
5395 mend = mstart = get_token(state, 1)->pos;
5397 /* Find the end of the macro */
5398 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5399 raw_eat(state, tok);
5400 /* Remember the end of the last non space token */
5402 if (tok != TOK_SPACE) {
5403 mend = get_token(state, 1)->pos;
5407 /* Now that I have found the body defined the token */
5408 do_define_macro(state, ident,
5409 char_strdup(state->file, mstart, mend, "macro buf"),
5415 const char *start, *end;
5418 pp_eat(state, TOK_MERROR);
5419 /* Find the start of the line */
5421 start = get_token(state, 1)->pos;
5423 /* Find the end of the line */
5424 while((tok = raw_peek(state)) != TOK_EOL) {
5425 raw_eat(state, tok);
5427 end = get_token(state, 1)->pos;
5429 if (!if_eat(state)) {
5430 error(state, 0, "%*.*s", len, len, start);
5436 const char *start, *end;
5439 pp_eat(state, TOK_MWARNING);
5441 /* Find the start of the line */
5443 start = get_token(state, 1)->pos;
5445 /* Find the end of the line */
5446 while((tok = raw_peek(state)) != TOK_EOL) {
5447 raw_eat(state, tok);
5449 end = get_token(state, 1)->pos;
5451 if (!if_eat(state)) {
5452 warning(state, 0, "%*.*s", len, len, start);
5463 pp_eat(state, TOK_MINCLUDE);
5464 if (if_eat(state)) {
5465 /* Find the end of the line */
5466 while((tok = raw_peek(state)) != TOK_EOL) {
5467 raw_eat(state, tok);
5472 if (tok == TOK_LIT_STRING) {
5476 tk = eat(state, TOK_LIT_STRING);
5477 name = xmalloc(tk->str_len, "include");
5478 token = tk->val.str +1;
5479 name_len = tk->str_len -2;
5480 if (*token == '"') {
5484 memcpy(name, token, name_len);
5485 name[name_len] = '\0';
5488 else if (tok == TOK_LESS) {
5489 struct macro_buf buf;
5490 eat(state, TOK_LESS);
5493 buf.str = xmalloc(buf.len, "include");
5497 while((tok != TOK_MORE) &&
5498 (tok != TOK_EOL) && (tok != TOK_EOF))
5501 tk = eat(state, tok);
5502 append_macro_chars(state, "include", &buf,
5503 state->file, tk->pos, state->file->pos);
5506 append_macro_text(state, "include", &buf, "\0", 1);
5507 if (peek(state) != TOK_MORE) {
5508 error(state, 0, "Unterminated include directive");
5510 eat(state, TOK_MORE);
5515 error(state, 0, "Invalid include directive");
5517 /* Error if there are any tokens after the include */
5518 if (pp_peek(state) != TOK_EOL) {
5519 error(state, 0, "garbage after include directive");
5521 if (!if_eat(state)) {
5522 compile_file(state, name, local);
5528 /* Ignore # without a follwing ident */
5532 const char *name1, *name2;
5533 name1 = tokens[tok];
5535 if (tok == TOK_MIDENT) {
5536 name2 = get_token(state, 1)->ident->name;
5538 error(state, 0, "Invalid preprocessor directive: %s %s",
5543 /* Consume the rest of the macro line */
5545 tok = pp_peek(state);
5547 } while((tok != TOK_EOF) && (tok != TOK_EOL));
5548 state->token_base = old_token_base;
5549 state->macro_file = NULL;
5553 /* Type helper functions */
5555 static struct type *new_type(
5556 unsigned int type, struct type *left, struct type *right)
5558 struct type *result;
5559 result = xmalloc(sizeof(*result), "type");
5560 result->type = type;
5561 result->left = left;
5562 result->right = right;
5563 result->field_ident = 0;
5564 result->type_ident = 0;
5565 result->elements = 0;
5569 static struct type *clone_type(unsigned int specifiers, struct type *old)
5571 struct type *result;
5572 result = xmalloc(sizeof(*result), "type");
5573 memcpy(result, old, sizeof(*result));
5574 result->type &= TYPE_MASK;
5575 result->type |= specifiers;
5579 static struct type *dup_type(struct compile_state *state, struct type *orig)
5582 new = xcmalloc(sizeof(*new), "type");
5583 new->type = orig->type;
5584 new->field_ident = orig->field_ident;
5585 new->type_ident = orig->type_ident;
5586 new->elements = orig->elements;
5588 new->left = dup_type(state, orig->left);
5591 new->right = dup_type(state, orig->right);
5597 static struct type *invalid_type(struct compile_state *state, struct type *type)
5599 struct type *invalid, *member;
5602 internal_error(state, 0, "type missing?");
5604 switch(type->type & TYPE_MASK) {
5606 case TYPE_CHAR: case TYPE_UCHAR:
5607 case TYPE_SHORT: case TYPE_USHORT:
5608 case TYPE_INT: case TYPE_UINT:
5609 case TYPE_LONG: case TYPE_ULONG:
5610 case TYPE_LLONG: case TYPE_ULLONG:
5615 invalid = invalid_type(state, type->left);
5618 invalid = invalid_type(state, type->left);
5622 member = type->left;
5623 while(member && (invalid == 0) &&
5624 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5625 invalid = invalid_type(state, member->left);
5626 member = member->right;
5629 invalid = invalid_type(state, member);
5634 member = type->left;
5635 while(member && (invalid == 0) &&
5636 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5637 invalid = invalid_type(state, member->left);
5638 member = member->right;
5641 invalid = invalid_type(state, member);
5652 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5653 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5654 static inline ulong_t mask_uint(ulong_t x)
5656 if (SIZEOF_INT < SIZEOF_LONG) {
5657 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5662 #define MASK_UINT(X) (mask_uint(X))
5663 #define MASK_ULONG(X) (X)
5665 static struct type void_type = { .type = TYPE_VOID };
5666 static struct type char_type = { .type = TYPE_CHAR };
5667 static struct type uchar_type = { .type = TYPE_UCHAR };
5668 #if DEBUG_ROMCC_WARNING
5669 static struct type short_type = { .type = TYPE_SHORT };
5671 static struct type ushort_type = { .type = TYPE_USHORT };
5672 static struct type int_type = { .type = TYPE_INT };
5673 static struct type uint_type = { .type = TYPE_UINT };
5674 static struct type long_type = { .type = TYPE_LONG };
5675 static struct type ulong_type = { .type = TYPE_ULONG };
5676 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5678 static struct type void_ptr_type = {
5679 .type = TYPE_POINTER,
5683 #if DEBUG_ROMCC_WARNING
5684 static struct type void_func_type = {
5685 .type = TYPE_FUNCTION,
5687 .right = &void_type,
5691 static size_t bits_to_bytes(size_t size)
5693 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5696 static struct triple *variable(struct compile_state *state, struct type *type)
5698 struct triple *result;
5699 if ((type->type & STOR_MASK) != STOR_PERM) {
5700 result = triple(state, OP_ADECL, type, 0, 0);
5701 generate_lhs_pieces(state, result);
5704 result = triple(state, OP_SDECL, type, 0, 0);
5709 static void stor_of(FILE *fp, struct type *type)
5711 switch(type->type & STOR_MASK) {
5713 fprintf(fp, "auto ");
5716 fprintf(fp, "static ");
5719 fprintf(fp, "local ");
5722 fprintf(fp, "extern ");
5725 fprintf(fp, "register ");
5728 fprintf(fp, "typedef ");
5730 case STOR_INLINE | STOR_LOCAL:
5731 fprintf(fp, "inline ");
5733 case STOR_INLINE | STOR_STATIC:
5734 fprintf(fp, "static inline");
5736 case STOR_INLINE | STOR_EXTERN:
5737 fprintf(fp, "extern inline");
5740 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5744 static void qual_of(FILE *fp, struct type *type)
5746 if (type->type & QUAL_CONST) {
5747 fprintf(fp, " const");
5749 if (type->type & QUAL_VOLATILE) {
5750 fprintf(fp, " volatile");
5752 if (type->type & QUAL_RESTRICT) {
5753 fprintf(fp, " restrict");
5757 static void name_of(FILE *fp, struct type *type)
5759 unsigned int base_type;
5760 base_type = type->type & TYPE_MASK;
5761 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5766 fprintf(fp, "void");
5770 fprintf(fp, "signed char");
5774 fprintf(fp, "unsigned char");
5778 fprintf(fp, "signed short");
5782 fprintf(fp, "unsigned short");
5786 fprintf(fp, "signed int");
5790 fprintf(fp, "unsigned int");
5794 fprintf(fp, "signed long");
5798 fprintf(fp, "unsigned long");
5802 name_of(fp, type->left);
5807 name_of(fp, type->left);
5809 name_of(fp, type->right);
5812 name_of(fp, type->left);
5814 name_of(fp, type->right);
5817 fprintf(fp, "enum %s",
5818 (type->type_ident)? type->type_ident->name : "");
5822 fprintf(fp, "struct %s { ",
5823 (type->type_ident)? type->type_ident->name : "");
5824 name_of(fp, type->left);
5829 fprintf(fp, "union %s { ",
5830 (type->type_ident)? type->type_ident->name : "");
5831 name_of(fp, type->left);
5836 name_of(fp, type->left);
5837 fprintf(fp, " (*)(");
5838 name_of(fp, type->right);
5842 name_of(fp, type->left);
5843 fprintf(fp, " [%ld]", (long)(type->elements));
5846 fprintf(fp, "tuple { ");
5847 name_of(fp, type->left);
5852 fprintf(fp, "join { ");
5853 name_of(fp, type->left);
5858 name_of(fp, type->left);
5859 fprintf(fp, " : %d ", type->elements);
5863 fprintf(fp, "unknown_t");
5866 fprintf(fp, "????: %x", base_type);
5869 if (type->field_ident && type->field_ident->name) {
5870 fprintf(fp, " .%s", type->field_ident->name);
5874 static size_t align_of(struct compile_state *state, struct type *type)
5878 switch(type->type & TYPE_MASK) {
5887 align = ALIGNOF_CHAR;
5891 align = ALIGNOF_SHORT;
5896 align = ALIGNOF_INT;
5900 align = ALIGNOF_LONG;
5903 align = ALIGNOF_POINTER;
5908 size_t left_align, right_align;
5909 left_align = align_of(state, type->left);
5910 right_align = align_of(state, type->right);
5911 align = (left_align >= right_align) ? left_align : right_align;
5915 align = align_of(state, type->left);
5921 align = align_of(state, type->left);
5924 error(state, 0, "alignof not yet defined for type\n");
5930 static size_t reg_align_of(struct compile_state *state, struct type *type)
5934 switch(type->type & TYPE_MASK) {
5943 align = REG_ALIGNOF_CHAR;
5947 align = REG_ALIGNOF_SHORT;
5952 align = REG_ALIGNOF_INT;
5956 align = REG_ALIGNOF_LONG;
5959 align = REG_ALIGNOF_POINTER;
5964 size_t left_align, right_align;
5965 left_align = reg_align_of(state, type->left);
5966 right_align = reg_align_of(state, type->right);
5967 align = (left_align >= right_align) ? left_align : right_align;
5971 align = reg_align_of(state, type->left);
5977 align = reg_align_of(state, type->left);
5980 error(state, 0, "alignof not yet defined for type\n");
5986 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5988 return bits_to_bytes(align_of(state, type));
5990 static size_t size_of(struct compile_state *state, struct type *type);
5991 static size_t reg_size_of(struct compile_state *state, struct type *type);
5993 static size_t needed_padding(struct compile_state *state,
5994 struct type *type, size_t offset)
5996 size_t padding, align;
5997 align = align_of(state, type);
5998 /* Align to the next machine word if the bitfield does completely
5999 * fit into the current word.
6001 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
6003 size = size_of(state, type);
6004 if ((offset + type->elements)/size != offset/size) {
6009 if (offset % align) {
6010 padding = align - (offset % align);
6015 static size_t reg_needed_padding(struct compile_state *state,
6016 struct type *type, size_t offset)
6018 size_t padding, align;
6019 align = reg_align_of(state, type);
6020 /* Align to the next register word if the bitfield does completely
6021 * fit into the current register.
6023 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6024 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6026 align = REG_SIZEOF_REG;
6029 if (offset % align) {
6030 padding = align - (offset % align);
6035 static size_t size_of(struct compile_state *state, struct type *type)
6039 switch(type->type & TYPE_MASK) {
6044 size = type->elements;
6052 size = SIZEOF_SHORT;
6064 size = SIZEOF_POINTER;
6070 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6071 pad = needed_padding(state, type->left, size);
6072 size = size + pad + size_of(state, type->left);
6075 pad = needed_padding(state, type, size);
6076 size = size + pad + size_of(state, type);
6081 size_t size_left, size_right;
6082 size_left = size_of(state, type->left);
6083 size_right = size_of(state, type->right);
6084 size = (size_left >= size_right)? size_left : size_right;
6088 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6089 internal_error(state, 0, "Invalid array type");
6091 size = size_of(state, type->left) * type->elements;
6098 size = size_of(state, type->left);
6099 /* Pad structures so their size is a multiples of their alignment */
6100 pad = needed_padding(state, type, size);
6108 size = size_of(state, type->left);
6109 /* Pad unions so their size is a multiple of their alignment */
6110 pad = needed_padding(state, type, size);
6115 internal_error(state, 0, "sizeof not yet defined for type");
6121 static size_t reg_size_of(struct compile_state *state, struct type *type)
6125 switch(type->type & TYPE_MASK) {
6130 size = type->elements;
6134 size = REG_SIZEOF_CHAR;
6138 size = REG_SIZEOF_SHORT;
6143 size = REG_SIZEOF_INT;
6147 size = REG_SIZEOF_LONG;
6150 size = REG_SIZEOF_POINTER;
6156 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6157 pad = reg_needed_padding(state, type->left, size);
6158 size = size + pad + reg_size_of(state, type->left);
6161 pad = reg_needed_padding(state, type, size);
6162 size = size + pad + reg_size_of(state, type);
6167 size_t size_left, size_right;
6168 size_left = reg_size_of(state, type->left);
6169 size_right = reg_size_of(state, type->right);
6170 size = (size_left >= size_right)? size_left : size_right;
6174 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6175 internal_error(state, 0, "Invalid array type");
6177 size = reg_size_of(state, type->left) * type->elements;
6184 size = reg_size_of(state, type->left);
6185 /* Pad structures so their size is a multiples of their alignment */
6186 pad = reg_needed_padding(state, type, size);
6194 size = reg_size_of(state, type->left);
6195 /* Pad unions so their size is a multiple of their alignment */
6196 pad = reg_needed_padding(state, type, size);
6201 internal_error(state, 0, "sizeof not yet defined for type");
6207 static size_t registers_of(struct compile_state *state, struct type *type)
6210 registers = reg_size_of(state, type);
6211 registers += REG_SIZEOF_REG - 1;
6212 registers /= REG_SIZEOF_REG;
6216 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6218 return bits_to_bytes(size_of(state, type));
6221 static size_t field_offset(struct compile_state *state,
6222 struct type *type, struct hash_entry *field)
6224 struct type *member;
6229 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6230 member = type->left;
6231 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6232 size += needed_padding(state, member->left, size);
6233 if (member->left->field_ident == field) {
6234 member = member->left;
6237 size += size_of(state, member->left);
6238 member = member->right;
6240 size += needed_padding(state, member, size);
6242 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6243 member = type->left;
6244 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6245 if (member->left->field_ident == field) {
6246 member = member->left;
6249 member = member->right;
6253 internal_error(state, 0, "field_offset only works on structures and unions");
6256 if (!member || (member->field_ident != field)) {
6257 error(state, 0, "member %s not present", field->name);
6262 static size_t field_reg_offset(struct compile_state *state,
6263 struct type *type, struct hash_entry *field)
6265 struct type *member;
6270 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6271 member = type->left;
6272 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6273 size += reg_needed_padding(state, member->left, size);
6274 if (member->left->field_ident == field) {
6275 member = member->left;
6278 size += reg_size_of(state, member->left);
6279 member = member->right;
6282 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6283 member = type->left;
6284 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6285 if (member->left->field_ident == field) {
6286 member = member->left;
6289 member = member->right;
6293 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6296 size += reg_needed_padding(state, member, size);
6297 if (!member || (member->field_ident != field)) {
6298 error(state, 0, "member %s not present", field->name);
6303 static struct type *field_type(struct compile_state *state,
6304 struct type *type, struct hash_entry *field)
6306 struct type *member;
6309 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6310 member = type->left;
6311 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6312 if (member->left->field_ident == field) {
6313 member = member->left;
6316 member = member->right;
6319 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6320 member = type->left;
6321 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6322 if (member->left->field_ident == field) {
6323 member = member->left;
6326 member = member->right;
6330 internal_error(state, 0, "field_type only works on structures and unions");
6333 if (!member || (member->field_ident != field)) {
6334 error(state, 0, "member %s not present", field->name);
6339 static size_t index_offset(struct compile_state *state,
6340 struct type *type, ulong_t index)
6342 struct type *member;
6345 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6346 size = size_of(state, type->left) * index;
6348 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6350 member = type->left;
6352 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6353 size += needed_padding(state, member->left, size);
6355 member = member->left;
6358 size += size_of(state, member->left);
6360 member = member->right;
6362 size += needed_padding(state, member, size);
6364 internal_error(state, 0, "Missing member index: %u", index);
6367 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6370 member = type->left;
6372 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6374 member = member->left;
6378 member = member->right;
6381 internal_error(state, 0, "Missing member index: %u", index);
6385 internal_error(state, 0,
6386 "request for index %u in something not an array, tuple or join",
6392 static size_t index_reg_offset(struct compile_state *state,
6393 struct type *type, ulong_t index)
6395 struct type *member;
6398 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6399 size = reg_size_of(state, type->left) * index;
6401 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6403 member = type->left;
6405 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6406 size += reg_needed_padding(state, member->left, size);
6408 member = member->left;
6411 size += reg_size_of(state, member->left);
6413 member = member->right;
6415 size += reg_needed_padding(state, member, size);
6417 internal_error(state, 0, "Missing member index: %u", index);
6421 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6424 member = type->left;
6426 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6428 member = member->left;
6432 member = member->right;
6435 internal_error(state, 0, "Missing member index: %u", index);
6439 internal_error(state, 0,
6440 "request for index %u in something not an array, tuple or join",
6446 static struct type *index_type(struct compile_state *state,
6447 struct type *type, ulong_t index)
6449 struct type *member;
6450 if (index >= type->elements) {
6451 internal_error(state, 0, "Invalid element %u requested", index);
6453 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6454 member = type->left;
6456 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6458 member = type->left;
6460 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6462 member = member->left;
6466 member = member->right;
6469 internal_error(state, 0, "Missing member index: %u", index);
6472 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6474 member = type->left;
6476 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6478 member = member->left;
6482 member = member->right;
6485 internal_error(state, 0, "Missing member index: %u", index);
6490 internal_error(state, 0,
6491 "request for index %u in something not an array, tuple or join",
6497 static struct type *unpack_type(struct compile_state *state, struct type *type)
6499 /* If I have a single register compound type not a bit-field
6500 * find the real type.
6502 struct type *start_type;
6504 /* Get out early if I need multiple registers for this type */
6505 size = reg_size_of(state, type);
6506 if (size > REG_SIZEOF_REG) {
6509 /* Get out early if I don't need any registers for this type */
6513 /* Loop until I have no more layers I can remove */
6516 switch(type->type & TYPE_MASK) {
6518 /* If I have a single element the unpacked type
6521 if (type->elements == 1) {
6527 /* If I have a single element the unpacked type
6530 if (type->elements == 1) {
6533 /* If I have multiple elements the unpacked
6534 * type is the non-void element.
6537 struct type *next, *member;
6538 struct type *sub_type;
6544 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6545 next = member->right;
6546 member = member->left;
6548 if (reg_size_of(state, member) > 0) {
6550 internal_error(state, 0, "true compound type in a register");
6563 /* If I have a single element the unpacked type
6566 if (type->elements == 1) {
6569 /* I can't in general unpack union types */
6572 /* If I'm not a compound type I can't unpack it */
6575 } while(start_type != type);
6576 switch(type->type & TYPE_MASK) {
6580 internal_error(state, 0, "irredicible type?");
6586 static int equiv_types(struct type *left, struct type *right);
6587 static int is_compound_type(struct type *type);
6589 static struct type *reg_type(
6590 struct compile_state *state, struct type *type, int reg_offset)
6592 struct type *member;
6595 struct type *invalid;
6596 invalid = invalid_type(state, type);
6598 fprintf(state->errout, "type: ");
6599 name_of(state->errout, type);
6600 fprintf(state->errout, "\n");
6601 fprintf(state->errout, "invalid: ");
6602 name_of(state->errout, invalid);
6603 fprintf(state->errout, "\n");
6604 internal_error(state, 0, "bad input type?");
6608 size = reg_size_of(state, type);
6609 if (reg_offset > size) {
6611 fprintf(state->errout, "type: ");
6612 name_of(state->errout, type);
6613 fprintf(state->errout, "\n");
6614 internal_error(state, 0, "offset outside of type");
6617 switch(type->type & TYPE_MASK) {
6618 /* Don't do anything with the basic types */
6620 case TYPE_CHAR: case TYPE_UCHAR:
6621 case TYPE_SHORT: case TYPE_USHORT:
6622 case TYPE_INT: case TYPE_UINT:
6623 case TYPE_LONG: case TYPE_ULONG:
6624 case TYPE_LLONG: case TYPE_ULLONG:
6625 case TYPE_FLOAT: case TYPE_DOUBLE:
6633 member = type->left;
6634 size = reg_size_of(state, member);
6635 if (size > REG_SIZEOF_REG) {
6636 member = reg_type(state, member, reg_offset % size);
6644 member = type->left;
6645 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6646 size = reg_size_of(state, member->left);
6647 offset += reg_needed_padding(state, member->left, offset);
6648 if ((offset + size) > reg_offset) {
6649 member = member->left;
6653 member = member->right;
6655 offset += reg_needed_padding(state, member, offset);
6656 member = reg_type(state, member, reg_offset - offset);
6662 struct type *join, **jnext, *mnext;
6663 join = new_type(TYPE_JOIN, 0, 0);
6664 jnext = &join->left;
6670 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6671 mnext = member->right;
6672 member = member->left;
6674 size = reg_size_of(state, member);
6675 if (size > reg_offset) {
6676 struct type *part, *hunt;
6677 part = reg_type(state, member, reg_offset);
6678 /* See if this type is already in the union */
6681 struct type *test = hunt;
6683 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6687 if (equiv_types(part, test)) {
6695 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6696 jnext = &(*jnext)->right;
6703 if (join->elements == 0) {
6704 internal_error(state, 0, "No elements?");
6711 fprintf(state->errout, "type: ");
6712 name_of(state->errout, type);
6713 fprintf(state->errout, "\n");
6714 internal_error(state, 0, "reg_type not yet defined for type");
6718 /* If I have a single register compound type not a bit-field
6719 * find the real type.
6721 member = unpack_type(state, member);
6723 size = reg_size_of(state, member);
6724 if (size > REG_SIZEOF_REG) {
6725 internal_error(state, 0, "Cannot find type of single register");
6728 invalid = invalid_type(state, member);
6730 fprintf(state->errout, "type: ");
6731 name_of(state->errout, member);
6732 fprintf(state->errout, "\n");
6733 fprintf(state->errout, "invalid: ");
6734 name_of(state->errout, invalid);
6735 fprintf(state->errout, "\n");
6736 internal_error(state, 0, "returning bad type?");
6742 static struct type *next_field(struct compile_state *state,
6743 struct type *type, struct type *prev_member)
6745 struct type *member;
6746 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6747 internal_error(state, 0, "next_field only works on structures");
6749 member = type->left;
6750 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6752 member = member->left;
6755 if (member->left == prev_member) {
6758 member = member->right;
6760 if (member == prev_member) {
6764 internal_error(state, 0, "prev_member %s not present",
6765 prev_member->field_ident->name);
6770 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6771 size_t ret_offset, size_t mem_offset, void *arg);
6773 static void walk_type_fields(struct compile_state *state,
6774 struct type *type, size_t reg_offset, size_t mem_offset,
6775 walk_type_fields_cb_t cb, void *arg);
6777 static void walk_struct_fields(struct compile_state *state,
6778 struct type *type, size_t reg_offset, size_t mem_offset,
6779 walk_type_fields_cb_t cb, void *arg)
6783 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6784 internal_error(state, 0, "walk_struct_fields only works on structures");
6787 for(i = 0; i < type->elements; i++) {
6790 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6791 mtype = mtype->left;
6793 walk_type_fields(state, mtype,
6795 field_reg_offset(state, type, mtype->field_ident),
6797 field_offset(state, type, mtype->field_ident),
6804 static void walk_type_fields(struct compile_state *state,
6805 struct type *type, size_t reg_offset, size_t mem_offset,
6806 walk_type_fields_cb_t cb, void *arg)
6808 switch(type->type & TYPE_MASK) {
6810 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6820 cb(state, type, reg_offset, mem_offset, arg);
6825 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6829 static void arrays_complete(struct compile_state *state, struct type *type)
6831 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6832 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6833 error(state, 0, "array size not specified");
6835 arrays_complete(state, type->left);
6839 static unsigned int get_basic_type(struct type *type)
6842 basic = type->type & TYPE_MASK;
6843 /* Convert enums to ints */
6844 if (basic == TYPE_ENUM) {
6847 /* Convert bitfields to standard types */
6848 else if (basic == TYPE_BITFIELD) {
6849 if (type->elements <= SIZEOF_CHAR) {
6852 else if (type->elements <= SIZEOF_SHORT) {
6855 else if (type->elements <= SIZEOF_INT) {
6858 else if (type->elements <= SIZEOF_LONG) {
6861 if (!TYPE_SIGNED(type->left->type)) {
6868 static unsigned int do_integral_promotion(unsigned int type)
6870 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6876 static unsigned int do_arithmetic_conversion(
6877 unsigned int left, unsigned int right)
6879 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6880 return TYPE_LDOUBLE;
6882 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6885 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6888 left = do_integral_promotion(left);
6889 right = do_integral_promotion(right);
6890 /* If both operands have the same size done */
6891 if (left == right) {
6894 /* If both operands have the same signedness pick the larger */
6895 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6896 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6898 /* If the signed type can hold everything use it */
6899 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6902 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6905 /* Convert to the unsigned type with the same rank as the signed type */
6906 else if (TYPE_SIGNED(left)) {
6907 return TYPE_MKUNSIGNED(left);
6910 return TYPE_MKUNSIGNED(right);
6914 /* see if two types are the same except for qualifiers */
6915 static int equiv_types(struct type *left, struct type *right)
6918 /* Error if the basic types do not match */
6919 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6922 type = left->type & TYPE_MASK;
6923 /* If the basic types match and it is a void type we are done */
6924 if (type == TYPE_VOID) {
6927 /* For bitfields we need to compare the sizes */
6928 else if (type == TYPE_BITFIELD) {
6929 return (left->elements == right->elements) &&
6930 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6932 /* if the basic types match and it is an arithmetic type we are done */
6933 else if (TYPE_ARITHMETIC(type)) {
6936 /* If it is a pointer type recurse and keep testing */
6937 else if (type == TYPE_POINTER) {
6938 return equiv_types(left->left, right->left);
6940 else if (type == TYPE_ARRAY) {
6941 return (left->elements == right->elements) &&
6942 equiv_types(left->left, right->left);
6944 /* test for struct equality */
6945 else if (type == TYPE_STRUCT) {
6946 return left->type_ident == right->type_ident;
6948 /* test for union equality */
6949 else if (type == TYPE_UNION) {
6950 return left->type_ident == right->type_ident;
6952 /* Test for equivalent functions */
6953 else if (type == TYPE_FUNCTION) {
6954 return equiv_types(left->left, right->left) &&
6955 equiv_types(left->right, right->right);
6957 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6958 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6959 else if (type == TYPE_PRODUCT) {
6960 return equiv_types(left->left, right->left) &&
6961 equiv_types(left->right, right->right);
6963 /* We should see TYPE_OVERLAP when comparing joins */
6964 else if (type == TYPE_OVERLAP) {
6965 return equiv_types(left->left, right->left) &&
6966 equiv_types(left->right, right->right);
6968 /* Test for equivalence of tuples */
6969 else if (type == TYPE_TUPLE) {
6970 return (left->elements == right->elements) &&
6971 equiv_types(left->left, right->left);
6973 /* Test for equivalence of joins */
6974 else if (type == TYPE_JOIN) {
6975 return (left->elements == right->elements) &&
6976 equiv_types(left->left, right->left);
6983 static int equiv_ptrs(struct type *left, struct type *right)
6985 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6986 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6989 return equiv_types(left->left, right->left);
6992 static struct type *compatible_types(struct type *left, struct type *right)
6994 struct type *result;
6995 unsigned int type, qual_type;
6996 /* Error if the basic types do not match */
6997 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7000 type = left->type & TYPE_MASK;
7001 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7003 /* if the basic types match and it is an arithmetic type we are done */
7004 if (TYPE_ARITHMETIC(type)) {
7005 result = new_type(qual_type, 0, 0);
7007 /* If it is a pointer type recurse and keep testing */
7008 else if (type == TYPE_POINTER) {
7009 result = compatible_types(left->left, right->left);
7011 result = new_type(qual_type, result, 0);
7014 /* test for struct equality */
7015 else if (type == TYPE_STRUCT) {
7016 if (left->type_ident == right->type_ident) {
7020 /* test for union equality */
7021 else if (type == TYPE_UNION) {
7022 if (left->type_ident == right->type_ident) {
7026 /* Test for equivalent functions */
7027 else if (type == TYPE_FUNCTION) {
7028 struct type *lf, *rf;
7029 lf = compatible_types(left->left, right->left);
7030 rf = compatible_types(left->right, right->right);
7032 result = new_type(qual_type, lf, rf);
7035 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7036 else if (type == TYPE_PRODUCT) {
7037 struct type *lf, *rf;
7038 lf = compatible_types(left->left, right->left);
7039 rf = compatible_types(left->right, right->right);
7041 result = new_type(qual_type, lf, rf);
7045 /* Nothing else is compatible */
7050 /* See if left is a equivalent to right or right is a union member of left */
7051 static int is_subset_type(struct type *left, struct type *right)
7053 if (equiv_types(left, right)) {
7056 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7057 struct type *member, *mnext;
7062 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7063 mnext = member->right;
7064 member = member->left;
7066 if (is_subset_type( member, right)) {
7074 static struct type *compatible_ptrs(struct type *left, struct type *right)
7076 struct type *result;
7077 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7078 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7081 result = compatible_types(left->left, right->left);
7083 unsigned int qual_type;
7084 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7085 result = new_type(qual_type, result, 0);
7090 static struct triple *integral_promotion(
7091 struct compile_state *state, struct triple *def)
7095 /* As all operations are carried out in registers
7096 * the values are converted on load I just convert
7097 * logical type of the operand.
7099 if (TYPE_INTEGER(type->type)) {
7100 unsigned int int_type;
7101 int_type = type->type & ~TYPE_MASK;
7102 int_type |= do_integral_promotion(get_basic_type(type));
7103 if (int_type != type->type) {
7104 if (def->op != OP_LOAD) {
7105 def->type = new_type(int_type, 0, 0);
7108 def = triple(state, OP_CONVERT,
7109 new_type(int_type, 0, 0), def, 0);
7117 static void arithmetic(struct compile_state *state, struct triple *def)
7119 if (!TYPE_ARITHMETIC(def->type->type)) {
7120 error(state, 0, "arithmetic type expexted");
7124 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7126 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7127 error(state, def, "pointer or arithmetic type expected");
7131 static int is_integral(struct triple *ins)
7133 return TYPE_INTEGER(ins->type->type);
7136 static void integral(struct compile_state *state, struct triple *def)
7138 if (!is_integral(def)) {
7139 error(state, 0, "integral type expected");
7144 static void bool(struct compile_state *state, struct triple *def)
7146 if (!TYPE_ARITHMETIC(def->type->type) &&
7147 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7148 error(state, 0, "arithmetic or pointer type expected");
7152 static int is_signed(struct type *type)
7154 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7157 return !!TYPE_SIGNED(type->type);
7159 static int is_compound_type(struct type *type)
7162 switch((type->type & TYPE_MASK)) {
7177 /* Is this value located in a register otherwise it must be in memory */
7178 static int is_in_reg(struct compile_state *state, struct triple *def)
7181 if (def->op == OP_ADECL) {
7184 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7187 else if (triple_is_part(state, def)) {
7188 in_reg = is_in_reg(state, MISC(def, 0));
7191 internal_error(state, def, "unknown expr storage location");
7197 /* Is this an auto or static variable location? Something that can
7198 * be assigned to. Otherwise it must must be a pure value, a temporary.
7200 static int is_lvalue(struct compile_state *state, struct triple *def)
7207 if ((def->op == OP_ADECL) ||
7208 (def->op == OP_SDECL) ||
7209 (def->op == OP_DEREF) ||
7210 (def->op == OP_BLOBCONST) ||
7211 (def->op == OP_LIST)) {
7214 else if (triple_is_part(state, def)) {
7215 ret = is_lvalue(state, MISC(def, 0));
7220 static void clvalue(struct compile_state *state, struct triple *def)
7223 internal_error(state, def, "nothing where lvalue expected?");
7225 if (!is_lvalue(state, def)) {
7226 error(state, def, "lvalue expected");
7229 static void lvalue(struct compile_state *state, struct triple *def)
7231 clvalue(state, def);
7232 if (def->type->type & QUAL_CONST) {
7233 error(state, def, "modifable lvalue expected");
7237 static int is_pointer(struct triple *def)
7239 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7242 static void pointer(struct compile_state *state, struct triple *def)
7244 if (!is_pointer(def)) {
7245 error(state, def, "pointer expected");
7249 static struct triple *int_const(
7250 struct compile_state *state, struct type *type, ulong_t value)
7252 struct triple *result;
7253 switch(type->type & TYPE_MASK) {
7255 case TYPE_INT: case TYPE_UINT:
7256 case TYPE_LONG: case TYPE_ULONG:
7259 internal_error(state, 0, "constant for unknown type");
7261 result = triple(state, OP_INTCONST, type, 0, 0);
7262 result->u.cval = value;
7267 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7269 static struct triple *do_mk_addr_expr(struct compile_state *state,
7270 struct triple *expr, struct type *type, ulong_t offset)
7272 struct triple *result;
7273 struct type *ptr_type;
7274 clvalue(state, expr);
7276 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7280 if (expr->op == OP_ADECL) {
7281 error(state, expr, "address of auto variables not supported");
7283 else if (expr->op == OP_SDECL) {
7284 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7285 MISC(result, 0) = expr;
7286 result->u.cval = offset;
7288 else if (expr->op == OP_DEREF) {
7289 result = triple(state, OP_ADD, ptr_type,
7291 int_const(state, &ulong_type, offset));
7293 else if (expr->op == OP_BLOBCONST) {
7295 internal_error(state, expr, "not yet implemented");
7297 else if (expr->op == OP_LIST) {
7298 error(state, 0, "Function addresses not supported");
7300 else if (triple_is_part(state, expr)) {
7301 struct triple *part;
7303 expr = MISC(expr, 0);
7304 if (part->op == OP_DOT) {
7305 offset += bits_to_bytes(
7306 field_offset(state, expr->type, part->u.field));
7308 else if (part->op == OP_INDEX) {
7309 offset += bits_to_bytes(
7310 index_offset(state, expr->type, part->u.cval));
7313 internal_error(state, part, "unhandled part type");
7315 result = do_mk_addr_expr(state, expr, type, offset);
7318 internal_error(state, expr, "cannot take address of expression");
7323 static struct triple *mk_addr_expr(
7324 struct compile_state *state, struct triple *expr, ulong_t offset)
7326 return do_mk_addr_expr(state, expr, expr->type, offset);
7329 static struct triple *mk_deref_expr(
7330 struct compile_state *state, struct triple *expr)
7332 struct type *base_type;
7333 pointer(state, expr);
7334 base_type = expr->type->left;
7335 return triple(state, OP_DEREF, base_type, expr, 0);
7338 /* lvalue conversions always apply except when certain operators
7339 * are applied. So I apply apply it when I know no more
7340 * operators will be applied.
7342 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7344 /* Tranform an array to a pointer to the first element */
7345 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7348 TYPE_POINTER | (def->type->type & QUAL_MASK),
7349 def->type->left, 0);
7350 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7351 struct triple *addrconst;
7352 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7353 internal_error(state, def, "bad array constant");
7355 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7356 MISC(addrconst, 0) = def;
7360 def = triple(state, OP_CONVERT, type, def, 0);
7363 /* Transform a function to a pointer to it */
7364 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7365 def = mk_addr_expr(state, def, 0);
7370 static struct triple *deref_field(
7371 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7373 struct triple *result;
7374 struct type *type, *member;
7377 internal_error(state, 0, "No field passed to deref_field");
7381 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7382 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7383 error(state, 0, "request for member %s in something not a struct or union",
7386 member = field_type(state, type, field);
7387 if ((type->type & STOR_MASK) == STOR_PERM) {
7388 /* Do the pointer arithmetic to get a deref the field */
7389 offset = bits_to_bytes(field_offset(state, type, field));
7390 result = do_mk_addr_expr(state, expr, member, offset);
7391 result = mk_deref_expr(state, result);
7394 /* Find the variable for the field I want. */
7395 result = triple(state, OP_DOT, member, expr, 0);
7396 result->u.field = field;
7401 static struct triple *deref_index(
7402 struct compile_state *state, struct triple *expr, size_t index)
7404 struct triple *result;
7405 struct type *type, *member;
7410 member = index_type(state, type, index);
7412 if ((type->type & STOR_MASK) == STOR_PERM) {
7413 offset = bits_to_bytes(index_offset(state, type, index));
7414 result = do_mk_addr_expr(state, expr, member, offset);
7415 result = mk_deref_expr(state, result);
7418 result = triple(state, OP_INDEX, member, expr, 0);
7419 result->u.cval = index;
7424 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7430 #if DEBUG_ROMCC_WARNINGS
7431 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7433 /* Transform lvalues into something we can read */
7434 def = lvalue_conversion(state, def);
7435 if (!is_lvalue(state, def)) {
7438 if (is_in_reg(state, def)) {
7441 if (def->op == OP_SDECL) {
7442 def = mk_addr_expr(state, def, 0);
7443 def = mk_deref_expr(state, def);
7447 def = triple(state, op, def->type, def, 0);
7448 if (def->type->type & QUAL_VOLATILE) {
7449 def->id |= TRIPLE_FLAG_VOLATILE;
7454 int is_write_compatible(struct compile_state *state,
7455 struct type *dest, struct type *rval)
7458 /* Both operands have arithmetic type */
7459 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7462 /* One operand is a pointer and the other is a pointer to void */
7463 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7464 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7465 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7466 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7469 /* If both types are the same without qualifiers we are good */
7470 else if (equiv_ptrs(dest, rval)) {
7473 /* test for struct/union equality */
7474 else if (equiv_types(dest, rval)) {
7480 static void write_compatible(struct compile_state *state,
7481 struct type *dest, struct type *rval)
7483 if (!is_write_compatible(state, dest, rval)) {
7484 FILE *fp = state->errout;
7485 fprintf(fp, "dest: ");
7487 fprintf(fp,"\nrval: ");
7490 error(state, 0, "Incompatible types in assignment");
7494 static int is_init_compatible(struct compile_state *state,
7495 struct type *dest, struct type *rval)
7498 if (is_write_compatible(state, dest, rval)) {
7501 else if (equiv_types(dest, rval)) {
7507 static struct triple *write_expr(
7508 struct compile_state *state, struct triple *dest, struct triple *rval)
7515 internal_error(state, 0, "missing rval");
7518 if (rval->op == OP_LIST) {
7519 internal_error(state, 0, "expression of type OP_LIST?");
7521 if (!is_lvalue(state, dest)) {
7522 internal_error(state, 0, "writing to a non lvalue?");
7524 if (dest->type->type & QUAL_CONST) {
7525 internal_error(state, 0, "modifable lvalue expexted");
7528 write_compatible(state, dest->type, rval->type);
7529 if (!equiv_types(dest->type, rval->type)) {
7530 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7533 /* Now figure out which assignment operator to use */
7535 if (is_in_reg(state, dest)) {
7536 def = triple(state, OP_WRITE, dest->type, rval, dest);
7537 if (MISC(def, 0) != dest) {
7538 internal_error(state, def, "huh?");
7540 if (RHS(def, 0) != rval) {
7541 internal_error(state, def, "huh?");
7544 def = triple(state, OP_STORE, dest->type, dest, rval);
7546 if (def->type->type & QUAL_VOLATILE) {
7547 def->id |= TRIPLE_FLAG_VOLATILE;
7552 static struct triple *init_expr(
7553 struct compile_state *state, struct triple *dest, struct triple *rval)
7559 internal_error(state, 0, "missing rval");
7561 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7562 rval = read_expr(state, rval);
7563 def = write_expr(state, dest, rval);
7566 /* Fill in the array size if necessary */
7567 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7568 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7569 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7570 dest->type->elements = rval->type->elements;
7573 if (!equiv_types(dest->type, rval->type)) {
7574 error(state, 0, "Incompatible types in inializer");
7576 MISC(dest, 0) = rval;
7577 insert_triple(state, dest, rval);
7578 rval->id |= TRIPLE_FLAG_FLATTENED;
7579 use_triple(MISC(dest, 0), dest);
7584 struct type *arithmetic_result(
7585 struct compile_state *state, struct triple *left, struct triple *right)
7588 /* Sanity checks to ensure I am working with arithmetic types */
7589 arithmetic(state, left);
7590 arithmetic(state, right);
7592 do_arithmetic_conversion(
7593 get_basic_type(left->type),
7594 get_basic_type(right->type)),
7599 struct type *ptr_arithmetic_result(
7600 struct compile_state *state, struct triple *left, struct triple *right)
7603 /* Sanity checks to ensure I am working with the proper types */
7604 ptr_arithmetic(state, left);
7605 arithmetic(state, right);
7606 if (TYPE_ARITHMETIC(left->type->type) &&
7607 TYPE_ARITHMETIC(right->type->type)) {
7608 type = arithmetic_result(state, left, right);
7610 else if (TYPE_PTR(left->type->type)) {
7614 internal_error(state, 0, "huh?");
7620 /* boolean helper function */
7622 static struct triple *ltrue_expr(struct compile_state *state,
7623 struct triple *expr)
7626 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7627 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7628 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7629 /* If the expression is already boolean do nothing */
7632 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7638 static struct triple *lfalse_expr(struct compile_state *state,
7639 struct triple *expr)
7641 return triple(state, OP_LFALSE, &int_type, expr, 0);
7644 static struct triple *mkland_expr(
7645 struct compile_state *state,
7646 struct triple *left, struct triple *right)
7648 struct triple *def, *val, *var, *jmp, *mid, *end;
7649 struct triple *lstore, *rstore;
7651 /* Generate some intermediate triples */
7653 var = variable(state, &int_type);
7655 /* Store the left hand side value */
7656 lstore = write_expr(state, var, left);
7658 /* Jump if the value is false */
7659 jmp = branch(state, end,
7660 lfalse_expr(state, read_expr(state, var)));
7663 /* Store the right hand side value */
7664 rstore = write_expr(state, var, right);
7666 /* An expression for the computed value */
7667 val = read_expr(state, var);
7669 /* Generate the prog for a logical and */
7670 def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0UL);
7675 static struct triple *mklor_expr(
7676 struct compile_state *state,
7677 struct triple *left, struct triple *right)
7679 struct triple *def, *val, *var, *jmp, *mid, *end;
7681 /* Generate some intermediate triples */
7683 var = variable(state, &int_type);
7685 /* Store the left hand side value */
7686 left = write_expr(state, var, left);
7688 /* Jump if the value is true */
7689 jmp = branch(state, end, read_expr(state, var));
7692 /* Store the right hand side value */
7693 right = write_expr(state, var, right);
7695 /* An expression for the computed value*/
7696 val = read_expr(state, var);
7698 /* Generate the prog for a logical or */
7699 def = mkprog(state, var, left, jmp, mid, right, end, val, 0UL);
7704 static struct triple *mkcond_expr(
7705 struct compile_state *state,
7706 struct triple *test, struct triple *left, struct triple *right)
7708 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7709 struct type *result_type;
7710 unsigned int left_type, right_type;
7712 left_type = left->type->type;
7713 right_type = right->type->type;
7715 /* Both operands have arithmetic type */
7716 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7717 result_type = arithmetic_result(state, left, right);
7719 /* Both operands have void type */
7720 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7721 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7722 result_type = &void_type;
7724 /* pointers to the same type... */
7725 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7728 /* Both operands are pointers and left is a pointer to void */
7729 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7730 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7731 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7732 result_type = right->type;
7734 /* Both operands are pointers and right is a pointer to void */
7735 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7736 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7737 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7738 result_type = left->type;
7741 error(state, 0, "Incompatible types in conditional expression");
7743 /* Generate some intermediate triples */
7746 var = variable(state, result_type);
7748 /* Branch if the test is false */
7749 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7752 /* Store the left hand side value */
7753 left = write_expr(state, var, left);
7755 /* Branch to the end */
7756 jmp2 = branch(state, end, 0);
7758 /* Store the right hand side value */
7759 right = write_expr(state, var, right);
7761 /* An expression for the computed value */
7762 val = read_expr(state, var);
7764 /* Generate the prog for a conditional expression */
7765 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0UL);
7771 static int expr_depth(struct compile_state *state, struct triple *ins)
7773 #if DEBUG_ROMCC_WARNINGS
7774 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7778 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7781 else if (ins->op == OP_DEREF) {
7782 count = expr_depth(state, RHS(ins, 0)) - 1;
7784 else if (ins->op == OP_VAL) {
7785 count = expr_depth(state, RHS(ins, 0)) - 1;
7787 else if (ins->op == OP_FCALL) {
7788 /* Don't figure the depth of a call just guess it is huge */
7792 struct triple **expr;
7793 expr = triple_rhs(state, ins, 0);
7794 for(;expr; expr = triple_rhs(state, ins, expr)) {
7797 depth = expr_depth(state, *expr);
7798 if (depth > count) {
7807 static struct triple *flatten_generic(
7808 struct compile_state *state, struct triple *first, struct triple *ptr,
7813 struct triple **ins;
7816 /* Only operations with just a rhs and a lhs should come here */
7819 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7820 internal_error(state, ptr, "unexpected args for: %d %s",
7821 ptr->op, tops(ptr->op));
7823 /* Find the depth of the rhs elements */
7824 for(i = 0; i < rhs; i++) {
7825 vector[i].ins = &RHS(ptr, i);
7826 vector[i].depth = expr_depth(state, *vector[i].ins);
7828 /* Selection sort the rhs */
7829 for(i = 0; i < rhs; i++) {
7831 for(j = i + 1; j < rhs; j++ ) {
7832 if (vector[j].depth > vector[max].depth) {
7837 struct rhs_vector tmp;
7839 vector[i] = vector[max];
7843 /* Now flatten the rhs elements */
7844 for(i = 0; i < rhs; i++) {
7845 *vector[i].ins = flatten(state, first, *vector[i].ins);
7846 use_triple(*vector[i].ins, ptr);
7849 insert_triple(state, first, ptr);
7850 ptr->id |= TRIPLE_FLAG_FLATTENED;
7851 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7853 /* Now flatten the lhs elements */
7854 for(i = 0; i < lhs; i++) {
7855 struct triple **ins = &LHS(ptr, i);
7856 *ins = flatten(state, first, *ins);
7857 use_triple(*ins, ptr);
7863 static struct triple *flatten_prog(
7864 struct compile_state *state, struct triple *first, struct triple *ptr)
7866 struct triple *head, *body, *val;
7871 release_triple(state, head);
7872 release_triple(state, ptr);
7874 body->prev = first->prev;
7875 body->prev->next = body;
7876 val->next->prev = val;
7878 if (triple_is_cbranch(state, body->prev) ||
7879 triple_is_call(state, body->prev)) {
7880 unuse_triple(first, body->prev);
7881 use_triple(body, body->prev);
7884 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7885 internal_error(state, val, "val not flattened?");
7892 static struct triple *flatten_part(
7893 struct compile_state *state, struct triple *first, struct triple *ptr)
7895 if (!triple_is_part(state, ptr)) {
7896 internal_error(state, ptr, "not a part");
7898 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7899 internal_error(state, ptr, "unexpected args for: %d %s",
7900 ptr->op, tops(ptr->op));
7902 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7903 use_triple(MISC(ptr, 0), ptr);
7904 return flatten_generic(state, first, ptr, 1);
7907 static struct triple *flatten(
7908 struct compile_state *state, struct triple *first, struct triple *ptr)
7910 struct triple *orig_ptr;
7915 /* Only flatten triples once */
7916 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7921 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7922 return MISC(ptr, 0);
7925 ptr = flatten_prog(state, first, ptr);
7928 ptr = flatten_generic(state, first, ptr, 1);
7929 insert_triple(state, first, ptr);
7930 ptr->id |= TRIPLE_FLAG_FLATTENED;
7931 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7932 if (ptr->next != ptr) {
7933 use_triple(ptr->next, ptr);
7938 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7939 use_triple(RHS(ptr, 0), ptr);
7942 ptr = flatten_generic(state, first, ptr, 1);
7943 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7944 use_triple(MISC(ptr, 0), ptr);
7947 use_triple(TARG(ptr, 0), ptr);
7950 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7951 use_triple(RHS(ptr, 0), ptr);
7952 use_triple(TARG(ptr, 0), ptr);
7953 insert_triple(state, first, ptr);
7954 ptr->id |= TRIPLE_FLAG_FLATTENED;
7955 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7956 if (ptr->next != ptr) {
7957 use_triple(ptr->next, ptr);
7961 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7962 use_triple(MISC(ptr, 0), ptr);
7963 use_triple(TARG(ptr, 0), ptr);
7964 insert_triple(state, first, ptr);
7965 ptr->id |= TRIPLE_FLAG_FLATTENED;
7966 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7967 if (ptr->next != ptr) {
7968 use_triple(ptr->next, ptr);
7972 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7973 use_triple(RHS(ptr, 0), ptr);
7976 insert_triple(state, state->global_pool, ptr);
7977 ptr->id |= TRIPLE_FLAG_FLATTENED;
7978 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7979 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7980 use_triple(MISC(ptr, 0), ptr);
7983 /* Since OP_DEREF is just a marker delete it when I flatten it */
7985 RHS(orig_ptr, 0) = 0;
7986 free_triple(state, orig_ptr);
7989 if (RHS(ptr, 0)->op == OP_DEREF) {
7990 struct triple *base, *left;
7992 base = MISC(ptr, 0);
7993 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7994 left = RHS(base, 0);
7995 ptr = triple(state, OP_ADD, left->type,
7996 read_expr(state, left),
7997 int_const(state, &ulong_type, offset));
7998 free_triple(state, base);
8001 ptr = flatten_part(state, first, ptr);
8005 if (RHS(ptr, 0)->op == OP_DEREF) {
8006 struct triple *base, *left;
8008 base = MISC(ptr, 0);
8009 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8010 left = RHS(base, 0);
8011 ptr = triple(state, OP_ADD, left->type,
8012 read_expr(state, left),
8013 int_const(state, &long_type, offset));
8014 free_triple(state, base);
8017 ptr = flatten_part(state, first, ptr);
8021 ptr = flatten_part(state, first, ptr);
8022 use_triple(ptr, MISC(ptr, 0));
8025 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8026 use_triple(MISC(ptr, 0), ptr);
8029 first = state->global_pool;
8030 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8031 use_triple(MISC(ptr, 0), ptr);
8032 insert_triple(state, first, ptr);
8033 ptr->id |= TRIPLE_FLAG_FLATTENED;
8034 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8037 ptr = flatten_generic(state, first, ptr, 0);
8040 /* Flatten the easy cases we don't override */
8041 ptr = flatten_generic(state, first, ptr, 0);
8044 } while(ptr && (ptr != orig_ptr));
8045 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8046 insert_triple(state, first, ptr);
8047 ptr->id |= TRIPLE_FLAG_FLATTENED;
8048 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8053 static void release_expr(struct compile_state *state, struct triple *expr)
8055 struct triple *head;
8056 head = label(state);
8057 flatten(state, head, expr);
8058 while(head->next != head) {
8059 release_triple(state, head->next);
8061 free_triple(state, head);
8064 static int replace_rhs_use(struct compile_state *state,
8065 struct triple *orig, struct triple *new, struct triple *use)
8067 struct triple **expr;
8070 expr = triple_rhs(state, use, 0);
8071 for(;expr; expr = triple_rhs(state, use, expr)) {
8072 if (*expr == orig) {
8078 unuse_triple(orig, use);
8079 use_triple(new, use);
8084 static int replace_lhs_use(struct compile_state *state,
8085 struct triple *orig, struct triple *new, struct triple *use)
8087 struct triple **expr;
8090 expr = triple_lhs(state, use, 0);
8091 for(;expr; expr = triple_lhs(state, use, expr)) {
8092 if (*expr == orig) {
8098 unuse_triple(orig, use);
8099 use_triple(new, use);
8104 static int replace_misc_use(struct compile_state *state,
8105 struct triple *orig, struct triple *new, struct triple *use)
8107 struct triple **expr;
8110 expr = triple_misc(state, use, 0);
8111 for(;expr; expr = triple_misc(state, use, expr)) {
8112 if (*expr == orig) {
8118 unuse_triple(orig, use);
8119 use_triple(new, use);
8124 static int replace_targ_use(struct compile_state *state,
8125 struct triple *orig, struct triple *new, struct triple *use)
8127 struct triple **expr;
8130 expr = triple_targ(state, use, 0);
8131 for(;expr; expr = triple_targ(state, use, expr)) {
8132 if (*expr == orig) {
8138 unuse_triple(orig, use);
8139 use_triple(new, use);
8144 static void replace_use(struct compile_state *state,
8145 struct triple *orig, struct triple *new, struct triple *use)
8149 found |= replace_rhs_use(state, orig, new, use);
8150 found |= replace_lhs_use(state, orig, new, use);
8151 found |= replace_misc_use(state, orig, new, use);
8152 found |= replace_targ_use(state, orig, new, use);
8154 internal_error(state, use, "use without use");
8158 static void propogate_use(struct compile_state *state,
8159 struct triple *orig, struct triple *new)
8161 struct triple_set *user, *next;
8162 for(user = orig->use; user; user = next) {
8163 /* Careful replace_use modifies the use chain and
8164 * removes use. So we must get a copy of the next
8168 replace_use(state, orig, new, user->member);
8171 internal_error(state, orig, "used after propogate_use");
8177 * ===========================
8180 static struct triple *mk_cast_expr(
8181 struct compile_state *state, struct type *type, struct triple *expr)
8184 def = read_expr(state, expr);
8185 def = triple(state, OP_CONVERT, type, def, 0);
8189 static struct triple *mk_add_expr(
8190 struct compile_state *state, struct triple *left, struct triple *right)
8192 struct type *result_type;
8193 /* Put pointer operands on the left */
8194 if (is_pointer(right)) {
8200 left = read_expr(state, left);
8201 right = read_expr(state, right);
8202 result_type = ptr_arithmetic_result(state, left, right);
8203 if (is_pointer(left)) {
8204 struct type *ptr_math;
8206 if (is_signed(right->type)) {
8207 ptr_math = &long_type;
8210 ptr_math = &ulong_type;
8213 if (!equiv_types(right->type, ptr_math)) {
8214 right = mk_cast_expr(state, ptr_math, right);
8216 right = triple(state, op, ptr_math, right,
8217 int_const(state, ptr_math,
8218 size_of_in_bytes(state, left->type->left)));
8220 return triple(state, OP_ADD, result_type, left, right);
8223 static struct triple *mk_sub_expr(
8224 struct compile_state *state, struct triple *left, struct triple *right)
8226 struct type *result_type;
8227 result_type = ptr_arithmetic_result(state, left, right);
8228 left = read_expr(state, left);
8229 right = read_expr(state, right);
8230 if (is_pointer(left)) {
8231 struct type *ptr_math;
8233 if (is_signed(right->type)) {
8234 ptr_math = &long_type;
8237 ptr_math = &ulong_type;
8240 if (!equiv_types(right->type, ptr_math)) {
8241 right = mk_cast_expr(state, ptr_math, right);
8243 right = triple(state, op, ptr_math, right,
8244 int_const(state, ptr_math,
8245 size_of_in_bytes(state, left->type->left)));
8247 return triple(state, OP_SUB, result_type, left, right);
8250 static struct triple *mk_pre_inc_expr(
8251 struct compile_state *state, struct triple *def)
8255 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8256 return triple(state, OP_VAL, def->type,
8257 write_expr(state, def, val),
8261 static struct triple *mk_pre_dec_expr(
8262 struct compile_state *state, struct triple *def)
8266 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8267 return triple(state, OP_VAL, def->type,
8268 write_expr(state, def, val),
8272 static struct triple *mk_post_inc_expr(
8273 struct compile_state *state, struct triple *def)
8277 val = read_expr(state, def);
8278 return triple(state, OP_VAL, def->type,
8279 write_expr(state, def,
8280 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8284 static struct triple *mk_post_dec_expr(
8285 struct compile_state *state, struct triple *def)
8289 val = read_expr(state, def);
8290 return triple(state, OP_VAL, def->type,
8291 write_expr(state, def,
8292 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8296 static struct triple *mk_subscript_expr(
8297 struct compile_state *state, struct triple *left, struct triple *right)
8299 left = read_expr(state, left);
8300 right = read_expr(state, right);
8301 if (!is_pointer(left) && !is_pointer(right)) {
8302 error(state, left, "subscripted value is not a pointer");
8304 return mk_deref_expr(state, mk_add_expr(state, left, right));
8309 * Compile time evaluation
8310 * ===========================
8312 static int is_const(struct triple *ins)
8314 return IS_CONST_OP(ins->op);
8317 static int is_simple_const(struct triple *ins)
8319 /* Is this a constant that u.cval has the value.
8320 * Or equivalently is this a constant that read_const
8322 * So far only OP_INTCONST qualifies.
8324 return (ins->op == OP_INTCONST);
8327 static int constants_equal(struct compile_state *state,
8328 struct triple *left, struct triple *right)
8331 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8334 else if (!is_const(left) || !is_const(right)) {
8337 else if (left->op != right->op) {
8340 else if (!equiv_types(left->type, right->type)) {
8347 if (left->u.cval == right->u.cval) {
8353 size_t lsize, rsize, bytes;
8354 lsize = size_of(state, left->type);
8355 rsize = size_of(state, right->type);
8356 if (lsize != rsize) {
8359 bytes = bits_to_bytes(lsize);
8360 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8366 if ((MISC(left, 0) == MISC(right, 0)) &&
8367 (left->u.cval == right->u.cval)) {
8372 internal_error(state, left, "uknown constant type");
8379 static int is_zero(struct triple *ins)
8381 return is_simple_const(ins) && (ins->u.cval == 0);
8384 static int is_one(struct triple *ins)
8386 return is_simple_const(ins) && (ins->u.cval == 1);
8389 #if DEBUG_ROMCC_WARNING
8390 static long_t bit_count(ulong_t value)
8395 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8408 static long_t bsr(ulong_t value)
8411 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8422 static long_t bsf(ulong_t value)
8425 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8436 static long_t ilog2(ulong_t value)
8441 static long_t tlog2(struct triple *ins)
8443 return ilog2(ins->u.cval);
8446 static int is_pow2(struct triple *ins)
8448 ulong_t value, mask;
8450 if (!is_const(ins)) {
8453 value = ins->u.cval;
8460 return ((value & mask) == value);
8463 static ulong_t read_const(struct compile_state *state,
8464 struct triple *ins, struct triple *rhs)
8466 switch(rhs->type->type &TYPE_MASK) {
8479 fprintf(state->errout, "type: ");
8480 name_of(state->errout, rhs->type);
8481 fprintf(state->errout, "\n");
8482 internal_warning(state, rhs, "bad type to read_const");
8485 if (!is_simple_const(rhs)) {
8486 internal_error(state, rhs, "bad op to read_const");
8491 static long_t read_sconst(struct compile_state *state,
8492 struct triple *ins, struct triple *rhs)
8494 return (long_t)(rhs->u.cval);
8497 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8499 if (!is_const(rhs)) {
8500 internal_error(state, 0, "non const passed to const_true");
8502 return !is_zero(rhs);
8505 int const_eq(struct compile_state *state, struct triple *ins,
8506 struct triple *left, struct triple *right)
8509 if (!is_const(left) || !is_const(right)) {
8510 internal_warning(state, ins, "non const passed to const_eq");
8513 else if (left == right) {
8516 else if (is_simple_const(left) && is_simple_const(right)) {
8518 lval = read_const(state, ins, left);
8519 rval = read_const(state, ins, right);
8520 result = (lval == rval);
8522 else if ((left->op == OP_ADDRCONST) &&
8523 (right->op == OP_ADDRCONST)) {
8524 result = (MISC(left, 0) == MISC(right, 0)) &&
8525 (left->u.cval == right->u.cval);
8528 internal_warning(state, ins, "incomparable constants passed to const_eq");
8535 int const_ucmp(struct compile_state *state, struct triple *ins,
8536 struct triple *left, struct triple *right)
8539 if (!is_const(left) || !is_const(right)) {
8540 internal_warning(state, ins, "non const past to const_ucmp");
8543 else if (left == right) {
8546 else if (is_simple_const(left) && is_simple_const(right)) {
8548 lval = read_const(state, ins, left);
8549 rval = read_const(state, ins, right);
8553 } else if (rval > lval) {
8557 else if ((left->op == OP_ADDRCONST) &&
8558 (right->op == OP_ADDRCONST) &&
8559 (MISC(left, 0) == MISC(right, 0))) {
8561 if (left->u.cval > right->u.cval) {
8563 } else if (left->u.cval < right->u.cval) {
8568 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8574 int const_scmp(struct compile_state *state, struct triple *ins,
8575 struct triple *left, struct triple *right)
8578 if (!is_const(left) || !is_const(right)) {
8579 internal_warning(state, ins, "non const past to ucmp_const");
8582 else if (left == right) {
8585 else if (is_simple_const(left) && is_simple_const(right)) {
8587 lval = read_sconst(state, ins, left);
8588 rval = read_sconst(state, ins, right);
8592 } else if (rval > lval) {
8597 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8603 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8605 struct triple **expr;
8606 expr = triple_rhs(state, ins, 0);
8607 for(;expr;expr = triple_rhs(state, ins, expr)) {
8609 unuse_triple(*expr, ins);
8615 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8617 struct triple **expr;
8618 expr = triple_lhs(state, ins, 0);
8619 for(;expr;expr = triple_lhs(state, ins, expr)) {
8620 unuse_triple(*expr, ins);
8625 #if DEBUG_ROMCC_WARNING
8626 static void unuse_misc(struct compile_state *state, struct triple *ins)
8628 struct triple **expr;
8629 expr = triple_misc(state, ins, 0);
8630 for(;expr;expr = triple_misc(state, ins, expr)) {
8631 unuse_triple(*expr, ins);
8636 static void unuse_targ(struct compile_state *state, struct triple *ins)
8639 struct triple **slot;
8640 slot = &TARG(ins, 0);
8641 for(i = 0; i < ins->targ; i++) {
8642 unuse_triple(slot[i], ins);
8647 static void check_lhs(struct compile_state *state, struct triple *ins)
8649 struct triple **expr;
8650 expr = triple_lhs(state, ins, 0);
8651 for(;expr;expr = triple_lhs(state, ins, expr)) {
8652 internal_error(state, ins, "unexpected lhs");
8658 static void check_misc(struct compile_state *state, struct triple *ins)
8660 struct triple **expr;
8661 expr = triple_misc(state, ins, 0);
8662 for(;expr;expr = triple_misc(state, ins, expr)) {
8664 internal_error(state, ins, "unexpected misc");
8669 static void check_targ(struct compile_state *state, struct triple *ins)
8671 struct triple **expr;
8672 expr = triple_targ(state, ins, 0);
8673 for(;expr;expr = triple_targ(state, ins, expr)) {
8674 internal_error(state, ins, "unexpected targ");
8678 static void wipe_ins(struct compile_state *state, struct triple *ins)
8680 /* Becareful which instructions you replace the wiped
8681 * instruction with, as there are not enough slots
8682 * in all instructions to hold all others.
8684 check_targ(state, ins);
8685 check_misc(state, ins);
8686 unuse_rhs(state, ins);
8687 unuse_lhs(state, ins);
8694 #if DEBUG_ROMCC_WARNING
8695 static void wipe_branch(struct compile_state *state, struct triple *ins)
8697 /* Becareful which instructions you replace the wiped
8698 * instruction with, as there are not enough slots
8699 * in all instructions to hold all others.
8701 unuse_rhs(state, ins);
8702 unuse_lhs(state, ins);
8703 unuse_misc(state, ins);
8704 unuse_targ(state, ins);
8712 static void mkcopy(struct compile_state *state,
8713 struct triple *ins, struct triple *rhs)
8715 struct block *block;
8716 if (!equiv_types(ins->type, rhs->type)) {
8717 FILE *fp = state->errout;
8718 fprintf(fp, "src type: ");
8719 name_of(fp, rhs->type);
8720 fprintf(fp, "\ndst type: ");
8721 name_of(fp, ins->type);
8723 internal_error(state, ins, "mkcopy type mismatch");
8725 block = block_of_triple(state, ins);
8726 wipe_ins(state, ins);
8729 ins->u.block = block;
8731 use_triple(RHS(ins, 0), ins);
8734 static void mkconst(struct compile_state *state,
8735 struct triple *ins, ulong_t value)
8737 if (!is_integral(ins) && !is_pointer(ins)) {
8738 fprintf(state->errout, "type: ");
8739 name_of(state->errout, ins->type);
8740 fprintf(state->errout, "\n");
8741 internal_error(state, ins, "unknown type to make constant value: %ld",
8744 wipe_ins(state, ins);
8745 ins->op = OP_INTCONST;
8746 ins->u.cval = value;
8749 static void mkaddr_const(struct compile_state *state,
8750 struct triple *ins, struct triple *sdecl, ulong_t value)
8752 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8753 internal_error(state, ins, "bad base for addrconst");
8755 wipe_ins(state, ins);
8756 ins->op = OP_ADDRCONST;
8758 MISC(ins, 0) = sdecl;
8759 ins->u.cval = value;
8760 use_triple(sdecl, ins);
8763 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8764 static void print_tuple(struct compile_state *state,
8765 struct triple *ins, struct triple *tuple)
8767 FILE *fp = state->dbgout;
8768 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8769 name_of(fp, tuple->type);
8770 if (tuple->lhs > 0) {
8771 fprintf(fp, " lhs: ");
8772 name_of(fp, LHS(tuple, 0)->type);
8779 static struct triple *decompose_with_tuple(struct compile_state *state,
8780 struct triple *ins, struct triple *tuple)
8782 struct triple *next;
8784 flatten(state, next, tuple);
8785 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8786 print_tuple(state, ins, tuple);
8789 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8791 if (tuple->lhs != 1) {
8792 internal_error(state, tuple, "plain type in multiple registers?");
8794 tmp = LHS(tuple, 0);
8795 release_triple(state, tuple);
8799 propogate_use(state, ins, tuple);
8800 release_triple(state, ins);
8805 static struct triple *decompose_unknownval(struct compile_state *state,
8808 struct triple *tuple;
8811 #if DEBUG_DECOMPOSE_HIRES
8812 FILE *fp = state->dbgout;
8813 fprintf(fp, "unknown type: ");
8814 name_of(fp, ins->type);
8818 get_occurance(ins->occurance);
8819 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8822 for(i = 0; i < tuple->lhs; i++) {
8823 struct type *piece_type;
8824 struct triple *unknown;
8826 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8827 get_occurance(tuple->occurance);
8828 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8830 LHS(tuple, i) = unknown;
8832 return decompose_with_tuple(state, ins, tuple);
8836 static struct triple *decompose_read(struct compile_state *state,
8839 struct triple *tuple, *lval;
8844 if (lval->op == OP_PIECE) {
8847 get_occurance(ins->occurance);
8848 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8851 if ((tuple->lhs != lval->lhs) &&
8852 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8854 internal_error(state, ins, "lhs size inconsistency?");
8856 for(i = 0; i < tuple->lhs; i++) {
8857 struct triple *piece, *read, *bitref;
8858 if ((i != 0) || !triple_is_def(state, lval)) {
8859 piece = LHS(lval, i);
8864 /* See if the piece is really a bitref */
8866 if (piece->op == OP_BITREF) {
8868 piece = RHS(bitref, 0);
8871 get_occurance(tuple->occurance);
8872 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8874 RHS(read, 0) = piece;
8877 struct triple *extract;
8879 if (is_signed(bitref->type->left)) {
8884 get_occurance(tuple->occurance);
8885 extract = alloc_triple(state, op, bitref->type, -1, -1,
8887 RHS(extract, 0) = read;
8888 extract->u.bitfield.size = bitref->u.bitfield.size;
8889 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8894 LHS(tuple, i) = read;
8896 return decompose_with_tuple(state, ins, tuple);
8899 static struct triple *decompose_write(struct compile_state *state,
8902 struct triple *tuple, *lval, *val;
8905 lval = MISC(ins, 0);
8907 get_occurance(ins->occurance);
8908 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8911 if ((tuple->lhs != lval->lhs) &&
8912 (!triple_is_def(state, lval) || tuple->lhs != 1))
8914 internal_error(state, ins, "lhs size inconsistency?");
8916 for(i = 0; i < tuple->lhs; i++) {
8917 struct triple *piece, *write, *pval, *bitref;
8918 if ((i != 0) || !triple_is_def(state, lval)) {
8919 piece = LHS(lval, i);
8923 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8928 internal_error(state, ins, "lhs size inconsistency?");
8933 /* See if the piece is really a bitref */
8935 if (piece->op == OP_BITREF) {
8936 struct triple *read, *deposit;
8938 piece = RHS(bitref, 0);
8940 /* Read the destination register */
8941 get_occurance(tuple->occurance);
8942 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8944 RHS(read, 0) = piece;
8946 /* Deposit the new bitfield value */
8947 get_occurance(tuple->occurance);
8948 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8950 RHS(deposit, 0) = read;
8951 RHS(deposit, 1) = pval;
8952 deposit->u.bitfield.size = bitref->u.bitfield.size;
8953 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8955 /* Now write the newly generated value */
8959 get_occurance(tuple->occurance);
8960 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
8962 MISC(write, 0) = piece;
8963 RHS(write, 0) = pval;
8964 LHS(tuple, i) = write;
8966 return decompose_with_tuple(state, ins, tuple);
8969 struct decompose_load_info {
8970 struct occurance *occurance;
8971 struct triple *lval;
8972 struct triple *tuple;
8974 static void decompose_load_cb(struct compile_state *state,
8975 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8977 struct decompose_load_info *info = arg;
8978 struct triple *load;
8980 if (reg_offset > info->tuple->lhs) {
8981 internal_error(state, info->tuple, "lhs to small?");
8983 get_occurance(info->occurance);
8984 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8985 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8986 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8989 static struct triple *decompose_load(struct compile_state *state,
8992 struct triple *tuple;
8993 struct decompose_load_info info;
8995 if (!is_compound_type(ins->type)) {
8998 get_occurance(ins->occurance);
8999 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9002 info.occurance = ins->occurance;
9003 info.lval = RHS(ins, 0);
9005 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
9007 return decompose_with_tuple(state, ins, tuple);
9011 struct decompose_store_info {
9012 struct occurance *occurance;
9013 struct triple *lval;
9015 struct triple *tuple;
9017 static void decompose_store_cb(struct compile_state *state,
9018 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9020 struct decompose_store_info *info = arg;
9021 struct triple *store;
9023 if (reg_offset > info->tuple->lhs) {
9024 internal_error(state, info->tuple, "lhs to small?");
9026 get_occurance(info->occurance);
9027 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9028 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9029 RHS(store, 1) = LHS(info->val, reg_offset);
9030 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9033 static struct triple *decompose_store(struct compile_state *state,
9036 struct triple *tuple;
9037 struct decompose_store_info info;
9039 if (!is_compound_type(ins->type)) {
9042 get_occurance(ins->occurance);
9043 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9046 info.occurance = ins->occurance;
9047 info.lval = RHS(ins, 0);
9048 info.val = RHS(ins, 1);
9050 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9052 return decompose_with_tuple(state, ins, tuple);
9055 static struct triple *decompose_dot(struct compile_state *state,
9058 struct triple *tuple, *lval;
9063 lval = MISC(ins, 0);
9064 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9065 idx = reg_offset/REG_SIZEOF_REG;
9066 type = field_type(state, lval->type, ins->u.field);
9067 #if DEBUG_DECOMPOSE_HIRES
9069 FILE *fp = state->dbgout;
9070 fprintf(fp, "field type: ");
9076 get_occurance(ins->occurance);
9077 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9080 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9083 internal_error(state, ins, "multi register bitfield?");
9086 for(i = 0; i < tuple->lhs; i++, idx++) {
9087 struct triple *piece;
9088 if (!triple_is_def(state, lval)) {
9089 if (idx > lval->lhs) {
9090 internal_error(state, ins, "inconsistent lhs count");
9092 piece = LHS(lval, idx);
9095 internal_error(state, ins, "bad reg_offset into def");
9098 internal_error(state, ins, "bad reg count from def");
9103 /* Remember the offset of the bitfield */
9104 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9105 get_occurance(ins->occurance);
9106 piece = build_triple(state, OP_BITREF, type, piece, 0,
9108 piece->u.bitfield.size = size_of(state, type);
9109 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9111 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9112 internal_error(state, ins,
9113 "request for a nonbitfield sub register?");
9116 LHS(tuple, i) = piece;
9119 return decompose_with_tuple(state, ins, tuple);
9122 static struct triple *decompose_index(struct compile_state *state,
9125 struct triple *tuple, *lval;
9129 lval = MISC(ins, 0);
9130 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9131 type = index_type(state, lval->type, ins->u.cval);
9132 #if DEBUG_DECOMPOSE_HIRES
9134 FILE *fp = state->dbgout;
9135 fprintf(fp, "index type: ");
9141 get_occurance(ins->occurance);
9142 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9145 for(i = 0; i < tuple->lhs; i++, idx++) {
9146 struct triple *piece;
9147 if (!triple_is_def(state, lval)) {
9148 if (idx > lval->lhs) {
9149 internal_error(state, ins, "inconsistent lhs count");
9151 piece = LHS(lval, idx);
9154 internal_error(state, ins, "bad reg_offset into def");
9157 internal_error(state, ins, "bad reg count from def");
9161 LHS(tuple, i) = piece;
9164 return decompose_with_tuple(state, ins, tuple);
9167 static void decompose_compound_types(struct compile_state *state)
9169 struct triple *ins, *next, *first;
9172 first = state->first;
9175 /* Pass one expand compound values into pseudo registers.
9183 next = decompose_unknownval(state, ins);
9187 next = decompose_read(state, ins);
9191 next = decompose_write(state, ins);
9195 /* Be very careful with the load/store logic. These
9196 * operations must convert from the in register layout
9197 * to the in memory layout, which is nontrivial.
9200 next = decompose_load(state, ins);
9203 next = decompose_store(state, ins);
9207 next = decompose_dot(state, ins);
9210 next = decompose_index(state, ins);
9214 #if DEBUG_DECOMPOSE_HIRES
9215 fprintf(fp, "decompose next: %p \n", next);
9217 fprintf(fp, "next->op: %d %s\n",
9218 next->op, tops(next->op));
9219 /* High resolution debugging mode */
9220 print_triples(state);
9222 } while (next != first);
9224 /* Pass two remove the tuples.
9229 if (ins->op == OP_TUPLE) {
9231 internal_error(state, ins, "tuple used");
9234 release_triple(state, ins);
9238 } while(ins != first);
9242 if (ins->op == OP_BITREF) {
9244 internal_error(state, ins, "bitref used");
9247 release_triple(state, ins);
9251 } while(ins != first);
9253 /* Pass three verify the state and set ->id to 0.
9259 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9260 if (triple_stores_block(state, ins)) {
9263 if (triple_is_def(state, ins)) {
9264 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9265 internal_error(state, ins, "multi register value remains?");
9268 if (ins->op == OP_DOT) {
9269 internal_error(state, ins, "OP_DOT remains?");
9271 if (ins->op == OP_INDEX) {
9272 internal_error(state, ins, "OP_INDEX remains?");
9274 if (ins->op == OP_BITREF) {
9275 internal_error(state, ins, "OP_BITREF remains?");
9277 if (ins->op == OP_TUPLE) {
9278 internal_error(state, ins, "OP_TUPLE remains?");
9280 } while(next != first);
9283 /* For those operations that cannot be simplified */
9284 static void simplify_noop(struct compile_state *state, struct triple *ins)
9289 static void simplify_smul(struct compile_state *state, struct triple *ins)
9291 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9294 RHS(ins, 0) = RHS(ins, 1);
9297 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9299 left = read_sconst(state, ins, RHS(ins, 0));
9300 right = read_sconst(state, ins, RHS(ins, 1));
9301 mkconst(state, ins, left * right);
9303 else if (is_zero(RHS(ins, 1))) {
9304 mkconst(state, ins, 0);
9306 else if (is_one(RHS(ins, 1))) {
9307 mkcopy(state, ins, RHS(ins, 0));
9309 else if (is_pow2(RHS(ins, 1))) {
9311 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9313 insert_triple(state, state->global_pool, val);
9314 unuse_triple(RHS(ins, 1), ins);
9315 use_triple(val, ins);
9320 static void simplify_umul(struct compile_state *state, struct triple *ins)
9322 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9325 RHS(ins, 0) = RHS(ins, 1);
9328 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9329 ulong_t left, right;
9330 left = read_const(state, ins, RHS(ins, 0));
9331 right = read_const(state, ins, RHS(ins, 1));
9332 mkconst(state, ins, left * right);
9334 else if (is_zero(RHS(ins, 1))) {
9335 mkconst(state, ins, 0);
9337 else if (is_one(RHS(ins, 1))) {
9338 mkcopy(state, ins, RHS(ins, 0));
9340 else if (is_pow2(RHS(ins, 1))) {
9342 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9344 insert_triple(state, state->global_pool, val);
9345 unuse_triple(RHS(ins, 1), ins);
9346 use_triple(val, ins);
9351 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9353 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9355 left = read_sconst(state, ins, RHS(ins, 0));
9356 right = read_sconst(state, ins, RHS(ins, 1));
9357 mkconst(state, ins, left / right);
9359 else if (is_zero(RHS(ins, 0))) {
9360 mkconst(state, ins, 0);
9362 else if (is_zero(RHS(ins, 1))) {
9363 error(state, ins, "division by zero");
9365 else if (is_one(RHS(ins, 1))) {
9366 mkcopy(state, ins, RHS(ins, 0));
9368 else if (is_pow2(RHS(ins, 1))) {
9370 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9372 insert_triple(state, state->global_pool, val);
9373 unuse_triple(RHS(ins, 1), ins);
9374 use_triple(val, ins);
9379 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9381 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9382 ulong_t left, right;
9383 left = read_const(state, ins, RHS(ins, 0));
9384 right = read_const(state, ins, RHS(ins, 1));
9385 mkconst(state, ins, left / right);
9387 else if (is_zero(RHS(ins, 0))) {
9388 mkconst(state, ins, 0);
9390 else if (is_zero(RHS(ins, 1))) {
9391 error(state, ins, "division by zero");
9393 else if (is_one(RHS(ins, 1))) {
9394 mkcopy(state, ins, RHS(ins, 0));
9396 else if (is_pow2(RHS(ins, 1))) {
9398 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9400 insert_triple(state, state->global_pool, val);
9401 unuse_triple(RHS(ins, 1), ins);
9402 use_triple(val, ins);
9407 static void simplify_smod(struct compile_state *state, struct triple *ins)
9409 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9411 left = read_const(state, ins, RHS(ins, 0));
9412 right = read_const(state, ins, RHS(ins, 1));
9413 mkconst(state, ins, left % right);
9415 else if (is_zero(RHS(ins, 0))) {
9416 mkconst(state, ins, 0);
9418 else if (is_zero(RHS(ins, 1))) {
9419 error(state, ins, "division by zero");
9421 else if (is_one(RHS(ins, 1))) {
9422 mkconst(state, ins, 0);
9424 else if (is_pow2(RHS(ins, 1))) {
9426 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9428 insert_triple(state, state->global_pool, val);
9429 unuse_triple(RHS(ins, 1), ins);
9430 use_triple(val, ins);
9435 static void simplify_umod(struct compile_state *state, struct triple *ins)
9437 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9438 ulong_t left, right;
9439 left = read_const(state, ins, RHS(ins, 0));
9440 right = read_const(state, ins, RHS(ins, 1));
9441 mkconst(state, ins, left % right);
9443 else if (is_zero(RHS(ins, 0))) {
9444 mkconst(state, ins, 0);
9446 else if (is_zero(RHS(ins, 1))) {
9447 error(state, ins, "division by zero");
9449 else if (is_one(RHS(ins, 1))) {
9450 mkconst(state, ins, 0);
9452 else if (is_pow2(RHS(ins, 1))) {
9454 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9456 insert_triple(state, state->global_pool, val);
9457 unuse_triple(RHS(ins, 1), ins);
9458 use_triple(val, ins);
9463 static void simplify_add(struct compile_state *state, struct triple *ins)
9465 /* start with the pointer on the left */
9466 if (is_pointer(RHS(ins, 1))) {
9469 RHS(ins, 0) = RHS(ins, 1);
9472 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9473 if (RHS(ins, 0)->op == OP_INTCONST) {
9474 ulong_t left, right;
9475 left = read_const(state, ins, RHS(ins, 0));
9476 right = read_const(state, ins, RHS(ins, 1));
9477 mkconst(state, ins, left + right);
9479 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9480 struct triple *sdecl;
9481 ulong_t left, right;
9482 sdecl = MISC(RHS(ins, 0), 0);
9483 left = RHS(ins, 0)->u.cval;
9484 right = RHS(ins, 1)->u.cval;
9485 mkaddr_const(state, ins, sdecl, left + right);
9488 internal_warning(state, ins, "Optimize me!");
9491 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9494 RHS(ins, 1) = RHS(ins, 0);
9499 static void simplify_sub(struct compile_state *state, struct triple *ins)
9501 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9502 if (RHS(ins, 0)->op == OP_INTCONST) {
9503 ulong_t left, right;
9504 left = read_const(state, ins, RHS(ins, 0));
9505 right = read_const(state, ins, RHS(ins, 1));
9506 mkconst(state, ins, left - right);
9508 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9509 struct triple *sdecl;
9510 ulong_t left, right;
9511 sdecl = MISC(RHS(ins, 0), 0);
9512 left = RHS(ins, 0)->u.cval;
9513 right = RHS(ins, 1)->u.cval;
9514 mkaddr_const(state, ins, sdecl, left - right);
9517 internal_warning(state, ins, "Optimize me!");
9522 static void simplify_sl(struct compile_state *state, struct triple *ins)
9524 if (is_simple_const(RHS(ins, 1))) {
9526 right = read_const(state, ins, RHS(ins, 1));
9527 if (right >= (size_of(state, ins->type))) {
9528 warning(state, ins, "left shift count >= width of type");
9531 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9532 ulong_t left, right;
9533 left = read_const(state, ins, RHS(ins, 0));
9534 right = read_const(state, ins, RHS(ins, 1));
9535 mkconst(state, ins, left << right);
9539 static void simplify_usr(struct compile_state *state, struct triple *ins)
9541 if (is_simple_const(RHS(ins, 1))) {
9543 right = read_const(state, ins, RHS(ins, 1));
9544 if (right >= (size_of(state, ins->type))) {
9545 warning(state, ins, "right shift count >= width of type");
9548 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9549 ulong_t left, right;
9550 left = read_const(state, ins, RHS(ins, 0));
9551 right = read_const(state, ins, RHS(ins, 1));
9552 mkconst(state, ins, left >> right);
9556 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9558 if (is_simple_const(RHS(ins, 1))) {
9560 right = read_const(state, ins, RHS(ins, 1));
9561 if (right >= (size_of(state, ins->type))) {
9562 warning(state, ins, "right shift count >= width of type");
9565 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9567 left = read_sconst(state, ins, RHS(ins, 0));
9568 right = read_sconst(state, ins, RHS(ins, 1));
9569 mkconst(state, ins, left >> right);
9573 static void simplify_and(struct compile_state *state, struct triple *ins)
9575 struct triple *left, *right;
9577 right = RHS(ins, 1);
9579 if (is_simple_const(left) && is_simple_const(right)) {
9581 lval = read_const(state, ins, left);
9582 rval = read_const(state, ins, right);
9583 mkconst(state, ins, lval & rval);
9585 else if (is_zero(right) || is_zero(left)) {
9586 mkconst(state, ins, 0);
9590 static void simplify_or(struct compile_state *state, struct triple *ins)
9592 struct triple *left, *right;
9594 right = RHS(ins, 1);
9596 if (is_simple_const(left) && is_simple_const(right)) {
9598 lval = read_const(state, ins, left);
9599 rval = read_const(state, ins, right);
9600 mkconst(state, ins, lval | rval);
9602 #if 0 /* I need to handle type mismatches here... */
9603 else if (is_zero(right)) {
9604 mkcopy(state, ins, left);
9606 else if (is_zero(left)) {
9607 mkcopy(state, ins, right);
9612 static void simplify_xor(struct compile_state *state, struct triple *ins)
9614 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9615 ulong_t left, right;
9616 left = read_const(state, ins, RHS(ins, 0));
9617 right = read_const(state, ins, RHS(ins, 1));
9618 mkconst(state, ins, left ^ right);
9622 static void simplify_pos(struct compile_state *state, struct triple *ins)
9624 if (is_const(RHS(ins, 0))) {
9625 mkconst(state, ins, RHS(ins, 0)->u.cval);
9628 mkcopy(state, ins, RHS(ins, 0));
9632 static void simplify_neg(struct compile_state *state, struct triple *ins)
9634 if (is_simple_const(RHS(ins, 0))) {
9636 left = read_const(state, ins, RHS(ins, 0));
9637 mkconst(state, ins, -left);
9639 else if (RHS(ins, 0)->op == OP_NEG) {
9640 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9644 static void simplify_invert(struct compile_state *state, struct triple *ins)
9646 if (is_simple_const(RHS(ins, 0))) {
9648 left = read_const(state, ins, RHS(ins, 0));
9649 mkconst(state, ins, ~left);
9653 static void simplify_eq(struct compile_state *state, struct triple *ins)
9655 struct triple *left, *right;
9657 right = RHS(ins, 1);
9659 if (is_const(left) && is_const(right)) {
9661 val = const_eq(state, ins, left, right);
9663 mkconst(state, ins, val == 1);
9666 else if (left == right) {
9667 mkconst(state, ins, 1);
9671 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9673 struct triple *left, *right;
9675 right = RHS(ins, 1);
9677 if (is_const(left) && is_const(right)) {
9679 val = const_eq(state, ins, left, right);
9681 mkconst(state, ins, val != 1);
9684 if (left == right) {
9685 mkconst(state, ins, 0);
9689 static void simplify_sless(struct compile_state *state, struct triple *ins)
9691 struct triple *left, *right;
9693 right = RHS(ins, 1);
9695 if (is_const(left) && is_const(right)) {
9697 val = const_scmp(state, ins, left, right);
9698 if ((val >= -1) && (val <= 1)) {
9699 mkconst(state, ins, val < 0);
9702 else if (left == right) {
9703 mkconst(state, ins, 0);
9707 static void simplify_uless(struct compile_state *state, struct triple *ins)
9709 struct triple *left, *right;
9711 right = RHS(ins, 1);
9713 if (is_const(left) && is_const(right)) {
9715 val = const_ucmp(state, ins, left, right);
9716 if ((val >= -1) && (val <= 1)) {
9717 mkconst(state, ins, val < 0);
9720 else if (is_zero(right)) {
9721 mkconst(state, ins, 0);
9723 else if (left == right) {
9724 mkconst(state, ins, 0);
9728 static void simplify_smore(struct compile_state *state, struct triple *ins)
9730 struct triple *left, *right;
9732 right = RHS(ins, 1);
9734 if (is_const(left) && is_const(right)) {
9736 val = const_scmp(state, ins, left, right);
9737 if ((val >= -1) && (val <= 1)) {
9738 mkconst(state, ins, val > 0);
9741 else if (left == right) {
9742 mkconst(state, ins, 0);
9746 static void simplify_umore(struct compile_state *state, struct triple *ins)
9748 struct triple *left, *right;
9750 right = RHS(ins, 1);
9752 if (is_const(left) && is_const(right)) {
9754 val = const_ucmp(state, ins, left, right);
9755 if ((val >= -1) && (val <= 1)) {
9756 mkconst(state, ins, val > 0);
9759 else if (is_zero(left)) {
9760 mkconst(state, ins, 0);
9762 else if (left == right) {
9763 mkconst(state, ins, 0);
9768 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9770 struct triple *left, *right;
9772 right = RHS(ins, 1);
9774 if (is_const(left) && is_const(right)) {
9776 val = const_scmp(state, ins, left, right);
9777 if ((val >= -1) && (val <= 1)) {
9778 mkconst(state, ins, val <= 0);
9781 else if (left == right) {
9782 mkconst(state, ins, 1);
9786 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9788 struct triple *left, *right;
9790 right = RHS(ins, 1);
9792 if (is_const(left) && is_const(right)) {
9794 val = const_ucmp(state, ins, left, right);
9795 if ((val >= -1) && (val <= 1)) {
9796 mkconst(state, ins, val <= 0);
9799 else if (is_zero(left)) {
9800 mkconst(state, ins, 1);
9802 else if (left == right) {
9803 mkconst(state, ins, 1);
9807 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9809 struct triple *left, *right;
9811 right = RHS(ins, 1);
9813 if (is_const(left) && is_const(right)) {
9815 val = const_scmp(state, ins, left, right);
9816 if ((val >= -1) && (val <= 1)) {
9817 mkconst(state, ins, val >= 0);
9820 else if (left == right) {
9821 mkconst(state, ins, 1);
9825 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9827 struct triple *left, *right;
9829 right = RHS(ins, 1);
9831 if (is_const(left) && is_const(right)) {
9833 val = const_ucmp(state, ins, left, right);
9834 if ((val >= -1) && (val <= 1)) {
9835 mkconst(state, ins, val >= 0);
9838 else if (is_zero(right)) {
9839 mkconst(state, ins, 1);
9841 else if (left == right) {
9842 mkconst(state, ins, 1);
9846 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9851 if (is_const(rhs)) {
9852 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9854 /* Otherwise if I am the only user... */
9855 else if ((rhs->use) &&
9856 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9858 /* Invert a boolean operation */
9860 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9861 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9862 case OP_EQ: rhs->op = OP_NOTEQ; break;
9863 case OP_NOTEQ: rhs->op = OP_EQ; break;
9864 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9865 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9866 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9867 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9868 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9869 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9870 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9871 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9877 mkcopy(state, ins, rhs);
9882 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9887 if (is_const(rhs)) {
9888 mkconst(state, ins, const_ltrue(state, ins, rhs));
9890 else switch(rhs->op) {
9891 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9892 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9893 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9894 mkcopy(state, ins, rhs);
9899 static void simplify_load(struct compile_state *state, struct triple *ins)
9901 struct triple *addr, *sdecl, *blob;
9903 /* If I am doing a load with a constant pointer from a constant
9904 * table get the value.
9907 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9908 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9909 (blob->op == OP_BLOBCONST)) {
9910 unsigned char buffer[SIZEOF_WORD];
9911 size_t reg_size, mem_size;
9912 const char *src, *end;
9914 reg_size = reg_size_of(state, ins->type);
9915 if (reg_size > REG_SIZEOF_REG) {
9916 internal_error(state, ins, "load size greater than register");
9918 mem_size = size_of(state, ins->type);
9920 end += bits_to_bytes(size_of(state, sdecl->type));
9922 src += addr->u.cval;
9925 error(state, ins, "Load address out of bounds");
9928 memset(buffer, 0, sizeof(buffer));
9929 memcpy(buffer, src, bits_to_bytes(mem_size));
9932 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
9933 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9934 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9935 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9937 internal_error(state, ins, "mem_size: %d not handled",
9942 mkconst(state, ins, val);
9946 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9948 if (is_simple_const(RHS(ins, 0))) {
9951 val = read_const(state, ins, RHS(ins, 0));
9953 mask <<= ins->u.bitfield.size;
9955 val >>= ins->u.bitfield.offset;
9957 mkconst(state, ins, val);
9961 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9963 if (is_simple_const(RHS(ins, 0))) {
9967 val = read_const(state, ins, RHS(ins, 0));
9969 mask <<= ins->u.bitfield.size;
9971 val >>= ins->u.bitfield.offset;
9973 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9975 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9976 mkconst(state, ins, sval);
9980 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9982 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9985 targ = read_const(state, ins, RHS(ins, 0));
9986 val = read_const(state, ins, RHS(ins, 1));
9988 mask <<= ins->u.bitfield.size;
9990 mask <<= ins->u.bitfield.offset;
9992 val <<= ins->u.bitfield.offset;
9995 mkconst(state, ins, targ);
9999 static void simplify_copy(struct compile_state *state, struct triple *ins)
10001 struct triple *right;
10002 right = RHS(ins, 0);
10003 if (is_subset_type(ins->type, right->type)) {
10004 ins->type = right->type;
10006 if (equiv_types(ins->type, right->type)) {
10007 ins->op = OP_COPY;/* I don't need to convert if the types match */
10009 if (ins->op == OP_COPY) {
10010 internal_error(state, ins, "type mismatch on copy");
10013 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10014 struct triple *sdecl;
10016 sdecl = MISC(right, 0);
10017 offset = right->u.cval;
10018 mkaddr_const(state, ins, sdecl, offset);
10020 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10021 switch(right->op) {
10025 left = read_const(state, ins, right);
10026 /* Ensure I have not overflowed the destination. */
10027 if (size_of(state, right->type) > size_of(state, ins->type)) {
10030 mask <<= size_of(state, ins->type);
10034 /* Ensure I am properly sign extended */
10035 if (size_of(state, right->type) < size_of(state, ins->type) &&
10036 is_signed(right->type)) {
10039 shift = SIZEOF_LONG - size_of(state, right->type);
10045 mkconst(state, ins, left);
10049 internal_error(state, ins, "uknown constant");
10055 static int phi_present(struct block *block)
10057 struct triple *ptr;
10061 ptr = block->first;
10063 if (ptr->op == OP_PHI) {
10067 } while(ptr != block->last);
10071 static int phi_dependency(struct block *block)
10073 /* A block has a phi dependency if a phi function
10074 * depends on that block to exist, and makes a block
10075 * that is otherwise useless unsafe to remove.
10078 struct block_set *edge;
10079 for(edge = block->edges; edge; edge = edge->next) {
10080 if (phi_present(edge->member)) {
10088 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10090 struct triple *targ;
10091 targ = TARG(ins, 0);
10092 /* During scc_transform temporary triples are allocated that
10093 * loop back onto themselves. If I see one don't advance the
10096 while(triple_is_structural(state, targ) &&
10097 (targ->next != targ) && (targ->next != state->first)) {
10104 static void simplify_branch(struct compile_state *state, struct triple *ins)
10106 int simplified, loops;
10107 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10108 internal_error(state, ins, "not branch");
10110 if (ins->use != 0) {
10111 internal_error(state, ins, "branch use");
10113 /* The challenge here with simplify branch is that I need to
10114 * make modifications to the control flow graph as well
10115 * as to the branch instruction itself. That is handled
10116 * by rebuilding the basic blocks after simplify all is called.
10119 /* If we have a branch to an unconditional branch update
10120 * our target. But watch out for dependencies from phi
10122 * Also only do this a limited number of times so
10123 * we don't get into an infinite loop.
10127 struct triple *targ;
10129 targ = branch_target(state, ins);
10130 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10131 !phi_dependency(targ->u.block))
10133 unuse_triple(TARG(ins, 0), ins);
10134 TARG(ins, 0) = TARG(targ, 0);
10135 use_triple(TARG(ins, 0), ins);
10138 } while(simplified && (++loops < 20));
10140 /* If we have a conditional branch with a constant condition
10141 * make it an unconditional branch.
10143 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10144 struct triple *targ;
10146 value = read_const(state, ins, RHS(ins, 0));
10147 unuse_triple(RHS(ins, 0), ins);
10148 targ = TARG(ins, 0);
10151 ins->op = OP_BRANCH;
10153 unuse_triple(ins->next, ins);
10154 TARG(ins, 0) = targ;
10157 unuse_triple(targ, ins);
10158 TARG(ins, 0) = ins->next;
10162 /* If we have a branch to the next instruction,
10165 if (TARG(ins, 0) == ins->next) {
10166 unuse_triple(TARG(ins, 0), ins);
10167 if (ins->op == OP_CBRANCH) {
10168 unuse_triple(RHS(ins, 0), ins);
10169 unuse_triple(ins->next, ins);
10177 internal_error(state, ins, "noop use != 0");
10182 static void simplify_label(struct compile_state *state, struct triple *ins)
10184 /* Ignore volatile labels */
10185 if (!triple_is_pure(state, ins, ins->id)) {
10188 if (ins->use == 0) {
10191 else if (ins->prev->op == OP_LABEL) {
10192 /* In general it is not safe to merge one label that
10193 * imediately follows another. The problem is that the empty
10194 * looking block may have phi functions that depend on it.
10196 if (!phi_dependency(ins->prev->u.block)) {
10197 struct triple_set *user, *next;
10199 for(user = ins->use; user; user = next) {
10200 struct triple *use, **expr;
10202 use = user->member;
10203 expr = triple_targ(state, use, 0);
10204 for(;expr; expr = triple_targ(state, use, expr)) {
10205 if (*expr == ins) {
10207 unuse_triple(ins, use);
10208 use_triple(ins->prev, use);
10214 internal_error(state, ins, "noop use != 0");
10220 static void simplify_phi(struct compile_state *state, struct triple *ins)
10222 struct triple **slot;
10223 struct triple *value;
10226 slot = &RHS(ins, 0);
10231 /* See if all of the rhs members of a phi have the same value */
10232 if (slot[0] && is_simple_const(slot[0])) {
10233 cvalue = read_const(state, ins, slot[0]);
10234 for(i = 1; i < zrhs; i++) {
10236 !is_simple_const(slot[i]) ||
10237 !equiv_types(slot[0]->type, slot[i]->type) ||
10238 (cvalue != read_const(state, ins, slot[i]))) {
10243 mkconst(state, ins, cvalue);
10248 /* See if all of rhs members of a phi are the same */
10250 for(i = 1; i < zrhs; i++) {
10251 if (slot[i] != value) {
10256 /* If the phi has a single value just copy it */
10257 if (!is_subset_type(ins->type, value->type)) {
10258 internal_error(state, ins, "bad input type to phi");
10260 /* Make the types match */
10261 if (!equiv_types(ins->type, value->type)) {
10262 ins->type = value->type;
10264 /* Now make the actual copy */
10265 mkcopy(state, ins, value);
10271 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10273 if (is_simple_const(RHS(ins, 0))) {
10275 left = read_const(state, ins, RHS(ins, 0));
10276 mkconst(state, ins, bsf(left));
10280 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10282 if (is_simple_const(RHS(ins, 0))) {
10284 left = read_const(state, ins, RHS(ins, 0));
10285 mkconst(state, ins, bsr(left));
10290 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10291 static const struct simplify_table {
10293 unsigned long flag;
10294 } table_simplify[] = {
10295 #define simplify_sdivt simplify_noop
10296 #define simplify_udivt simplify_noop
10297 #define simplify_piece simplify_noop
10299 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10300 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10301 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10302 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10303 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10304 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10305 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10306 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10307 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10308 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10309 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10310 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10311 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10312 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10313 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10314 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10315 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10316 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10317 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10319 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10320 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10321 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10322 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10323 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10324 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10325 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10326 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10327 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10328 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10329 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10330 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10332 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10333 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10335 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10336 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10337 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10339 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10341 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10342 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10343 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10344 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10346 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10347 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10348 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10349 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10350 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10351 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10353 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10354 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10356 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10357 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10358 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10359 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10360 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10361 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10362 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10363 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10364 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10366 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10367 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10368 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10369 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10370 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10371 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10372 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10373 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10374 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10375 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10376 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10379 static inline void debug_simplify(struct compile_state *state,
10380 simplify_t do_simplify, struct triple *ins)
10382 #if DEBUG_SIMPLIFY_HIRES
10383 if (state->functions_joined && (do_simplify != simplify_noop)) {
10384 /* High resolution debugging mode */
10385 fprintf(state->dbgout, "simplifing: ");
10386 display_triple(state->dbgout, ins);
10389 do_simplify(state, ins);
10390 #if DEBUG_SIMPLIFY_HIRES
10391 if (state->functions_joined && (do_simplify != simplify_noop)) {
10392 /* High resolution debugging mode */
10393 fprintf(state->dbgout, "simplified: ");
10394 display_triple(state->dbgout, ins);
10398 static void simplify(struct compile_state *state, struct triple *ins)
10401 simplify_t do_simplify;
10402 if (ins == &unknown_triple) {
10403 internal_error(state, ins, "simplifying the unknown triple?");
10408 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10412 do_simplify = table_simplify[op].func;
10415 !(state->compiler->flags & table_simplify[op].flag)) {
10416 do_simplify = simplify_noop;
10418 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10419 do_simplify = simplify_noop;
10422 if (!do_simplify) {
10423 internal_error(state, ins, "cannot simplify op: %d %s",
10427 debug_simplify(state, do_simplify, ins);
10428 } while(ins->op != op);
10431 static void rebuild_ssa_form(struct compile_state *state);
10433 static void simplify_all(struct compile_state *state)
10435 struct triple *ins, *first;
10436 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10439 first = state->first;
10442 simplify(state, ins);
10444 } while(ins != first->prev);
10447 simplify(state, ins);
10449 }while(ins != first);
10450 rebuild_ssa_form(state);
10452 print_blocks(state, __func__, state->dbgout);
10457 * ============================
10460 static void register_builtin_function(struct compile_state *state,
10461 const char *name, int op, struct type *rtype, ...)
10463 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10464 struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10465 struct hash_entry *ident;
10466 struct file_state file;
10472 /* Dummy file state to get debug handling right */
10473 memset(&file, 0, sizeof(file));
10474 file.basename = "<built-in>";
10476 file.report_line = 1;
10477 file.report_name = file.basename;
10478 file.prev = state->file;
10479 state->file = &file;
10480 state->function = name;
10482 /* Find the Parameter count */
10483 valid_op(state, op);
10484 parameters = table_ops[op].rhs;
10485 if (parameters < 0 ) {
10486 internal_error(state, 0, "Invalid builtin parameter count");
10489 /* Find the function type */
10490 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10491 ftype->elements = parameters;
10492 next = &ftype->right;
10493 va_start(args, rtype);
10494 for(i = 0; i < parameters; i++) {
10495 atype = va_arg(args, struct type *);
10499 *next = new_type(TYPE_PRODUCT, *next, atype);
10500 next = &((*next)->right);
10504 *next = &void_type;
10508 /* Get the initial closure type */
10509 ctype = new_type(TYPE_JOIN, &void_type, 0);
10510 ctype->elements = 1;
10512 /* Get the return type */
10513 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10514 crtype->elements = 2;
10516 /* Generate the needed triples */
10517 def = triple(state, OP_LIST, ftype, 0, 0);
10518 first = label(state);
10519 RHS(def, 0) = first;
10520 result = flatten(state, first, variable(state, crtype));
10521 retvar = flatten(state, first, variable(state, &void_ptr_type));
10522 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10524 /* Now string them together */
10525 param = ftype->right;
10526 for(i = 0; i < parameters; i++) {
10527 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10528 atype = param->left;
10532 arg = flatten(state, first, variable(state, atype));
10533 param = param->right;
10535 work = new_triple(state, op, rtype, -1, parameters);
10536 generate_lhs_pieces(state, work);
10537 for(i = 0; i < parameters; i++) {
10538 RHS(work, i) = read_expr(state, farg(state, def, i));
10540 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10541 work = write_expr(state, deref_index(state, result, 1), work);
10543 work = flatten(state, first, work);
10544 last = flatten(state, first, label(state));
10545 ret = flatten(state, first, ret);
10546 name_len = strlen(name);
10547 ident = lookup(state, name, name_len);
10548 ftype->type_ident = ident;
10549 symbol(state, ident, &ident->sym_ident, def, ftype);
10551 state->file = file.prev;
10552 state->function = 0;
10553 state->main_function = 0;
10555 if (!state->functions) {
10556 state->functions = def;
10558 insert_triple(state, state->functions, def);
10560 if (state->compiler->debug & DEBUG_INLINE) {
10561 FILE *fp = state->dbgout;
10564 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10565 display_func(state, fp, def);
10566 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10570 static struct type *partial_struct(struct compile_state *state,
10571 const char *field_name, struct type *type, struct type *rest)
10573 struct hash_entry *field_ident;
10574 struct type *result;
10575 int field_name_len;
10577 field_name_len = strlen(field_name);
10578 field_ident = lookup(state, field_name, field_name_len);
10580 result = clone_type(0, type);
10581 result->field_ident = field_ident;
10584 result = new_type(TYPE_PRODUCT, result, rest);
10589 static struct type *register_builtin_type(struct compile_state *state,
10590 const char *name, struct type *type)
10592 struct hash_entry *ident;
10595 name_len = strlen(name);
10596 ident = lookup(state, name, name_len);
10598 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10599 ulong_t elements = 0;
10600 struct type *field;
10601 type = new_type(TYPE_STRUCT, type, 0);
10602 field = type->left;
10603 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10605 field = field->right;
10608 symbol(state, ident, &ident->sym_tag, 0, type);
10609 type->type_ident = ident;
10610 type->elements = elements;
10612 symbol(state, ident, &ident->sym_ident, 0, type);
10613 ident->tok = TOK_TYPE_NAME;
10618 static void register_builtins(struct compile_state *state)
10620 struct type *div_type, *ldiv_type;
10621 struct type *udiv_type, *uldiv_type;
10622 struct type *msr_type;
10624 div_type = register_builtin_type(state, "__builtin_div_t",
10625 partial_struct(state, "quot", &int_type,
10626 partial_struct(state, "rem", &int_type, 0)));
10627 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10628 partial_struct(state, "quot", &long_type,
10629 partial_struct(state, "rem", &long_type, 0)));
10630 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10631 partial_struct(state, "quot", &uint_type,
10632 partial_struct(state, "rem", &uint_type, 0)));
10633 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10634 partial_struct(state, "quot", &ulong_type,
10635 partial_struct(state, "rem", &ulong_type, 0)));
10637 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10638 &int_type, &int_type);
10639 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10640 &long_type, &long_type);
10641 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10642 &uint_type, &uint_type);
10643 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10644 &ulong_type, &ulong_type);
10646 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10648 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10650 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10653 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10654 &uchar_type, &ushort_type);
10655 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10656 &ushort_type, &ushort_type);
10657 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10658 &uint_type, &ushort_type);
10660 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10662 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10665 msr_type = register_builtin_type(state, "__builtin_msr_t",
10666 partial_struct(state, "lo", &ulong_type,
10667 partial_struct(state, "hi", &ulong_type, 0)));
10669 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10671 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10672 &ulong_type, &ulong_type, &ulong_type);
10674 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10678 static struct type *declarator(
10679 struct compile_state *state, struct type *type,
10680 struct hash_entry **ident, int need_ident);
10681 static void decl(struct compile_state *state, struct triple *first);
10682 static struct type *specifier_qualifier_list(struct compile_state *state);
10683 #if DEBUG_ROMCC_WARNING
10684 static int isdecl_specifier(int tok);
10686 static struct type *decl_specifiers(struct compile_state *state);
10687 static int istype(int tok);
10688 static struct triple *expr(struct compile_state *state);
10689 static struct triple *assignment_expr(struct compile_state *state);
10690 static struct type *type_name(struct compile_state *state);
10691 static void statement(struct compile_state *state, struct triple *first);
10693 static struct triple *call_expr(
10694 struct compile_state *state, struct triple *func)
10696 struct triple *def;
10697 struct type *param, *type;
10698 ulong_t pvals, index;
10700 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10701 error(state, 0, "Called object is not a function");
10703 if (func->op != OP_LIST) {
10704 internal_error(state, 0, "improper function");
10706 eat(state, TOK_LPAREN);
10707 /* Find the return type without any specifiers */
10708 type = clone_type(0, func->type->left);
10709 /* Count the number of rhs entries for OP_FCALL */
10710 param = func->type->right;
10712 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10714 param = param->right;
10716 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10719 def = new_triple(state, OP_FCALL, type, -1, pvals);
10720 MISC(def, 0) = func;
10722 param = func->type->right;
10723 for(index = 0; index < pvals; index++) {
10724 struct triple *val;
10725 struct type *arg_type;
10726 val = read_expr(state, assignment_expr(state));
10728 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10729 arg_type = param->left;
10731 write_compatible(state, arg_type, val->type);
10732 RHS(def, index) = val;
10733 if (index != (pvals - 1)) {
10734 eat(state, TOK_COMMA);
10735 param = param->right;
10738 eat(state, TOK_RPAREN);
10743 static struct triple *character_constant(struct compile_state *state)
10745 struct triple *def;
10747 const signed char *str, *end;
10750 tk = eat(state, TOK_LIT_CHAR);
10751 str = (signed char *)tk->val.str + 1;
10752 str_len = tk->str_len - 2;
10753 if (str_len <= 0) {
10754 error(state, 0, "empty character constant");
10756 end = str + str_len;
10757 c = char_value(state, &str, end);
10759 error(state, 0, "multibyte character constant not supported");
10761 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10765 static struct triple *string_constant(struct compile_state *state)
10767 struct triple *def;
10770 const signed char *str, *end;
10771 signed char *buf, *ptr;
10775 type = new_type(TYPE_ARRAY, &char_type, 0);
10776 type->elements = 0;
10777 /* The while loop handles string concatenation */
10779 tk = eat(state, TOK_LIT_STRING);
10780 str = (signed char *)tk->val.str + 1;
10781 str_len = tk->str_len - 2;
10783 error(state, 0, "negative string constant length");
10785 end = str + str_len;
10787 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10788 memcpy(buf, ptr, type->elements);
10789 ptr = buf + type->elements;
10791 *ptr++ = char_value(state, &str, end);
10792 } while(str < end);
10793 type->elements = ptr - buf;
10794 } while(peek(state) == TOK_LIT_STRING);
10796 type->elements += 1;
10797 def = triple(state, OP_BLOBCONST, type, 0, 0);
10804 static struct triple *integer_constant(struct compile_state *state)
10806 struct triple *def;
10813 tk = eat(state, TOK_LIT_INT);
10815 decimal = (tk->val.str[0] != '0');
10816 val = strtoul(tk->val.str, &end, 0);
10817 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10818 error(state, 0, "Integer constant to large");
10821 if ((*end == 'u') || (*end == 'U')) {
10825 if ((*end == 'l') || (*end == 'L')) {
10829 if ((*end == 'u') || (*end == 'U')) {
10834 error(state, 0, "Junk at end of integer constant");
10837 type = &ulong_type;
10841 if (!decimal && (val > LONG_T_MAX)) {
10842 type = &ulong_type;
10847 if (val > UINT_T_MAX) {
10848 type = &ulong_type;
10853 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10856 else if (!decimal && (val > LONG_T_MAX)) {
10857 type = &ulong_type;
10859 else if (val > INT_T_MAX) {
10863 def = int_const(state, type, val);
10867 static struct triple *primary_expr(struct compile_state *state)
10869 struct triple *def;
10875 struct hash_entry *ident;
10876 /* Here ident is either:
10880 ident = eat(state, TOK_IDENT)->ident;
10881 if (!ident->sym_ident) {
10882 error(state, 0, "%s undeclared", ident->name);
10884 def = ident->sym_ident->def;
10887 case TOK_ENUM_CONST:
10889 struct hash_entry *ident;
10890 /* Here ident is an enumeration constant */
10891 ident = eat(state, TOK_ENUM_CONST)->ident;
10892 if (!ident->sym_ident) {
10893 error(state, 0, "%s undeclared", ident->name);
10895 def = ident->sym_ident->def;
10900 struct hash_entry *ident;
10901 ident = eat(state, TOK_MIDENT)->ident;
10902 warning(state, 0, "Replacing undefined macro: %s with 0",
10904 def = int_const(state, &int_type, 0);
10908 eat(state, TOK_LPAREN);
10910 eat(state, TOK_RPAREN);
10913 def = integer_constant(state);
10915 case TOK_LIT_FLOAT:
10916 eat(state, TOK_LIT_FLOAT);
10917 error(state, 0, "Floating point constants not supported");
10922 def = character_constant(state);
10924 case TOK_LIT_STRING:
10925 def = string_constant(state);
10929 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10934 static struct triple *postfix_expr(struct compile_state *state)
10936 struct triple *def;
10938 def = primary_expr(state);
10940 struct triple *left;
10944 switch((tok = peek(state))) {
10946 eat(state, TOK_LBRACKET);
10947 def = mk_subscript_expr(state, left, expr(state));
10948 eat(state, TOK_RBRACKET);
10951 def = call_expr(state, def);
10955 struct hash_entry *field;
10956 eat(state, TOK_DOT);
10957 field = eat(state, TOK_IDENT)->ident;
10958 def = deref_field(state, def, field);
10963 struct hash_entry *field;
10964 eat(state, TOK_ARROW);
10965 field = eat(state, TOK_IDENT)->ident;
10966 def = mk_deref_expr(state, read_expr(state, def));
10967 def = deref_field(state, def, field);
10971 eat(state, TOK_PLUSPLUS);
10972 def = mk_post_inc_expr(state, left);
10974 case TOK_MINUSMINUS:
10975 eat(state, TOK_MINUSMINUS);
10976 def = mk_post_dec_expr(state, left);
10986 static struct triple *cast_expr(struct compile_state *state);
10988 static struct triple *unary_expr(struct compile_state *state)
10990 struct triple *def, *right;
10992 switch((tok = peek(state))) {
10994 eat(state, TOK_PLUSPLUS);
10995 def = mk_pre_inc_expr(state, unary_expr(state));
10997 case TOK_MINUSMINUS:
10998 eat(state, TOK_MINUSMINUS);
10999 def = mk_pre_dec_expr(state, unary_expr(state));
11002 eat(state, TOK_AND);
11003 def = mk_addr_expr(state, cast_expr(state), 0);
11006 eat(state, TOK_STAR);
11007 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11010 eat(state, TOK_PLUS);
11011 right = read_expr(state, cast_expr(state));
11012 arithmetic(state, right);
11013 def = integral_promotion(state, right);
11016 eat(state, TOK_MINUS);
11017 right = read_expr(state, cast_expr(state));
11018 arithmetic(state, right);
11019 def = integral_promotion(state, right);
11020 def = triple(state, OP_NEG, def->type, def, 0);
11023 eat(state, TOK_TILDE);
11024 right = read_expr(state, cast_expr(state));
11025 integral(state, right);
11026 def = integral_promotion(state, right);
11027 def = triple(state, OP_INVERT, def->type, def, 0);
11030 eat(state, TOK_BANG);
11031 right = read_expr(state, cast_expr(state));
11032 bool(state, right);
11033 def = lfalse_expr(state, right);
11039 eat(state, TOK_SIZEOF);
11040 tok1 = peek(state);
11041 tok2 = peek2(state);
11042 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11043 eat(state, TOK_LPAREN);
11044 type = type_name(state);
11045 eat(state, TOK_RPAREN);
11048 struct triple *expr;
11049 expr = unary_expr(state);
11051 release_expr(state, expr);
11053 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11060 eat(state, TOK_ALIGNOF);
11061 tok1 = peek(state);
11062 tok2 = peek2(state);
11063 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11064 eat(state, TOK_LPAREN);
11065 type = type_name(state);
11066 eat(state, TOK_RPAREN);
11069 struct triple *expr;
11070 expr = unary_expr(state);
11072 release_expr(state, expr);
11074 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11079 /* We only come here if we are called from the preprocessor */
11080 struct hash_entry *ident;
11082 eat(state, TOK_MDEFINED);
11084 if (pp_peek(state) == TOK_LPAREN) {
11085 pp_eat(state, TOK_LPAREN);
11088 ident = pp_eat(state, TOK_MIDENT)->ident;
11090 eat(state, TOK_RPAREN);
11092 def = int_const(state, &int_type, ident->sym_define != 0);
11096 def = postfix_expr(state);
11102 static struct triple *cast_expr(struct compile_state *state)
11104 struct triple *def;
11106 tok1 = peek(state);
11107 tok2 = peek2(state);
11108 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11110 eat(state, TOK_LPAREN);
11111 type = type_name(state);
11112 eat(state, TOK_RPAREN);
11113 def = mk_cast_expr(state, type, cast_expr(state));
11116 def = unary_expr(state);
11121 static struct triple *mult_expr(struct compile_state *state)
11123 struct triple *def;
11125 def = cast_expr(state);
11127 struct triple *left, *right;
11128 struct type *result_type;
11136 left = read_expr(state, def);
11137 arithmetic(state, left);
11141 right = read_expr(state, cast_expr(state));
11142 arithmetic(state, right);
11144 result_type = arithmetic_result(state, left, right);
11145 sign = is_signed(result_type);
11148 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11149 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11150 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11152 def = triple(state, op, result_type, left, right);
11162 static struct triple *add_expr(struct compile_state *state)
11164 struct triple *def;
11166 def = mult_expr(state);
11169 switch( peek(state)) {
11171 eat(state, TOK_PLUS);
11172 def = mk_add_expr(state, def, mult_expr(state));
11175 eat(state, TOK_MINUS);
11176 def = mk_sub_expr(state, def, mult_expr(state));
11186 static struct triple *shift_expr(struct compile_state *state)
11188 struct triple *def;
11190 def = add_expr(state);
11192 struct triple *left, *right;
11195 switch((tok = peek(state))) {
11198 left = read_expr(state, def);
11199 integral(state, left);
11200 left = integral_promotion(state, left);
11204 right = read_expr(state, add_expr(state));
11205 integral(state, right);
11206 right = integral_promotion(state, right);
11208 op = (tok == TOK_SL)? OP_SL :
11209 is_signed(left->type)? OP_SSR: OP_USR;
11211 def = triple(state, op, left->type, left, right);
11221 static struct triple *relational_expr(struct compile_state *state)
11223 #if DEBUG_ROMCC_WARNINGS
11224 #warning "Extend relational exprs to work on more than arithmetic types"
11226 struct triple *def;
11228 def = shift_expr(state);
11230 struct triple *left, *right;
11231 struct type *arg_type;
11234 switch((tok = peek(state))) {
11239 left = read_expr(state, def);
11240 arithmetic(state, left);
11244 right = read_expr(state, shift_expr(state));
11245 arithmetic(state, right);
11247 arg_type = arithmetic_result(state, left, right);
11248 sign = is_signed(arg_type);
11251 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11252 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11253 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11254 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11256 def = triple(state, op, &int_type, left, right);
11266 static struct triple *equality_expr(struct compile_state *state)
11268 #if DEBUG_ROMCC_WARNINGS
11269 #warning "Extend equality exprs to work on more than arithmetic types"
11271 struct triple *def;
11273 def = relational_expr(state);
11275 struct triple *left, *right;
11278 switch((tok = peek(state))) {
11281 left = read_expr(state, def);
11282 arithmetic(state, left);
11284 right = read_expr(state, relational_expr(state));
11285 arithmetic(state, right);
11286 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11287 def = triple(state, op, &int_type, left, right);
11297 static struct triple *and_expr(struct compile_state *state)
11299 struct triple *def;
11300 def = equality_expr(state);
11301 while(peek(state) == TOK_AND) {
11302 struct triple *left, *right;
11303 struct type *result_type;
11304 left = read_expr(state, def);
11305 integral(state, left);
11306 eat(state, TOK_AND);
11307 right = read_expr(state, equality_expr(state));
11308 integral(state, right);
11309 result_type = arithmetic_result(state, left, right);
11310 def = triple(state, OP_AND, result_type, left, right);
11315 static struct triple *xor_expr(struct compile_state *state)
11317 struct triple *def;
11318 def = and_expr(state);
11319 while(peek(state) == TOK_XOR) {
11320 struct triple *left, *right;
11321 struct type *result_type;
11322 left = read_expr(state, def);
11323 integral(state, left);
11324 eat(state, TOK_XOR);
11325 right = read_expr(state, and_expr(state));
11326 integral(state, right);
11327 result_type = arithmetic_result(state, left, right);
11328 def = triple(state, OP_XOR, result_type, left, right);
11333 static struct triple *or_expr(struct compile_state *state)
11335 struct triple *def;
11336 def = xor_expr(state);
11337 while(peek(state) == TOK_OR) {
11338 struct triple *left, *right;
11339 struct type *result_type;
11340 left = read_expr(state, def);
11341 integral(state, left);
11342 eat(state, TOK_OR);
11343 right = read_expr(state, xor_expr(state));
11344 integral(state, right);
11345 result_type = arithmetic_result(state, left, right);
11346 def = triple(state, OP_OR, result_type, left, right);
11351 static struct triple *land_expr(struct compile_state *state)
11353 struct triple *def;
11354 def = or_expr(state);
11355 while(peek(state) == TOK_LOGAND) {
11356 struct triple *left, *right;
11357 left = read_expr(state, def);
11359 eat(state, TOK_LOGAND);
11360 right = read_expr(state, or_expr(state));
11361 bool(state, right);
11363 def = mkland_expr(state,
11364 ltrue_expr(state, left),
11365 ltrue_expr(state, right));
11370 static struct triple *lor_expr(struct compile_state *state)
11372 struct triple *def;
11373 def = land_expr(state);
11374 while(peek(state) == TOK_LOGOR) {
11375 struct triple *left, *right;
11376 left = read_expr(state, def);
11378 eat(state, TOK_LOGOR);
11379 right = read_expr(state, land_expr(state));
11380 bool(state, right);
11382 def = mklor_expr(state,
11383 ltrue_expr(state, left),
11384 ltrue_expr(state, right));
11389 static struct triple *conditional_expr(struct compile_state *state)
11391 struct triple *def;
11392 def = lor_expr(state);
11393 if (peek(state) == TOK_QUEST) {
11394 struct triple *test, *left, *right;
11396 test = ltrue_expr(state, read_expr(state, def));
11397 eat(state, TOK_QUEST);
11398 left = read_expr(state, expr(state));
11399 eat(state, TOK_COLON);
11400 right = read_expr(state, conditional_expr(state));
11402 def = mkcond_expr(state, test, left, right);
11408 struct triple *val;
11412 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11413 struct triple *dest, struct triple *val)
11415 if (cv[dest->id].val) {
11416 free_triple(state, cv[dest->id].val);
11418 cv[dest->id].val = val;
11420 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11421 struct triple *src)
11423 return cv[src->id].val;
11426 static struct triple *eval_const_expr(
11427 struct compile_state *state, struct triple *expr)
11429 struct triple *def;
11430 if (is_const(expr)) {
11434 /* If we don't start out as a constant simplify into one */
11435 struct triple *head, *ptr;
11436 struct cv_triple *cv;
11438 head = label(state); /* dummy initial triple */
11439 flatten(state, head, expr);
11441 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11444 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11446 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11448 cv[i].id = ptr->id;
11454 valid_ins(state, ptr);
11455 if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11456 internal_error(state, ptr,
11457 "unexpected %s in constant expression",
11460 else if (ptr->op == OP_LIST) {
11462 else if (triple_is_structural(state, ptr)) {
11465 else if (triple_is_ubranch(state, ptr)) {
11466 ptr = TARG(ptr, 0);
11468 else if (triple_is_cbranch(state, ptr)) {
11469 struct triple *cond_val;
11470 cond_val = get_cv(state, cv, RHS(ptr, 0));
11471 if (!cond_val || !is_const(cond_val) ||
11472 (cond_val->op != OP_INTCONST))
11474 internal_error(state, ptr, "bad branch condition");
11476 if (cond_val->u.cval == 0) {
11479 ptr = TARG(ptr, 0);
11482 else if (triple_is_branch(state, ptr)) {
11483 error(state, ptr, "bad branch type in constant expression");
11485 else if (ptr->op == OP_WRITE) {
11486 struct triple *val;
11487 val = get_cv(state, cv, RHS(ptr, 0));
11489 set_cv(state, cv, MISC(ptr, 0),
11490 copy_triple(state, val));
11491 set_cv(state, cv, ptr,
11492 copy_triple(state, val));
11495 else if (ptr->op == OP_READ) {
11496 set_cv(state, cv, ptr,
11498 get_cv(state, cv, RHS(ptr, 0))));
11501 else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11502 struct triple *val, **rhs;
11503 val = copy_triple(state, ptr);
11504 rhs = triple_rhs(state, val, 0);
11505 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11507 internal_error(state, ptr, "Missing rhs");
11509 *rhs = get_cv(state, cv, *rhs);
11511 simplify(state, val);
11512 set_cv(state, cv, ptr, val);
11516 error(state, ptr, "impure operation in constant expression");
11519 } while(ptr != head);
11521 /* Get the result value */
11522 def = get_cv(state, cv, head->prev);
11523 cv[head->prev->id].val = 0;
11525 /* Free the temporary values */
11526 for(i = 0; i < count; i++) {
11528 free_triple(state, cv[i].val);
11533 /* Free the intermediate expressions */
11534 while(head->next != head) {
11535 release_triple(state, head->next);
11537 free_triple(state, head);
11539 if (!is_const(def)) {
11540 error(state, expr, "Not a constant expression");
11545 static struct triple *constant_expr(struct compile_state *state)
11547 return eval_const_expr(state, conditional_expr(state));
11550 static struct triple *assignment_expr(struct compile_state *state)
11552 struct triple *def, *left, *right;
11554 /* The C grammer in K&R shows assignment expressions
11555 * only taking unary expressions as input on their
11556 * left hand side. But specifies the precedence of
11557 * assignemnt as the lowest operator except for comma.
11559 * Allowing conditional expressions on the left hand side
11560 * of an assignement results in a grammar that accepts
11561 * a larger set of statements than standard C. As long
11562 * as the subset of the grammar that is standard C behaves
11563 * correctly this should cause no problems.
11565 * For the extra token strings accepted by the grammar
11566 * none of them should produce a valid lvalue, so they
11567 * should not produce functioning programs.
11569 * GCC has this bug as well, so surprises should be minimal.
11571 def = conditional_expr(state);
11573 switch((tok = peek(state))) {
11575 lvalue(state, left);
11576 eat(state, TOK_EQ);
11577 def = write_expr(state, left,
11578 read_expr(state, assignment_expr(state)));
11583 lvalue(state, left);
11584 arithmetic(state, left);
11586 right = read_expr(state, assignment_expr(state));
11587 arithmetic(state, right);
11589 sign = is_signed(left->type);
11592 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11593 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11594 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11596 def = write_expr(state, left,
11597 triple(state, op, left->type,
11598 read_expr(state, left), right));
11601 lvalue(state, left);
11602 eat(state, TOK_PLUSEQ);
11603 def = write_expr(state, left,
11604 mk_add_expr(state, left, assignment_expr(state)));
11607 lvalue(state, left);
11608 eat(state, TOK_MINUSEQ);
11609 def = write_expr(state, left,
11610 mk_sub_expr(state, left, assignment_expr(state)));
11617 lvalue(state, left);
11618 integral(state, left);
11620 right = read_expr(state, assignment_expr(state));
11621 integral(state, right);
11622 right = integral_promotion(state, right);
11623 sign = is_signed(left->type);
11626 case TOK_SLEQ: op = OP_SL; break;
11627 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11628 case TOK_ANDEQ: op = OP_AND; break;
11629 case TOK_XOREQ: op = OP_XOR; break;
11630 case TOK_OREQ: op = OP_OR; break;
11632 def = write_expr(state, left,
11633 triple(state, op, left->type,
11634 read_expr(state, left), right));
11640 static struct triple *expr(struct compile_state *state)
11642 struct triple *def;
11643 def = assignment_expr(state);
11644 while(peek(state) == TOK_COMMA) {
11645 eat(state, TOK_COMMA);
11646 def = mkprog(state, def, assignment_expr(state), 0UL);
11651 static void expr_statement(struct compile_state *state, struct triple *first)
11653 if (peek(state) != TOK_SEMI) {
11654 /* lvalue conversions always apply except when certian operators
11655 * are applied. I apply the lvalue conversions here
11656 * as I know no more operators will be applied.
11658 flatten(state, first, lvalue_conversion(state, expr(state)));
11660 eat(state, TOK_SEMI);
11663 static void if_statement(struct compile_state *state, struct triple *first)
11665 struct triple *test, *jmp1, *jmp2, *middle, *end;
11667 jmp1 = jmp2 = middle = 0;
11668 eat(state, TOK_IF);
11669 eat(state, TOK_LPAREN);
11670 test = expr(state);
11672 /* Cleanup and invert the test */
11673 test = lfalse_expr(state, read_expr(state, test));
11674 eat(state, TOK_RPAREN);
11675 /* Generate the needed pieces */
11676 middle = label(state);
11677 jmp1 = branch(state, middle, test);
11678 /* Thread the pieces together */
11679 flatten(state, first, test);
11680 flatten(state, first, jmp1);
11681 flatten(state, first, label(state));
11682 statement(state, first);
11683 if (peek(state) == TOK_ELSE) {
11684 eat(state, TOK_ELSE);
11685 /* Generate the rest of the pieces */
11686 end = label(state);
11687 jmp2 = branch(state, end, 0);
11688 /* Thread them together */
11689 flatten(state, first, jmp2);
11690 flatten(state, first, middle);
11691 statement(state, first);
11692 flatten(state, first, end);
11695 flatten(state, first, middle);
11699 static void for_statement(struct compile_state *state, struct triple *first)
11701 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11702 struct triple *label1, *label2, *label3;
11703 struct hash_entry *ident;
11705 eat(state, TOK_FOR);
11706 eat(state, TOK_LPAREN);
11707 head = test = tail = jmp1 = jmp2 = 0;
11708 if (peek(state) != TOK_SEMI) {
11709 head = expr(state);
11711 eat(state, TOK_SEMI);
11712 if (peek(state) != TOK_SEMI) {
11713 test = expr(state);
11715 test = ltrue_expr(state, read_expr(state, test));
11717 eat(state, TOK_SEMI);
11718 if (peek(state) != TOK_RPAREN) {
11719 tail = expr(state);
11721 eat(state, TOK_RPAREN);
11722 /* Generate the needed pieces */
11723 label1 = label(state);
11724 label2 = label(state);
11725 label3 = label(state);
11727 jmp1 = branch(state, label3, 0);
11728 jmp2 = branch(state, label1, test);
11731 jmp2 = branch(state, label1, 0);
11733 end = label(state);
11734 /* Remember where break and continue go */
11735 start_scope(state);
11736 ident = state->i_break;
11737 symbol(state, ident, &ident->sym_ident, end, end->type);
11738 ident = state->i_continue;
11739 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11740 /* Now include the body */
11741 flatten(state, first, head);
11742 flatten(state, first, jmp1);
11743 flatten(state, first, label1);
11744 statement(state, first);
11745 flatten(state, first, label2);
11746 flatten(state, first, tail);
11747 flatten(state, first, label3);
11748 flatten(state, first, test);
11749 flatten(state, first, jmp2);
11750 flatten(state, first, end);
11751 /* Cleanup the break/continue scope */
11755 static void while_statement(struct compile_state *state, struct triple *first)
11757 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11758 struct hash_entry *ident;
11759 eat(state, TOK_WHILE);
11760 eat(state, TOK_LPAREN);
11761 test = expr(state);
11763 test = ltrue_expr(state, read_expr(state, test));
11764 eat(state, TOK_RPAREN);
11765 /* Generate the needed pieces */
11766 label1 = label(state);
11767 label2 = label(state);
11768 jmp1 = branch(state, label2, 0);
11769 jmp2 = branch(state, label1, test);
11770 end = label(state);
11771 /* Remember where break and continue go */
11772 start_scope(state);
11773 ident = state->i_break;
11774 symbol(state, ident, &ident->sym_ident, end, end->type);
11775 ident = state->i_continue;
11776 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11777 /* Thread them together */
11778 flatten(state, first, jmp1);
11779 flatten(state, first, label1);
11780 statement(state, first);
11781 flatten(state, first, label2);
11782 flatten(state, first, test);
11783 flatten(state, first, jmp2);
11784 flatten(state, first, end);
11785 /* Cleanup the break/continue scope */
11789 static void do_statement(struct compile_state *state, struct triple *first)
11791 struct triple *label1, *label2, *test, *end;
11792 struct hash_entry *ident;
11793 eat(state, TOK_DO);
11794 /* Generate the needed pieces */
11795 label1 = label(state);
11796 label2 = label(state);
11797 end = label(state);
11798 /* Remember where break and continue go */
11799 start_scope(state);
11800 ident = state->i_break;
11801 symbol(state, ident, &ident->sym_ident, end, end->type);
11802 ident = state->i_continue;
11803 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11804 /* Now include the body */
11805 flatten(state, first, label1);
11806 statement(state, first);
11807 /* Cleanup the break/continue scope */
11809 /* Eat the rest of the loop */
11810 eat(state, TOK_WHILE);
11811 eat(state, TOK_LPAREN);
11812 test = read_expr(state, expr(state));
11814 eat(state, TOK_RPAREN);
11815 eat(state, TOK_SEMI);
11816 /* Thread the pieces together */
11817 test = ltrue_expr(state, test);
11818 flatten(state, first, label2);
11819 flatten(state, first, test);
11820 flatten(state, first, branch(state, label1, test));
11821 flatten(state, first, end);
11825 static void return_statement(struct compile_state *state, struct triple *first)
11827 struct triple *jmp, *mv, *dest, *var, *val;
11829 eat(state, TOK_RETURN);
11831 #if DEBUG_ROMCC_WARNINGS
11832 #warning "FIXME implement a more general excess branch elimination"
11835 /* If we have a return value do some more work */
11836 if (peek(state) != TOK_SEMI) {
11837 val = read_expr(state, expr(state));
11839 eat(state, TOK_SEMI);
11841 /* See if this last statement in a function */
11842 last = ((peek(state) == TOK_RBRACE) &&
11843 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11845 /* Find the return variable */
11846 var = fresult(state, state->main_function);
11848 /* Find the return destination */
11849 dest = state->i_return->sym_ident->def;
11851 /* If needed generate a jump instruction */
11853 jmp = branch(state, dest, 0);
11855 /* If needed generate an assignment instruction */
11857 mv = write_expr(state, deref_index(state, var, 1), val);
11859 /* Now put the code together */
11861 flatten(state, first, mv);
11862 flatten(state, first, jmp);
11865 flatten(state, first, jmp);
11869 static void break_statement(struct compile_state *state, struct triple *first)
11871 struct triple *dest;
11872 eat(state, TOK_BREAK);
11873 eat(state, TOK_SEMI);
11874 if (!state->i_break->sym_ident) {
11875 error(state, 0, "break statement not within loop or switch");
11877 dest = state->i_break->sym_ident->def;
11878 flatten(state, first, branch(state, dest, 0));
11881 static void continue_statement(struct compile_state *state, struct triple *first)
11883 struct triple *dest;
11884 eat(state, TOK_CONTINUE);
11885 eat(state, TOK_SEMI);
11886 if (!state->i_continue->sym_ident) {
11887 error(state, 0, "continue statement outside of a loop");
11889 dest = state->i_continue->sym_ident->def;
11890 flatten(state, first, branch(state, dest, 0));
11893 static void goto_statement(struct compile_state *state, struct triple *first)
11895 struct hash_entry *ident;
11896 eat(state, TOK_GOTO);
11897 ident = eat(state, TOK_IDENT)->ident;
11898 if (!ident->sym_label) {
11899 /* If this is a forward branch allocate the label now,
11900 * it will be flattend in the appropriate location later.
11902 struct triple *ins;
11903 ins = label(state);
11904 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11906 eat(state, TOK_SEMI);
11908 flatten(state, first, branch(state, ident->sym_label->def, 0));
11911 static void labeled_statement(struct compile_state *state, struct triple *first)
11913 struct triple *ins;
11914 struct hash_entry *ident;
11916 ident = eat(state, TOK_IDENT)->ident;
11917 if (ident->sym_label && ident->sym_label->def) {
11918 ins = ident->sym_label->def;
11919 put_occurance(ins->occurance);
11920 ins->occurance = new_occurance(state);
11923 ins = label(state);
11924 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11926 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11927 error(state, 0, "label %s already defined", ident->name);
11929 flatten(state, first, ins);
11931 eat(state, TOK_COLON);
11932 statement(state, first);
11935 static void switch_statement(struct compile_state *state, struct triple *first)
11937 struct triple *value, *top, *end, *dbranch;
11938 struct hash_entry *ident;
11940 /* See if we have a valid switch statement */
11941 eat(state, TOK_SWITCH);
11942 eat(state, TOK_LPAREN);
11943 value = expr(state);
11944 integral(state, value);
11945 value = read_expr(state, value);
11946 eat(state, TOK_RPAREN);
11947 /* Generate the needed pieces */
11948 top = label(state);
11949 end = label(state);
11950 dbranch = branch(state, end, 0);
11951 /* Remember where case branches and break goes */
11952 start_scope(state);
11953 ident = state->i_switch;
11954 symbol(state, ident, &ident->sym_ident, value, value->type);
11955 ident = state->i_case;
11956 symbol(state, ident, &ident->sym_ident, top, top->type);
11957 ident = state->i_break;
11958 symbol(state, ident, &ident->sym_ident, end, end->type);
11959 ident = state->i_default;
11960 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11961 /* Thread them together */
11962 flatten(state, first, value);
11963 flatten(state, first, top);
11964 flatten(state, first, dbranch);
11965 statement(state, first);
11966 flatten(state, first, end);
11967 /* Cleanup the switch scope */
11971 static void case_statement(struct compile_state *state, struct triple *first)
11973 struct triple *cvalue, *dest, *test, *jmp;
11974 struct triple *ptr, *value, *top, *dbranch;
11976 /* See if w have a valid case statement */
11977 eat(state, TOK_CASE);
11978 cvalue = constant_expr(state);
11979 integral(state, cvalue);
11980 if (cvalue->op != OP_INTCONST) {
11981 error(state, 0, "integer constant expected");
11983 eat(state, TOK_COLON);
11984 if (!state->i_case->sym_ident) {
11985 error(state, 0, "case statement not within a switch");
11988 /* Lookup the interesting pieces */
11989 top = state->i_case->sym_ident->def;
11990 value = state->i_switch->sym_ident->def;
11991 dbranch = state->i_default->sym_ident->def;
11993 /* See if this case label has already been used */
11994 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11995 if (ptr->op != OP_EQ) {
11998 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11999 error(state, 0, "duplicate case %d statement",
12003 /* Generate the needed pieces */
12004 dest = label(state);
12005 test = triple(state, OP_EQ, &int_type, value, cvalue);
12006 jmp = branch(state, dest, test);
12007 /* Thread the pieces together */
12008 flatten(state, dbranch, test);
12009 flatten(state, dbranch, jmp);
12010 flatten(state, dbranch, label(state));
12011 flatten(state, first, dest);
12012 statement(state, first);
12015 static void default_statement(struct compile_state *state, struct triple *first)
12017 struct triple *dest;
12018 struct triple *dbranch, *end;
12020 /* See if we have a valid default statement */
12021 eat(state, TOK_DEFAULT);
12022 eat(state, TOK_COLON);
12024 if (!state->i_case->sym_ident) {
12025 error(state, 0, "default statement not within a switch");
12028 /* Lookup the interesting pieces */
12029 dbranch = state->i_default->sym_ident->def;
12030 end = state->i_break->sym_ident->def;
12032 /* See if a default statement has already happened */
12033 if (TARG(dbranch, 0) != end) {
12034 error(state, 0, "duplicate default statement");
12037 /* Generate the needed pieces */
12038 dest = label(state);
12040 /* Blame the branch on the default statement */
12041 put_occurance(dbranch->occurance);
12042 dbranch->occurance = new_occurance(state);
12044 /* Thread the pieces together */
12045 TARG(dbranch, 0) = dest;
12046 use_triple(dest, dbranch);
12047 flatten(state, first, dest);
12048 statement(state, first);
12051 static void asm_statement(struct compile_state *state, struct triple *first)
12053 struct asm_info *info;
12055 struct triple *constraint;
12056 struct triple *expr;
12057 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12058 struct triple *def, *asm_str;
12059 int out, in, clobbers, more, colons, i;
12063 eat(state, TOK_ASM);
12064 /* For now ignore the qualifiers */
12065 switch(peek(state)) {
12067 eat(state, TOK_CONST);
12070 eat(state, TOK_VOLATILE);
12071 flags |= TRIPLE_FLAG_VOLATILE;
12074 eat(state, TOK_LPAREN);
12075 asm_str = string_constant(state);
12078 out = in = clobbers = 0;
12080 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12081 eat(state, TOK_COLON);
12083 more = (peek(state) == TOK_LIT_STRING);
12085 struct triple *var;
12086 struct triple *constraint;
12089 if (out > MAX_LHS) {
12090 error(state, 0, "Maximum output count exceeded.");
12092 constraint = string_constant(state);
12093 str = constraint->u.blob;
12094 if (str[0] != '=') {
12095 error(state, 0, "Output constraint does not start with =");
12097 constraint->u.blob = str + 1;
12098 eat(state, TOK_LPAREN);
12099 var = conditional_expr(state);
12100 eat(state, TOK_RPAREN);
12102 lvalue(state, var);
12103 out_param[out].constraint = constraint;
12104 out_param[out].expr = var;
12105 if (peek(state) == TOK_COMMA) {
12106 eat(state, TOK_COMMA);
12113 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12114 eat(state, TOK_COLON);
12116 more = (peek(state) == TOK_LIT_STRING);
12118 struct triple *val;
12119 struct triple *constraint;
12122 if (in > MAX_RHS) {
12123 error(state, 0, "Maximum input count exceeded.");
12125 constraint = string_constant(state);
12126 str = constraint->u.blob;
12127 if (digitp(str[0] && str[1] == '\0')) {
12129 val = digval(str[0]);
12130 if ((val < 0) || (val >= out)) {
12131 error(state, 0, "Invalid input constraint %d", val);
12134 eat(state, TOK_LPAREN);
12135 val = conditional_expr(state);
12136 eat(state, TOK_RPAREN);
12138 in_param[in].constraint = constraint;
12139 in_param[in].expr = val;
12140 if (peek(state) == TOK_COMMA) {
12141 eat(state, TOK_COMMA);
12149 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12150 eat(state, TOK_COLON);
12152 more = (peek(state) == TOK_LIT_STRING);
12154 struct triple *clobber;
12156 if ((clobbers + out) > MAX_LHS) {
12157 error(state, 0, "Maximum clobber limit exceeded.");
12159 clobber = string_constant(state);
12161 clob_param[clobbers].constraint = clobber;
12162 if (peek(state) == TOK_COMMA) {
12163 eat(state, TOK_COMMA);
12169 eat(state, TOK_RPAREN);
12170 eat(state, TOK_SEMI);
12173 info = xcmalloc(sizeof(*info), "asm_info");
12174 info->str = asm_str->u.blob;
12175 free_triple(state, asm_str);
12177 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12178 def->u.ainfo = info;
12181 /* Find the register constraints */
12182 for(i = 0; i < out; i++) {
12183 struct triple *constraint;
12184 constraint = out_param[i].constraint;
12185 info->tmpl.lhs[i] = arch_reg_constraint(state,
12186 out_param[i].expr->type, constraint->u.blob);
12187 free_triple(state, constraint);
12189 for(; i - out < clobbers; i++) {
12190 struct triple *constraint;
12191 constraint = clob_param[i - out].constraint;
12192 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12193 free_triple(state, constraint);
12195 for(i = 0; i < in; i++) {
12196 struct triple *constraint;
12198 constraint = in_param[i].constraint;
12199 str = constraint->u.blob;
12200 if (digitp(str[0]) && str[1] == '\0') {
12201 struct reg_info cinfo;
12203 val = digval(str[0]);
12204 cinfo.reg = info->tmpl.lhs[val].reg;
12205 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12206 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12207 if (cinfo.reg == REG_UNSET) {
12208 cinfo.reg = REG_VIRT0 + val;
12210 if (cinfo.regcm == 0) {
12211 error(state, 0, "No registers for %d", val);
12213 info->tmpl.lhs[val] = cinfo;
12214 info->tmpl.rhs[i] = cinfo;
12217 info->tmpl.rhs[i] = arch_reg_constraint(state,
12218 in_param[i].expr->type, str);
12220 free_triple(state, constraint);
12223 /* Now build the helper expressions */
12224 for(i = 0; i < in; i++) {
12225 RHS(def, i) = read_expr(state, in_param[i].expr);
12227 flatten(state, first, def);
12228 for(i = 0; i < (out + clobbers); i++) {
12230 struct triple *piece;
12232 type = out_param[i].expr->type;
12234 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12235 if (size >= SIZEOF_LONG) {
12236 type = &ulong_type;
12238 else if (size >= SIZEOF_INT) {
12241 else if (size >= SIZEOF_SHORT) {
12242 type = &ushort_type;
12245 type = &uchar_type;
12248 piece = triple(state, OP_PIECE, type, def, 0);
12250 LHS(def, i) = piece;
12251 flatten(state, first, piece);
12253 /* And write the helpers to their destinations */
12254 for(i = 0; i < out; i++) {
12255 struct triple *piece;
12256 piece = LHS(def, i);
12257 flatten(state, first,
12258 write_expr(state, out_param[i].expr, piece));
12263 static int isdecl(int tok)
12286 case TOK_TYPE_NAME: /* typedef name */
12293 static void compound_statement(struct compile_state *state, struct triple *first)
12295 eat(state, TOK_LBRACE);
12296 start_scope(state);
12298 /* statement-list opt */
12299 while (peek(state) != TOK_RBRACE) {
12300 statement(state, first);
12303 eat(state, TOK_RBRACE);
12306 static void statement(struct compile_state *state, struct triple *first)
12310 if (tok == TOK_LBRACE) {
12311 compound_statement(state, first);
12313 else if (tok == TOK_IF) {
12314 if_statement(state, first);
12316 else if (tok == TOK_FOR) {
12317 for_statement(state, first);
12319 else if (tok == TOK_WHILE) {
12320 while_statement(state, first);
12322 else if (tok == TOK_DO) {
12323 do_statement(state, first);
12325 else if (tok == TOK_RETURN) {
12326 return_statement(state, first);
12328 else if (tok == TOK_BREAK) {
12329 break_statement(state, first);
12331 else if (tok == TOK_CONTINUE) {
12332 continue_statement(state, first);
12334 else if (tok == TOK_GOTO) {
12335 goto_statement(state, first);
12337 else if (tok == TOK_SWITCH) {
12338 switch_statement(state, first);
12340 else if (tok == TOK_ASM) {
12341 asm_statement(state, first);
12343 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12344 labeled_statement(state, first);
12346 else if (tok == TOK_CASE) {
12347 case_statement(state, first);
12349 else if (tok == TOK_DEFAULT) {
12350 default_statement(state, first);
12352 else if (isdecl(tok)) {
12353 /* This handles C99 intermixing of statements and decls */
12354 decl(state, first);
12357 expr_statement(state, first);
12361 static struct type *param_decl(struct compile_state *state)
12364 struct hash_entry *ident;
12365 /* Cheat so the declarator will know we are not global */
12366 start_scope(state);
12368 type = decl_specifiers(state);
12369 type = declarator(state, type, &ident, 0);
12370 type->field_ident = ident;
12375 static struct type *param_type_list(struct compile_state *state, struct type *type)
12377 struct type *ftype, **next;
12378 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12379 next = &ftype->right;
12380 ftype->elements = 1;
12381 while(peek(state) == TOK_COMMA) {
12382 eat(state, TOK_COMMA);
12383 if (peek(state) == TOK_DOTS) {
12384 eat(state, TOK_DOTS);
12385 error(state, 0, "variadic functions not supported");
12388 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12389 next = &((*next)->right);
12396 static struct type *type_name(struct compile_state *state)
12399 type = specifier_qualifier_list(state);
12400 /* abstract-declarator (may consume no tokens) */
12401 type = declarator(state, type, 0, 0);
12405 static struct type *direct_declarator(
12406 struct compile_state *state, struct type *type,
12407 struct hash_entry **pident, int need_ident)
12409 struct hash_entry *ident;
12410 struct type *outer;
12413 arrays_complete(state, type);
12414 switch(peek(state)) {
12416 ident = eat(state, TOK_IDENT)->ident;
12418 error(state, 0, "Unexpected identifier found");
12420 /* The name of what we are declaring */
12424 eat(state, TOK_LPAREN);
12425 outer = declarator(state, type, pident, need_ident);
12426 eat(state, TOK_RPAREN);
12430 error(state, 0, "Identifier expected");
12436 arrays_complete(state, type);
12437 switch(peek(state)) {
12439 eat(state, TOK_LPAREN);
12440 type = param_type_list(state, type);
12441 eat(state, TOK_RPAREN);
12445 unsigned int qualifiers;
12446 struct triple *value;
12448 eat(state, TOK_LBRACKET);
12449 if (peek(state) != TOK_RBRACKET) {
12450 value = constant_expr(state);
12451 integral(state, value);
12453 eat(state, TOK_RBRACKET);
12455 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12456 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12458 type->elements = value->u.cval;
12459 free_triple(state, value);
12461 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12472 struct type *inner;
12473 arrays_complete(state, type);
12475 for(inner = outer; inner->left; inner = inner->left)
12477 inner->left = type;
12483 static struct type *declarator(
12484 struct compile_state *state, struct type *type,
12485 struct hash_entry **pident, int need_ident)
12487 while(peek(state) == TOK_STAR) {
12488 eat(state, TOK_STAR);
12489 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12491 type = direct_declarator(state, type, pident, need_ident);
12495 static struct type *typedef_name(
12496 struct compile_state *state, unsigned int specifiers)
12498 struct hash_entry *ident;
12500 ident = eat(state, TOK_TYPE_NAME)->ident;
12501 type = ident->sym_ident->type;
12502 specifiers |= type->type & QUAL_MASK;
12503 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12504 (type->type & (STOR_MASK | QUAL_MASK))) {
12505 type = clone_type(specifiers, type);
12510 static struct type *enum_specifier(
12511 struct compile_state *state, unsigned int spec)
12513 struct hash_entry *ident;
12516 struct type *enum_type;
12519 eat(state, TOK_ENUM);
12521 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12522 ident = eat(state, tok)->ident;
12525 if (!ident || (peek(state) == TOK_LBRACE)) {
12526 struct type **next;
12527 eat(state, TOK_LBRACE);
12528 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12529 enum_type->type_ident = ident;
12530 next = &enum_type->right;
12532 struct hash_entry *eident;
12533 struct triple *value;
12534 struct type *entry;
12535 eident = eat(state, TOK_IDENT)->ident;
12536 if (eident->sym_ident) {
12537 error(state, 0, "%s already declared",
12540 eident->tok = TOK_ENUM_CONST;
12541 if (peek(state) == TOK_EQ) {
12542 struct triple *val;
12543 eat(state, TOK_EQ);
12544 val = constant_expr(state);
12545 integral(state, val);
12546 base = val->u.cval;
12548 value = int_const(state, &int_type, base);
12549 symbol(state, eident, &eident->sym_ident, value, &int_type);
12550 entry = new_type(TYPE_LIST, 0, 0);
12551 entry->field_ident = eident;
12553 next = &entry->right;
12555 if (peek(state) == TOK_COMMA) {
12556 eat(state, TOK_COMMA);
12558 } while(peek(state) != TOK_RBRACE);
12559 eat(state, TOK_RBRACE);
12561 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12564 if (ident && ident->sym_tag &&
12565 ident->sym_tag->type &&
12566 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12567 enum_type = clone_type(spec, ident->sym_tag->type);
12569 else if (ident && !enum_type) {
12570 error(state, 0, "enum %s undeclared", ident->name);
12575 static struct type *struct_declarator(
12576 struct compile_state *state, struct type *type, struct hash_entry **ident)
12578 if (peek(state) != TOK_COLON) {
12579 type = declarator(state, type, ident, 1);
12581 if (peek(state) == TOK_COLON) {
12582 struct triple *value;
12583 eat(state, TOK_COLON);
12584 value = constant_expr(state);
12585 if (value->op != OP_INTCONST) {
12586 error(state, 0, "Invalid constant expression");
12588 if (value->u.cval > size_of(state, type)) {
12589 error(state, 0, "bitfield larger than base type");
12591 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12592 error(state, 0, "bitfield base not an integer type");
12594 type = new_type(TYPE_BITFIELD, type, 0);
12595 type->elements = value->u.cval;
12600 static struct type *struct_or_union_specifier(
12601 struct compile_state *state, unsigned int spec)
12603 struct type *struct_type;
12604 struct hash_entry *ident;
12605 unsigned int type_main;
12606 unsigned int type_join;
12610 switch(peek(state)) {
12612 eat(state, TOK_STRUCT);
12613 type_main = TYPE_STRUCT;
12614 type_join = TYPE_PRODUCT;
12617 eat(state, TOK_UNION);
12618 type_main = TYPE_UNION;
12619 type_join = TYPE_OVERLAP;
12622 eat(state, TOK_STRUCT);
12623 type_main = TYPE_STRUCT;
12624 type_join = TYPE_PRODUCT;
12628 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12629 ident = eat(state, tok)->ident;
12631 if (!ident || (peek(state) == TOK_LBRACE)) {
12633 struct type **next;
12635 eat(state, TOK_LBRACE);
12636 next = &struct_type;
12638 struct type *base_type;
12640 base_type = specifier_qualifier_list(state);
12643 struct hash_entry *fident;
12645 type = struct_declarator(state, base_type, &fident);
12647 if (peek(state) == TOK_COMMA) {
12649 eat(state, TOK_COMMA);
12651 type = clone_type(0, type);
12652 type->field_ident = fident;
12654 *next = new_type(type_join, *next, type);
12655 next = &((*next)->right);
12660 eat(state, TOK_SEMI);
12661 } while(peek(state) != TOK_RBRACE);
12662 eat(state, TOK_RBRACE);
12663 struct_type = new_type(type_main | spec, struct_type, 0);
12664 struct_type->type_ident = ident;
12665 struct_type->elements = elements;
12667 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12670 if (ident && ident->sym_tag &&
12671 ident->sym_tag->type &&
12672 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12673 struct_type = clone_type(spec, ident->sym_tag->type);
12675 else if (ident && !struct_type) {
12676 error(state, 0, "%s %s undeclared",
12677 (type_main == TYPE_STRUCT)?"struct" : "union",
12680 return struct_type;
12683 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12685 unsigned int specifiers;
12686 switch(peek(state)) {
12688 eat(state, TOK_AUTO);
12689 specifiers = STOR_AUTO;
12692 eat(state, TOK_REGISTER);
12693 specifiers = STOR_REGISTER;
12696 eat(state, TOK_STATIC);
12697 specifiers = STOR_STATIC;
12700 eat(state, TOK_EXTERN);
12701 specifiers = STOR_EXTERN;
12704 eat(state, TOK_TYPEDEF);
12705 specifiers = STOR_TYPEDEF;
12708 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12709 specifiers = STOR_LOCAL;
12712 specifiers = STOR_AUTO;
12718 static unsigned int function_specifier_opt(struct compile_state *state)
12720 /* Ignore the inline keyword */
12721 unsigned int specifiers;
12723 switch(peek(state)) {
12725 eat(state, TOK_INLINE);
12726 specifiers = STOR_INLINE;
12731 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12733 int tok = peek(state);
12737 /* The empty attribute ignore it */
12740 case TOK_ENUM_CONST:
12741 case TOK_TYPE_NAME:
12743 struct hash_entry *ident;
12744 ident = eat(state, TOK_IDENT)->ident;
12746 if (ident == state->i_noinline) {
12747 if (attributes & ATTRIB_ALWAYS_INLINE) {
12748 error(state, 0, "both always_inline and noinline attribtes");
12750 attributes |= ATTRIB_NOINLINE;
12752 else if (ident == state->i_always_inline) {
12753 if (attributes & ATTRIB_NOINLINE) {
12754 error(state, 0, "both noinline and always_inline attribtes");
12756 attributes |= ATTRIB_ALWAYS_INLINE;
12759 error(state, 0, "Unknown attribute:%s", ident->name);
12764 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12770 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12772 type = attrib(state, type);
12773 while(peek(state) == TOK_COMMA) {
12774 eat(state, TOK_COMMA);
12775 type = attrib(state, type);
12780 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12782 if (peek(state) == TOK_ATTRIBUTE) {
12783 eat(state, TOK_ATTRIBUTE);
12784 eat(state, TOK_LPAREN);
12785 eat(state, TOK_LPAREN);
12786 type = attribute_list(state, type);
12787 eat(state, TOK_RPAREN);
12788 eat(state, TOK_RPAREN);
12793 static unsigned int type_qualifiers(struct compile_state *state)
12795 unsigned int specifiers;
12798 specifiers = QUAL_NONE;
12800 switch(peek(state)) {
12802 eat(state, TOK_CONST);
12803 specifiers |= QUAL_CONST;
12806 eat(state, TOK_VOLATILE);
12807 specifiers |= QUAL_VOLATILE;
12810 eat(state, TOK_RESTRICT);
12811 specifiers |= QUAL_RESTRICT;
12821 static struct type *type_specifier(
12822 struct compile_state *state, unsigned int spec)
12827 switch((tok = peek(state))) {
12829 eat(state, TOK_VOID);
12830 type = new_type(TYPE_VOID | spec, 0, 0);
12833 eat(state, TOK_CHAR);
12834 type = new_type(TYPE_CHAR | spec, 0, 0);
12837 eat(state, TOK_SHORT);
12838 if (peek(state) == TOK_INT) {
12839 eat(state, TOK_INT);
12841 type = new_type(TYPE_SHORT | spec, 0, 0);
12844 eat(state, TOK_INT);
12845 type = new_type(TYPE_INT | spec, 0, 0);
12848 eat(state, TOK_LONG);
12849 switch(peek(state)) {
12851 eat(state, TOK_LONG);
12852 error(state, 0, "long long not supported");
12855 eat(state, TOK_DOUBLE);
12856 error(state, 0, "long double not supported");
12859 eat(state, TOK_INT);
12860 type = new_type(TYPE_LONG | spec, 0, 0);
12863 type = new_type(TYPE_LONG | spec, 0, 0);
12868 eat(state, TOK_FLOAT);
12869 error(state, 0, "type float not supported");
12872 eat(state, TOK_DOUBLE);
12873 error(state, 0, "type double not supported");
12876 eat(state, TOK_SIGNED);
12877 switch(peek(state)) {
12879 eat(state, TOK_LONG);
12880 switch(peek(state)) {
12882 eat(state, TOK_LONG);
12883 error(state, 0, "type long long not supported");
12886 eat(state, TOK_INT);
12887 type = new_type(TYPE_LONG | spec, 0, 0);
12890 type = new_type(TYPE_LONG | spec, 0, 0);
12895 eat(state, TOK_INT);
12896 type = new_type(TYPE_INT | spec, 0, 0);
12899 eat(state, TOK_SHORT);
12900 type = new_type(TYPE_SHORT | spec, 0, 0);
12903 eat(state, TOK_CHAR);
12904 type = new_type(TYPE_CHAR | spec, 0, 0);
12907 type = new_type(TYPE_INT | spec, 0, 0);
12912 eat(state, TOK_UNSIGNED);
12913 switch(peek(state)) {
12915 eat(state, TOK_LONG);
12916 switch(peek(state)) {
12918 eat(state, TOK_LONG);
12919 error(state, 0, "unsigned long long not supported");
12922 eat(state, TOK_INT);
12923 type = new_type(TYPE_ULONG | spec, 0, 0);
12926 type = new_type(TYPE_ULONG | spec, 0, 0);
12931 eat(state, TOK_INT);
12932 type = new_type(TYPE_UINT | spec, 0, 0);
12935 eat(state, TOK_SHORT);
12936 type = new_type(TYPE_USHORT | spec, 0, 0);
12939 eat(state, TOK_CHAR);
12940 type = new_type(TYPE_UCHAR | spec, 0, 0);
12943 type = new_type(TYPE_UINT | spec, 0, 0);
12947 /* struct or union specifier */
12950 type = struct_or_union_specifier(state, spec);
12952 /* enum-spefifier */
12954 type = enum_specifier(state, spec);
12957 case TOK_TYPE_NAME:
12958 type = typedef_name(state, spec);
12961 error(state, 0, "bad type specifier %s",
12968 static int istype(int tok)
12986 case TOK_TYPE_NAME:
12994 static struct type *specifier_qualifier_list(struct compile_state *state)
12997 unsigned int specifiers = 0;
12999 /* type qualifiers */
13000 specifiers |= type_qualifiers(state);
13002 /* type specifier */
13003 type = type_specifier(state, specifiers);
13008 #if DEBUG_ROMCC_WARNING
13009 static int isdecl_specifier(int tok)
13012 /* storage class specifier */
13018 /* type qualifier */
13022 /* type specifiers */
13032 /* struct or union specifier */
13035 /* enum-spefifier */
13038 case TOK_TYPE_NAME:
13039 /* function specifiers */
13048 static struct type *decl_specifiers(struct compile_state *state)
13051 unsigned int specifiers;
13052 /* I am overly restrictive in the arragement of specifiers supported.
13053 * C is overly flexible in this department it makes interpreting
13054 * the parse tree difficult.
13058 /* storage class specifier */
13059 specifiers |= storage_class_specifier_opt(state);
13061 /* function-specifier */
13062 specifiers |= function_specifier_opt(state);
13065 specifiers |= attributes_opt(state, 0);
13067 /* type qualifier */
13068 specifiers |= type_qualifiers(state);
13070 /* type specifier */
13071 type = type_specifier(state, specifiers);
13075 struct field_info {
13080 static struct field_info designator(struct compile_state *state, struct type *type)
13083 struct field_info info;
13087 switch(peek(state)) {
13090 struct triple *value;
13091 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13092 error(state, 0, "Array designator not in array initializer");
13094 eat(state, TOK_LBRACKET);
13095 value = constant_expr(state);
13096 eat(state, TOK_RBRACKET);
13098 info.type = type->left;
13099 info.offset = value->u.cval * size_of(state, info.type);
13104 struct hash_entry *field;
13105 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13106 ((type->type & TYPE_MASK) != TYPE_UNION))
13108 error(state, 0, "Struct designator not in struct initializer");
13110 eat(state, TOK_DOT);
13111 field = eat(state, TOK_IDENT)->ident;
13112 info.offset = field_offset(state, type, field);
13113 info.type = field_type(state, type, field);
13117 error(state, 0, "Invalid designator");
13120 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13121 eat(state, TOK_EQ);
13125 static struct triple *initializer(
13126 struct compile_state *state, struct type *type)
13128 struct triple *result;
13129 #if DEBUG_ROMCC_WARNINGS
13130 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13132 if (peek(state) != TOK_LBRACE) {
13133 result = assignment_expr(state);
13134 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13135 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13136 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13137 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13138 (equiv_types(type->left, result->type->left))) {
13139 type->elements = result->type->elements;
13141 if (is_lvalue(state, result) &&
13142 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13143 (type->type & TYPE_MASK) != TYPE_ARRAY)
13145 result = lvalue_conversion(state, result);
13147 if (!is_init_compatible(state, type, result->type)) {
13148 error(state, 0, "Incompatible types in initializer");
13150 if (!equiv_types(type, result->type)) {
13151 result = mk_cast_expr(state, type, result);
13157 struct field_info info;
13159 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13160 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13161 internal_error(state, 0, "unknown initializer type");
13164 info.type = type->left;
13165 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13166 info.type = next_field(state, type, 0);
13168 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13171 max_offset = size_of(state, type);
13173 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13174 eat(state, TOK_LBRACE);
13176 struct triple *value;
13177 struct type *value_type;
13183 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13184 info = designator(state, type);
13186 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13187 (info.offset >= max_offset)) {
13188 error(state, 0, "element beyond bounds");
13190 value_type = info.type;
13191 value = eval_const_expr(state, initializer(state, value_type));
13192 value_size = size_of(state, value_type);
13193 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13194 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13195 (max_offset <= info.offset)) {
13199 old_size = max_offset;
13200 max_offset = info.offset + value_size;
13201 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13202 memcpy(buf, old_buf, bits_to_bytes(old_size));
13205 dest = ((char *)buf) + bits_to_bytes(info.offset);
13206 #if DEBUG_INITIALIZER
13207 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13209 bits_to_bytes(max_offset),
13210 bits_to_bytes(value_size),
13213 if (value->op == OP_BLOBCONST) {
13214 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13216 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13217 #if DEBUG_INITIALIZER
13218 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13220 *((uint8_t *)dest) = value->u.cval & 0xff;
13222 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13223 *((uint16_t *)dest) = value->u.cval & 0xffff;
13225 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13226 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13229 internal_error(state, 0, "unhandled constant initializer");
13231 free_triple(state, value);
13232 if (peek(state) == TOK_COMMA) {
13233 eat(state, TOK_COMMA);
13236 info.offset += value_size;
13237 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13238 info.type = next_field(state, type, info.type);
13239 info.offset = field_offset(state, type,
13240 info.type->field_ident);
13242 } while(comma && (peek(state) != TOK_RBRACE));
13243 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13244 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13245 type->elements = max_offset / size_of(state, type->left);
13247 eat(state, TOK_RBRACE);
13248 result = triple(state, OP_BLOBCONST, type, 0, 0);
13249 result->u.blob = buf;
13254 static void resolve_branches(struct compile_state *state, struct triple *first)
13256 /* Make a second pass and finish anything outstanding
13257 * with respect to branches. The only outstanding item
13258 * is to see if there are goto to labels that have not
13259 * been defined and to error about them.
13262 struct triple *ins;
13263 /* Also error on branches that do not use their targets */
13266 if (!triple_is_ret(state, ins)) {
13267 struct triple **expr ;
13268 struct triple_set *set;
13269 expr = triple_targ(state, ins, 0);
13270 for(; expr; expr = triple_targ(state, ins, expr)) {
13271 struct triple *targ;
13273 for(set = targ?targ->use:0; set; set = set->next) {
13274 if (set->member == ins) {
13279 internal_error(state, ins, "targ not used");
13284 } while(ins != first);
13285 /* See if there are goto to labels that have not been defined */
13286 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13287 struct hash_entry *entry;
13288 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13289 struct triple *ins;
13290 if (!entry->sym_label) {
13293 ins = entry->sym_label->def;
13294 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13295 error(state, ins, "label `%s' used but not defined",
13302 static struct triple *function_definition(
13303 struct compile_state *state, struct type *type)
13305 struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13306 struct triple *fname;
13307 struct type *fname_type;
13308 struct hash_entry *ident;
13309 struct type *param, *crtype, *ctype;
13311 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13312 error(state, 0, "Invalid function header");
13315 /* Verify the function type */
13316 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13317 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13318 (type->right->field_ident == 0)) {
13319 error(state, 0, "Invalid function parameters");
13321 param = type->right;
13323 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13325 if (!param->left->field_ident) {
13326 error(state, 0, "No identifier for parameter %d\n", i);
13328 param = param->right;
13331 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13332 error(state, 0, "No identifier for paramter %d\n", i);
13335 /* Get a list of statements for this function. */
13336 def = triple(state, OP_LIST, type, 0, 0);
13338 /* Start a new scope for the passed parameters */
13339 start_scope(state);
13341 /* Put a label at the very start of a function */
13342 first = label(state);
13343 RHS(def, 0) = first;
13345 /* Put a label at the very end of a function */
13346 end = label(state);
13347 flatten(state, first, end);
13348 /* Remember where return goes */
13349 ident = state->i_return;
13350 symbol(state, ident, &ident->sym_ident, end, end->type);
13352 /* Get the initial closure type */
13353 ctype = new_type(TYPE_JOIN, &void_type, 0);
13354 ctype->elements = 1;
13356 /* Add a variable for the return value */
13357 crtype = new_type(TYPE_TUPLE,
13358 /* Remove all type qualifiers from the return type */
13359 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13360 crtype->elements = 2;
13361 result = flatten(state, end, variable(state, crtype));
13363 /* Allocate a variable for the return address */
13364 retvar = flatten(state, end, variable(state, &void_ptr_type));
13366 /* Add in the return instruction */
13367 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13368 ret = flatten(state, first, ret);
13370 /* Walk through the parameters and create symbol table entries
13373 param = type->right;
13374 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13375 ident = param->left->field_ident;
13376 tmp = variable(state, param->left);
13377 var_symbol(state, ident, tmp);
13378 flatten(state, end, tmp);
13379 param = param->right;
13381 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13382 /* And don't forget the last parameter */
13383 ident = param->field_ident;
13384 tmp = variable(state, param);
13385 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13386 flatten(state, end, tmp);
13389 /* Add the declaration static const char __func__ [] = "func-name" */
13390 fname_type = new_type(TYPE_ARRAY,
13391 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13392 fname_type->type |= QUAL_CONST | STOR_STATIC;
13393 fname_type->elements = strlen(state->function) + 1;
13395 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13396 fname->u.blob = (void *)state->function;
13397 fname = flatten(state, end, fname);
13399 ident = state->i___func__;
13400 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13402 /* Remember which function I am compiling.
13403 * Also assume the last defined function is the main function.
13405 state->main_function = def;
13407 /* Now get the actual function definition */
13408 compound_statement(state, end);
13410 /* Finish anything unfinished with branches */
13411 resolve_branches(state, first);
13413 /* Remove the parameter scope */
13417 /* Remember I have defined a function */
13418 if (!state->functions) {
13419 state->functions = def;
13421 insert_triple(state, state->functions, def);
13423 if (state->compiler->debug & DEBUG_INLINE) {
13424 FILE *fp = state->dbgout;
13427 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13428 display_func(state, fp, def);
13429 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13435 static struct triple *do_decl(struct compile_state *state,
13436 struct type *type, struct hash_entry *ident)
13438 struct triple *def;
13440 /* Clean up the storage types used */
13441 switch (type->type & STOR_MASK) {
13444 /* These are the good types I am aiming for */
13446 case STOR_REGISTER:
13447 type->type &= ~STOR_MASK;
13448 type->type |= STOR_AUTO;
13452 type->type &= ~STOR_MASK;
13453 type->type |= STOR_STATIC;
13457 error(state, 0, "typedef without name");
13459 symbol(state, ident, &ident->sym_ident, 0, type);
13460 ident->tok = TOK_TYPE_NAME;
13464 internal_error(state, 0, "Undefined storage class");
13466 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13467 error(state, 0, "Function prototypes not supported");
13470 ((type->type & STOR_MASK) == STOR_STATIC) &&
13471 ((type->type & QUAL_CONST) == 0)) {
13472 error(state, 0, "non const static variables not supported");
13475 def = variable(state, type);
13476 var_symbol(state, ident, def);
13481 static void decl(struct compile_state *state, struct triple *first)
13483 struct type *base_type, *type;
13484 struct hash_entry *ident;
13485 struct triple *def;
13487 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13488 base_type = decl_specifiers(state);
13490 type = declarator(state, base_type, &ident, 0);
13491 type->type = attributes_opt(state, type->type);
13492 if (global && ident && (peek(state) == TOK_LBRACE)) {
13494 type->type_ident = ident;
13495 state->function = ident->name;
13496 def = function_definition(state, type);
13497 symbol(state, ident, &ident->sym_ident, def, type);
13498 state->function = 0;
13502 flatten(state, first, do_decl(state, type, ident));
13503 /* type or variable definition */
13506 if (peek(state) == TOK_EQ) {
13508 error(state, 0, "cannot assign to a type");
13510 eat(state, TOK_EQ);
13511 flatten(state, first,
13513 ident->sym_ident->def,
13514 initializer(state, type)));
13516 arrays_complete(state, type);
13517 if (peek(state) == TOK_COMMA) {
13518 eat(state, TOK_COMMA);
13520 type = declarator(state, base_type, &ident, 0);
13521 flatten(state, first, do_decl(state, type, ident));
13525 eat(state, TOK_SEMI);
13529 static void decls(struct compile_state *state)
13531 struct triple *list;
13533 list = label(state);
13536 if (tok == TOK_EOF) {
13539 if (tok == TOK_SPACE) {
13540 eat(state, TOK_SPACE);
13543 if (list->next != list) {
13544 error(state, 0, "global variables not supported");
13550 * Function inlining
13552 struct triple_reg_set {
13553 struct triple_reg_set *next;
13554 struct triple *member;
13555 struct triple *new;
13558 struct block *block;
13559 struct triple_reg_set *in;
13560 struct triple_reg_set *out;
13563 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13564 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13565 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13566 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13567 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13568 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13570 static void print_block(
13571 struct compile_state *state, struct block *block, void *arg);
13572 static int do_triple_set(struct triple_reg_set **head,
13573 struct triple *member, struct triple *new_member);
13574 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13575 static struct reg_block *compute_variable_lifetimes(
13576 struct compile_state *state, struct basic_blocks *bb);
13577 static void free_variable_lifetimes(struct compile_state *state,
13578 struct basic_blocks *bb, struct reg_block *blocks);
13579 #if DEBUG_EXPLICIT_CLOSURES
13580 static void print_live_variables(struct compile_state *state,
13581 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13585 static struct triple *call(struct compile_state *state,
13586 struct triple *retvar, struct triple *ret_addr,
13587 struct triple *targ, struct triple *ret)
13589 struct triple *call;
13591 if (!retvar || !is_lvalue(state, retvar)) {
13592 internal_error(state, 0, "writing to a non lvalue?");
13594 write_compatible(state, retvar->type, &void_ptr_type);
13596 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13597 TARG(call, 0) = targ;
13598 MISC(call, 0) = ret;
13599 if (!targ || (targ->op != OP_LABEL)) {
13600 internal_error(state, 0, "call not to a label");
13602 if (!ret || (ret->op != OP_RET)) {
13603 internal_error(state, 0, "call not matched with return");
13608 static void walk_functions(struct compile_state *state,
13609 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13612 struct triple *func, *first;
13613 func = first = state->functions;
13615 cb(state, func, arg);
13617 } while(func != first);
13620 static void reverse_walk_functions(struct compile_state *state,
13621 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13624 struct triple *func, *first;
13625 func = first = state->functions;
13628 cb(state, func, arg);
13629 } while(func != first);
13633 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13635 struct triple *ptr, *first;
13636 if (func->u.cval == 0) {
13639 ptr = first = RHS(func, 0);
13641 if (ptr->op == OP_FCALL) {
13642 struct triple *called_func;
13643 called_func = MISC(ptr, 0);
13644 /* Mark the called function as used */
13645 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13646 called_func->u.cval++;
13648 /* Remove the called function from the list */
13649 called_func->prev->next = called_func->next;
13650 called_func->next->prev = called_func->prev;
13652 /* Place the called function before me on the list */
13653 called_func->next = func;
13654 called_func->prev = func->prev;
13655 called_func->prev->next = called_func;
13656 called_func->next->prev = called_func;
13659 } while(ptr != first);
13660 func->id |= TRIPLE_FLAG_FLATTENED;
13663 static void mark_live_functions(struct compile_state *state)
13665 /* Ensure state->main_function is the last function in
13666 * the list of functions.
13668 if ((state->main_function->next != state->functions) ||
13669 (state->functions->prev != state->main_function)) {
13670 internal_error(state, 0,
13671 "state->main_function is not at the end of the function list ");
13673 state->main_function->u.cval = 1;
13674 reverse_walk_functions(state, mark_live, 0);
13677 static int local_triple(struct compile_state *state,
13678 struct triple *func, struct triple *ins)
13680 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13683 FILE *fp = state->errout;
13684 fprintf(fp, "global: ");
13685 display_triple(fp, ins);
13691 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13692 struct occurance *base_occurance)
13694 struct triple *nfunc;
13695 struct triple *nfirst, *ofirst;
13696 struct triple *new, *old;
13698 if (state->compiler->debug & DEBUG_INLINE) {
13699 FILE *fp = state->dbgout;
13702 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13703 display_func(state, fp, ofunc);
13704 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13707 /* Make a new copy of the old function */
13708 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13710 ofirst = old = RHS(ofunc, 0);
13712 struct triple *new;
13713 struct occurance *occurance;
13714 int old_lhs, old_rhs;
13715 old_lhs = old->lhs;
13716 old_rhs = old->rhs;
13717 occurance = inline_occurance(state, base_occurance, old->occurance);
13718 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13719 MISC(old, 0)->u.cval += 1;
13721 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13723 if (!triple_stores_block(state, new)) {
13724 memcpy(&new->u, &old->u, sizeof(new->u));
13727 RHS(nfunc, 0) = nfirst = new;
13730 insert_triple(state, nfirst, new);
13732 new->id |= TRIPLE_FLAG_FLATTENED;
13733 new->id |= old->id & TRIPLE_FLAG_COPY;
13735 /* During the copy remember new as user of old */
13736 use_triple(old, new);
13738 /* Remember which instructions are local */
13739 old->id |= TRIPLE_FLAG_LOCAL;
13741 } while(old != ofirst);
13743 /* Make a second pass to fix up any unresolved references */
13747 struct triple **oexpr, **nexpr;
13749 /* Lookup where the copy is, to join pointers */
13750 count = TRIPLE_SIZE(old);
13751 for(i = 0; i < count; i++) {
13752 oexpr = &old->param[i];
13753 nexpr = &new->param[i];
13754 if (*oexpr && !*nexpr) {
13755 if (!local_triple(state, ofunc, *oexpr)) {
13758 else if ((*oexpr)->use) {
13759 *nexpr = (*oexpr)->use->member;
13761 if (*nexpr == old) {
13762 internal_error(state, 0, "new == old?");
13764 use_triple(*nexpr, new);
13766 if (!*nexpr && *oexpr) {
13767 internal_error(state, 0, "Could not copy %d", i);
13772 } while((old != ofirst) && (new != nfirst));
13774 /* Make a third pass to cleanup the extra useses */
13778 unuse_triple(old, new);
13779 /* Forget which instructions are local */
13780 old->id &= ~TRIPLE_FLAG_LOCAL;
13783 } while ((old != ofirst) && (new != nfirst));
13787 static void expand_inline_call(
13788 struct compile_state *state, struct triple *me, struct triple *fcall)
13790 /* Inline the function call */
13791 struct type *ptype;
13792 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13793 struct triple *end, *nend;
13796 /* Find the triples */
13797 ofunc = MISC(fcall, 0);
13798 if (ofunc->op != OP_LIST) {
13799 internal_error(state, 0, "improper function");
13801 nfunc = copy_func(state, ofunc, fcall->occurance);
13802 /* Prepend the parameter reading into the new function list */
13803 ptype = nfunc->type->right;
13804 pvals = fcall->rhs;
13805 for(i = 0; i < pvals; i++) {
13806 struct type *atype;
13807 struct triple *arg, *param;
13809 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13810 atype = ptype->left;
13812 param = farg(state, nfunc, i);
13813 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13814 internal_error(state, fcall, "param %d type mismatch", i);
13816 arg = RHS(fcall, i);
13817 flatten(state, fcall, write_expr(state, param, arg));
13818 ptype = ptype->right;
13821 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13822 result = read_expr(state,
13823 deref_index(state, fresult(state, nfunc), 1));
13825 if (state->compiler->debug & DEBUG_INLINE) {
13826 FILE *fp = state->dbgout;
13829 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13830 display_func(state, fp, nfunc);
13831 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13835 * Get rid of the extra triples
13837 /* Remove the read of the return address */
13838 ins = RHS(nfunc, 0)->prev->prev;
13839 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13840 internal_error(state, ins, "Not return addres read?");
13842 release_triple(state, ins);
13843 /* Remove the return instruction */
13844 ins = RHS(nfunc, 0)->prev;
13845 if (ins->op != OP_RET) {
13846 internal_error(state, ins, "Not return?");
13848 release_triple(state, ins);
13849 /* Remove the retaddres variable */
13850 retvar = fretaddr(state, nfunc);
13851 if ((retvar->lhs != 1) ||
13852 (retvar->op != OP_ADECL) ||
13853 (retvar->next->op != OP_PIECE) ||
13854 (MISC(retvar->next, 0) != retvar)) {
13855 internal_error(state, retvar, "Not the return address?");
13857 release_triple(state, retvar->next);
13858 release_triple(state, retvar);
13860 /* Remove the label at the start of the function */
13861 ins = RHS(nfunc, 0);
13862 if (ins->op != OP_LABEL) {
13863 internal_error(state, ins, "Not label?");
13865 nfirst = ins->next;
13866 free_triple(state, ins);
13867 /* Release the new function header */
13869 free_triple(state, nfunc);
13871 /* Append the new function list onto the return list */
13873 nend = nfirst->prev;
13874 end->next = nfirst;
13875 nfirst->prev = end;
13876 nend->next = fcall;
13877 fcall->prev = nend;
13879 /* Now the result reading code */
13881 result = flatten(state, fcall, result);
13882 propogate_use(state, fcall, result);
13885 /* Release the original fcall instruction */
13886 release_triple(state, fcall);
13893 * Type of the result variable.
13897 * +----------+------------+
13899 * union of closures result_type
13901 * +------------------+---------------+
13903 * closure1 ... closuerN
13905 * +----+--+-+--------+-----+ +----+----+---+-----+
13906 * | | | | | | | | |
13907 * var1 var2 var3 ... varN result var1 var2 ... varN result
13909 * +--------+---------+
13911 * union of closures result_type
13913 * +-----+-------------------+
13915 * closure1 ... closureN
13917 * +-----+---+----+----+ +----+---+----+-----+
13919 * var1 var2 ... varN result var1 var2 ... varN result
13922 static int add_closure_type(struct compile_state *state,
13923 struct triple *func, struct type *closure_type)
13925 struct type *type, *ctype, **next;
13926 struct triple *var, *new_var;
13930 FILE *fp = state->errout;
13931 fprintf(fp, "original_type: ");
13932 name_of(fp, fresult(state, func)->type);
13935 /* find the original type */
13936 var = fresult(state, func);
13938 if (type->elements != 2) {
13939 internal_error(state, var, "bad return type");
13942 /* Find the complete closure type and update it */
13943 ctype = type->left->left;
13944 next = &ctype->left;
13945 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13946 next = &(*next)->right;
13948 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13949 ctype->elements += 1;
13952 fprintf(fp, "new_type: ");
13955 fprintf(fp, "ctype: %p %d bits: %d ",
13956 ctype, ctype->elements, reg_size_of(state, ctype));
13957 name_of(fp, ctype);
13961 /* Regenerate the variable with the new type definition */
13962 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13963 new_var->id |= TRIPLE_FLAG_FLATTENED;
13964 for(i = 0; i < new_var->lhs; i++) {
13965 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13968 /* Point everyone at the new variable */
13969 propogate_use(state, var, new_var);
13971 /* Release the original variable */
13972 for(i = 0; i < var->lhs; i++) {
13973 release_triple(state, LHS(var, i));
13975 release_triple(state, var);
13977 /* Return the index of the added closure type */
13978 return ctype->elements - 1;
13981 static struct triple *closure_expr(struct compile_state *state,
13982 struct triple *func, int closure_idx, int var_idx)
13984 return deref_index(state,
13986 deref_index(state, fresult(state, func), 0),
13992 static void insert_triple_set(
13993 struct triple_reg_set **head, struct triple *member)
13995 struct triple_reg_set *new;
13996 new = xcmalloc(sizeof(*new), "triple_set");
13997 new->member = member;
14003 static int ordered_triple_set(
14004 struct triple_reg_set **head, struct triple *member)
14006 struct triple_reg_set **ptr;
14011 if (member == (*ptr)->member) {
14014 /* keep the list ordered */
14015 if (member->id < (*ptr)->member->id) {
14018 ptr = &(*ptr)->next;
14020 insert_triple_set(ptr, member);
14025 static void free_closure_variables(struct compile_state *state,
14026 struct triple_reg_set **enclose)
14028 struct triple_reg_set *entry, *next;
14029 for(entry = *enclose; entry; entry = next) {
14030 next = entry->next;
14031 do_triple_unset(enclose, entry->member);
14035 static int lookup_closure_index(struct compile_state *state,
14036 struct triple *me, struct triple *val)
14038 struct triple *first, *ins, *next;
14039 first = RHS(me, 0);
14040 ins = next = first;
14042 struct triple *result;
14043 struct triple *index0, *index1, *index2, *read, *write;
14046 if (ins->op != OP_CALL) {
14049 /* I am at a previous call point examine it closely */
14050 if (ins->next->op != OP_LABEL) {
14051 internal_error(state, ins, "call not followed by label");
14053 /* Does this call does not enclose any variables? */
14054 if ((ins->next->next->op != OP_INDEX) ||
14055 (ins->next->next->u.cval != 0) ||
14056 (result = MISC(ins->next->next, 0)) ||
14057 (result->id & TRIPLE_FLAG_LOCAL)) {
14060 index0 = ins->next->next;
14062 * 0 index result < 0 >
14068 for(index0 = ins->next->next;
14069 (index0->op == OP_INDEX) &&
14070 (MISC(index0, 0) == result) &&
14071 (index0->u.cval == 0) ;
14072 index0 = write->next)
14074 index1 = index0->next;
14075 index2 = index1->next;
14076 read = index2->next;
14077 write = read->next;
14078 if ((index0->op != OP_INDEX) ||
14079 (index1->op != OP_INDEX) ||
14080 (index2->op != OP_INDEX) ||
14081 (read->op != OP_READ) ||
14082 (write->op != OP_WRITE) ||
14083 (MISC(index1, 0) != index0) ||
14084 (MISC(index2, 0) != index1) ||
14085 (RHS(read, 0) != index2) ||
14086 (RHS(write, 0) != read)) {
14087 internal_error(state, index0, "bad var read");
14089 if (MISC(write, 0) == val) {
14090 return index2->u.cval;
14093 } while(next != first);
14097 static inline int enclose_triple(struct triple *ins)
14099 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14102 static void compute_closure_variables(struct compile_state *state,
14103 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14105 struct triple_reg_set *set, *vars, **last_var;
14106 struct basic_blocks bb;
14107 struct reg_block *rb;
14108 struct block *block;
14109 struct triple *old_result, *first, *ins;
14111 unsigned long used_indicies;
14113 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14114 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14121 /* Find the basic blocks of this function */
14123 bb.first = RHS(me, 0);
14125 if (!triple_is_ret(state, bb.first->prev)) {
14128 old_result = fresult(state, me);
14130 analyze_basic_blocks(state, &bb);
14132 /* Find which variables are currently alive in a given block */
14133 rb = compute_variable_lifetimes(state, &bb);
14135 /* Find the variables that are currently alive */
14136 block = block_of_triple(state, fcall);
14137 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14138 internal_error(state, fcall, "No reg block? block: %p", block);
14141 #if DEBUG_EXPLICIT_CLOSURES
14142 print_live_variables(state, &bb, rb, state->dbgout);
14143 fflush(state->dbgout);
14146 /* Count the number of triples in the function */
14147 first = RHS(me, 0);
14153 } while(ins != first);
14155 /* Allocate some memory to temorary hold the id info */
14156 info = xcmalloc(sizeof(*info) * (count +1), "info");
14158 /* Mark the local function */
14159 first = RHS(me, 0);
14163 info[idx].id = ins->id;
14164 ins->id = TRIPLE_FLAG_LOCAL | idx;
14167 } while(ins != first);
14170 * Build the list of variables to enclose.
14172 * A target it to put the same variable in the
14173 * same slot for ever call of a given function.
14174 * After coloring this removes all of the variable
14175 * manipulation code.
14177 * The list of variables to enclose is built ordered
14178 * program order because except in corner cases this
14179 * gives me the stability of assignment I need.
14181 * To gurantee that stability I lookup the variables
14182 * to see where they have been used before and
14183 * I build my final list with the assigned indicies.
14186 if (enclose_triple(old_result)) {
14187 ordered_triple_set(&vars, old_result);
14189 for(set = rb[block->vertex].out; set; set = set->next) {
14190 if (!enclose_triple(set->member)) {
14193 if ((set->member == fcall) || (set->member == old_result)) {
14196 if (!local_triple(state, me, set->member)) {
14197 internal_error(state, set->member, "not local?");
14199 ordered_triple_set(&vars, set->member);
14202 /* Lookup the current indicies of the live varialbe */
14205 for(set = vars; set ; set = set->next) {
14206 struct triple *ins;
14209 index = lookup_closure_index(state, me, ins);
14210 info[ID_BITS(ins->id)].index = index;
14214 if (index >= MAX_INDICIES) {
14215 internal_error(state, ins, "index unexpectedly large");
14217 if (used_indicies & (1 << index)) {
14218 internal_error(state, ins, "index previously used?");
14220 /* Remember which indicies have been used */
14221 used_indicies |= (1 << index);
14222 if (index > max_index) {
14227 /* Walk through the live variables and make certain
14228 * everything is assigned an index.
14230 for(set = vars; set; set = set->next) {
14231 struct triple *ins;
14234 index = info[ID_BITS(ins->id)].index;
14238 /* Find the lowest unused index value */
14239 for(index = 0; index < MAX_INDICIES; index++) {
14240 if (!(used_indicies & (1 << index))) {
14244 if (index == MAX_INDICIES) {
14245 internal_error(state, ins, "no free indicies?");
14247 info[ID_BITS(ins->id)].index = index;
14248 /* Remember which indicies have been used */
14249 used_indicies |= (1 << index);
14250 if (index > max_index) {
14255 /* Build the return list of variables with positions matching
14259 last_var = enclose;
14260 for(i = 0; i <= max_index; i++) {
14261 struct triple *var;
14263 if (used_indicies & (1 << i)) {
14264 for(set = vars; set; set = set->next) {
14266 index = info[ID_BITS(set->member->id)].index;
14273 internal_error(state, me, "missing variable");
14276 insert_triple_set(last_var, var);
14277 last_var = &(*last_var)->next;
14280 #if DEBUG_EXPLICIT_CLOSURES
14281 /* Print out the variables to be enclosed */
14282 loc(state->dbgout, state, fcall);
14283 fprintf(state->dbgout, "Alive: \n");
14284 for(set = *enclose; set; set = set->next) {
14285 display_triple(state->dbgout, set->member);
14287 fflush(state->dbgout);
14290 /* Clear the marks */
14293 ins->id = info[ID_BITS(ins->id)].id;
14295 } while(ins != first);
14297 /* Release the ordered list of live variables */
14298 free_closure_variables(state, &vars);
14300 /* Release the storage of the old ids */
14303 /* Release the variable lifetime information */
14304 free_variable_lifetimes(state, &bb, rb);
14306 /* Release the basic blocks of this function */
14307 free_basic_blocks(state, &bb);
14310 static void expand_function_call(
14311 struct compile_state *state, struct triple *me, struct triple *fcall)
14313 /* Generate an ordinary function call */
14314 struct type *closure_type, **closure_next;
14315 struct triple *func, *func_first, *func_last, *retvar;
14316 struct triple *first;
14317 struct type *ptype, *rtype;
14318 struct triple *jmp;
14319 struct triple *ret_addr, *ret_loc, *ret_set;
14320 struct triple_reg_set *enclose, *set;
14321 int closure_idx, pvals, i;
14323 #if DEBUG_EXPLICIT_CLOSURES
14324 FILE *fp = state->dbgout;
14325 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14326 display_func(state, fp, MISC(fcall, 0));
14327 display_func(state, fp, me);
14328 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14331 /* Find the triples */
14332 func = MISC(fcall, 0);
14333 func_first = RHS(func, 0);
14334 retvar = fretaddr(state, func);
14335 func_last = func_first->prev;
14336 first = fcall->next;
14338 /* Find what I need to enclose */
14339 compute_closure_variables(state, me, fcall, &enclose);
14341 /* Compute the closure type */
14342 closure_type = new_type(TYPE_TUPLE, 0, 0);
14343 closure_type->elements = 0;
14344 closure_next = &closure_type->left;
14345 for(set = enclose; set ; set = set->next) {
14349 type = set->member->type;
14351 if (!*closure_next) {
14352 *closure_next = type;
14354 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14356 closure_next = &(*closure_next)->right;
14358 closure_type->elements += 1;
14360 if (closure_type->elements == 0) {
14361 closure_type->type = TYPE_VOID;
14365 #if DEBUG_EXPLICIT_CLOSURES
14366 fprintf(state->dbgout, "closure type: ");
14367 name_of(state->dbgout, closure_type);
14368 fprintf(state->dbgout, "\n");
14371 /* Update the called functions closure variable */
14372 closure_idx = add_closure_type(state, func, closure_type);
14374 /* Generate some needed triples */
14375 ret_loc = label(state);
14376 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14378 /* Pass the parameters to the new function */
14379 ptype = func->type->right;
14380 pvals = fcall->rhs;
14381 for(i = 0; i < pvals; i++) {
14382 struct type *atype;
14383 struct triple *arg, *param;
14385 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14386 atype = ptype->left;
14388 param = farg(state, func, i);
14389 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14390 internal_error(state, fcall, "param type mismatch");
14392 arg = RHS(fcall, i);
14393 flatten(state, first, write_expr(state, param, arg));
14394 ptype = ptype->right;
14396 rtype = func->type->left;
14398 /* Thread the triples together */
14399 ret_loc = flatten(state, first, ret_loc);
14401 /* Save the active variables in the result variable */
14402 for(i = 0, set = enclose; set ; set = set->next, i++) {
14403 if (!set->member) {
14406 flatten(state, ret_loc,
14408 closure_expr(state, func, closure_idx, i),
14409 read_expr(state, set->member)));
14412 /* Initialize the return value */
14413 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14414 flatten(state, ret_loc,
14416 deref_index(state, fresult(state, func), 1),
14417 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14420 ret_addr = flatten(state, ret_loc, ret_addr);
14421 ret_set = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14422 jmp = flatten(state, ret_loc,
14423 call(state, retvar, ret_addr, func_first, func_last));
14425 /* Find the result */
14426 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14427 struct triple * result;
14428 result = flatten(state, first,
14430 deref_index(state, fresult(state, func), 1)));
14432 propogate_use(state, fcall, result);
14435 /* Release the original fcall instruction */
14436 release_triple(state, fcall);
14438 /* Restore the active variables from the result variable */
14439 for(i = 0, set = enclose; set ; set = set->next, i++) {
14440 struct triple_set *use, *next;
14441 struct triple *new;
14442 struct basic_blocks bb;
14443 if (!set->member || (set->member == fcall)) {
14446 /* Generate an expression for the value */
14447 new = flatten(state, first,
14449 closure_expr(state, func, closure_idx, i)));
14452 /* If the original is an lvalue restore the preserved value */
14453 if (is_lvalue(state, set->member)) {
14454 flatten(state, first,
14455 write_expr(state, set->member, new));
14459 * If the original is a value update the dominated uses.
14462 /* Analyze the basic blocks so I can see who dominates whom */
14464 bb.first = RHS(me, 0);
14465 if (!triple_is_ret(state, bb.first->prev)) {
14468 analyze_basic_blocks(state, &bb);
14471 #if DEBUG_EXPLICIT_CLOSURES
14472 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14475 /* If fcall dominates the use update the expression */
14476 for(use = set->member->use; use; use = next) {
14477 /* Replace use modifies the use chain and
14478 * removes use, so I must take a copy of the
14479 * next entry early.
14482 if (!tdominates(state, fcall, use->member)) {
14485 replace_use(state, set->member, new, use->member);
14488 /* Release the basic blocks, the instructions will be
14489 * different next time, and flatten/insert_triple does
14490 * not update the block values so I can't cache the analysis.
14492 free_basic_blocks(state, &bb);
14495 /* Release the closure variable list */
14496 free_closure_variables(state, &enclose);
14498 if (state->compiler->debug & DEBUG_INLINE) {
14499 FILE *fp = state->dbgout;
14502 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14503 display_func(state, fp, func);
14504 display_func(state, fp, me);
14505 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14511 static int do_inline(struct compile_state *state, struct triple *func)
14516 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14518 case COMPILER_INLINE_ALWAYS:
14520 if (func->type->type & ATTRIB_NOINLINE) {
14521 error(state, func, "noinline with always_inline compiler option");
14524 case COMPILER_INLINE_NEVER:
14526 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14527 error(state, func, "always_inline with noinline compiler option");
14530 case COMPILER_INLINE_DEFAULTON:
14531 switch(func->type->type & STOR_MASK) {
14532 case STOR_STATIC | STOR_INLINE:
14533 case STOR_LOCAL | STOR_INLINE:
14534 case STOR_EXTERN | STOR_INLINE:
14542 case COMPILER_INLINE_DEFAULTOFF:
14543 switch(func->type->type & STOR_MASK) {
14544 case STOR_STATIC | STOR_INLINE:
14545 case STOR_LOCAL | STOR_INLINE:
14546 case STOR_EXTERN | STOR_INLINE:
14554 case COMPILER_INLINE_NOPENALTY:
14555 switch(func->type->type & STOR_MASK) {
14556 case STOR_STATIC | STOR_INLINE:
14557 case STOR_LOCAL | STOR_INLINE:
14558 case STOR_EXTERN | STOR_INLINE:
14562 do_inline = (func->u.cval == 1);
14568 internal_error(state, 0, "Unimplemented inline policy");
14571 /* Force inlining */
14572 if (func->type->type & ATTRIB_NOINLINE) {
14575 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14581 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14583 struct triple *first, *ptr, *next;
14584 /* If the function is not used don't bother */
14585 if (me->u.cval <= 0) {
14588 if (state->compiler->debug & DEBUG_CALLS2) {
14589 FILE *fp = state->dbgout;
14590 fprintf(fp, "in: %s\n",
14591 me->type->type_ident->name);
14594 first = RHS(me, 0);
14595 ptr = next = first;
14597 struct triple *func, *prev;
14601 if (ptr->op != OP_FCALL) {
14604 func = MISC(ptr, 0);
14605 /* See if the function should be inlined */
14606 if (!do_inline(state, func)) {
14607 /* Put a label after the fcall */
14608 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14611 if (state->compiler->debug & DEBUG_CALLS) {
14612 FILE *fp = state->dbgout;
14613 if (state->compiler->debug & DEBUG_CALLS2) {
14614 loc(fp, state, ptr);
14616 fprintf(fp, "inlining %s\n",
14617 func->type->type_ident->name);
14621 /* Update the function use counts */
14624 /* Replace the fcall with the called function */
14625 expand_inline_call(state, me, ptr);
14628 } while (next != first);
14630 ptr = next = first;
14632 struct triple *prev, *func;
14636 if (ptr->op != OP_FCALL) {
14639 func = MISC(ptr, 0);
14640 if (state->compiler->debug & DEBUG_CALLS) {
14641 FILE *fp = state->dbgout;
14642 if (state->compiler->debug & DEBUG_CALLS2) {
14643 loc(fp, state, ptr);
14645 fprintf(fp, "calling %s\n",
14646 func->type->type_ident->name);
14649 /* Replace the fcall with the instruction sequence
14650 * needed to make the call.
14652 expand_function_call(state, me, ptr);
14654 } while(next != first);
14657 static void inline_functions(struct compile_state *state, struct triple *func)
14659 inline_function(state, func, 0);
14660 reverse_walk_functions(state, inline_function, 0);
14663 static void insert_function(struct compile_state *state,
14664 struct triple *func, void *arg)
14666 struct triple *first, *end, *ffirst, *fend;
14668 if (state->compiler->debug & DEBUG_INLINE) {
14669 FILE *fp = state->errout;
14670 fprintf(fp, "%s func count: %d\n",
14671 func->type->type_ident->name, func->u.cval);
14673 if (func->u.cval == 0) {
14677 /* Find the end points of the lists */
14680 ffirst = RHS(func, 0);
14681 fend = ffirst->prev;
14683 /* splice the lists together */
14684 end->next = ffirst;
14685 ffirst->prev = end;
14686 fend->next = first;
14687 first->prev = fend;
14690 struct triple *input_asm(struct compile_state *state)
14692 struct asm_info *info;
14693 struct triple *def;
14696 info = xcmalloc(sizeof(*info), "asm_info");
14699 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14700 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14702 def = new_triple(state, OP_ASM, &void_type, out, 0);
14703 def->u.ainfo = info;
14704 def->id |= TRIPLE_FLAG_VOLATILE;
14706 for(i = 0; i < out; i++) {
14707 struct triple *piece;
14708 piece = triple(state, OP_PIECE, &int_type, def, 0);
14710 LHS(def, i) = piece;
14716 struct triple *output_asm(struct compile_state *state)
14718 struct asm_info *info;
14719 struct triple *def;
14722 info = xcmalloc(sizeof(*info), "asm_info");
14725 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14726 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14728 def = new_triple(state, OP_ASM, &void_type, 0, in);
14729 def->u.ainfo = info;
14730 def->id |= TRIPLE_FLAG_VOLATILE;
14735 static void join_functions(struct compile_state *state)
14737 struct triple *jmp, *start, *end, *call, *in, *out, *func;
14738 struct file_state file;
14739 struct type *pnext, *param;
14740 struct type *result_type, *args_type;
14743 /* Be clear the functions have not been joined yet */
14744 state->functions_joined = 0;
14746 /* Dummy file state to get debug handing right */
14747 memset(&file, 0, sizeof(file));
14748 file.basename = "";
14750 file.report_line = 0;
14751 file.report_name = file.basename;
14752 file.prev = state->file;
14753 state->file = &file;
14754 state->function = "";
14756 if (!state->main_function) {
14757 error(state, 0, "No functions to compile\n");
14760 /* The type of arguments */
14761 args_type = state->main_function->type->right;
14762 /* The return type without any specifiers */
14763 result_type = clone_type(0, state->main_function->type->left);
14766 /* Verify the external arguments */
14767 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14768 error(state, state->main_function,
14769 "Too many external input arguments");
14771 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14772 error(state, state->main_function,
14773 "Too many external output arguments");
14776 /* Lay down the basic program structure */
14777 end = label(state);
14778 start = label(state);
14779 start = flatten(state, state->first, start);
14780 end = flatten(state, state->first, end);
14781 in = input_asm(state);
14782 out = output_asm(state);
14783 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14784 MISC(call, 0) = state->main_function;
14785 in = flatten(state, state->first, in);
14786 call = flatten(state, state->first, call);
14787 out = flatten(state, state->first, out);
14790 /* Read the external input arguments */
14793 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14794 struct triple *expr;
14797 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14798 pnext = param->right;
14799 param = param->left;
14801 if (registers_of(state, param) != 1) {
14802 error(state, state->main_function,
14803 "Arg: %d %s requires multiple registers",
14804 idx + 1, param->field_ident->name);
14806 expr = read_expr(state, LHS(in, idx));
14807 RHS(call, idx) = expr;
14808 expr = flatten(state, call, expr);
14809 use_triple(expr, call);
14815 /* Write the external output arguments */
14816 pnext = result_type;
14817 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14818 pnext = result_type->left;
14820 for(idx = 0; idx < out->rhs; idx++) {
14821 struct triple *expr;
14824 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14825 pnext = param->right;
14826 param = param->left;
14828 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14832 if (registers_of(state, param) != 1) {
14833 error(state, state->main_function,
14834 "Result: %d %s requires multiple registers",
14835 idx, param->field_ident->name);
14837 expr = read_expr(state, call);
14838 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14839 expr = deref_field(state, expr, param->field_ident);
14842 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14844 flatten(state, out, expr);
14845 RHS(out, idx) = expr;
14846 use_triple(expr, out);
14849 /* Allocate a dummy containing function */
14850 func = triple(state, OP_LIST,
14851 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14852 func->type->type_ident = lookup(state, "", 0);
14853 RHS(func, 0) = state->first;
14856 /* See which functions are called, and how often */
14857 mark_live_functions(state);
14858 inline_functions(state, func);
14859 walk_functions(state, insert_function, end);
14861 if (start->next != end) {
14862 jmp = flatten(state, start, branch(state, end, 0));
14865 /* OK now the functions have been joined. */
14866 state->functions_joined = 1;
14868 /* Done now cleanup */
14869 state->file = file.prev;
14870 state->function = 0;
14874 * Data structurs for optimation.
14878 static int do_use_block(
14879 struct block *used, struct block_set **head, struct block *user,
14882 struct block_set **ptr, *new;
14889 if ((*ptr)->member == user) {
14892 ptr = &(*ptr)->next;
14894 new = xcmalloc(sizeof(*new), "block_set");
14895 new->member = user;
14906 static int do_unuse_block(
14907 struct block *used, struct block_set **head, struct block *unuser)
14909 struct block_set *use, **ptr;
14915 if (use->member == unuser) {
14917 memset(use, -1, sizeof(*use));
14928 static void use_block(struct block *used, struct block *user)
14931 /* Append new to the head of the list, print_block
14934 count = do_use_block(used, &used->use, user, 1);
14935 used->users += count;
14937 static void unuse_block(struct block *used, struct block *unuser)
14940 count = do_unuse_block(used, &used->use, unuser);
14941 used->users -= count;
14944 static void add_block_edge(struct block *block, struct block *edge, int front)
14947 count = do_use_block(block, &block->edges, edge, front);
14948 block->edge_count += count;
14951 static void remove_block_edge(struct block *block, struct block *edge)
14954 count = do_unuse_block(block, &block->edges, edge);
14955 block->edge_count -= count;
14958 static void idom_block(struct block *idom, struct block *user)
14960 do_use_block(idom, &idom->idominates, user, 0);
14963 static void unidom_block(struct block *idom, struct block *unuser)
14965 do_unuse_block(idom, &idom->idominates, unuser);
14968 static void domf_block(struct block *block, struct block *domf)
14970 do_use_block(block, &block->domfrontier, domf, 0);
14973 static void undomf_block(struct block *block, struct block *undomf)
14975 do_unuse_block(block, &block->domfrontier, undomf);
14978 static void ipdom_block(struct block *ipdom, struct block *user)
14980 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14983 static void unipdom_block(struct block *ipdom, struct block *unuser)
14985 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14988 static void ipdomf_block(struct block *block, struct block *ipdomf)
14990 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14993 static void unipdomf_block(struct block *block, struct block *unipdomf)
14995 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14998 static int walk_triples(
14999 struct compile_state *state,
15000 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
15003 struct triple *ptr;
15005 ptr = state->first;
15007 result = cb(state, ptr, arg);
15008 if (ptr->next->prev != ptr) {
15009 internal_error(state, ptr->next, "bad prev");
15012 } while((result == 0) && (ptr != state->first));
15016 #define PRINT_LIST 1
15017 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15022 if (op == OP_LIST) {
15027 if ((op == OP_LABEL) && (ins->use)) {
15028 fprintf(fp, "\n%p:\n", ins);
15030 display_triple(fp, ins);
15032 if (triple_is_branch(state, ins) && ins->use &&
15033 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15034 internal_error(state, ins, "branch used?");
15036 if (triple_is_branch(state, ins)) {
15042 static void print_triples(struct compile_state *state)
15044 if (state->compiler->debug & DEBUG_TRIPLES) {
15045 FILE *fp = state->dbgout;
15046 fprintf(fp, "--------------- triples ---------------\n");
15047 walk_triples(state, do_print_triple, fp);
15053 struct block *block;
15055 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15057 struct block_set *edge;
15058 if (!block || (cf[block->vertex].block == block)) {
15061 cf[block->vertex].block = block;
15062 for(edge = block->edges; edge; edge = edge->next) {
15063 find_cf_blocks(cf, edge->member);
15067 static void print_control_flow(struct compile_state *state,
15068 FILE *fp, struct basic_blocks *bb)
15070 struct cf_block *cf;
15072 fprintf(fp, "\ncontrol flow\n");
15073 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15074 find_cf_blocks(cf, bb->first_block);
15076 for(i = 1; i <= bb->last_vertex; i++) {
15077 struct block *block;
15078 struct block_set *edge;
15079 block = cf[i].block;
15082 fprintf(fp, "(%p) %d:", block, block->vertex);
15083 for(edge = block->edges; edge; edge = edge->next) {
15084 fprintf(fp, " %d", edge->member->vertex);
15092 static void free_basic_block(struct compile_state *state, struct block *block)
15094 struct block_set *edge, *entry;
15095 struct block *child;
15099 if (block->vertex == -1) {
15102 block->vertex = -1;
15103 for(edge = block->edges; edge; edge = edge->next) {
15104 if (edge->member) {
15105 unuse_block(edge->member, block);
15109 unidom_block(block->idom, block);
15112 if (block->ipdom) {
15113 unipdom_block(block->ipdom, block);
15116 while((entry = block->use)) {
15117 child = entry->member;
15118 unuse_block(block, child);
15119 if (child && (child->vertex != -1)) {
15120 for(edge = child->edges; edge; edge = edge->next) {
15125 while((entry = block->idominates)) {
15126 child = entry->member;
15127 unidom_block(block, child);
15128 if (child && (child->vertex != -1)) {
15132 while((entry = block->domfrontier)) {
15133 child = entry->member;
15134 undomf_block(block, child);
15136 while((entry = block->ipdominates)) {
15137 child = entry->member;
15138 unipdom_block(block, child);
15139 if (child && (child->vertex != -1)) {
15143 while((entry = block->ipdomfrontier)) {
15144 child = entry->member;
15145 unipdomf_block(block, child);
15147 if (block->users != 0) {
15148 internal_error(state, 0, "block still has users");
15150 while((edge = block->edges)) {
15151 child = edge->member;
15152 remove_block_edge(block, child);
15154 if (child && (child->vertex != -1)) {
15155 free_basic_block(state, child);
15158 memset(block, -1, sizeof(*block));
15164 static void free_basic_blocks(struct compile_state *state,
15165 struct basic_blocks *bb)
15167 struct triple *first, *ins;
15168 free_basic_block(state, bb->first_block);
15169 bb->last_vertex = 0;
15170 bb->first_block = bb->last_block = 0;
15174 if (triple_stores_block(state, ins)) {
15178 } while(ins != first);
15182 static struct block *basic_block(struct compile_state *state,
15183 struct basic_blocks *bb, struct triple *first)
15185 struct block *block;
15186 struct triple *ptr;
15187 if (!triple_is_label(state, first)) {
15188 internal_error(state, first, "block does not start with a label");
15190 /* See if this basic block has already been setup */
15191 if (first->u.block != 0) {
15192 return first->u.block;
15194 /* Allocate another basic block structure */
15195 bb->last_vertex += 1;
15196 block = xcmalloc(sizeof(*block), "block");
15197 block->first = block->last = first;
15198 block->vertex = bb->last_vertex;
15201 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15205 /* If ptr->u is not used remember where the baic block is */
15206 if (triple_stores_block(state, ptr)) {
15207 ptr->u.block = block;
15209 if (triple_is_branch(state, ptr)) {
15213 } while (ptr != bb->first);
15214 if ((ptr == bb->first) ||
15215 ((ptr->next == bb->first) && (
15216 triple_is_end(state, ptr) ||
15217 triple_is_ret(state, ptr))))
15219 /* The block has no outflowing edges */
15221 else if (triple_is_label(state, ptr)) {
15222 struct block *next;
15223 next = basic_block(state, bb, ptr);
15224 add_block_edge(block, next, 0);
15225 use_block(next, block);
15227 else if (triple_is_branch(state, ptr)) {
15228 struct triple **expr, *first;
15229 struct block *child;
15230 /* Find the branch targets.
15231 * I special case the first branch as that magically
15232 * avoids some difficult cases for the register allocator.
15234 expr = triple_edge_targ(state, ptr, 0);
15236 internal_error(state, ptr, "branch without targets");
15239 expr = triple_edge_targ(state, ptr, expr);
15240 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15241 if (!*expr) continue;
15242 child = basic_block(state, bb, *expr);
15243 use_block(child, block);
15244 add_block_edge(block, child, 0);
15247 child = basic_block(state, bb, first);
15248 use_block(child, block);
15249 add_block_edge(block, child, 1);
15251 /* Be certain the return block of a call is
15252 * in a basic block. When it is not find
15253 * start of the block, insert a label if
15254 * necessary and build the basic block.
15255 * Then add a fake edge from the start block
15256 * to the return block of the function.
15258 if (state->functions_joined && triple_is_call(state, ptr)
15259 && !block_of_triple(state, MISC(ptr, 0))) {
15260 struct block *tail;
15261 struct triple *start;
15262 start = triple_to_block_start(state, MISC(ptr, 0));
15263 if (!triple_is_label(state, start)) {
15264 start = pre_triple(state,
15265 start, OP_LABEL, &void_type, 0, 0);
15267 tail = basic_block(state, bb, start);
15268 add_block_edge(child, tail, 0);
15269 use_block(tail, child);
15274 internal_error(state, 0, "Bad basic block split");
15278 struct block_set *edge;
15279 FILE *fp = state->errout;
15280 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15281 block, block->vertex,
15282 block->first, block->last);
15283 for(edge = block->edges; edge; edge = edge->next) {
15284 fprintf(fp, " %10p [%2d]",
15285 edge->member ? edge->member->first : 0,
15286 edge->member ? edge->member->vertex : -1);
15295 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15296 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15299 struct triple *ptr, *first;
15300 struct block *last_block;
15305 if (triple_stores_block(state, ptr)) {
15306 struct block *block;
15307 block = ptr->u.block;
15308 if (block && (block != last_block)) {
15309 cb(state, block, arg);
15311 last_block = block;
15314 } while(ptr != first);
15317 static void print_block(
15318 struct compile_state *state, struct block *block, void *arg)
15320 struct block_set *user, *edge;
15321 struct triple *ptr;
15324 fprintf(fp, "\nblock: %p (%d) ",
15328 for(edge = block->edges; edge; edge = edge->next) {
15329 fprintf(fp, " %p<-%p",
15331 (edge->member && edge->member->use)?
15332 edge->member->use->member : 0);
15335 if (block->first->op == OP_LABEL) {
15336 fprintf(fp, "%p:\n", block->first);
15338 for(ptr = block->first; ; ) {
15339 display_triple(fp, ptr);
15340 if (ptr == block->last)
15343 if (ptr == block->first) {
15344 internal_error(state, 0, "missing block last?");
15347 fprintf(fp, "users %d: ", block->users);
15348 for(user = block->use; user; user = user->next) {
15349 fprintf(fp, "%p (%d) ",
15351 user->member->vertex);
15353 fprintf(fp,"\n\n");
15357 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15359 fprintf(fp, "--------------- blocks ---------------\n");
15360 walk_blocks(state, &state->bb, print_block, fp);
15362 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15364 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15365 fprintf(fp, "After %s\n", func);
15366 romcc_print_blocks(state, fp);
15367 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15368 print_dominators(state, fp, &state->bb);
15369 print_dominance_frontiers(state, fp, &state->bb);
15371 print_control_flow(state, fp, &state->bb);
15375 static void prune_nonblock_triples(struct compile_state *state,
15376 struct basic_blocks *bb)
15378 struct block *block;
15379 struct triple *first, *ins, *next;
15380 /* Delete the triples not in a basic block */
15386 if (ins->op == OP_LABEL) {
15387 block = ins->u.block;
15390 struct triple_set *use;
15391 for(use = ins->use; use; use = use->next) {
15392 struct block *block;
15393 block = block_of_triple(state, use->member);
15395 internal_error(state, ins, "pruning used ins?");
15398 release_triple(state, ins);
15400 if (block && block->last == ins) {
15404 } while(ins != first);
15407 static void setup_basic_blocks(struct compile_state *state,
15408 struct basic_blocks *bb)
15410 if (!triple_stores_block(state, bb->first)) {
15411 internal_error(state, 0, "ins will not store block?");
15413 /* Initialize the state */
15414 bb->first_block = bb->last_block = 0;
15415 bb->last_vertex = 0;
15416 free_basic_blocks(state, bb);
15418 /* Find the basic blocks */
15419 bb->first_block = basic_block(state, bb, bb->first);
15421 /* Be certain the last instruction of a function, or the
15422 * entire program is in a basic block. When it is not find
15423 * the start of the block, insert a label if necessary and build
15424 * basic block. Then add a fake edge from the start block
15425 * to the final block.
15427 if (!block_of_triple(state, bb->first->prev)) {
15428 struct triple *start;
15429 struct block *tail;
15430 start = triple_to_block_start(state, bb->first->prev);
15431 if (!triple_is_label(state, start)) {
15432 start = pre_triple(state,
15433 start, OP_LABEL, &void_type, 0, 0);
15435 tail = basic_block(state, bb, start);
15436 add_block_edge(bb->first_block, tail, 0);
15437 use_block(tail, bb->first_block);
15440 /* Find the last basic block.
15442 bb->last_block = block_of_triple(state, bb->first->prev);
15444 /* Delete the triples not in a basic block */
15445 prune_nonblock_triples(state, bb);
15448 /* If we are debugging print what I have just done */
15449 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15450 print_blocks(state, state->dbgout);
15451 print_control_flow(state, bb);
15457 struct sdom_block {
15458 struct block *block;
15459 struct sdom_block *sdominates;
15460 struct sdom_block *sdom_next;
15461 struct sdom_block *sdom;
15462 struct sdom_block *label;
15463 struct sdom_block *parent;
15464 struct sdom_block *ancestor;
15469 static void unsdom_block(struct sdom_block *block)
15471 struct sdom_block **ptr;
15472 if (!block->sdom_next) {
15475 ptr = &block->sdom->sdominates;
15477 if ((*ptr) == block) {
15478 *ptr = block->sdom_next;
15481 ptr = &(*ptr)->sdom_next;
15485 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15487 unsdom_block(block);
15488 block->sdom = sdom;
15489 block->sdom_next = sdom->sdominates;
15490 sdom->sdominates = block;
15495 static int initialize_sdblock(struct sdom_block *sd,
15496 struct block *parent, struct block *block, int vertex)
15498 struct block_set *edge;
15499 if (!block || (sd[block->vertex].block == block)) {
15503 /* Renumber the blocks in a convinient fashion */
15504 block->vertex = vertex;
15505 sd[vertex].block = block;
15506 sd[vertex].sdom = &sd[vertex];
15507 sd[vertex].label = &sd[vertex];
15508 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15509 sd[vertex].ancestor = 0;
15510 sd[vertex].vertex = vertex;
15511 for(edge = block->edges; edge; edge = edge->next) {
15512 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15517 static int initialize_spdblock(
15518 struct compile_state *state, struct sdom_block *sd,
15519 struct block *parent, struct block *block, int vertex)
15521 struct block_set *user;
15522 if (!block || (sd[block->vertex].block == block)) {
15526 /* Renumber the blocks in a convinient fashion */
15527 block->vertex = vertex;
15528 sd[vertex].block = block;
15529 sd[vertex].sdom = &sd[vertex];
15530 sd[vertex].label = &sd[vertex];
15531 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15532 sd[vertex].ancestor = 0;
15533 sd[vertex].vertex = vertex;
15534 for(user = block->use; user; user = user->next) {
15535 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15540 static int setup_spdblocks(struct compile_state *state,
15541 struct basic_blocks *bb, struct sdom_block *sd)
15543 struct block *block;
15545 /* Setup as many sdpblocks as possible without using fake edges */
15546 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15548 /* Walk through the graph and find unconnected blocks. Add a
15549 * fake edge from the unconnected blocks to the end of the
15552 block = bb->first_block->last->next->u.block;
15553 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15554 if (sd[block->vertex].block == block) {
15557 #if DEBUG_SDP_BLOCKS
15559 FILE *fp = state->errout;
15560 fprintf(fp, "Adding %d\n", vertex +1);
15563 add_block_edge(block, bb->last_block, 0);
15564 use_block(bb->last_block, block);
15566 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15571 static void compress_ancestors(struct sdom_block *v)
15573 /* This procedure assumes ancestor(v) != 0 */
15574 /* if (ancestor(ancestor(v)) != 0) {
15575 * compress(ancestor(ancestor(v)));
15576 * if (semi(label(ancestor(v))) < semi(label(v))) {
15577 * label(v) = label(ancestor(v));
15579 * ancestor(v) = ancestor(ancestor(v));
15582 if (!v->ancestor) {
15585 if (v->ancestor->ancestor) {
15586 compress_ancestors(v->ancestor->ancestor);
15587 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15588 v->label = v->ancestor->label;
15590 v->ancestor = v->ancestor->ancestor;
15594 static void compute_sdom(struct compile_state *state,
15595 struct basic_blocks *bb, struct sdom_block *sd)
15599 * for each v <= pred(w) {
15601 * if (semi[u] < semi[w] {
15602 * semi[w] = semi[u];
15605 * add w to bucket(vertex(semi[w]));
15606 * LINK(parent(w), w);
15609 * for each v <= bucket(parent(w)) {
15610 * delete v from bucket(parent(w));
15612 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15615 for(i = bb->last_vertex; i >= 2; i--) {
15616 struct sdom_block *v, *parent, *next;
15617 struct block_set *user;
15618 struct block *block;
15619 block = sd[i].block;
15620 parent = sd[i].parent;
15622 for(user = block->use; user; user = user->next) {
15623 struct sdom_block *v, *u;
15624 v = &sd[user->member->vertex];
15625 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15626 if (u->sdom->vertex < sd[i].sdom->vertex) {
15627 sd[i].sdom = u->sdom;
15630 sdom_block(sd[i].sdom, &sd[i]);
15631 sd[i].ancestor = parent;
15633 for(v = parent->sdominates; v; v = next) {
15634 struct sdom_block *u;
15635 next = v->sdom_next;
15637 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15638 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15639 u->block : parent->block;
15644 static void compute_spdom(struct compile_state *state,
15645 struct basic_blocks *bb, struct sdom_block *sd)
15649 * for each v <= pred(w) {
15651 * if (semi[u] < semi[w] {
15652 * semi[w] = semi[u];
15655 * add w to bucket(vertex(semi[w]));
15656 * LINK(parent(w), w);
15659 * for each v <= bucket(parent(w)) {
15660 * delete v from bucket(parent(w));
15662 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15665 for(i = bb->last_vertex; i >= 2; i--) {
15666 struct sdom_block *u, *v, *parent, *next;
15667 struct block_set *edge;
15668 struct block *block;
15669 block = sd[i].block;
15670 parent = sd[i].parent;
15672 for(edge = block->edges; edge; edge = edge->next) {
15673 v = &sd[edge->member->vertex];
15674 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15675 if (u->sdom->vertex < sd[i].sdom->vertex) {
15676 sd[i].sdom = u->sdom;
15679 sdom_block(sd[i].sdom, &sd[i]);
15680 sd[i].ancestor = parent;
15682 for(v = parent->sdominates; v; v = next) {
15683 struct sdom_block *u;
15684 next = v->sdom_next;
15686 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15687 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15688 u->block : parent->block;
15693 static void compute_idom(struct compile_state *state,
15694 struct basic_blocks *bb, struct sdom_block *sd)
15697 for(i = 2; i <= bb->last_vertex; i++) {
15698 struct block *block;
15699 block = sd[i].block;
15700 if (block->idom->vertex != sd[i].sdom->vertex) {
15701 block->idom = block->idom->idom;
15703 idom_block(block->idom, block);
15705 sd[1].block->idom = 0;
15708 static void compute_ipdom(struct compile_state *state,
15709 struct basic_blocks *bb, struct sdom_block *sd)
15712 for(i = 2; i <= bb->last_vertex; i++) {
15713 struct block *block;
15714 block = sd[i].block;
15715 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15716 block->ipdom = block->ipdom->ipdom;
15718 ipdom_block(block->ipdom, block);
15720 sd[1].block->ipdom = 0;
15724 * Every vertex of a flowgraph G = (V, E, r) except r has
15725 * a unique immediate dominator.
15726 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15727 * rooted at r, called the dominator tree of G, such that
15728 * v dominates w if and only if v is a proper ancestor of w in
15729 * the dominator tree.
15732 * If v and w are vertices of G such that v <= w,
15733 * than any path from v to w must contain a common ancestor
15736 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15737 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15738 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15740 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15741 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15744 * Let w != r and let u be a vertex for which sdom(u) is
15745 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15746 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15748 /* Lemma 5: Let vertices v,w satisfy v -> w.
15749 * Then v -> idom(w) or idom(w) -> idom(v)
15752 static void find_immediate_dominators(struct compile_state *state,
15753 struct basic_blocks *bb)
15755 struct sdom_block *sd;
15756 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15757 * vi > w for (1 <= i <= k - 1}
15760 * For any vertex w != r.
15762 * {v|(v,w) <= E and v < w } U
15763 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15766 * Let w != r and let u be a vertex for which sdom(u) is
15767 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15769 * { sdom(w) if sdom(w) = sdom(u),
15771 * { idom(u) otherwise
15773 /* The algorithm consists of the following 4 steps.
15774 * Step 1. Carry out a depth-first search of the problem graph.
15775 * Number the vertices from 1 to N as they are reached during
15776 * the search. Initialize the variables used in succeeding steps.
15777 * Step 2. Compute the semidominators of all vertices by applying
15778 * theorem 4. Carry out the computation vertex by vertex in
15779 * decreasing order by number.
15780 * Step 3. Implicitly define the immediate dominator of each vertex
15781 * by applying Corollary 1.
15782 * Step 4. Explicitly define the immediate dominator of each vertex,
15783 * carrying out the computation vertex by vertex in increasing order
15786 /* Step 1 initialize the basic block information */
15787 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15788 initialize_sdblock(sd, 0, bb->first_block, 0);
15794 /* Step 2 compute the semidominators */
15795 /* Step 3 implicitly define the immediate dominator of each vertex */
15796 compute_sdom(state, bb, sd);
15797 /* Step 4 explicitly define the immediate dominator of each vertex */
15798 compute_idom(state, bb, sd);
15802 static void find_post_dominators(struct compile_state *state,
15803 struct basic_blocks *bb)
15805 struct sdom_block *sd;
15807 /* Step 1 initialize the basic block information */
15808 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15810 vertex = setup_spdblocks(state, bb, sd);
15811 if (vertex != bb->last_vertex) {
15812 internal_error(state, 0, "missing %d blocks",
15813 bb->last_vertex - vertex);
15816 /* Step 2 compute the semidominators */
15817 /* Step 3 implicitly define the immediate dominator of each vertex */
15818 compute_spdom(state, bb, sd);
15819 /* Step 4 explicitly define the immediate dominator of each vertex */
15820 compute_ipdom(state, bb, sd);
15826 static void find_block_domf(struct compile_state *state, struct block *block)
15828 struct block *child;
15829 struct block_set *user, *edge;
15830 if (block->domfrontier != 0) {
15831 internal_error(state, block->first, "domfrontier present?");
15833 for(user = block->idominates; user; user = user->next) {
15834 child = user->member;
15835 if (child->idom != block) {
15836 internal_error(state, block->first, "bad idom");
15838 find_block_domf(state, child);
15840 for(edge = block->edges; edge; edge = edge->next) {
15841 if (edge->member->idom != block) {
15842 domf_block(block, edge->member);
15845 for(user = block->idominates; user; user = user->next) {
15846 struct block_set *frontier;
15847 child = user->member;
15848 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15849 if (frontier->member->idom != block) {
15850 domf_block(block, frontier->member);
15856 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15858 struct block *child;
15859 struct block_set *user;
15860 if (block->ipdomfrontier != 0) {
15861 internal_error(state, block->first, "ipdomfrontier present?");
15863 for(user = block->ipdominates; user; user = user->next) {
15864 child = user->member;
15865 if (child->ipdom != block) {
15866 internal_error(state, block->first, "bad ipdom");
15868 find_block_ipdomf(state, child);
15870 for(user = block->use; user; user = user->next) {
15871 if (user->member->ipdom != block) {
15872 ipdomf_block(block, user->member);
15875 for(user = block->ipdominates; user; user = user->next) {
15876 struct block_set *frontier;
15877 child = user->member;
15878 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15879 if (frontier->member->ipdom != block) {
15880 ipdomf_block(block, frontier->member);
15886 static void print_dominated(
15887 struct compile_state *state, struct block *block, void *arg)
15889 struct block_set *user;
15892 fprintf(fp, "%d:", block->vertex);
15893 for(user = block->idominates; user; user = user->next) {
15894 fprintf(fp, " %d", user->member->vertex);
15895 if (user->member->idom != block) {
15896 internal_error(state, user->member->first, "bad idom");
15902 static void print_dominated2(
15903 struct compile_state *state, FILE *fp, int depth, struct block *block)
15905 struct block_set *user;
15906 struct triple *ins;
15907 struct occurance *ptr, *ptr2;
15908 const char *filename1, *filename2;
15909 int equal_filenames;
15911 for(i = 0; i < depth; i++) {
15914 fprintf(fp, "%3d: %p (%p - %p) @",
15915 block->vertex, block, block->first, block->last);
15916 ins = block->first;
15917 while(ins != block->last && (ins->occurance->line == 0)) {
15920 ptr = ins->occurance;
15921 ptr2 = block->last->occurance;
15922 filename1 = ptr->filename? ptr->filename : "";
15923 filename2 = ptr2->filename? ptr2->filename : "";
15924 equal_filenames = (strcmp(filename1, filename2) == 0);
15925 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15926 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15927 } else if (equal_filenames) {
15928 fprintf(fp, " %s:(%d - %d)",
15929 ptr->filename, ptr->line, ptr2->line);
15931 fprintf(fp, " (%s:%d - %s:%d)",
15932 ptr->filename, ptr->line,
15933 ptr2->filename, ptr2->line);
15936 for(user = block->idominates; user; user = user->next) {
15937 print_dominated2(state, fp, depth + 1, user->member);
15941 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15943 fprintf(fp, "\ndominates\n");
15944 walk_blocks(state, bb, print_dominated, fp);
15945 fprintf(fp, "dominates\n");
15946 print_dominated2(state, fp, 0, bb->first_block);
15950 static int print_frontiers(
15951 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15953 struct block_set *user, *edge;
15955 if (!block || (block->vertex != vertex + 1)) {
15960 fprintf(fp, "%d:", block->vertex);
15961 for(user = block->domfrontier; user; user = user->next) {
15962 fprintf(fp, " %d", user->member->vertex);
15966 for(edge = block->edges; edge; edge = edge->next) {
15967 vertex = print_frontiers(state, fp, edge->member, vertex);
15971 static void print_dominance_frontiers(struct compile_state *state,
15972 FILE *fp, struct basic_blocks *bb)
15974 fprintf(fp, "\ndominance frontiers\n");
15975 print_frontiers(state, fp, bb->first_block, 0);
15979 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15981 /* Find the immediate dominators */
15982 find_immediate_dominators(state, bb);
15983 /* Find the dominance frontiers */
15984 find_block_domf(state, bb->first_block);
15985 /* If debuging print the print what I have just found */
15986 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15987 print_dominators(state, state->dbgout, bb);
15988 print_dominance_frontiers(state, state->dbgout, bb);
15989 print_control_flow(state, state->dbgout, bb);
15994 static void print_ipdominated(
15995 struct compile_state *state, struct block *block, void *arg)
15997 struct block_set *user;
16000 fprintf(fp, "%d:", block->vertex);
16001 for(user = block->ipdominates; user; user = user->next) {
16002 fprintf(fp, " %d", user->member->vertex);
16003 if (user->member->ipdom != block) {
16004 internal_error(state, user->member->first, "bad ipdom");
16010 static void print_ipdominators(struct compile_state *state, FILE *fp,
16011 struct basic_blocks *bb)
16013 fprintf(fp, "\nipdominates\n");
16014 walk_blocks(state, bb, print_ipdominated, fp);
16017 static int print_pfrontiers(
16018 struct compile_state *state, FILE *fp, struct block *block, int vertex)
16020 struct block_set *user;
16022 if (!block || (block->vertex != vertex + 1)) {
16027 fprintf(fp, "%d:", block->vertex);
16028 for(user = block->ipdomfrontier; user; user = user->next) {
16029 fprintf(fp, " %d", user->member->vertex);
16032 for(user = block->use; user; user = user->next) {
16033 vertex = print_pfrontiers(state, fp, user->member, vertex);
16037 static void print_ipdominance_frontiers(struct compile_state *state,
16038 FILE *fp, struct basic_blocks *bb)
16040 fprintf(fp, "\nipdominance frontiers\n");
16041 print_pfrontiers(state, fp, bb->last_block, 0);
16045 static void analyze_ipdominators(struct compile_state *state,
16046 struct basic_blocks *bb)
16048 /* Find the post dominators */
16049 find_post_dominators(state, bb);
16050 /* Find the control dependencies (post dominance frontiers) */
16051 find_block_ipdomf(state, bb->last_block);
16052 /* If debuging print the print what I have just found */
16053 if (state->compiler->debug & DEBUG_RDOMINATORS) {
16054 print_ipdominators(state, state->dbgout, bb);
16055 print_ipdominance_frontiers(state, state->dbgout, bb);
16056 print_control_flow(state, state->dbgout, bb);
16060 static int bdominates(struct compile_state *state,
16061 struct block *dom, struct block *sub)
16063 while(sub && (sub != dom)) {
16069 static int tdominates(struct compile_state *state,
16070 struct triple *dom, struct triple *sub)
16072 struct block *bdom, *bsub;
16074 bdom = block_of_triple(state, dom);
16075 bsub = block_of_triple(state, sub);
16076 if (bdom != bsub) {
16077 result = bdominates(state, bdom, bsub);
16080 struct triple *ins;
16081 if (!bdom || !bsub) {
16082 internal_error(state, dom, "huh?");
16085 while((ins != bsub->first) && (ins != dom)) {
16088 result = (ins == dom);
16093 static void analyze_basic_blocks(
16094 struct compile_state *state, struct basic_blocks *bb)
16096 setup_basic_blocks(state, bb);
16097 analyze_idominators(state, bb);
16098 analyze_ipdominators(state, bb);
16101 static void insert_phi_operations(struct compile_state *state)
16104 struct triple *first;
16105 int *has_already, *work;
16106 struct block *work_list, **work_list_tail;
16108 struct triple *var, *vnext;
16110 size = sizeof(int) * (state->bb.last_vertex + 1);
16111 has_already = xcmalloc(size, "has_already");
16112 work = xcmalloc(size, "work");
16115 first = state->first;
16116 for(var = first->next; var != first ; var = vnext) {
16117 struct block *block;
16118 struct triple_set *user, *unext;
16121 if (!triple_is_auto_var(state, var) || !var->use) {
16127 work_list_tail = &work_list;
16128 for(user = var->use; user; user = unext) {
16129 unext = user->next;
16130 if (MISC(var, 0) == user->member) {
16133 if (user->member->op == OP_READ) {
16136 if (user->member->op != OP_WRITE) {
16137 internal_error(state, user->member,
16138 "bad variable access");
16140 block = user->member->u.block;
16142 warning(state, user->member, "dead code");
16143 release_triple(state, user->member);
16146 if (work[block->vertex] >= iter) {
16149 work[block->vertex] = iter;
16150 *work_list_tail = block;
16151 block->work_next = 0;
16152 work_list_tail = &block->work_next;
16154 for(block = work_list; block; block = block->work_next) {
16155 struct block_set *df;
16156 for(df = block->domfrontier; df; df = df->next) {
16157 struct triple *phi;
16158 struct block *front;
16160 front = df->member;
16162 if (has_already[front->vertex] >= iter) {
16165 /* Count how many edges flow into this block */
16166 in_edges = front->users;
16167 /* Insert a phi function for this variable */
16168 get_occurance(var->occurance);
16169 phi = alloc_triple(
16170 state, OP_PHI, var->type, -1, in_edges,
16172 phi->u.block = front;
16173 MISC(phi, 0) = var;
16174 use_triple(var, phi);
16176 if (phi->rhs != in_edges) {
16177 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16178 phi->rhs, in_edges);
16181 /* Insert the phi functions immediately after the label */
16182 insert_triple(state, front->first->next, phi);
16183 if (front->first == front->last) {
16184 front->last = front->first->next;
16186 has_already[front->vertex] = iter;
16187 transform_to_arch_instruction(state, phi);
16189 /* If necessary plan to visit the basic block */
16190 if (work[front->vertex] >= iter) {
16193 work[front->vertex] = iter;
16194 *work_list_tail = front;
16195 front->work_next = 0;
16196 work_list_tail = &front->work_next;
16200 xfree(has_already);
16206 struct triple_set *top;
16210 static int count_auto_vars(struct compile_state *state)
16212 struct triple *first, *ins;
16214 first = state->first;
16217 if (triple_is_auto_var(state, ins)) {
16221 } while(ins != first);
16225 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16227 struct triple *first, *ins;
16229 first = state->first;
16232 if (triple_is_auto_var(state, ins)) {
16234 stacks[auto_vars].orig_id = ins->id;
16235 ins->id = auto_vars;
16238 } while(ins != first);
16241 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16243 struct triple *first, *ins;
16244 first = state->first;
16247 if (triple_is_auto_var(state, ins)) {
16248 ins->id = stacks[ins->id].orig_id;
16251 } while(ins != first);
16254 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16256 struct triple_set *head;
16257 struct triple *top_val;
16259 head = stacks[var->id].top;
16261 top_val = head->member;
16266 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16268 struct triple_set *new;
16269 /* Append new to the head of the list,
16270 * it's the only sensible behavoir for a stack.
16272 new = xcmalloc(sizeof(*new), "triple_set");
16274 new->next = stacks[var->id].top;
16275 stacks[var->id].top = new;
16278 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16280 struct triple_set *set, **ptr;
16281 ptr = &stacks[var->id].top;
16284 if (set->member == oldval) {
16287 /* Only free one occurance from the stack */
16300 static void fixup_block_phi_variables(
16301 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16303 struct block_set *set;
16304 struct triple *ptr;
16306 if (!parent || !block)
16308 /* Find the edge I am coming in on */
16310 for(set = block->use; set; set = set->next, edge++) {
16311 if (set->member == parent) {
16316 internal_error(state, 0, "phi input is not on a control predecessor");
16318 for(ptr = block->first; ; ptr = ptr->next) {
16319 if (ptr->op == OP_PHI) {
16320 struct triple *var, *val, **slot;
16321 var = MISC(ptr, 0);
16323 internal_error(state, ptr, "no var???");
16325 /* Find the current value of the variable */
16326 val = peek_triple(stacks, var);
16327 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16328 internal_error(state, val, "bad value in phi");
16330 if (edge >= ptr->rhs) {
16331 internal_error(state, ptr, "edges > phi rhs");
16333 slot = &RHS(ptr, edge);
16334 if ((*slot != 0) && (*slot != val)) {
16335 internal_error(state, ptr, "phi already bound on this edge");
16338 use_triple(val, ptr);
16340 if (ptr == block->last) {
16347 static void rename_block_variables(
16348 struct compile_state *state, struct stack *stacks, struct block *block)
16350 struct block_set *user, *edge;
16351 struct triple *ptr, *next, *last;
16355 last = block->first;
16357 for(ptr = block->first; !done; ptr = next) {
16359 if (ptr == block->last) {
16363 if (ptr->op == OP_READ) {
16364 struct triple *var, *val;
16366 if (!triple_is_auto_var(state, var)) {
16367 internal_error(state, ptr, "read of non auto var!");
16369 unuse_triple(var, ptr);
16370 /* Find the current value of the variable */
16371 val = peek_triple(stacks, var);
16373 /* Let the optimizer at variables that are not initially
16374 * set. But give it a bogus value so things seem to
16375 * work by accident. This is useful for bitfields because
16376 * setting them always involves a read-modify-write.
16378 if (TYPE_ARITHMETIC(ptr->type->type)) {
16379 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16380 val->u.cval = 0xdeadbeaf;
16382 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16386 error(state, ptr, "variable used without being set");
16388 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16389 internal_error(state, val, "bad value in read");
16391 propogate_use(state, ptr, val);
16392 release_triple(state, ptr);
16396 if (ptr->op == OP_WRITE) {
16397 struct triple *var, *val, *tval;
16398 var = MISC(ptr, 0);
16399 if (!triple_is_auto_var(state, var)) {
16400 internal_error(state, ptr, "write to non auto var!");
16402 tval = val = RHS(ptr, 0);
16403 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16404 triple_is_auto_var(state, val)) {
16405 internal_error(state, ptr, "bad value in write");
16407 /* Insert a cast if the types differ */
16408 if (!is_subset_type(ptr->type, val->type)) {
16409 if (val->op == OP_INTCONST) {
16410 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16411 tval->u.cval = val->u.cval;
16414 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16415 use_triple(val, tval);
16417 transform_to_arch_instruction(state, tval);
16418 unuse_triple(val, ptr);
16419 RHS(ptr, 0) = tval;
16420 use_triple(tval, ptr);
16422 propogate_use(state, ptr, tval);
16423 unuse_triple(var, ptr);
16424 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16425 push_triple(stacks, var, tval);
16427 if (ptr->op == OP_PHI) {
16428 struct triple *var;
16429 var = MISC(ptr, 0);
16430 if (!triple_is_auto_var(state, var)) {
16431 internal_error(state, ptr, "phi references non auto var!");
16433 /* Push OP_PHI onto a stack of variable uses */
16434 push_triple(stacks, var, ptr);
16438 block->last = last;
16440 /* Fixup PHI functions in the cf successors */
16441 for(edge = block->edges; edge; edge = edge->next) {
16442 fixup_block_phi_variables(state, stacks, block, edge->member);
16444 /* rename variables in the dominated nodes */
16445 for(user = block->idominates; user; user = user->next) {
16446 rename_block_variables(state, stacks, user->member);
16448 /* pop the renamed variable stack */
16449 last = block->first;
16451 for(ptr = block->first; !done ; ptr = next) {
16453 if (ptr == block->last) {
16456 if (ptr->op == OP_WRITE) {
16457 struct triple *var;
16458 var = MISC(ptr, 0);
16459 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16460 pop_triple(stacks, var, RHS(ptr, 0));
16461 release_triple(state, ptr);
16464 if (ptr->op == OP_PHI) {
16465 struct triple *var;
16466 var = MISC(ptr, 0);
16467 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16468 pop_triple(stacks, var, ptr);
16472 block->last = last;
16475 static void rename_variables(struct compile_state *state)
16477 struct stack *stacks;
16480 /* Allocate stacks for the Variables */
16481 auto_vars = count_auto_vars(state);
16482 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16484 /* Give each auto_var a stack */
16485 number_auto_vars(state, stacks);
16487 /* Rename the variables */
16488 rename_block_variables(state, stacks, state->bb.first_block);
16490 /* Remove the stacks from the auto_vars */
16491 restore_auto_vars(state, stacks);
16495 static void prune_block_variables(struct compile_state *state,
16496 struct block *block)
16498 struct block_set *user;
16499 struct triple *next, *ptr;
16503 for(ptr = block->first; !done; ptr = next) {
16504 /* Be extremely careful I am deleting the list
16505 * as I walk trhough it.
16508 if (ptr == block->last) {
16511 if (triple_is_auto_var(state, ptr)) {
16512 struct triple_set *user, *next;
16513 for(user = ptr->use; user; user = next) {
16514 struct triple *use;
16516 use = user->member;
16517 if (MISC(ptr, 0) == user->member) {
16520 if (use->op != OP_PHI) {
16521 internal_error(state, use, "decl still used");
16523 if (MISC(use, 0) != ptr) {
16524 internal_error(state, use, "bad phi use of decl");
16526 unuse_triple(ptr, use);
16529 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16530 /* Delete the adecl */
16531 release_triple(state, MISC(ptr, 0));
16532 /* And the piece */
16533 release_triple(state, ptr);
16538 for(user = block->idominates; user; user = user->next) {
16539 prune_block_variables(state, user->member);
16543 struct phi_triple {
16544 struct triple *phi;
16549 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16551 struct triple **slot;
16553 if (live[phi->id].alive) {
16556 live[phi->id].alive = 1;
16558 slot = &RHS(phi, 0);
16559 for(i = 0; i < zrhs; i++) {
16560 struct triple *used;
16562 if (used && (used->op == OP_PHI)) {
16563 keep_phi(state, live, used);
16568 static void prune_unused_phis(struct compile_state *state)
16570 struct triple *first, *phi;
16571 struct phi_triple *live;
16574 /* Find the first instruction */
16575 first = state->first;
16577 /* Count how many phi functions I need to process */
16579 for(phi = first->next; phi != first; phi = phi->next) {
16580 if (phi->op == OP_PHI) {
16585 /* Mark them all dead */
16586 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16588 for(phi = first->next; phi != first; phi = phi->next) {
16589 if (phi->op != OP_PHI) {
16592 live[phis].alive = 0;
16593 live[phis].orig_id = phi->id;
16594 live[phis].phi = phi;
16599 /* Mark phis alive that are used by non phis */
16600 for(i = 0; i < phis; i++) {
16601 struct triple_set *set;
16602 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16603 if (set->member->op != OP_PHI) {
16604 keep_phi(state, live, live[i].phi);
16610 /* Delete the extraneous phis */
16611 for(i = 0; i < phis; i++) {
16612 struct triple **slot;
16614 if (!live[i].alive) {
16615 release_triple(state, live[i].phi);
16619 slot = &RHS(phi, 0);
16621 for(j = 0; j < zrhs; j++) {
16623 struct triple *unknown;
16624 get_occurance(phi->occurance);
16625 unknown = flatten(state, state->global_pool,
16626 alloc_triple(state, OP_UNKNOWNVAL,
16627 phi->type, 0, 0, phi->occurance));
16629 use_triple(unknown, phi);
16630 transform_to_arch_instruction(state, unknown);
16632 warning(state, phi, "variable not set at index %d on all paths to use", j);
16640 static void transform_to_ssa_form(struct compile_state *state)
16642 insert_phi_operations(state);
16643 rename_variables(state);
16645 prune_block_variables(state, state->bb.first_block);
16646 prune_unused_phis(state);
16648 print_blocks(state, __func__, state->dbgout);
16652 static void clear_vertex(
16653 struct compile_state *state, struct block *block, void *arg)
16655 /* Clear the current blocks vertex and the vertex of all
16656 * of the current blocks neighbors in case there are malformed
16657 * blocks with now instructions at this point.
16659 struct block_set *user, *edge;
16661 for(edge = block->edges; edge; edge = edge->next) {
16662 edge->member->vertex = 0;
16664 for(user = block->use; user; user = user->next) {
16665 user->member->vertex = 0;
16669 static void mark_live_block(
16670 struct compile_state *state, struct block *block, int *next_vertex)
16672 /* See if this is a block that has not been marked */
16673 if (block->vertex != 0) {
16676 block->vertex = *next_vertex;
16678 if (triple_is_branch(state, block->last)) {
16679 struct triple **targ;
16680 targ = triple_edge_targ(state, block->last, 0);
16681 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16685 if (!triple_stores_block(state, *targ)) {
16686 internal_error(state, 0, "bad targ");
16688 mark_live_block(state, (*targ)->u.block, next_vertex);
16690 /* Ensure the last block of a function remains alive */
16691 if (triple_is_call(state, block->last)) {
16692 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16695 else if (block->last->next != state->first) {
16696 struct triple *ins;
16697 ins = block->last->next;
16698 if (!triple_stores_block(state, ins)) {
16699 internal_error(state, 0, "bad block start");
16701 mark_live_block(state, ins->u.block, next_vertex);
16705 static void transform_from_ssa_form(struct compile_state *state)
16707 /* To get out of ssa form we insert moves on the incoming
16708 * edges to blocks containting phi functions.
16710 struct triple *first;
16711 struct triple *phi, *var, *next;
16714 /* Walk the control flow to see which blocks remain alive */
16715 walk_blocks(state, &state->bb, clear_vertex, 0);
16717 mark_live_block(state, state->bb.first_block, &next_vertex);
16719 /* Walk all of the operations to find the phi functions */
16720 first = state->first;
16721 for(phi = first->next; phi != first ; phi = next) {
16722 struct block_set *set;
16723 struct block *block;
16724 struct triple **slot;
16725 struct triple *var;
16726 struct triple_set *use, *use_next;
16727 int edge, writers, readers;
16729 if (phi->op != OP_PHI) {
16733 block = phi->u.block;
16734 slot = &RHS(phi, 0);
16736 /* If this phi is in a dead block just forget it */
16737 if (block->vertex == 0) {
16738 release_triple(state, phi);
16742 /* Forget uses from code in dead blocks */
16743 for(use = phi->use; use; use = use_next) {
16744 struct block *ublock;
16745 struct triple **expr;
16746 use_next = use->next;
16747 ublock = block_of_triple(state, use->member);
16748 if ((use->member == phi) || (ublock->vertex != 0)) {
16751 expr = triple_rhs(state, use->member, 0);
16752 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16753 if (*expr == phi) {
16757 unuse_triple(phi, use->member);
16759 /* A variable to replace the phi function */
16760 if (registers_of(state, phi->type) != 1) {
16761 internal_error(state, phi, "phi->type does not fit in a single register!");
16763 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16764 var = var->next; /* point at the var */
16766 /* Replaces use of phi with var */
16767 propogate_use(state, phi, var);
16769 /* Count the readers */
16771 for(use = var->use; use; use = use->next) {
16772 if (use->member != MISC(var, 0)) {
16777 /* Walk all of the incoming edges/blocks and insert moves.
16780 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16781 struct block *eblock, *vblock;
16782 struct triple *move;
16783 struct triple *val, *base;
16784 eblock = set->member;
16787 unuse_triple(val, phi);
16788 vblock = block_of_triple(state, val);
16790 /* If we don't have a value that belongs in an OP_WRITE
16793 if (!val || (val == &unknown_triple) || (val == phi)
16794 || (vblock && (vblock->vertex == 0))) {
16797 /* If the value should never occur error */
16799 internal_error(state, val, "no vblock?");
16803 /* If the value occurs in a dead block see if a replacement
16804 * block can be found.
16806 while(eblock && (eblock->vertex == 0)) {
16807 eblock = eblock->idom;
16809 /* If not continue on with the next value. */
16810 if (!eblock || (eblock->vertex == 0)) {
16814 /* If we have an empty incoming block ignore it. */
16815 if (!eblock->first) {
16816 internal_error(state, 0, "empty block?");
16819 /* Make certain the write is placed in the edge block... */
16820 /* Walk through the edge block backwards to find an
16821 * appropriate location for the OP_WRITE.
16823 for(base = eblock->last; base != eblock->first; base = base->prev) {
16824 struct triple **expr;
16825 if (base->op == OP_PIECE) {
16826 base = MISC(base, 0);
16828 if ((base == var) || (base == val)) {
16831 expr = triple_lhs(state, base, 0);
16832 for(; expr; expr = triple_lhs(state, base, expr)) {
16833 if ((*expr) == val) {
16837 expr = triple_rhs(state, base, 0);
16838 for(; expr; expr = triple_rhs(state, base, expr)) {
16839 if ((*expr) == var) {
16845 if (triple_is_branch(state, base)) {
16846 internal_error(state, base,
16847 "Could not insert write to phi");
16849 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16850 use_triple(val, move);
16851 use_triple(var, move);
16854 if (!writers && readers) {
16855 internal_error(state, var, "no value written to in use phi?");
16857 /* If var is not used free it */
16859 release_triple(state, MISC(var, 0));
16860 release_triple(state, var);
16862 /* Release the phi function */
16863 release_triple(state, phi);
16866 /* Walk all of the operations to find the adecls */
16867 for(var = first->next; var != first ; var = var->next) {
16868 struct triple_set *use, *use_next;
16869 if (!triple_is_auto_var(state, var)) {
16873 /* Walk through all of the rhs uses of var and
16874 * replace them with read of var.
16876 for(use = var->use; use; use = use_next) {
16877 struct triple *read, *user;
16878 struct triple **slot;
16880 use_next = use->next;
16881 user = use->member;
16883 /* Generate a read of var */
16884 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16885 use_triple(var, read);
16887 /* Find the rhs uses and see if they need to be replaced */
16890 slot = &RHS(user, 0);
16891 for(i = 0; i < zrhs; i++) {
16892 if (slot[i] == var) {
16897 /* If we did use it cleanup the uses */
16899 unuse_triple(var, user);
16900 use_triple(read, user);
16902 /* If we didn't use it release the extra triple */
16904 release_triple(state, read);
16910 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16911 FILE *fp = state->dbgout; \
16912 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16915 static void rebuild_ssa_form(struct compile_state *state)
16918 transform_from_ssa_form(state);
16920 state->bb.first = state->first;
16921 free_basic_blocks(state, &state->bb);
16922 analyze_basic_blocks(state, &state->bb);
16924 insert_phi_operations(state);
16926 rename_variables(state);
16929 prune_block_variables(state, state->bb.first_block);
16931 prune_unused_phis(state);
16937 * Register conflict resolution
16938 * =========================================================
16941 static struct reg_info find_def_color(
16942 struct compile_state *state, struct triple *def)
16944 struct triple_set *set;
16945 struct reg_info info;
16946 info.reg = REG_UNSET;
16948 if (!triple_is_def(state, def)) {
16951 info = arch_reg_lhs(state, def, 0);
16952 if (info.reg >= MAX_REGISTERS) {
16953 info.reg = REG_UNSET;
16955 for(set = def->use; set; set = set->next) {
16956 struct reg_info tinfo;
16958 i = find_rhs_use(state, set->member, def);
16962 tinfo = arch_reg_rhs(state, set->member, i);
16963 if (tinfo.reg >= MAX_REGISTERS) {
16964 tinfo.reg = REG_UNSET;
16966 if ((tinfo.reg != REG_UNSET) &&
16967 (info.reg != REG_UNSET) &&
16968 (tinfo.reg != info.reg)) {
16969 internal_error(state, def, "register conflict");
16971 if ((info.regcm & tinfo.regcm) == 0) {
16972 internal_error(state, def, "regcm conflict %x & %x == 0",
16973 info.regcm, tinfo.regcm);
16975 if (info.reg == REG_UNSET) {
16976 info.reg = tinfo.reg;
16978 info.regcm &= tinfo.regcm;
16980 if (info.reg >= MAX_REGISTERS) {
16981 internal_error(state, def, "register out of range");
16986 static struct reg_info find_lhs_pre_color(
16987 struct compile_state *state, struct triple *ins, int index)
16989 struct reg_info info;
16993 if (!zlhs && triple_is_def(state, ins)) {
16996 if (index >= zlhs) {
16997 internal_error(state, ins, "Bad lhs %d", index);
16999 info = arch_reg_lhs(state, ins, index);
17000 for(i = 0; i < zrhs; i++) {
17001 struct reg_info rinfo;
17002 rinfo = arch_reg_rhs(state, ins, i);
17003 if ((info.reg == rinfo.reg) &&
17004 (rinfo.reg >= MAX_REGISTERS)) {
17005 struct reg_info tinfo;
17006 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
17007 info.reg = tinfo.reg;
17008 info.regcm &= tinfo.regcm;
17012 if (info.reg >= MAX_REGISTERS) {
17013 info.reg = REG_UNSET;
17018 static struct reg_info find_rhs_post_color(
17019 struct compile_state *state, struct triple *ins, int index);
17021 static struct reg_info find_lhs_post_color(
17022 struct compile_state *state, struct triple *ins, int index)
17024 struct triple_set *set;
17025 struct reg_info info;
17026 struct triple *lhs;
17027 #if DEBUG_TRIPLE_COLOR
17028 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17031 if ((index == 0) && triple_is_def(state, ins)) {
17034 else if (index < ins->lhs) {
17035 lhs = LHS(ins, index);
17038 internal_error(state, ins, "Bad lhs %d", index);
17041 info = arch_reg_lhs(state, ins, index);
17042 if (info.reg >= MAX_REGISTERS) {
17043 info.reg = REG_UNSET;
17045 for(set = lhs->use; set; set = set->next) {
17046 struct reg_info rinfo;
17047 struct triple *user;
17049 user = set->member;
17051 for(i = 0; i < zrhs; i++) {
17052 if (RHS(user, i) != lhs) {
17055 rinfo = find_rhs_post_color(state, user, i);
17056 if ((info.reg != REG_UNSET) &&
17057 (rinfo.reg != REG_UNSET) &&
17058 (info.reg != rinfo.reg)) {
17059 internal_error(state, ins, "register conflict");
17061 if ((info.regcm & rinfo.regcm) == 0) {
17062 internal_error(state, ins, "regcm conflict %x & %x == 0",
17063 info.regcm, rinfo.regcm);
17065 if (info.reg == REG_UNSET) {
17066 info.reg = rinfo.reg;
17068 info.regcm &= rinfo.regcm;
17071 #if DEBUG_TRIPLE_COLOR
17072 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17073 ins, index, info.reg, info.regcm);
17078 static struct reg_info find_rhs_post_color(
17079 struct compile_state *state, struct triple *ins, int index)
17081 struct reg_info info, rinfo;
17083 #if DEBUG_TRIPLE_COLOR
17084 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17087 rinfo = arch_reg_rhs(state, ins, index);
17089 if (!zlhs && triple_is_def(state, ins)) {
17093 if (info.reg >= MAX_REGISTERS) {
17094 info.reg = REG_UNSET;
17096 for(i = 0; i < zlhs; i++) {
17097 struct reg_info linfo;
17098 linfo = arch_reg_lhs(state, ins, i);
17099 if ((linfo.reg == rinfo.reg) &&
17100 (linfo.reg >= MAX_REGISTERS)) {
17101 struct reg_info tinfo;
17102 tinfo = find_lhs_post_color(state, ins, i);
17103 if (tinfo.reg >= MAX_REGISTERS) {
17104 tinfo.reg = REG_UNSET;
17106 info.regcm &= linfo.regcm;
17107 info.regcm &= tinfo.regcm;
17108 if (info.reg != REG_UNSET) {
17109 internal_error(state, ins, "register conflict");
17111 if (info.regcm == 0) {
17112 internal_error(state, ins, "regcm conflict");
17114 info.reg = tinfo.reg;
17117 #if DEBUG_TRIPLE_COLOR
17118 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17119 ins, index, info.reg, info.regcm);
17124 static struct reg_info find_lhs_color(
17125 struct compile_state *state, struct triple *ins, int index)
17127 struct reg_info pre, post, info;
17128 #if DEBUG_TRIPLE_COLOR
17129 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17132 pre = find_lhs_pre_color(state, ins, index);
17133 post = find_lhs_post_color(state, ins, index);
17134 if ((pre.reg != post.reg) &&
17135 (pre.reg != REG_UNSET) &&
17136 (post.reg != REG_UNSET)) {
17137 internal_error(state, ins, "register conflict");
17139 info.regcm = pre.regcm & post.regcm;
17140 info.reg = pre.reg;
17141 if (info.reg == REG_UNSET) {
17142 info.reg = post.reg;
17144 #if DEBUG_TRIPLE_COLOR
17145 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17146 ins, index, info.reg, info.regcm,
17147 pre.reg, pre.regcm, post.reg, post.regcm);
17152 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17154 struct triple_set *entry, *next;
17155 struct triple *out;
17156 struct reg_info info, rinfo;
17158 info = arch_reg_lhs(state, ins, 0);
17159 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17160 use_triple(RHS(out, 0), out);
17161 /* Get the users of ins to use out instead */
17162 for(entry = ins->use; entry; entry = next) {
17164 next = entry->next;
17165 if (entry->member == out) {
17168 i = find_rhs_use(state, entry->member, ins);
17172 rinfo = arch_reg_rhs(state, entry->member, i);
17173 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17176 replace_rhs_use(state, ins, out, entry->member);
17178 transform_to_arch_instruction(state, out);
17182 static struct triple *typed_pre_copy(
17183 struct compile_state *state, struct type *type, struct triple *ins, int index)
17185 /* Carefully insert enough operations so that I can
17186 * enter any operation with a GPR32.
17189 struct triple **expr;
17191 struct reg_info info;
17193 if (ins->op == OP_PHI) {
17194 internal_error(state, ins, "pre_copy on a phi?");
17196 classes = arch_type_to_regcm(state, type);
17197 info = arch_reg_rhs(state, ins, index);
17198 expr = &RHS(ins, index);
17199 if ((info.regcm & classes) == 0) {
17200 FILE *fp = state->errout;
17201 fprintf(fp, "src_type: ");
17202 name_of(fp, ins->type);
17203 fprintf(fp, "\ndst_type: ");
17206 internal_error(state, ins, "pre_copy with no register classes");
17209 if (!equiv_types(type, (*expr)->type)) {
17212 in = pre_triple(state, ins, op, type, *expr, 0);
17213 unuse_triple(*expr, ins);
17215 use_triple(RHS(in, 0), in);
17216 use_triple(in, ins);
17217 transform_to_arch_instruction(state, in);
17221 static struct triple *pre_copy(
17222 struct compile_state *state, struct triple *ins, int index)
17224 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17228 static void insert_copies_to_phi(struct compile_state *state)
17230 /* To get out of ssa form we insert moves on the incoming
17231 * edges to blocks containting phi functions.
17233 struct triple *first;
17234 struct triple *phi;
17236 /* Walk all of the operations to find the phi functions */
17237 first = state->first;
17238 for(phi = first->next; phi != first ; phi = phi->next) {
17239 struct block_set *set;
17240 struct block *block;
17241 struct triple **slot, *copy;
17243 if (phi->op != OP_PHI) {
17246 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17247 block = phi->u.block;
17248 slot = &RHS(phi, 0);
17249 /* Phi's that feed into mandatory live range joins
17250 * cause nasty complications. Insert a copy of
17251 * the phi value so I never have to deal with
17252 * that in the rest of the code.
17254 copy = post_copy(state, phi);
17255 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17256 /* Walk all of the incoming edges/blocks and insert moves.
17258 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17259 struct block *eblock;
17260 struct triple *move;
17261 struct triple *val;
17262 struct triple *ptr;
17263 eblock = set->member;
17270 get_occurance(val->occurance);
17271 move = build_triple(state, OP_COPY, val->type, val, 0,
17273 move->u.block = eblock;
17274 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17275 use_triple(val, move);
17278 unuse_triple(val, phi);
17279 use_triple(move, phi);
17281 /* Walk up the dominator tree until I have found the appropriate block */
17282 while(eblock && !tdominates(state, val, eblock->last)) {
17283 eblock = eblock->idom;
17286 internal_error(state, phi, "Cannot find block dominated by %p",
17290 /* Walk through the block backwards to find
17291 * an appropriate location for the OP_COPY.
17293 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17294 struct triple **expr;
17295 if (ptr->op == OP_PIECE) {
17296 ptr = MISC(ptr, 0);
17298 if ((ptr == phi) || (ptr == val)) {
17301 expr = triple_lhs(state, ptr, 0);
17302 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17303 if ((*expr) == val) {
17307 expr = triple_rhs(state, ptr, 0);
17308 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17309 if ((*expr) == phi) {
17315 if (triple_is_branch(state, ptr)) {
17316 internal_error(state, ptr,
17317 "Could not insert write to phi");
17319 insert_triple(state, after_lhs(state, ptr), move);
17320 if (eblock->last == after_lhs(state, ptr)->prev) {
17321 eblock->last = move;
17323 transform_to_arch_instruction(state, move);
17326 print_blocks(state, __func__, state->dbgout);
17329 struct triple_reg_set;
17333 static int do_triple_set(struct triple_reg_set **head,
17334 struct triple *member, struct triple *new_member)
17336 struct triple_reg_set **ptr, *new;
17341 if ((*ptr)->member == member) {
17344 ptr = &(*ptr)->next;
17346 new = xcmalloc(sizeof(*new), "triple_set");
17347 new->member = member;
17348 new->new = new_member;
17354 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17356 struct triple_reg_set *entry, **ptr;
17360 if (entry->member == member) {
17361 *ptr = entry->next;
17366 ptr = &entry->next;
17371 static int in_triple(struct reg_block *rb, struct triple *in)
17373 return do_triple_set(&rb->in, in, 0);
17376 #if DEBUG_ROMCC_WARNING
17377 static void unin_triple(struct reg_block *rb, struct triple *unin)
17379 do_triple_unset(&rb->in, unin);
17383 static int out_triple(struct reg_block *rb, struct triple *out)
17385 return do_triple_set(&rb->out, out, 0);
17387 #if DEBUG_ROMCC_WARNING
17388 static void unout_triple(struct reg_block *rb, struct triple *unout)
17390 do_triple_unset(&rb->out, unout);
17394 static int initialize_regblock(struct reg_block *blocks,
17395 struct block *block, int vertex)
17397 struct block_set *user;
17398 if (!block || (blocks[block->vertex].block == block)) {
17402 /* Renumber the blocks in a convinient fashion */
17403 block->vertex = vertex;
17404 blocks[vertex].block = block;
17405 blocks[vertex].vertex = vertex;
17406 for(user = block->use; user; user = user->next) {
17407 vertex = initialize_regblock(blocks, user->member, vertex);
17412 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17414 /* Part to piece is a best attempt and it cannot be correct all by
17415 * itself. If various values are read as different sizes in different
17416 * parts of the code this function cannot work. Or rather it cannot
17417 * work in conjunction with compute_variable_liftimes. As the
17418 * analysis will get confused.
17420 struct triple *base;
17422 if (!is_lvalue(state, ins)) {
17427 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17428 base = MISC(ins, 0);
17431 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17434 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17437 internal_error(state, ins, "unhandled part");
17443 if (reg > base->lhs) {
17444 internal_error(state, base, "part out of range?");
17446 ins = LHS(base, reg);
17451 static int this_def(struct compile_state *state,
17452 struct triple *ins, struct triple *other)
17454 if (ins == other) {
17457 if (ins->op == OP_WRITE) {
17458 ins = part_to_piece(state, MISC(ins, 0));
17460 return ins == other;
17463 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17464 struct reg_block *rb, struct block *suc)
17466 /* Read the conditional input set of a successor block
17467 * (i.e. the input to the phi nodes) and place it in the
17468 * current blocks output set.
17470 struct block_set *set;
17471 struct triple *ptr;
17475 /* Find the edge I am coming in on */
17476 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17477 if (set->member == rb->block) {
17482 internal_error(state, 0, "Not coming on a control edge?");
17484 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17485 struct triple **slot, *expr, *ptr2;
17486 int out_change, done2;
17487 done = (ptr == suc->last);
17488 if (ptr->op != OP_PHI) {
17491 slot = &RHS(ptr, 0);
17493 out_change = out_triple(rb, expr);
17497 /* If we don't define the variable also plast it
17498 * in the current blocks input set.
17500 ptr2 = rb->block->first;
17501 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17502 if (this_def(state, ptr2, expr)) {
17505 done2 = (ptr2 == rb->block->last);
17510 change |= in_triple(rb, expr);
17515 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17516 struct reg_block *rb, struct block *suc)
17518 struct triple_reg_set *in_set;
17521 /* Read the input set of a successor block
17522 * and place it in the current blocks output set.
17524 in_set = blocks[suc->vertex].in;
17525 for(; in_set; in_set = in_set->next) {
17526 int out_change, done;
17527 struct triple *first, *last, *ptr;
17528 out_change = out_triple(rb, in_set->member);
17532 /* If we don't define the variable also place it
17533 * in the current blocks input set.
17535 first = rb->block->first;
17536 last = rb->block->last;
17538 for(ptr = first; !done; ptr = ptr->next) {
17539 if (this_def(state, ptr, in_set->member)) {
17542 done = (ptr == last);
17547 change |= in_triple(rb, in_set->member);
17549 change |= phi_in(state, blocks, rb, suc);
17553 static int use_in(struct compile_state *state, struct reg_block *rb)
17555 /* Find the variables we use but don't define and add
17556 * it to the current blocks input set.
17558 #if DEBUG_ROMCC_WARNINGS
17559 #warning "FIXME is this O(N^2) algorithm bad?"
17561 struct block *block;
17562 struct triple *ptr;
17567 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17568 struct triple **expr;
17569 done = (ptr == block->first);
17570 /* The variable a phi function uses depends on the
17571 * control flow, and is handled in phi_in, not
17574 if (ptr->op == OP_PHI) {
17577 expr = triple_rhs(state, ptr, 0);
17578 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17579 struct triple *rhs, *test;
17581 rhs = part_to_piece(state, *expr);
17586 /* See if rhs is defined in this block.
17587 * A write counts as a definition.
17589 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17590 tdone = (test == block->first);
17591 if (this_def(state, test, rhs)) {
17596 /* If I still have a valid rhs add it to in */
17597 change |= in_triple(rb, rhs);
17603 static struct reg_block *compute_variable_lifetimes(
17604 struct compile_state *state, struct basic_blocks *bb)
17606 struct reg_block *blocks;
17609 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17610 initialize_regblock(blocks, bb->last_block, 0);
17614 for(i = 1; i <= bb->last_vertex; i++) {
17615 struct block_set *edge;
17616 struct reg_block *rb;
17618 /* Add the all successor's input set to in */
17619 for(edge = rb->block->edges; edge; edge = edge->next) {
17620 change |= reg_in(state, blocks, rb, edge->member);
17622 /* Add use to in... */
17623 change |= use_in(state, rb);
17629 static void free_variable_lifetimes(struct compile_state *state,
17630 struct basic_blocks *bb, struct reg_block *blocks)
17633 /* free in_set && out_set on each block */
17634 for(i = 1; i <= bb->last_vertex; i++) {
17635 struct triple_reg_set *entry, *next;
17636 struct reg_block *rb;
17638 for(entry = rb->in; entry ; entry = next) {
17639 next = entry->next;
17640 do_triple_unset(&rb->in, entry->member);
17642 for(entry = rb->out; entry; entry = next) {
17643 next = entry->next;
17644 do_triple_unset(&rb->out, entry->member);
17651 typedef void (*wvl_cb_t)(
17652 struct compile_state *state,
17653 struct reg_block *blocks, struct triple_reg_set *live,
17654 struct reg_block *rb, struct triple *ins, void *arg);
17656 static void walk_variable_lifetimes(struct compile_state *state,
17657 struct basic_blocks *bb, struct reg_block *blocks,
17658 wvl_cb_t cb, void *arg)
17662 for(i = 1; i <= state->bb.last_vertex; i++) {
17663 struct triple_reg_set *live;
17664 struct triple_reg_set *entry, *next;
17665 struct triple *ptr, *prev;
17666 struct reg_block *rb;
17667 struct block *block;
17670 /* Get the blocks */
17674 /* Copy out into live */
17676 for(entry = rb->out; entry; entry = next) {
17677 next = entry->next;
17678 do_triple_set(&live, entry->member, entry->new);
17680 /* Walk through the basic block calculating live */
17681 for(done = 0, ptr = block->last; !done; ptr = prev) {
17682 struct triple **expr;
17685 done = (ptr == block->first);
17687 /* Ensure the current definition is in live */
17688 if (triple_is_def(state, ptr)) {
17689 do_triple_set(&live, ptr, 0);
17692 /* Inform the callback function of what is
17695 cb(state, blocks, live, rb, ptr, arg);
17697 /* Remove the current definition from live */
17698 do_triple_unset(&live, ptr);
17700 /* Add the current uses to live.
17702 * It is safe to skip phi functions because they do
17703 * not have any block local uses, and the block
17704 * output sets already properly account for what
17705 * control flow depedent uses phi functions do have.
17707 if (ptr->op == OP_PHI) {
17710 expr = triple_rhs(state, ptr, 0);
17711 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17712 /* If the triple is not a definition skip it. */
17713 if (!*expr || !triple_is_def(state, *expr)) {
17716 do_triple_set(&live, *expr, 0);
17720 for(entry = live; entry; entry = next) {
17721 next = entry->next;
17722 do_triple_unset(&live, entry->member);
17727 struct print_live_variable_info {
17728 struct reg_block *rb;
17731 #if DEBUG_EXPLICIT_CLOSURES
17732 static void print_live_variables_block(
17733 struct compile_state *state, struct block *block, void *arg)
17736 struct print_live_variable_info *info = arg;
17737 struct block_set *edge;
17738 FILE *fp = info->fp;
17739 struct reg_block *rb;
17740 struct triple *ptr;
17743 rb = &info->rb[block->vertex];
17745 fprintf(fp, "\nblock: %p (%d),",
17746 block, block->vertex);
17747 for(edge = block->edges; edge; edge = edge->next) {
17748 fprintf(fp, " %p<-%p",
17750 edge->member && edge->member->use?edge->member->use->member : 0);
17754 struct triple_reg_set *in_set;
17755 fprintf(fp, " in:");
17756 for(in_set = rb->in; in_set; in_set = in_set->next) {
17757 fprintf(fp, " %-10p", in_set->member);
17762 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17763 done = (ptr == block->last);
17764 if (ptr->op == OP_PHI) {
17771 for(edge = 0; edge < block->users; edge++) {
17772 fprintf(fp, " in(%d):", edge);
17773 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17774 struct triple **slot;
17775 done = (ptr == block->last);
17776 if (ptr->op != OP_PHI) {
17779 slot = &RHS(ptr, 0);
17780 fprintf(fp, " %-10p", slot[edge]);
17785 if (block->first->op == OP_LABEL) {
17786 fprintf(fp, "%p:\n", block->first);
17788 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17789 done = (ptr == block->last);
17790 display_triple(fp, ptr);
17793 struct triple_reg_set *out_set;
17794 fprintf(fp, " out:");
17795 for(out_set = rb->out; out_set; out_set = out_set->next) {
17796 fprintf(fp, " %-10p", out_set->member);
17803 static void print_live_variables(struct compile_state *state,
17804 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17806 struct print_live_variable_info info;
17809 fprintf(fp, "\nlive variables by block\n");
17810 walk_blocks(state, bb, print_live_variables_block, &info);
17815 static int count_triples(struct compile_state *state)
17817 struct triple *first, *ins;
17819 first = state->first;
17824 } while (ins != first);
17829 struct dead_triple {
17830 struct triple *triple;
17831 struct dead_triple *work_next;
17832 struct block *block;
17835 #define TRIPLE_FLAG_ALIVE 1
17836 #define TRIPLE_FLAG_FREE 1
17839 static void print_dead_triples(struct compile_state *state,
17840 struct dead_triple *dtriple)
17842 struct triple *first, *ins;
17843 struct dead_triple *dt;
17845 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17848 fp = state->dbgout;
17849 fprintf(fp, "--------------- dtriples ---------------\n");
17850 first = state->first;
17853 dt = &dtriple[ins->id];
17854 if ((ins->op == OP_LABEL) && (ins->use)) {
17855 fprintf(fp, "\n%p:\n", ins);
17858 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17859 display_triple(fp, ins);
17860 if (triple_is_branch(state, ins)) {
17864 } while(ins != first);
17869 static void awaken(
17870 struct compile_state *state,
17871 struct dead_triple *dtriple, struct triple **expr,
17872 struct dead_triple ***work_list_tail)
17874 struct triple *triple;
17875 struct dead_triple *dt;
17883 if (triple->id <= 0) {
17884 internal_error(state, triple, "bad triple id: %d",
17887 if (triple->op == OP_NOOP) {
17888 internal_error(state, triple, "awakening noop?");
17891 dt = &dtriple[triple->id];
17892 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17893 dt->flags |= TRIPLE_FLAG_ALIVE;
17894 if (!dt->work_next) {
17895 **work_list_tail = dt;
17896 *work_list_tail = &dt->work_next;
17901 static void eliminate_inefectual_code(struct compile_state *state)
17903 struct block *block;
17904 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17906 struct triple *first, *final, *ins;
17908 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17912 /* Setup the work list */
17914 work_list_tail = &work_list;
17916 first = state->first;
17917 final = state->first->prev;
17919 /* Count how many triples I have */
17920 triples = count_triples(state);
17922 /* Now put then in an array and mark all of the triples dead */
17923 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17929 dtriple[i].triple = ins;
17930 dtriple[i].block = block_of_triple(state, ins);
17931 dtriple[i].flags = 0;
17932 dtriple[i].old_id = ins->id;
17934 /* See if it is an operation we always keep */
17935 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17936 awaken(state, dtriple, &ins, &work_list_tail);
17940 } while(ins != first);
17942 struct block *block;
17943 struct dead_triple *dt;
17944 struct block_set *user;
17945 struct triple **expr;
17947 work_list = dt->work_next;
17949 work_list_tail = &work_list;
17951 /* Make certain the block the current instruction is in lives */
17952 block = block_of_triple(state, dt->triple);
17953 awaken(state, dtriple, &block->first, &work_list_tail);
17954 if (triple_is_branch(state, block->last)) {
17955 awaken(state, dtriple, &block->last, &work_list_tail);
17957 awaken(state, dtriple, &block->last->next, &work_list_tail);
17960 /* Wake up the data depencencies of this triple */
17963 expr = triple_rhs(state, dt->triple, expr);
17964 awaken(state, dtriple, expr, &work_list_tail);
17967 expr = triple_lhs(state, dt->triple, expr);
17968 awaken(state, dtriple, expr, &work_list_tail);
17971 expr = triple_misc(state, dt->triple, expr);
17972 awaken(state, dtriple, expr, &work_list_tail);
17974 /* Wake up the forward control dependencies */
17976 expr = triple_targ(state, dt->triple, expr);
17977 awaken(state, dtriple, expr, &work_list_tail);
17979 /* Wake up the reverse control dependencies of this triple */
17980 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17981 struct triple *last;
17982 last = user->member->last;
17983 while((last->op == OP_NOOP) && (last != user->member->first)) {
17984 #if DEBUG_ROMCC_WARNINGS
17985 #warning "Should we bring the awakening noops back?"
17987 // internal_warning(state, last, "awakening noop?");
17990 awaken(state, dtriple, &last, &work_list_tail);
17993 print_dead_triples(state, dtriple);
17994 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17995 if ((dt->triple->op == OP_NOOP) &&
17996 (dt->flags & TRIPLE_FLAG_ALIVE)) {
17997 internal_error(state, dt->triple, "noop effective?");
17999 dt->triple->id = dt->old_id; /* Restore the color */
18000 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
18001 release_triple(state, dt->triple);
18006 rebuild_ssa_form(state);
18008 print_blocks(state, __func__, state->dbgout);
18012 static void insert_mandatory_copies(struct compile_state *state)
18014 struct triple *ins, *first;
18016 /* The object is with a minimum of inserted copies,
18017 * to resolve in fundamental register conflicts between
18018 * register value producers and consumers.
18019 * Theoretically we may be greater than minimal when we
18020 * are inserting copies before instructions but that
18021 * case should be rare.
18023 first = state->first;
18026 struct triple_set *entry, *next;
18027 struct triple *tmp;
18028 struct reg_info info;
18029 unsigned reg, regcm;
18030 int do_post_copy, do_pre_copy;
18032 if (!triple_is_def(state, ins)) {
18035 /* Find the architecture specific color information */
18036 info = find_lhs_pre_color(state, ins, 0);
18037 if (info.reg >= MAX_REGISTERS) {
18038 info.reg = REG_UNSET;
18042 regcm = arch_type_to_regcm(state, ins->type);
18043 do_post_copy = do_pre_copy = 0;
18045 /* Walk through the uses of ins and check for conflicts */
18046 for(entry = ins->use; entry; entry = next) {
18047 struct reg_info rinfo;
18049 next = entry->next;
18050 i = find_rhs_use(state, entry->member, ins);
18055 /* Find the users color requirements */
18056 rinfo = arch_reg_rhs(state, entry->member, i);
18057 if (rinfo.reg >= MAX_REGISTERS) {
18058 rinfo.reg = REG_UNSET;
18061 /* See if I need a pre_copy */
18062 if (rinfo.reg != REG_UNSET) {
18063 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18068 regcm &= rinfo.regcm;
18069 regcm = arch_regcm_normalize(state, regcm);
18073 /* Always use pre_copies for constants.
18074 * They do not take up any registers until a
18075 * copy places them in one.
18077 if ((info.reg == REG_UNNEEDED) &&
18078 (rinfo.reg != REG_UNNEEDED)) {
18084 (((info.reg != REG_UNSET) &&
18085 (reg != REG_UNSET) &&
18086 (info.reg != reg)) ||
18087 ((info.regcm & regcm) == 0));
18090 regcm = info.regcm;
18091 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18092 for(entry = ins->use; entry; entry = next) {
18093 struct reg_info rinfo;
18095 next = entry->next;
18096 i = find_rhs_use(state, entry->member, ins);
18101 /* Find the users color requirements */
18102 rinfo = arch_reg_rhs(state, entry->member, i);
18103 if (rinfo.reg >= MAX_REGISTERS) {
18104 rinfo.reg = REG_UNSET;
18107 /* Now see if it is time to do the pre_copy */
18108 if (rinfo.reg != REG_UNSET) {
18109 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18110 ((regcm & rinfo.regcm) == 0) ||
18111 /* Don't let a mandatory coalesce sneak
18112 * into a operation that is marked to prevent
18115 ((reg != REG_UNNEEDED) &&
18116 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18117 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18120 struct triple *user;
18121 user = entry->member;
18122 if (RHS(user, i) != ins) {
18123 internal_error(state, user, "bad rhs");
18125 tmp = pre_copy(state, user, i);
18126 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18134 if ((regcm & rinfo.regcm) == 0) {
18136 struct triple *user;
18137 user = entry->member;
18138 if (RHS(user, i) != ins) {
18139 internal_error(state, user, "bad rhs");
18141 tmp = pre_copy(state, user, i);
18142 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18148 regcm &= rinfo.regcm;
18151 if (do_post_copy) {
18152 struct reg_info pre, post;
18153 tmp = post_copy(state, ins);
18154 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18155 pre = arch_reg_lhs(state, ins, 0);
18156 post = arch_reg_lhs(state, tmp, 0);
18157 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18158 internal_error(state, tmp, "useless copy");
18163 } while(ins != first);
18165 print_blocks(state, __func__, state->dbgout);
18169 struct live_range_edge;
18170 struct live_range_def;
18171 struct live_range {
18172 struct live_range_edge *edges;
18173 struct live_range_def *defs;
18174 /* Note. The list pointed to by defs is kept in order.
18175 * That is baring splits in the flow control
18176 * defs dominates defs->next wich dominates defs->next->next
18183 struct live_range *group_next, **group_prev;
18186 struct live_range_edge {
18187 struct live_range_edge *next;
18188 struct live_range *node;
18191 struct live_range_def {
18192 struct live_range_def *next;
18193 struct live_range_def *prev;
18194 struct live_range *lr;
18195 struct triple *def;
18199 #define LRE_HASH_SIZE 2048
18201 struct lre_hash *next;
18202 struct live_range *left;
18203 struct live_range *right;
18208 struct lre_hash *hash[LRE_HASH_SIZE];
18209 struct reg_block *blocks;
18210 struct live_range_def *lrd;
18211 struct live_range *lr;
18212 struct live_range *low, **low_tail;
18213 struct live_range *high, **high_tail;
18216 int passes, max_passes;
18220 struct print_interference_block_info {
18221 struct reg_state *rstate;
18225 static void print_interference_block(
18226 struct compile_state *state, struct block *block, void *arg)
18229 struct print_interference_block_info *info = arg;
18230 struct reg_state *rstate = info->rstate;
18231 struct block_set *edge;
18232 FILE *fp = info->fp;
18233 struct reg_block *rb;
18234 struct triple *ptr;
18237 rb = &rstate->blocks[block->vertex];
18239 fprintf(fp, "\nblock: %p (%d),",
18240 block, block->vertex);
18241 for(edge = block->edges; edge; edge = edge->next) {
18242 fprintf(fp, " %p<-%p",
18244 edge->member && edge->member->use?edge->member->use->member : 0);
18248 struct triple_reg_set *in_set;
18249 fprintf(fp, " in:");
18250 for(in_set = rb->in; in_set; in_set = in_set->next) {
18251 fprintf(fp, " %-10p", in_set->member);
18256 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18257 done = (ptr == block->last);
18258 if (ptr->op == OP_PHI) {
18265 for(edge = 0; edge < block->users; edge++) {
18266 fprintf(fp, " in(%d):", edge);
18267 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18268 struct triple **slot;
18269 done = (ptr == block->last);
18270 if (ptr->op != OP_PHI) {
18273 slot = &RHS(ptr, 0);
18274 fprintf(fp, " %-10p", slot[edge]);
18279 if (block->first->op == OP_LABEL) {
18280 fprintf(fp, "%p:\n", block->first);
18282 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18283 struct live_range *lr;
18287 done = (ptr == block->last);
18288 lr = rstate->lrd[ptr->id].lr;
18291 ptr->id = rstate->lrd[id].orig_id;
18292 SET_REG(ptr->id, lr->color);
18293 display_triple(fp, ptr);
18296 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18297 internal_error(state, ptr, "lr has no defs!");
18299 if (info->need_edges) {
18301 struct live_range_def *lrd;
18302 fprintf(fp, " range:");
18305 fprintf(fp, " %-10p", lrd->def);
18307 } while(lrd != lr->defs);
18310 if (lr->edges > 0) {
18311 struct live_range_edge *edge;
18312 fprintf(fp, " edges:");
18313 for(edge = lr->edges; edge; edge = edge->next) {
18314 struct live_range_def *lrd;
18315 lrd = edge->node->defs;
18317 fprintf(fp, " %-10p", lrd->def);
18319 } while(lrd != edge->node->defs);
18325 /* Do a bunch of sanity checks */
18326 valid_ins(state, ptr);
18327 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18328 internal_error(state, ptr, "Invalid triple id: %d",
18333 struct triple_reg_set *out_set;
18334 fprintf(fp, " out:");
18335 for(out_set = rb->out; out_set; out_set = out_set->next) {
18336 fprintf(fp, " %-10p", out_set->member);
18343 static void print_interference_blocks(
18344 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18346 struct print_interference_block_info info;
18347 info.rstate = rstate;
18349 info.need_edges = need_edges;
18350 fprintf(fp, "\nlive variables by block\n");
18351 walk_blocks(state, &state->bb, print_interference_block, &info);
18355 static unsigned regc_max_size(struct compile_state *state, int classes)
18360 for(i = 0; i < MAX_REGC; i++) {
18361 if (classes & (1 << i)) {
18363 size = arch_regc_size(state, i);
18364 if (size > max_size) {
18372 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18374 unsigned equivs[MAX_REG_EQUIVS];
18376 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18377 internal_error(state, 0, "invalid register");
18379 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18380 internal_error(state, 0, "invalid register");
18382 arch_reg_equivs(state, equivs, reg1);
18383 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18384 if (equivs[i] == reg2) {
18391 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18393 unsigned equivs[MAX_REG_EQUIVS];
18395 if (reg == REG_UNNEEDED) {
18398 arch_reg_equivs(state, equivs, reg);
18399 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18400 used[equivs[i]] = 1;
18405 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18407 unsigned equivs[MAX_REG_EQUIVS];
18409 if (reg == REG_UNNEEDED) {
18412 arch_reg_equivs(state, equivs, reg);
18413 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18414 used[equivs[i]] += 1;
18419 static unsigned int hash_live_edge(
18420 struct live_range *left, struct live_range *right)
18422 unsigned int hash, val;
18423 unsigned long lval, rval;
18424 lval = ((unsigned long)left)/sizeof(struct live_range);
18425 rval = ((unsigned long)right)/sizeof(struct live_range);
18430 hash = (hash *263) + val;
18435 hash = (hash *263) + val;
18437 hash = hash & (LRE_HASH_SIZE - 1);
18441 static struct lre_hash **lre_probe(struct reg_state *rstate,
18442 struct live_range *left, struct live_range *right)
18444 struct lre_hash **ptr;
18445 unsigned int index;
18446 /* Ensure left <= right */
18447 if (left > right) {
18448 struct live_range *tmp;
18453 index = hash_live_edge(left, right);
18455 ptr = &rstate->hash[index];
18457 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18460 ptr = &(*ptr)->next;
18465 static int interfere(struct reg_state *rstate,
18466 struct live_range *left, struct live_range *right)
18468 struct lre_hash **ptr;
18469 ptr = lre_probe(rstate, left, right);
18470 return ptr && *ptr;
18473 static void add_live_edge(struct reg_state *rstate,
18474 struct live_range *left, struct live_range *right)
18476 /* FIXME the memory allocation overhead is noticeable here... */
18477 struct lre_hash **ptr, *new_hash;
18478 struct live_range_edge *edge;
18480 if (left == right) {
18483 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18486 /* Ensure left <= right */
18487 if (left > right) {
18488 struct live_range *tmp;
18493 ptr = lre_probe(rstate, left, right);
18498 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18501 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18502 new_hash->next = *ptr;
18503 new_hash->left = left;
18504 new_hash->right = right;
18507 edge = xmalloc(sizeof(*edge), "live_range_edge");
18508 edge->next = left->edges;
18509 edge->node = right;
18510 left->edges = edge;
18513 edge = xmalloc(sizeof(*edge), "live_range_edge");
18514 edge->next = right->edges;
18516 right->edges = edge;
18517 right->degree += 1;
18520 static void remove_live_edge(struct reg_state *rstate,
18521 struct live_range *left, struct live_range *right)
18523 struct live_range_edge *edge, **ptr;
18524 struct lre_hash **hptr, *entry;
18525 hptr = lre_probe(rstate, left, right);
18526 if (!hptr || !*hptr) {
18530 *hptr = entry->next;
18533 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18535 if (edge->node == right) {
18537 memset(edge, 0, sizeof(*edge));
18543 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18545 if (edge->node == left) {
18547 memset(edge, 0, sizeof(*edge));
18555 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18557 struct live_range_edge *edge, *next;
18558 for(edge = range->edges; edge; edge = next) {
18560 remove_live_edge(rstate, range, edge->node);
18564 static void transfer_live_edges(struct reg_state *rstate,
18565 struct live_range *dest, struct live_range *src)
18567 struct live_range_edge *edge, *next;
18568 for(edge = src->edges; edge; edge = next) {
18569 struct live_range *other;
18571 other = edge->node;
18572 remove_live_edge(rstate, src, other);
18573 add_live_edge(rstate, dest, other);
18578 /* Interference graph...
18580 * new(n) --- Return a graph with n nodes but no edges.
18581 * add(g,x,y) --- Return a graph including g with an between x and y
18582 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18583 * x and y in the graph g
18584 * degree(g, x) --- Return the degree of the node x in the graph g
18585 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18587 * Implement with a hash table && a set of adjcency vectors.
18588 * The hash table supports constant time implementations of add and interfere.
18589 * The adjacency vectors support an efficient implementation of neighbors.
18593 * +---------------------------------------------------+
18594 * | +--------------+ |
18596 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18598 * -- In simplify implment optimistic coloring... (No backtracking)
18599 * -- Implement Rematerialization it is the only form of spilling we can perform
18600 * Essentially this means dropping a constant from a register because
18601 * we can regenerate it later.
18603 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18604 * coalesce at phi points...
18605 * --- Bias coloring if at all possible do the coalesing a compile time.
18610 #if DEBUG_ROMCC_WARNING
18611 static void different_colored(
18612 struct compile_state *state, struct reg_state *rstate,
18613 struct triple *parent, struct triple *ins)
18615 struct live_range *lr;
18616 struct triple **expr;
18617 lr = rstate->lrd[ins->id].lr;
18618 expr = triple_rhs(state, ins, 0);
18619 for(;expr; expr = triple_rhs(state, ins, expr)) {
18620 struct live_range *lr2;
18621 if (!*expr || (*expr == parent) || (*expr == ins)) {
18624 lr2 = rstate->lrd[(*expr)->id].lr;
18625 if (lr->color == lr2->color) {
18626 internal_error(state, ins, "live range too big");
18632 static struct live_range *coalesce_ranges(
18633 struct compile_state *state, struct reg_state *rstate,
18634 struct live_range *lr1, struct live_range *lr2)
18636 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18642 if (!lr1->defs || !lr2->defs) {
18643 internal_error(state, 0,
18644 "cannot coalese dead live ranges");
18646 if ((lr1->color == REG_UNNEEDED) ||
18647 (lr2->color == REG_UNNEEDED)) {
18648 internal_error(state, 0,
18649 "cannot coalesce live ranges without a possible color");
18651 if ((lr1->color != lr2->color) &&
18652 (lr1->color != REG_UNSET) &&
18653 (lr2->color != REG_UNSET)) {
18654 internal_error(state, lr1->defs->def,
18655 "cannot coalesce live ranges of different colors");
18657 color = lr1->color;
18658 if (color == REG_UNSET) {
18659 color = lr2->color;
18661 classes = lr1->classes & lr2->classes;
18663 internal_error(state, lr1->defs->def,
18664 "cannot coalesce live ranges with dissimilar register classes");
18666 if (state->compiler->debug & DEBUG_COALESCING) {
18667 FILE *fp = state->errout;
18668 fprintf(fp, "coalescing:");
18671 fprintf(fp, " %p", lrd->def);
18673 } while(lrd != lr1->defs);
18677 fprintf(fp, " %p", lrd->def);
18679 } while(lrd != lr2->defs);
18682 /* If there is a clear dominate live range put it in lr1,
18683 * For purposes of this test phi functions are
18684 * considered dominated by the definitions that feed into
18687 if ((lr1->defs->prev->def->op == OP_PHI) ||
18688 ((lr2->defs->prev->def->op != OP_PHI) &&
18689 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18690 struct live_range *tmp;
18696 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18697 fprintf(state->errout, "lr1 post\n");
18699 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18700 fprintf(state->errout, "lr1 pre\n");
18702 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18703 fprintf(state->errout, "lr2 post\n");
18705 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18706 fprintf(state->errout, "lr2 pre\n");
18710 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18717 /* Append lr2 onto lr1 */
18718 #if DEBUG_ROMCC_WARNINGS
18719 #warning "FIXME should this be a merge instead of a splice?"
18721 /* This FIXME item applies to the correctness of live_range_end
18722 * and to the necessity of making multiple passes of coalesce_live_ranges.
18723 * A failure to find some coalesce opportunities in coaleace_live_ranges
18724 * does not impact the correct of the compiler just the efficiency with
18725 * which registers are allocated.
18728 mid1 = lr1->defs->prev;
18730 end = lr2->defs->prev;
18738 /* Fixup the live range in the added live range defs */
18743 } while(lrd != head);
18745 /* Mark lr2 as free. */
18747 lr2->color = REG_UNNEEDED;
18751 internal_error(state, 0, "lr1->defs == 0 ?");
18754 lr1->color = color;
18755 lr1->classes = classes;
18757 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18758 transfer_live_edges(rstate, lr1, lr2);
18763 static struct live_range_def *live_range_head(
18764 struct compile_state *state, struct live_range *lr,
18765 struct live_range_def *last)
18767 struct live_range_def *result;
18772 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18773 result = last->next;
18778 static struct live_range_def *live_range_end(
18779 struct compile_state *state, struct live_range *lr,
18780 struct live_range_def *last)
18782 struct live_range_def *result;
18785 result = lr->defs->prev;
18787 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18788 result = last->prev;
18794 static void initialize_live_ranges(
18795 struct compile_state *state, struct reg_state *rstate)
18797 struct triple *ins, *first;
18798 size_t count, size;
18801 first = state->first;
18802 /* First count how many instructions I have.
18804 count = count_triples(state);
18805 /* Potentially I need one live range definitions for each
18808 rstate->defs = count;
18809 /* Potentially I need one live range for each instruction
18810 * plus an extra for the dummy live range.
18812 rstate->ranges = count + 1;
18813 size = sizeof(rstate->lrd[0]) * rstate->defs;
18814 rstate->lrd = xcmalloc(size, "live_range_def");
18815 size = sizeof(rstate->lr[0]) * rstate->ranges;
18816 rstate->lr = xcmalloc(size, "live_range");
18818 /* Setup the dummy live range */
18819 rstate->lr[0].classes = 0;
18820 rstate->lr[0].color = REG_UNSET;
18821 rstate->lr[0].defs = 0;
18825 /* If the triple is a variable give it a live range */
18826 if (triple_is_def(state, ins)) {
18827 struct reg_info info;
18828 /* Find the architecture specific color information */
18829 info = find_def_color(state, ins);
18831 rstate->lr[i].defs = &rstate->lrd[j];
18832 rstate->lr[i].color = info.reg;
18833 rstate->lr[i].classes = info.regcm;
18834 rstate->lr[i].degree = 0;
18835 rstate->lrd[j].lr = &rstate->lr[i];
18837 /* Otherwise give the triple the dummy live range. */
18839 rstate->lrd[j].lr = &rstate->lr[0];
18842 /* Initalize the live_range_def */
18843 rstate->lrd[j].next = &rstate->lrd[j];
18844 rstate->lrd[j].prev = &rstate->lrd[j];
18845 rstate->lrd[j].def = ins;
18846 rstate->lrd[j].orig_id = ins->id;
18851 } while(ins != first);
18852 rstate->ranges = i;
18854 /* Make a second pass to handle achitecture specific register
18859 int zlhs, zrhs, i, j;
18860 if (ins->id > rstate->defs) {
18861 internal_error(state, ins, "bad id");
18864 /* Walk through the template of ins and coalesce live ranges */
18866 if ((zlhs == 0) && triple_is_def(state, ins)) {
18871 if (state->compiler->debug & DEBUG_COALESCING2) {
18872 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18876 for(i = 0; i < zlhs; i++) {
18877 struct reg_info linfo;
18878 struct live_range_def *lhs;
18879 linfo = arch_reg_lhs(state, ins, i);
18880 if (linfo.reg < MAX_REGISTERS) {
18883 if (triple_is_def(state, ins)) {
18884 lhs = &rstate->lrd[ins->id];
18886 lhs = &rstate->lrd[LHS(ins, i)->id];
18889 if (state->compiler->debug & DEBUG_COALESCING2) {
18890 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18891 i, lhs, linfo.reg);
18894 for(j = 0; j < zrhs; j++) {
18895 struct reg_info rinfo;
18896 struct live_range_def *rhs;
18897 rinfo = arch_reg_rhs(state, ins, j);
18898 if (rinfo.reg < MAX_REGISTERS) {
18901 rhs = &rstate->lrd[RHS(ins, j)->id];
18903 if (state->compiler->debug & DEBUG_COALESCING2) {
18904 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18905 j, rhs, rinfo.reg);
18908 if (rinfo.reg == linfo.reg) {
18909 coalesce_ranges(state, rstate,
18915 } while(ins != first);
18918 static void graph_ins(
18919 struct compile_state *state,
18920 struct reg_block *blocks, struct triple_reg_set *live,
18921 struct reg_block *rb, struct triple *ins, void *arg)
18923 struct reg_state *rstate = arg;
18924 struct live_range *def;
18925 struct triple_reg_set *entry;
18927 /* If the triple is not a definition
18928 * we do not have a definition to add to
18929 * the interference graph.
18931 if (!triple_is_def(state, ins)) {
18934 def = rstate->lrd[ins->id].lr;
18936 /* Create an edge between ins and everything that is
18937 * alive, unless the live_range cannot share
18938 * a physical register with ins.
18940 for(entry = live; entry; entry = entry->next) {
18941 struct live_range *lr;
18942 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18943 internal_error(state, 0, "bad entry?");
18945 lr = rstate->lrd[entry->member->id].lr;
18949 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18952 add_live_edge(rstate, def, lr);
18957 #if DEBUG_CONSISTENCY > 1
18958 static struct live_range *get_verify_live_range(
18959 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18961 struct live_range *lr;
18962 struct live_range_def *lrd;
18964 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18965 internal_error(state, ins, "bad ins?");
18967 lr = rstate->lrd[ins->id].lr;
18971 if (lrd->def == ins) {
18975 } while(lrd != lr->defs);
18977 internal_error(state, ins, "ins not in live range");
18982 static void verify_graph_ins(
18983 struct compile_state *state,
18984 struct reg_block *blocks, struct triple_reg_set *live,
18985 struct reg_block *rb, struct triple *ins, void *arg)
18987 struct reg_state *rstate = arg;
18988 struct triple_reg_set *entry1, *entry2;
18991 /* Compare live against edges and make certain the code is working */
18992 for(entry1 = live; entry1; entry1 = entry1->next) {
18993 struct live_range *lr1;
18994 lr1 = get_verify_live_range(state, rstate, entry1->member);
18995 for(entry2 = live; entry2; entry2 = entry2->next) {
18996 struct live_range *lr2;
18997 struct live_range_edge *edge2;
19000 if (entry2 == entry1) {
19003 lr2 = get_verify_live_range(state, rstate, entry2->member);
19005 internal_error(state, entry2->member,
19006 "live range with 2 values simultaneously alive");
19008 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19011 if (!interfere(rstate, lr1, lr2)) {
19012 internal_error(state, entry2->member,
19013 "edges don't interfere?");
19018 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19020 if (edge2->node == lr1) {
19024 if (lr2_degree != lr2->degree) {
19025 internal_error(state, entry2->member,
19026 "computed degree: %d does not match reported degree: %d\n",
19027 lr2_degree, lr2->degree);
19030 internal_error(state, entry2->member, "missing edge");
19038 static void print_interference_ins(
19039 struct compile_state *state,
19040 struct reg_block *blocks, struct triple_reg_set *live,
19041 struct reg_block *rb, struct triple *ins, void *arg)
19043 struct reg_state *rstate = arg;
19044 struct live_range *lr;
19046 FILE *fp = state->dbgout;
19048 lr = rstate->lrd[ins->id].lr;
19050 ins->id = rstate->lrd[id].orig_id;
19051 SET_REG(ins->id, lr->color);
19052 display_triple(state->dbgout, ins);
19056 struct live_range_def *lrd;
19057 fprintf(fp, " range:");
19060 fprintf(fp, " %-10p", lrd->def);
19062 } while(lrd != lr->defs);
19066 struct triple_reg_set *entry;
19067 fprintf(fp, " live:");
19068 for(entry = live; entry; entry = entry->next) {
19069 fprintf(fp, " %-10p", entry->member);
19074 struct live_range_edge *entry;
19075 fprintf(fp, " edges:");
19076 for(entry = lr->edges; entry; entry = entry->next) {
19077 struct live_range_def *lrd;
19078 lrd = entry->node->defs;
19080 fprintf(fp, " %-10p", lrd->def);
19082 } while(lrd != entry->node->defs);
19087 if (triple_is_branch(state, ins)) {
19093 static int coalesce_live_ranges(
19094 struct compile_state *state, struct reg_state *rstate)
19096 /* At the point where a value is moved from one
19097 * register to another that value requires two
19098 * registers, thus increasing register pressure.
19099 * Live range coaleescing reduces the register
19100 * pressure by keeping a value in one register
19103 * In the case of a phi function all paths leading
19104 * into it must be allocated to the same register
19105 * otherwise the phi function may not be removed.
19107 * Forcing a value to stay in a single register
19108 * for an extended period of time does have
19109 * limitations when applied to non homogenous
19112 * The two cases I have identified are:
19113 * 1) Two forced register assignments may
19115 * 2) Registers may go unused because they
19116 * are only good for storing the value
19117 * and not manipulating it.
19119 * Because of this I need to split live ranges,
19120 * even outside of the context of coalesced live
19121 * ranges. The need to split live ranges does
19122 * impose some constraints on live range coalescing.
19124 * - Live ranges may not be coalesced across phi
19125 * functions. This creates a 2 headed live
19126 * range that cannot be sanely split.
19128 * - phi functions (coalesced in initialize_live_ranges)
19129 * are handled as pre split live ranges so we will
19130 * never attempt to split them.
19136 for(i = 0; i <= rstate->ranges; i++) {
19137 struct live_range *lr1;
19138 struct live_range_def *lrd1;
19139 lr1 = &rstate->lr[i];
19143 lrd1 = live_range_end(state, lr1, 0);
19144 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19145 struct triple_set *set;
19146 if (lrd1->def->op != OP_COPY) {
19149 /* Skip copies that are the result of a live range split. */
19150 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19153 for(set = lrd1->def->use; set; set = set->next) {
19154 struct live_range_def *lrd2;
19155 struct live_range *lr2, *res;
19157 lrd2 = &rstate->lrd[set->member->id];
19159 /* Don't coalesce with instructions
19160 * that are the result of a live range
19163 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19166 lr2 = rstate->lrd[set->member->id].lr;
19170 if ((lr1->color != lr2->color) &&
19171 (lr1->color != REG_UNSET) &&
19172 (lr2->color != REG_UNSET)) {
19175 if ((lr1->classes & lr2->classes) == 0) {
19179 if (interfere(rstate, lr1, lr2)) {
19183 res = coalesce_ranges(state, rstate, lr1, lr2);
19197 static void fix_coalesce_conflicts(struct compile_state *state,
19198 struct reg_block *blocks, struct triple_reg_set *live,
19199 struct reg_block *rb, struct triple *ins, void *arg)
19201 int *conflicts = arg;
19202 int zlhs, zrhs, i, j;
19204 /* See if we have a mandatory coalesce operation between
19205 * a lhs and a rhs value. If so and the rhs value is also
19206 * alive then this triple needs to be pre copied. Otherwise
19207 * we would have two definitions in the same live range simultaneously
19211 if ((zlhs == 0) && triple_is_def(state, ins)) {
19215 for(i = 0; i < zlhs; i++) {
19216 struct reg_info linfo;
19217 linfo = arch_reg_lhs(state, ins, i);
19218 if (linfo.reg < MAX_REGISTERS) {
19221 for(j = 0; j < zrhs; j++) {
19222 struct reg_info rinfo;
19223 struct triple *rhs;
19224 struct triple_reg_set *set;
19227 rinfo = arch_reg_rhs(state, ins, j);
19228 if (rinfo.reg != linfo.reg) {
19232 for(set = live; set && !found; set = set->next) {
19233 if (set->member == rhs) {
19238 struct triple *copy;
19239 copy = pre_copy(state, ins, j);
19240 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19248 static int correct_coalesce_conflicts(
19249 struct compile_state *state, struct reg_block *blocks)
19253 walk_variable_lifetimes(state, &state->bb, blocks,
19254 fix_coalesce_conflicts, &conflicts);
19258 static void replace_set_use(struct compile_state *state,
19259 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19261 struct triple_reg_set *set;
19262 for(set = head; set; set = set->next) {
19263 if (set->member == orig) {
19269 static void replace_block_use(struct compile_state *state,
19270 struct reg_block *blocks, struct triple *orig, struct triple *new)
19273 #if DEBUG_ROMCC_WARNINGS
19274 #warning "WISHLIST visit just those blocks that need it *"
19276 for(i = 1; i <= state->bb.last_vertex; i++) {
19277 struct reg_block *rb;
19279 replace_set_use(state, rb->in, orig, new);
19280 replace_set_use(state, rb->out, orig, new);
19284 static void color_instructions(struct compile_state *state)
19286 struct triple *ins, *first;
19287 first = state->first;
19290 if (triple_is_def(state, ins)) {
19291 struct reg_info info;
19292 info = find_lhs_color(state, ins, 0);
19293 if (info.reg >= MAX_REGISTERS) {
19294 info.reg = REG_UNSET;
19296 SET_INFO(ins->id, info);
19299 } while(ins != first);
19302 static struct reg_info read_lhs_color(
19303 struct compile_state *state, struct triple *ins, int index)
19305 struct reg_info info;
19306 if ((index == 0) && triple_is_def(state, ins)) {
19307 info.reg = ID_REG(ins->id);
19308 info.regcm = ID_REGCM(ins->id);
19310 else if (index < ins->lhs) {
19311 info = read_lhs_color(state, LHS(ins, index), 0);
19314 internal_error(state, ins, "Bad lhs %d", index);
19315 info.reg = REG_UNSET;
19321 static struct triple *resolve_tangle(
19322 struct compile_state *state, struct triple *tangle)
19324 struct reg_info info, uinfo;
19325 struct triple_set *set, *next;
19326 struct triple *copy;
19328 #if DEBUG_ROMCC_WARNINGS
19329 #warning "WISHLIST recalculate all affected instructions colors"
19331 info = find_lhs_color(state, tangle, 0);
19332 for(set = tangle->use; set; set = next) {
19333 struct triple *user;
19336 user = set->member;
19338 for(i = 0; i < zrhs; i++) {
19339 if (RHS(user, i) != tangle) {
19342 uinfo = find_rhs_post_color(state, user, i);
19343 if (uinfo.reg == info.reg) {
19344 copy = pre_copy(state, user, i);
19345 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19346 SET_INFO(copy->id, uinfo);
19351 uinfo = find_lhs_pre_color(state, tangle, 0);
19352 if (uinfo.reg == info.reg) {
19353 struct reg_info linfo;
19354 copy = post_copy(state, tangle);
19355 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19356 linfo = find_lhs_color(state, copy, 0);
19357 SET_INFO(copy->id, linfo);
19359 info = find_lhs_color(state, tangle, 0);
19360 SET_INFO(tangle->id, info);
19366 static void fix_tangles(struct compile_state *state,
19367 struct reg_block *blocks, struct triple_reg_set *live,
19368 struct reg_block *rb, struct triple *ins, void *arg)
19370 int *tangles = arg;
19371 struct triple *tangle;
19373 char used[MAX_REGISTERS];
19374 struct triple_reg_set *set;
19377 /* Find out which registers have multiple uses at this point */
19378 memset(used, 0, sizeof(used));
19379 for(set = live; set; set = set->next) {
19380 struct reg_info info;
19381 info = read_lhs_color(state, set->member, 0);
19382 if (info.reg == REG_UNSET) {
19385 reg_inc_used(state, used, info.reg);
19388 /* Now find the least dominated definition of a register in
19389 * conflict I have seen so far.
19391 for(set = live; set; set = set->next) {
19392 struct reg_info info;
19393 info = read_lhs_color(state, set->member, 0);
19394 if (used[info.reg] < 2) {
19397 /* Changing copies that feed into phi functions
19400 if (set->member->use &&
19401 (set->member->use->member->op == OP_PHI)) {
19404 if (!tangle || tdominates(state, set->member, tangle)) {
19405 tangle = set->member;
19408 /* If I have found a tangle resolve it */
19410 struct triple *post_copy;
19412 post_copy = resolve_tangle(state, tangle);
19414 replace_block_use(state, blocks, tangle, post_copy);
19416 if (post_copy && (tangle != ins)) {
19417 replace_set_use(state, live, tangle, post_copy);
19424 static int correct_tangles(
19425 struct compile_state *state, struct reg_block *blocks)
19429 color_instructions(state);
19430 walk_variable_lifetimes(state, &state->bb, blocks,
19431 fix_tangles, &tangles);
19436 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19437 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19439 struct triple *find_constrained_def(
19440 struct compile_state *state, struct live_range *range, struct triple *constrained)
19442 struct live_range_def *lrd, *lrd_next;
19443 lrd_next = range->defs;
19445 struct reg_info info;
19449 lrd_next = lrd->next;
19451 regcm = arch_type_to_regcm(state, lrd->def->type);
19452 info = find_lhs_color(state, lrd->def, 0);
19453 regcm = arch_regcm_reg_normalize(state, regcm);
19454 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19455 /* If the 2 register class masks are equal then
19456 * the current register class is not constrained.
19458 if (regcm == info.regcm) {
19462 /* If there is just one use.
19463 * That use cannot accept a larger register class.
19464 * There are no intervening definitions except
19465 * definitions that feed into that use.
19466 * Then a triple is not constrained.
19467 * FIXME handle this case!
19469 #if DEBUG_ROMCC_WARNINGS
19470 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19474 /* Of the constrained live ranges deal with the
19475 * least dominated one first.
19477 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19478 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19479 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19481 if (!constrained ||
19482 tdominates(state, lrd->def, constrained))
19484 constrained = lrd->def;
19486 } while(lrd_next != range->defs);
19487 return constrained;
19490 static int split_constrained_ranges(
19491 struct compile_state *state, struct reg_state *rstate,
19492 struct live_range *range)
19494 /* Walk through the edges in conflict and our current live
19495 * range, and find definitions that are more severly constrained
19496 * than they type of data they contain require.
19498 * Then pick one of those ranges and relax the constraints.
19500 struct live_range_edge *edge;
19501 struct triple *constrained;
19504 for(edge = range->edges; edge; edge = edge->next) {
19505 constrained = find_constrained_def(state, edge->node, constrained);
19507 #if DEBUG_ROMCC_WARNINGS
19508 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19510 if (!constrained) {
19511 constrained = find_constrained_def(state, range, constrained);
19514 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19515 fprintf(state->errout, "constrained: ");
19516 display_triple(state->errout, constrained);
19519 ids_from_rstate(state, rstate);
19520 cleanup_rstate(state, rstate);
19521 resolve_tangle(state, constrained);
19523 return !!constrained;
19526 static int split_ranges(
19527 struct compile_state *state, struct reg_state *rstate,
19528 char *used, struct live_range *range)
19531 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19532 fprintf(state->errout, "split_ranges %d %s %p\n",
19533 rstate->passes, tops(range->defs->def->op), range->defs->def);
19535 if ((range->color == REG_UNNEEDED) ||
19536 (rstate->passes >= rstate->max_passes)) {
19539 split = split_constrained_ranges(state, rstate, range);
19541 /* Ideally I would split the live range that will not be used
19542 * for the longest period of time in hopes that this will
19543 * (a) allow me to spill a register or
19544 * (b) allow me to place a value in another register.
19546 * So far I don't have a test case for this, the resolving
19547 * of mandatory constraints has solved all of my
19548 * know issues. So I have choosen not to write any
19549 * code until I cat get a better feel for cases where
19550 * it would be useful to have.
19553 #if DEBUG_ROMCC_WARNINGS
19554 #warning "WISHLIST implement live range splitting..."
19557 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19558 FILE *fp = state->errout;
19559 print_interference_blocks(state, rstate, fp, 0);
19560 print_dominators(state, fp, &state->bb);
19565 static FILE *cgdebug_fp(struct compile_state *state)
19569 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19570 fp = state->errout;
19572 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19573 fp = state->dbgout;
19578 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19581 fp = cgdebug_fp(state);
19584 va_start(args, fmt);
19585 vfprintf(fp, fmt, args);
19590 static void cgdebug_flush(struct compile_state *state)
19593 fp = cgdebug_fp(state);
19599 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19602 fp = cgdebug_fp(state);
19604 loc(fp, state, ins);
19608 static int select_free_color(struct compile_state *state,
19609 struct reg_state *rstate, struct live_range *range)
19611 struct triple_set *entry;
19612 struct live_range_def *lrd;
19613 struct live_range_def *phi;
19614 struct live_range_edge *edge;
19615 char used[MAX_REGISTERS];
19616 struct triple **expr;
19618 /* Instead of doing just the trivial color select here I try
19619 * a few extra things because a good color selection will help reduce
19623 /* Find the registers currently in use */
19624 memset(used, 0, sizeof(used));
19625 for(edge = range->edges; edge; edge = edge->next) {
19626 if (edge->node->color == REG_UNSET) {
19629 reg_fill_used(state, used, edge->node->color);
19632 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19635 for(edge = range->edges; edge; edge = edge->next) {
19638 cgdebug_printf(state, "\n%s edges: %d",
19639 tops(range->defs->def->op), i);
19640 cgdebug_loc(state, range->defs->def);
19641 cgdebug_printf(state, "\n");
19642 for(i = 0; i < MAX_REGISTERS; i++) {
19644 cgdebug_printf(state, "used: %s\n",
19650 /* If a color is already assigned see if it will work */
19651 if (range->color != REG_UNSET) {
19652 struct live_range_def *lrd;
19653 if (!used[range->color]) {
19656 for(edge = range->edges; edge; edge = edge->next) {
19657 if (edge->node->color != range->color) {
19660 warning(state, edge->node->defs->def, "edge: ");
19661 lrd = edge->node->defs;
19663 warning(state, lrd->def, " %p %s",
19664 lrd->def, tops(lrd->def->op));
19666 } while(lrd != edge->node->defs);
19669 warning(state, range->defs->def, "def: ");
19671 warning(state, lrd->def, " %p %s",
19672 lrd->def, tops(lrd->def->op));
19674 } while(lrd != range->defs);
19675 internal_error(state, range->defs->def,
19676 "live range with already used color %s",
19677 arch_reg_str(range->color));
19680 /* If I feed into an expression reuse it's color.
19681 * This should help remove copies in the case of 2 register instructions
19682 * and phi functions.
19685 lrd = live_range_end(state, range, 0);
19686 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19687 entry = lrd->def->use;
19688 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19689 struct live_range_def *insd;
19691 insd = &rstate->lrd[entry->member->id];
19692 if (insd->lr->defs == 0) {
19695 if (!phi && (insd->def->op == OP_PHI) &&
19696 !interfere(rstate, range, insd->lr)) {
19699 if (insd->lr->color == REG_UNSET) {
19702 regcm = insd->lr->classes;
19703 if (((regcm & range->classes) == 0) ||
19704 (used[insd->lr->color])) {
19707 if (interfere(rstate, range, insd->lr)) {
19710 range->color = insd->lr->color;
19713 /* If I feed into a phi function reuse it's color or the color
19714 * of something else that feeds into the phi function.
19717 if (phi->lr->color != REG_UNSET) {
19718 if (used[phi->lr->color]) {
19719 range->color = phi->lr->color;
19723 expr = triple_rhs(state, phi->def, 0);
19724 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19725 struct live_range *lr;
19730 lr = rstate->lrd[(*expr)->id].lr;
19731 if (lr->color == REG_UNSET) {
19734 regcm = lr->classes;
19735 if (((regcm & range->classes) == 0) ||
19736 (used[lr->color])) {
19739 if (interfere(rstate, range, lr)) {
19742 range->color = lr->color;
19746 /* If I don't interfere with a rhs node reuse it's color */
19747 lrd = live_range_head(state, range, 0);
19748 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19749 expr = triple_rhs(state, lrd->def, 0);
19750 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19751 struct live_range *lr;
19756 lr = rstate->lrd[(*expr)->id].lr;
19757 if (lr->color == REG_UNSET) {
19760 regcm = lr->classes;
19761 if (((regcm & range->classes) == 0) ||
19762 (used[lr->color])) {
19765 if (interfere(rstate, range, lr)) {
19768 range->color = lr->color;
19772 /* If I have not opportunitically picked a useful color
19773 * pick the first color that is free.
19775 if (range->color == REG_UNSET) {
19777 arch_select_free_register(state, used, range->classes);
19779 if (range->color == REG_UNSET) {
19780 struct live_range_def *lrd;
19782 if (split_ranges(state, rstate, used, range)) {
19785 for(edge = range->edges; edge; edge = edge->next) {
19786 warning(state, edge->node->defs->def, "edge reg %s",
19787 arch_reg_str(edge->node->color));
19788 lrd = edge->node->defs;
19790 warning(state, lrd->def, " %s %p",
19791 tops(lrd->def->op), lrd->def);
19793 } while(lrd != edge->node->defs);
19795 warning(state, range->defs->def, "range: ");
19798 warning(state, lrd->def, " %s %p",
19799 tops(lrd->def->op), lrd->def);
19801 } while(lrd != range->defs);
19803 warning(state, range->defs->def, "classes: %x",
19805 for(i = 0; i < MAX_REGISTERS; i++) {
19807 warning(state, range->defs->def, "used: %s",
19811 error(state, range->defs->def, "too few registers");
19813 range->classes &= arch_reg_regcm(state, range->color);
19814 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19815 internal_error(state, range->defs->def, "select_free_color did not?");
19820 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19823 struct live_range_edge *edge;
19824 struct live_range *range;
19826 cgdebug_printf(state, "Lo: ");
19827 range = rstate->low;
19828 if (*range->group_prev != range) {
19829 internal_error(state, 0, "lo: *prev != range?");
19831 *range->group_prev = range->group_next;
19832 if (range->group_next) {
19833 range->group_next->group_prev = range->group_prev;
19835 if (&range->group_next == rstate->low_tail) {
19836 rstate->low_tail = range->group_prev;
19838 if (rstate->low == range) {
19839 internal_error(state, 0, "low: next != prev?");
19842 else if (rstate->high) {
19843 cgdebug_printf(state, "Hi: ");
19844 range = rstate->high;
19845 if (*range->group_prev != range) {
19846 internal_error(state, 0, "hi: *prev != range?");
19848 *range->group_prev = range->group_next;
19849 if (range->group_next) {
19850 range->group_next->group_prev = range->group_prev;
19852 if (&range->group_next == rstate->high_tail) {
19853 rstate->high_tail = range->group_prev;
19855 if (rstate->high == range) {
19856 internal_error(state, 0, "high: next != prev?");
19862 cgdebug_printf(state, " %d\n", range - rstate->lr);
19863 range->group_prev = 0;
19864 for(edge = range->edges; edge; edge = edge->next) {
19865 struct live_range *node;
19867 /* Move nodes from the high to the low list */
19868 if (node->group_prev && (node->color == REG_UNSET) &&
19869 (node->degree == regc_max_size(state, node->classes))) {
19870 if (*node->group_prev != node) {
19871 internal_error(state, 0, "move: *prev != node?");
19873 *node->group_prev = node->group_next;
19874 if (node->group_next) {
19875 node->group_next->group_prev = node->group_prev;
19877 if (&node->group_next == rstate->high_tail) {
19878 rstate->high_tail = node->group_prev;
19880 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19881 node->group_prev = rstate->low_tail;
19882 node->group_next = 0;
19883 *rstate->low_tail = node;
19884 rstate->low_tail = &node->group_next;
19885 if (*node->group_prev != node) {
19886 internal_error(state, 0, "move2: *prev != node?");
19891 colored = color_graph(state, rstate);
19893 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19894 cgdebug_loc(state, range->defs->def);
19895 cgdebug_flush(state);
19896 colored = select_free_color(state, rstate, range);
19898 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19904 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19906 struct live_range *lr;
19907 struct live_range_edge *edge;
19908 struct triple *ins, *first;
19909 char used[MAX_REGISTERS];
19910 first = state->first;
19913 if (triple_is_def(state, ins)) {
19914 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19915 internal_error(state, ins,
19916 "triple without a live range def");
19918 lr = rstate->lrd[ins->id].lr;
19919 if (lr->color == REG_UNSET) {
19920 internal_error(state, ins,
19921 "triple without a color");
19923 /* Find the registers used by the edges */
19924 memset(used, 0, sizeof(used));
19925 for(edge = lr->edges; edge; edge = edge->next) {
19926 if (edge->node->color == REG_UNSET) {
19927 internal_error(state, 0,
19928 "live range without a color");
19930 reg_fill_used(state, used, edge->node->color);
19932 if (used[lr->color]) {
19933 internal_error(state, ins,
19934 "triple with already used color");
19938 } while(ins != first);
19941 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19943 struct live_range_def *lrd;
19944 struct live_range *lr;
19945 struct triple *first, *ins;
19946 first = state->first;
19949 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19950 internal_error(state, ins,
19951 "triple without a live range");
19953 lrd = &rstate->lrd[ins->id];
19955 ins->id = lrd->orig_id;
19956 SET_REG(ins->id, lr->color);
19958 } while (ins != first);
19961 static struct live_range *merge_sort_lr(
19962 struct live_range *first, struct live_range *last)
19964 struct live_range *mid, *join, **join_tail, *pick;
19966 size = (last - first) + 1;
19968 mid = first + size/2;
19969 first = merge_sort_lr(first, mid -1);
19970 mid = merge_sort_lr(mid, last);
19974 /* merge the two lists */
19975 while(first && mid) {
19976 if ((first->degree < mid->degree) ||
19977 ((first->degree == mid->degree) &&
19978 (first->length < mid->length))) {
19980 first = first->group_next;
19982 first->group_prev = 0;
19987 mid = mid->group_next;
19989 mid->group_prev = 0;
19992 pick->group_next = 0;
19993 pick->group_prev = join_tail;
19995 join_tail = &pick->group_next;
19997 /* Splice the remaining list */
19998 pick = (first)? first : mid;
20001 pick->group_prev = join_tail;
20005 if (!first->defs) {
20013 static void ids_from_rstate(struct compile_state *state,
20014 struct reg_state *rstate)
20016 struct triple *ins, *first;
20017 if (!rstate->defs) {
20020 /* Display the graph if desired */
20021 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20022 FILE *fp = state->dbgout;
20023 print_interference_blocks(state, rstate, fp, 0);
20024 print_control_flow(state, fp, &state->bb);
20027 first = state->first;
20031 struct live_range_def *lrd;
20032 lrd = &rstate->lrd[ins->id];
20033 ins->id = lrd->orig_id;
20036 } while(ins != first);
20039 static void cleanup_live_edges(struct reg_state *rstate)
20042 /* Free the edges on each node */
20043 for(i = 1; i <= rstate->ranges; i++) {
20044 remove_live_edges(rstate, &rstate->lr[i]);
20048 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20050 cleanup_live_edges(rstate);
20051 xfree(rstate->lrd);
20054 /* Free the variable lifetime information */
20055 if (rstate->blocks) {
20056 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20059 rstate->ranges = 0;
20062 rstate->blocks = 0;
20065 static void verify_consistency(struct compile_state *state);
20066 static void allocate_registers(struct compile_state *state)
20068 struct reg_state rstate;
20071 /* Clear out the reg_state */
20072 memset(&rstate, 0, sizeof(rstate));
20073 rstate.max_passes = state->compiler->max_allocation_passes;
20076 struct live_range **point, **next;
20081 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20082 FILE *fp = state->errout;
20083 fprintf(fp, "pass: %d\n", rstate.passes);
20088 ids_from_rstate(state, &rstate);
20090 /* Cleanup the temporary data structures */
20091 cleanup_rstate(state, &rstate);
20093 /* Compute the variable lifetimes */
20094 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20096 /* Fix invalid mandatory live range coalesce conflicts */
20097 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20099 /* Fix two simultaneous uses of the same register.
20100 * In a few pathlogical cases a partial untangle moves
20101 * the tangle to a part of the graph we won't revisit.
20102 * So we keep looping until we have no more tangle fixes
20106 tangles = correct_tangles(state, rstate.blocks);
20110 print_blocks(state, "resolve_tangles", state->dbgout);
20111 verify_consistency(state);
20113 /* Allocate and initialize the live ranges */
20114 initialize_live_ranges(state, &rstate);
20116 /* Note currently doing coalescing in a loop appears to
20117 * buys me nothing. The code is left this way in case
20118 * there is some value in it. Or if a future bugfix
20119 * yields some benefit.
20122 if (state->compiler->debug & DEBUG_COALESCING) {
20123 fprintf(state->errout, "coalescing\n");
20126 /* Remove any previous live edge calculations */
20127 cleanup_live_edges(&rstate);
20129 /* Compute the interference graph */
20130 walk_variable_lifetimes(
20131 state, &state->bb, rstate.blocks,
20132 graph_ins, &rstate);
20134 /* Display the interference graph if desired */
20135 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20136 print_interference_blocks(state, &rstate, state->dbgout, 1);
20137 fprintf(state->dbgout, "\nlive variables by instruction\n");
20138 walk_variable_lifetimes(
20139 state, &state->bb, rstate.blocks,
20140 print_interference_ins, &rstate);
20143 coalesced = coalesce_live_ranges(state, &rstate);
20145 if (state->compiler->debug & DEBUG_COALESCING) {
20146 fprintf(state->errout, "coalesced: %d\n", coalesced);
20148 } while(coalesced);
20150 #if DEBUG_CONSISTENCY > 1
20152 fprintf(state->errout, "verify_graph_ins...\n");
20154 /* Verify the interference graph */
20155 walk_variable_lifetimes(
20156 state, &state->bb, rstate.blocks,
20157 verify_graph_ins, &rstate);
20159 fprintf(state->errout, "verify_graph_ins done\n");
20163 /* Build the groups low and high. But with the nodes
20164 * first sorted by degree order.
20166 rstate.low_tail = &rstate.low;
20167 rstate.high_tail = &rstate.high;
20168 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20170 rstate.high->group_prev = &rstate.high;
20172 for(point = &rstate.high; *point; point = &(*point)->group_next)
20174 rstate.high_tail = point;
20175 /* Walk through the high list and move everything that needs
20178 for(point = &rstate.high; *point; point = next) {
20179 struct live_range *range;
20180 next = &(*point)->group_next;
20183 /* If it has a low degree or it already has a color
20184 * place the node in low.
20186 if ((range->degree < regc_max_size(state, range->classes)) ||
20187 (range->color != REG_UNSET)) {
20188 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20189 range - rstate.lr, range->degree,
20190 (range->color != REG_UNSET) ? " (colored)": "");
20191 *range->group_prev = range->group_next;
20192 if (range->group_next) {
20193 range->group_next->group_prev = range->group_prev;
20195 if (&range->group_next == rstate.high_tail) {
20196 rstate.high_tail = range->group_prev;
20198 range->group_prev = rstate.low_tail;
20199 range->group_next = 0;
20200 *rstate.low_tail = range;
20201 rstate.low_tail = &range->group_next;
20205 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20206 range - rstate.lr, range->degree,
20207 (range->color != REG_UNSET) ? " (colored)": "");
20210 /* Color the live_ranges */
20211 colored = color_graph(state, &rstate);
20213 } while (!colored);
20215 /* Verify the graph was properly colored */
20216 verify_colors(state, &rstate);
20218 /* Move the colors from the graph to the triples */
20219 color_triples(state, &rstate);
20221 /* Cleanup the temporary data structures */
20222 cleanup_rstate(state, &rstate);
20224 /* Display the new graph */
20225 print_blocks(state, __func__, state->dbgout);
20228 /* Sparce Conditional Constant Propogation
20229 * =========================================
20233 struct lattice_node {
20235 struct triple *def;
20236 struct ssa_edge *out;
20237 struct flow_block *fblock;
20238 struct triple *val;
20239 /* lattice high val == def
20240 * lattice const is_const(val)
20241 * lattice low other
20245 struct lattice_node *src;
20246 struct lattice_node *dst;
20247 struct ssa_edge *work_next;
20248 struct ssa_edge *work_prev;
20249 struct ssa_edge *out_next;
20252 struct flow_block *src;
20253 struct flow_block *dst;
20254 struct flow_edge *work_next;
20255 struct flow_edge *work_prev;
20256 struct flow_edge *in_next;
20257 struct flow_edge *out_next;
20260 #define MAX_FLOW_BLOCK_EDGES 3
20261 struct flow_block {
20262 struct block *block;
20263 struct flow_edge *in;
20264 struct flow_edge *out;
20265 struct flow_edge *edges;
20270 struct lattice_node *lattice;
20271 struct ssa_edge *ssa_edges;
20272 struct flow_block *flow_blocks;
20273 struct flow_edge *flow_work_list;
20274 struct ssa_edge *ssa_work_list;
20278 static int is_scc_const(struct compile_state *state, struct triple *ins)
20280 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20283 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20285 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20288 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20290 return is_scc_const(state, lnode->val);
20293 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20295 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20298 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20299 struct flow_edge *fedge)
20301 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20302 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20304 fedge->src->block?fedge->src->block->last->id: 0,
20305 fedge->dst->block?fedge->dst->block->first->id: 0);
20307 if ((fedge == scc->flow_work_list) ||
20308 (fedge->work_next != fedge) ||
20309 (fedge->work_prev != fedge)) {
20311 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20312 fprintf(state->errout, "dupped fedge: %p\n",
20317 if (!scc->flow_work_list) {
20318 scc->flow_work_list = fedge;
20319 fedge->work_next = fedge->work_prev = fedge;
20322 struct flow_edge *ftail;
20323 ftail = scc->flow_work_list->work_prev;
20324 fedge->work_next = ftail->work_next;
20325 fedge->work_prev = ftail;
20326 fedge->work_next->work_prev = fedge;
20327 fedge->work_prev->work_next = fedge;
20331 static struct flow_edge *scc_next_fedge(
20332 struct compile_state *state, struct scc_state *scc)
20334 struct flow_edge *fedge;
20335 fedge = scc->flow_work_list;
20337 fedge->work_next->work_prev = fedge->work_prev;
20338 fedge->work_prev->work_next = fedge->work_next;
20339 if (fedge->work_next != fedge) {
20340 scc->flow_work_list = fedge->work_next;
20342 scc->flow_work_list = 0;
20344 fedge->work_next = fedge->work_prev = fedge;
20349 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20350 struct ssa_edge *sedge)
20352 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20353 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20354 (long)(sedge - scc->ssa_edges),
20355 sedge->src->def->id,
20356 sedge->dst->def->id);
20358 if ((sedge == scc->ssa_work_list) ||
20359 (sedge->work_next != sedge) ||
20360 (sedge->work_prev != sedge)) {
20362 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20363 fprintf(state->errout, "dupped sedge: %5ld\n",
20364 (long)(sedge - scc->ssa_edges));
20368 if (!scc->ssa_work_list) {
20369 scc->ssa_work_list = sedge;
20370 sedge->work_next = sedge->work_prev = sedge;
20373 struct ssa_edge *stail;
20374 stail = scc->ssa_work_list->work_prev;
20375 sedge->work_next = stail->work_next;
20376 sedge->work_prev = stail;
20377 sedge->work_next->work_prev = sedge;
20378 sedge->work_prev->work_next = sedge;
20382 static struct ssa_edge *scc_next_sedge(
20383 struct compile_state *state, struct scc_state *scc)
20385 struct ssa_edge *sedge;
20386 sedge = scc->ssa_work_list;
20388 sedge->work_next->work_prev = sedge->work_prev;
20389 sedge->work_prev->work_next = sedge->work_next;
20390 if (sedge->work_next != sedge) {
20391 scc->ssa_work_list = sedge->work_next;
20393 scc->ssa_work_list = 0;
20395 sedge->work_next = sedge->work_prev = sedge;
20400 static void initialize_scc_state(
20401 struct compile_state *state, struct scc_state *scc)
20403 int ins_count, ssa_edge_count;
20404 int ins_index, ssa_edge_index, fblock_index;
20405 struct triple *first, *ins;
20406 struct block *block;
20407 struct flow_block *fblock;
20409 memset(scc, 0, sizeof(*scc));
20411 /* Inialize pass zero find out how much memory we need */
20412 first = state->first;
20414 ins_count = ssa_edge_count = 0;
20416 struct triple_set *edge;
20418 for(edge = ins->use; edge; edge = edge->next) {
20422 } while(ins != first);
20423 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20424 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20425 ins_count, ssa_edge_count, state->bb.last_vertex);
20427 scc->ins_count = ins_count;
20429 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20431 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20433 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20436 /* Initialize pass one collect up the nodes */
20439 ins_index = ssa_edge_index = fblock_index = 0;
20442 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20443 block = ins->u.block;
20445 internal_error(state, ins, "label without block");
20448 block->vertex = fblock_index;
20449 fblock = &scc->flow_blocks[fblock_index];
20450 fblock->block = block;
20451 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20455 struct lattice_node *lnode;
20457 lnode = &scc->lattice[ins_index];
20460 lnode->fblock = fblock;
20461 lnode->val = ins; /* LATTICE HIGH */
20462 if (lnode->val->op == OP_UNKNOWNVAL) {
20463 lnode->val = 0; /* LATTICE LOW by definition */
20465 lnode->old_id = ins->id;
20466 ins->id = ins_index;
20469 } while(ins != first);
20470 /* Initialize pass two collect up the edges */
20476 struct triple_set *edge;
20477 struct ssa_edge **stail;
20478 struct lattice_node *lnode;
20479 lnode = &scc->lattice[ins->id];
20481 stail = &lnode->out;
20482 for(edge = ins->use; edge; edge = edge->next) {
20483 struct ssa_edge *sedge;
20484 ssa_edge_index += 1;
20485 sedge = &scc->ssa_edges[ssa_edge_index];
20487 stail = &sedge->out_next;
20488 sedge->src = lnode;
20489 sedge->dst = &scc->lattice[edge->member->id];
20490 sedge->work_next = sedge->work_prev = sedge;
20491 sedge->out_next = 0;
20494 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20495 struct flow_edge *fedge, **ftail;
20496 struct block_set *bedge;
20497 block = ins->u.block;
20498 fblock = &scc->flow_blocks[block->vertex];
20501 ftail = &fblock->out;
20503 fedge = fblock->edges;
20504 bedge = block->edges;
20505 for(; bedge; bedge = bedge->next, fedge++) {
20506 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20507 if (fedge->dst->block != bedge->member) {
20508 internal_error(state, 0, "block mismatch");
20511 ftail = &fedge->out_next;
20512 fedge->out_next = 0;
20514 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20515 fedge->src = fblock;
20516 fedge->work_next = fedge->work_prev = fedge;
20517 fedge->executable = 0;
20521 } while (ins != first);
20526 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20527 struct flow_edge **ftail;
20528 struct block_set *bedge;
20529 block = ins->u.block;
20530 fblock = &scc->flow_blocks[block->vertex];
20531 ftail = &fblock->in;
20532 for(bedge = block->use; bedge; bedge = bedge->next) {
20533 struct block *src_block;
20534 struct flow_block *sfblock;
20535 struct flow_edge *sfedge;
20536 src_block = bedge->member;
20537 sfblock = &scc->flow_blocks[src_block->vertex];
20538 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20539 if (sfedge->dst == fblock) {
20544 internal_error(state, 0, "edge mismatch");
20547 ftail = &sfedge->in_next;
20548 sfedge->in_next = 0;
20552 } while(ins != first);
20553 /* Setup a dummy block 0 as a node above the start node */
20555 struct flow_block *fblock, *dst;
20556 struct flow_edge *fedge;
20557 fblock = &scc->flow_blocks[0];
20559 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20561 fblock->out = fblock->edges;
20562 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20563 fedge = fblock->edges;
20564 fedge->src = fblock;
20566 fedge->work_next = fedge;
20567 fedge->work_prev = fedge;
20568 fedge->in_next = fedge->dst->in;
20569 fedge->out_next = 0;
20570 fedge->executable = 0;
20571 fedge->dst->in = fedge;
20573 /* Initialize the work lists */
20574 scc->flow_work_list = 0;
20575 scc->ssa_work_list = 0;
20576 scc_add_fedge(state, scc, fedge);
20578 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20579 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20580 ins_index, ssa_edge_index, fblock_index);
20585 static void free_scc_state(
20586 struct compile_state *state, struct scc_state *scc)
20589 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20590 struct flow_block *fblock;
20591 fblock = &scc->flow_blocks[i];
20592 if (fblock->edges) {
20593 xfree(fblock->edges);
20597 xfree(scc->flow_blocks);
20598 xfree(scc->ssa_edges);
20599 xfree(scc->lattice);
20603 static struct lattice_node *triple_to_lattice(
20604 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20606 if (ins->id <= 0) {
20607 internal_error(state, ins, "bad id");
20609 return &scc->lattice[ins->id];
20612 static struct triple *preserve_lval(
20613 struct compile_state *state, struct lattice_node *lnode)
20615 struct triple *old;
20616 /* Preserve the original value */
20618 old = dup_triple(state, lnode->val);
20619 if (lnode->val != lnode->def) {
20629 static int lval_changed(struct compile_state *state,
20630 struct triple *old, struct lattice_node *lnode)
20633 /* See if the lattice value has changed */
20635 if (!old && !lnode->val) {
20639 lnode->val && old &&
20640 (memcmp(lnode->val->param, old->param,
20641 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20642 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20652 static void scc_debug_lnode(
20653 struct compile_state *state, struct scc_state *scc,
20654 struct lattice_node *lnode, int changed)
20656 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20657 display_triple_changes(state->errout, lnode->val, lnode->def);
20659 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20660 FILE *fp = state->errout;
20661 struct triple *val, **expr;
20662 val = lnode->val? lnode->val : lnode->def;
20663 fprintf(fp, "%p %s %3d %10s (",
20665 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20667 tops(lnode->def->op));
20668 expr = triple_rhs(state, lnode->def, 0);
20669 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20671 fprintf(fp, " %d", (*expr)->id);
20674 if (val->op == OP_INTCONST) {
20675 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20677 fprintf(fp, " ) -> %s %s\n",
20678 (is_lattice_hi(state, lnode)? "hi":
20679 is_lattice_const(state, lnode)? "const" : "lo"),
20680 changed? "changed" : ""
20685 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20686 struct lattice_node *lnode)
20689 struct triple *old, *scratch;
20690 struct triple **dexpr, **vexpr;
20693 /* Store the original value */
20694 old = preserve_lval(state, lnode);
20696 /* Reinitialize the value */
20697 lnode->val = scratch = dup_triple(state, lnode->def);
20698 scratch->id = lnode->old_id;
20699 scratch->next = scratch;
20700 scratch->prev = scratch;
20703 count = TRIPLE_SIZE(scratch);
20704 for(i = 0; i < count; i++) {
20705 dexpr = &lnode->def->param[i];
20706 vexpr = &scratch->param[i];
20708 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20709 (i >= TRIPLE_TARG_OFF(scratch))) &&
20711 struct lattice_node *tmp;
20712 tmp = triple_to_lattice(state, scc, *dexpr);
20713 *vexpr = (tmp->val)? tmp->val : tmp->def;
20716 if (triple_is_branch(state, scratch)) {
20717 scratch->next = lnode->def->next;
20719 /* Recompute the value */
20720 #if DEBUG_ROMCC_WARNINGS
20721 #warning "FIXME see if simplify does anything bad"
20723 /* So far it looks like only the strength reduction
20724 * optimization are things I need to worry about.
20726 simplify(state, scratch);
20727 /* Cleanup my value */
20728 if (scratch->use) {
20729 internal_error(state, lnode->def, "scratch used?");
20731 if ((scratch->prev != scratch) ||
20732 ((scratch->next != scratch) &&
20733 (!triple_is_branch(state, lnode->def) ||
20734 (scratch->next != lnode->def->next)))) {
20735 internal_error(state, lnode->def, "scratch in list?");
20737 /* undo any uses... */
20738 count = TRIPLE_SIZE(scratch);
20739 for(i = 0; i < count; i++) {
20740 vexpr = &scratch->param[i];
20742 unuse_triple(*vexpr, scratch);
20745 if (lnode->val->op == OP_UNKNOWNVAL) {
20746 lnode->val = 0; /* Lattice low by definition */
20748 /* Find the case when I am lattice high */
20750 (lnode->val->op == lnode->def->op) &&
20751 (memcmp(lnode->val->param, lnode->def->param,
20752 count * sizeof(lnode->val->param[0])) == 0) &&
20753 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20754 lnode->val = lnode->def;
20756 /* Only allow lattice high when all of my inputs
20757 * are also lattice high. Occassionally I can
20758 * have constants with a lattice low input, so
20759 * I do not need to check that case.
20761 if (is_lattice_hi(state, lnode)) {
20762 struct lattice_node *tmp;
20764 rhs = lnode->val->rhs;
20765 for(i = 0; i < rhs; i++) {
20766 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20767 if (!is_lattice_hi(state, tmp)) {
20773 /* Find the cases that are always lattice lo */
20775 triple_is_def(state, lnode->val) &&
20776 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20779 /* See if the lattice value has changed */
20780 changed = lval_changed(state, old, lnode);
20781 /* See if this value should not change */
20782 if ((lnode->val != lnode->def) &&
20783 (( !triple_is_def(state, lnode->def) &&
20784 !triple_is_cbranch(state, lnode->def)) ||
20785 (lnode->def->op == OP_PIECE))) {
20786 #if DEBUG_ROMCC_WARNINGS
20787 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20790 internal_warning(state, lnode->def, "non def changes value?");
20795 /* See if we need to free the scratch value */
20796 if (lnode->val != scratch) {
20804 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20805 struct lattice_node *lnode)
20807 struct lattice_node *cond;
20808 struct flow_edge *left, *right;
20811 /* Update the branch value */
20812 changed = compute_lnode_val(state, scc, lnode);
20813 scc_debug_lnode(state, scc, lnode, changed);
20815 /* This only applies to conditional branches */
20816 if (!triple_is_cbranch(state, lnode->def)) {
20817 internal_error(state, lnode->def, "not a conditional branch");
20820 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20821 struct flow_edge *fedge;
20822 FILE *fp = state->errout;
20823 fprintf(fp, "%s: %d (",
20824 tops(lnode->def->op),
20827 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20828 fprintf(fp, " %d", fedge->dst->block->vertex);
20831 if (lnode->def->rhs > 0) {
20832 fprintf(fp, " <- %d",
20833 RHS(lnode->def, 0)->id);
20837 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20838 for(left = cond->fblock->out; left; left = left->out_next) {
20839 if (left->dst->block->first == lnode->def->next) {
20844 internal_error(state, lnode->def, "Cannot find left branch edge");
20846 for(right = cond->fblock->out; right; right = right->out_next) {
20847 if (right->dst->block->first == TARG(lnode->def, 0)) {
20852 internal_error(state, lnode->def, "Cannot find right branch edge");
20854 /* I should only come here if the controlling expressions value
20855 * has changed, which means it must be either a constant or lo.
20857 if (is_lattice_hi(state, cond)) {
20858 internal_error(state, cond->def, "condition high?");
20861 if (is_lattice_lo(state, cond)) {
20862 scc_add_fedge(state, scc, left);
20863 scc_add_fedge(state, scc, right);
20865 else if (cond->val->u.cval) {
20866 scc_add_fedge(state, scc, right);
20868 scc_add_fedge(state, scc, left);
20874 static void scc_add_sedge_dst(struct compile_state *state,
20875 struct scc_state *scc, struct ssa_edge *sedge)
20877 if (triple_is_cbranch(state, sedge->dst->def)) {
20878 scc_visit_cbranch(state, scc, sedge->dst);
20880 else if (triple_is_def(state, sedge->dst->def)) {
20881 scc_add_sedge(state, scc, sedge);
20885 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20886 struct lattice_node *lnode)
20888 struct lattice_node *tmp;
20889 struct triple **slot, *old;
20890 struct flow_edge *fedge;
20893 if (lnode->def->op != OP_PHI) {
20894 internal_error(state, lnode->def, "not phi");
20896 /* Store the original value */
20897 old = preserve_lval(state, lnode);
20899 /* default to lattice high */
20900 lnode->val = lnode->def;
20901 slot = &RHS(lnode->def, 0);
20903 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20904 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20905 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20907 fedge->dst->block->vertex,
20911 if (!fedge->executable) {
20914 if (!slot[index]) {
20915 internal_error(state, lnode->def, "no phi value");
20917 tmp = triple_to_lattice(state, scc, slot[index]);
20918 /* meet(X, lattice low) = lattice low */
20919 if (is_lattice_lo(state, tmp)) {
20922 /* meet(X, lattice high) = X */
20923 else if (is_lattice_hi(state, tmp)) {
20924 lnode->val = lnode->val;
20926 /* meet(lattice high, X) = X */
20927 else if (is_lattice_hi(state, lnode)) {
20928 lnode->val = dup_triple(state, tmp->val);
20929 /* Only change the type if necessary */
20930 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20931 lnode->val->type = lnode->def->type;
20934 /* meet(const, const) = const or lattice low */
20935 else if (!constants_equal(state, lnode->val, tmp->val)) {
20939 /* meet(lattice low, X) = lattice low */
20940 if (is_lattice_lo(state, lnode)) {
20945 changed = lval_changed(state, old, lnode);
20946 scc_debug_lnode(state, scc, lnode, changed);
20948 /* If the lattice value has changed update the work lists. */
20950 struct ssa_edge *sedge;
20951 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20952 scc_add_sedge_dst(state, scc, sedge);
20958 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20959 struct lattice_node *lnode)
20963 if (!triple_is_def(state, lnode->def)) {
20964 internal_warning(state, lnode->def, "not visiting an expression?");
20966 changed = compute_lnode_val(state, scc, lnode);
20967 scc_debug_lnode(state, scc, lnode, changed);
20970 struct ssa_edge *sedge;
20971 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20972 scc_add_sedge_dst(state, scc, sedge);
20977 static void scc_writeback_values(
20978 struct compile_state *state, struct scc_state *scc)
20980 struct triple *first, *ins;
20981 first = state->first;
20984 struct lattice_node *lnode;
20985 lnode = triple_to_lattice(state, scc, ins);
20986 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20987 if (is_lattice_hi(state, lnode) &&
20988 (lnode->val->op != OP_NOOP))
20990 struct flow_edge *fedge;
20993 for(fedge = lnode->fblock->in;
20994 !executable && fedge; fedge = fedge->in_next) {
20995 executable |= fedge->executable;
20998 internal_warning(state, lnode->def,
20999 "lattice node %d %s->%s still high?",
21001 tops(lnode->def->op),
21002 tops(lnode->val->op));
21008 ins->id = lnode->old_id;
21009 if (lnode->val && (lnode->val != ins)) {
21010 /* See if it something I know how to write back */
21011 switch(lnode->val->op) {
21013 mkconst(state, ins, lnode->val->u.cval);
21016 mkaddr_const(state, ins,
21017 MISC(lnode->val, 0), lnode->val->u.cval);
21020 /* By default don't copy the changes,
21021 * recompute them in place instead.
21023 simplify(state, ins);
21026 if (is_const(lnode->val) &&
21027 !constants_equal(state, lnode->val, ins)) {
21028 internal_error(state, 0, "constants not equal");
21030 /* Free the lattice nodes */
21035 } while(ins != first);
21038 static void scc_transform(struct compile_state *state)
21040 struct scc_state scc;
21041 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21045 initialize_scc_state(state, &scc);
21047 while(scc.flow_work_list || scc.ssa_work_list) {
21048 struct flow_edge *fedge;
21049 struct ssa_edge *sedge;
21050 struct flow_edge *fptr;
21051 while((fedge = scc_next_fedge(state, &scc))) {
21052 struct block *block;
21053 struct triple *ptr;
21054 struct flow_block *fblock;
21057 if (fedge->executable) {
21061 internal_error(state, 0, "fedge without dst");
21064 internal_error(state, 0, "fedge without src");
21066 fedge->executable = 1;
21067 fblock = fedge->dst;
21068 block = fblock->block;
21070 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21071 if (fptr->executable) {
21076 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21077 fprintf(state->errout, "vertex: %d reps: %d\n",
21078 block->vertex, reps);
21082 for(ptr = block->first; !done; ptr = ptr->next) {
21083 struct lattice_node *lnode;
21084 done = (ptr == block->last);
21085 lnode = &scc.lattice[ptr->id];
21086 if (ptr->op == OP_PHI) {
21087 scc_visit_phi(state, &scc, lnode);
21089 else if ((reps == 1) && triple_is_def(state, ptr))
21091 scc_visit_expr(state, &scc, lnode);
21094 /* Add unconditional branch edges */
21095 if (!triple_is_cbranch(state, fblock->block->last)) {
21096 struct flow_edge *out;
21097 for(out = fblock->out; out; out = out->out_next) {
21098 scc_add_fedge(state, &scc, out);
21102 while((sedge = scc_next_sedge(state, &scc))) {
21103 struct lattice_node *lnode;
21104 struct flow_block *fblock;
21105 lnode = sedge->dst;
21106 fblock = lnode->fblock;
21108 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21109 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21110 sedge - scc.ssa_edges,
21111 sedge->src->def->id,
21112 sedge->dst->def->id);
21115 if (lnode->def->op == OP_PHI) {
21116 scc_visit_phi(state, &scc, lnode);
21119 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21120 if (fptr->executable) {
21125 scc_visit_expr(state, &scc, lnode);
21131 scc_writeback_values(state, &scc);
21132 free_scc_state(state, &scc);
21133 rebuild_ssa_form(state);
21135 print_blocks(state, __func__, state->dbgout);
21139 static void transform_to_arch_instructions(struct compile_state *state)
21141 struct triple *ins, *first;
21142 first = state->first;
21145 ins = transform_to_arch_instruction(state, ins);
21146 } while(ins != first);
21148 print_blocks(state, __func__, state->dbgout);
21151 #if DEBUG_CONSISTENCY
21152 static void verify_uses(struct compile_state *state)
21154 struct triple *first, *ins;
21155 struct triple_set *set;
21156 first = state->first;
21159 struct triple **expr;
21160 expr = triple_rhs(state, ins, 0);
21161 for(; expr; expr = triple_rhs(state, ins, expr)) {
21162 struct triple *rhs;
21164 for(set = rhs?rhs->use:0; set; set = set->next) {
21165 if (set->member == ins) {
21170 internal_error(state, ins, "rhs not used");
21173 expr = triple_lhs(state, ins, 0);
21174 for(; expr; expr = triple_lhs(state, ins, expr)) {
21175 struct triple *lhs;
21177 for(set = lhs?lhs->use:0; set; set = set->next) {
21178 if (set->member == ins) {
21183 internal_error(state, ins, "lhs not used");
21186 expr = triple_misc(state, ins, 0);
21187 if (ins->op != OP_PHI) {
21188 for(; expr; expr = triple_targ(state, ins, expr)) {
21189 struct triple *misc;
21191 for(set = misc?misc->use:0; set; set = set->next) {
21192 if (set->member == ins) {
21197 internal_error(state, ins, "misc not used");
21201 if (!triple_is_ret(state, ins)) {
21202 expr = triple_targ(state, ins, 0);
21203 for(; expr; expr = triple_targ(state, ins, expr)) {
21204 struct triple *targ;
21206 for(set = targ?targ->use:0; set; set = set->next) {
21207 if (set->member == ins) {
21212 internal_error(state, ins, "targ not used");
21217 } while(ins != first);
21220 static void verify_blocks_present(struct compile_state *state)
21222 struct triple *first, *ins;
21223 if (!state->bb.first_block) {
21226 first = state->first;
21229 valid_ins(state, ins);
21230 if (triple_stores_block(state, ins)) {
21231 if (!ins->u.block) {
21232 internal_error(state, ins,
21233 "%p not in a block?", ins);
21237 } while(ins != first);
21242 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21244 struct block_set *bedge;
21245 struct block *targ;
21246 targ = block_of_triple(state, edge);
21247 for(bedge = block->edges; bedge; bedge = bedge->next) {
21248 if (bedge->member == targ) {
21255 static void verify_blocks(struct compile_state *state)
21257 struct triple *ins;
21258 struct block *block;
21260 block = state->bb.first_block;
21267 struct block_set *user, *edge;
21269 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21270 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21271 internal_error(state, ins, "inconsitent block specified");
21273 valid_ins(state, ins);
21276 for(user = block->use; user; user = user->next) {
21278 if (!user->member->first) {
21279 internal_error(state, block->first, "user is empty");
21281 if ((block == state->bb.last_block) &&
21282 (user->member == state->bb.first_block)) {
21285 for(edge = user->member->edges; edge; edge = edge->next) {
21286 if (edge->member == block) {
21291 internal_error(state, user->member->first,
21292 "user does not use block");
21295 if (triple_is_branch(state, block->last)) {
21296 struct triple **expr;
21297 expr = triple_edge_targ(state, block->last, 0);
21298 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21299 if (*expr && !edge_present(state, block, *expr)) {
21300 internal_error(state, block->last, "no edge to targ");
21304 if (!triple_is_ubranch(state, block->last) &&
21305 (block != state->bb.last_block) &&
21306 !edge_present(state, block, block->last->next)) {
21307 internal_error(state, block->last, "no edge to block->last->next");
21309 for(edge = block->edges; edge; edge = edge->next) {
21310 for(user = edge->member->use; user; user = user->next) {
21311 if (user->member == block) {
21315 if (!user || user->member != block) {
21316 internal_error(state, block->first,
21317 "block does not use edge");
21319 if (!edge->member->first) {
21320 internal_error(state, block->first, "edge block is empty");
21323 if (block->users != users) {
21324 internal_error(state, block->first,
21325 "computed users %d != stored users %d",
21326 users, block->users);
21328 if (!triple_stores_block(state, block->last->next)) {
21329 internal_error(state, block->last->next,
21330 "cannot find next block");
21332 block = block->last->next->u.block;
21334 internal_error(state, block->last->next,
21337 } while(block != state->bb.first_block);
21338 if (blocks != state->bb.last_vertex) {
21339 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21340 blocks, state->bb.last_vertex);
21344 static void verify_domination(struct compile_state *state)
21346 struct triple *first, *ins;
21347 struct triple_set *set;
21348 if (!state->bb.first_block) {
21352 first = state->first;
21355 for(set = ins->use; set; set = set->next) {
21356 struct triple **slot;
21357 struct triple *use_point;
21360 zrhs = set->member->rhs;
21361 slot = &RHS(set->member, 0);
21362 /* See if the use is on the right hand side */
21363 for(i = 0; i < zrhs; i++) {
21364 if (slot[i] == ins) {
21369 use_point = set->member;
21370 if (set->member->op == OP_PHI) {
21371 struct block_set *bset;
21373 bset = set->member->u.block->use;
21374 for(edge = 0; bset && (edge < i); edge++) {
21378 internal_error(state, set->member,
21379 "no edge for phi rhs %d", i);
21381 use_point = bset->member->last;
21385 !tdominates(state, ins, use_point)) {
21386 if (is_const(ins)) {
21387 internal_warning(state, ins,
21388 "non dominated rhs use point %p?", use_point);
21391 internal_error(state, ins,
21392 "non dominated rhs use point %p?", use_point);
21397 } while(ins != first);
21400 static void verify_rhs(struct compile_state *state)
21402 struct triple *first, *ins;
21403 first = state->first;
21406 struct triple **slot;
21409 slot = &RHS(ins, 0);
21410 for(i = 0; i < zrhs; i++) {
21411 if (slot[i] == 0) {
21412 internal_error(state, ins,
21413 "missing rhs %d on %s",
21416 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21417 internal_error(state, ins,
21418 "ins == rhs[%d] on %s",
21423 } while(ins != first);
21426 static void verify_piece(struct compile_state *state)
21428 struct triple *first, *ins;
21429 first = state->first;
21432 struct triple *ptr;
21435 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21436 if (ptr != LHS(ins, i)) {
21437 internal_error(state, ins, "malformed lhs on %s",
21440 if (ptr->op != OP_PIECE) {
21441 internal_error(state, ins, "bad lhs op %s at %d on %s",
21442 tops(ptr->op), i, tops(ins->op));
21444 if (ptr->u.cval != i) {
21445 internal_error(state, ins, "bad u.cval of %d %d expected",
21450 } while(ins != first);
21453 static void verify_ins_colors(struct compile_state *state)
21455 struct triple *first, *ins;
21457 first = state->first;
21461 } while(ins != first);
21464 static void verify_unknown(struct compile_state *state)
21466 struct triple *first, *ins;
21467 if ( (unknown_triple.next != &unknown_triple) ||
21468 (unknown_triple.prev != &unknown_triple) ||
21470 (unknown_triple.use != 0) ||
21472 (unknown_triple.op != OP_UNKNOWNVAL) ||
21473 (unknown_triple.lhs != 0) ||
21474 (unknown_triple.rhs != 0) ||
21475 (unknown_triple.misc != 0) ||
21476 (unknown_triple.targ != 0) ||
21477 (unknown_triple.template_id != 0) ||
21478 (unknown_triple.id != -1) ||
21479 (unknown_triple.type != &unknown_type) ||
21480 (unknown_triple.occurance != &dummy_occurance) ||
21481 (unknown_triple.param[0] != 0) ||
21482 (unknown_triple.param[1] != 0)) {
21483 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21485 if ( (dummy_occurance.count != 2) ||
21486 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21487 (strcmp(dummy_occurance.function, "") != 0) ||
21488 (dummy_occurance.col != 0) ||
21489 (dummy_occurance.parent != 0)) {
21490 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21492 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21493 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21495 first = state->first;
21499 if (ins == &unknown_triple) {
21500 internal_error(state, ins, "unknown triple in list");
21502 params = TRIPLE_SIZE(ins);
21503 for(i = 0; i < params; i++) {
21504 if (ins->param[i] == &unknown_triple) {
21505 internal_error(state, ins, "unknown triple used!");
21509 } while(ins != first);
21512 static void verify_types(struct compile_state *state)
21514 struct triple *first, *ins;
21515 first = state->first;
21518 struct type *invalid;
21519 invalid = invalid_type(state, ins->type);
21521 FILE *fp = state->errout;
21522 fprintf(fp, "type: ");
21523 name_of(fp, ins->type);
21525 fprintf(fp, "invalid type: ");
21526 name_of(fp, invalid);
21528 internal_error(state, ins, "invalid ins type");
21530 } while(ins != first);
21533 static void verify_copy(struct compile_state *state)
21535 struct triple *first, *ins, *next;
21536 first = state->first;
21537 next = ins = first;
21541 if (ins->op != OP_COPY) {
21544 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21545 FILE *fp = state->errout;
21546 fprintf(fp, "src type: ");
21547 name_of(fp, RHS(ins, 0)->type);
21549 fprintf(fp, "dst type: ");
21550 name_of(fp, ins->type);
21552 internal_error(state, ins, "type mismatch in copy");
21554 } while(next != first);
21557 static void verify_consistency(struct compile_state *state)
21559 verify_unknown(state);
21560 verify_uses(state);
21561 verify_blocks_present(state);
21562 verify_blocks(state);
21563 verify_domination(state);
21565 verify_piece(state);
21566 verify_ins_colors(state);
21567 verify_types(state);
21568 verify_copy(state);
21569 if (state->compiler->debug & DEBUG_VERIFICATION) {
21570 fprintf(state->dbgout, "consistency verified\n");
21574 static void verify_consistency(struct compile_state *state) {}
21575 #endif /* DEBUG_CONSISTENCY */
21577 static void optimize(struct compile_state *state)
21579 /* Join all of the functions into one giant function */
21580 join_functions(state);
21582 /* Dump what the instruction graph intially looks like */
21583 print_triples(state);
21585 /* Replace structures with simpler data types */
21586 decompose_compound_types(state);
21587 print_triples(state);
21589 verify_consistency(state);
21590 /* Analyze the intermediate code */
21591 state->bb.first = state->first;
21592 analyze_basic_blocks(state, &state->bb);
21594 /* Transform the code to ssa form. */
21596 * The transformation to ssa form puts a phi function
21597 * on each of edge of a dominance frontier where that
21598 * phi function might be needed. At -O2 if we don't
21599 * eleminate the excess phi functions we can get an
21600 * exponential code size growth. So I kill the extra
21601 * phi functions early and I kill them often.
21603 transform_to_ssa_form(state);
21604 verify_consistency(state);
21606 /* Remove dead code */
21607 eliminate_inefectual_code(state);
21608 verify_consistency(state);
21610 /* Do strength reduction and simple constant optimizations */
21611 simplify_all(state);
21612 verify_consistency(state);
21613 /* Propogate constants throughout the code */
21614 scc_transform(state);
21615 verify_consistency(state);
21616 #if DEBUG_ROMCC_WARNINGS
21617 #warning "WISHLIST implement single use constants (least possible register pressure)"
21618 #warning "WISHLIST implement induction variable elimination"
21620 /* Select architecture instructions and an initial partial
21621 * coloring based on architecture constraints.
21623 transform_to_arch_instructions(state);
21624 verify_consistency(state);
21626 /* Remove dead code */
21627 eliminate_inefectual_code(state);
21628 verify_consistency(state);
21630 /* Color all of the variables to see if they will fit in registers */
21631 insert_copies_to_phi(state);
21632 verify_consistency(state);
21634 insert_mandatory_copies(state);
21635 verify_consistency(state);
21637 allocate_registers(state);
21638 verify_consistency(state);
21640 /* Remove the optimization information.
21641 * This is more to check for memory consistency than to free memory.
21643 free_basic_blocks(state, &state->bb);
21646 static void print_op_asm(struct compile_state *state,
21647 struct triple *ins, FILE *fp)
21649 struct asm_info *info;
21651 unsigned lhs, rhs, i;
21652 info = ins->u.ainfo;
21655 /* Don't count the clobbers in lhs */
21656 for(i = 0; i < lhs; i++) {
21657 if (LHS(ins, i)->type == &void_type) {
21662 fprintf(fp, "#ASM\n");
21664 for(ptr = info->str; *ptr; ptr++) {
21666 unsigned long param;
21667 struct triple *piece;
21677 param = strtoul(ptr, &next, 10);
21679 error(state, ins, "Invalid asm template");
21681 if (param >= (lhs + rhs)) {
21682 error(state, ins, "Invalid param %%%u in asm template",
21685 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21687 arch_reg_str(ID_REG(piece->id)));
21690 fprintf(fp, "\n#NOT ASM\n");
21694 /* Only use the low x86 byte registers. This allows me
21695 * allocate the entire register when a byte register is used.
21697 #define X86_4_8BIT_GPRS 1
21700 #define X86_MMX_REGS (1<<0)
21701 #define X86_XMM_REGS (1<<1)
21702 #define X86_NOOP_COPY (1<<2)
21704 /* The x86 register classes */
21705 #define REGC_FLAGS 0
21706 #define REGC_GPR8 1
21707 #define REGC_GPR16 2
21708 #define REGC_GPR32 3
21709 #define REGC_DIVIDEND64 4
21710 #define REGC_DIVIDEND32 5
21713 #define REGC_GPR32_8 8
21714 #define REGC_GPR16_8 9
21715 #define REGC_GPR8_LO 10
21716 #define REGC_IMM32 11
21717 #define REGC_IMM16 12
21718 #define REGC_IMM8 13
21719 #define LAST_REGC REGC_IMM8
21720 #if LAST_REGC >= MAX_REGC
21721 #error "MAX_REGC is to low"
21724 /* Register class masks */
21725 #define REGCM_FLAGS (1 << REGC_FLAGS)
21726 #define REGCM_GPR8 (1 << REGC_GPR8)
21727 #define REGCM_GPR16 (1 << REGC_GPR16)
21728 #define REGCM_GPR32 (1 << REGC_GPR32)
21729 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21730 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21731 #define REGCM_MMX (1 << REGC_MMX)
21732 #define REGCM_XMM (1 << REGC_XMM)
21733 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21734 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21735 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21736 #define REGCM_IMM32 (1 << REGC_IMM32)
21737 #define REGCM_IMM16 (1 << REGC_IMM16)
21738 #define REGCM_IMM8 (1 << REGC_IMM8)
21739 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21740 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21742 /* The x86 registers */
21743 #define REG_EFLAGS 2
21744 #define REGC_FLAGS_FIRST REG_EFLAGS
21745 #define REGC_FLAGS_LAST REG_EFLAGS
21754 #define REGC_GPR8_LO_FIRST REG_AL
21755 #define REGC_GPR8_LO_LAST REG_DL
21756 #define REGC_GPR8_FIRST REG_AL
21757 #define REGC_GPR8_LAST REG_DH
21766 #define REGC_GPR16_FIRST REG_AX
21767 #define REGC_GPR16_LAST REG_SP
21776 #define REGC_GPR32_FIRST REG_EAX
21777 #define REGC_GPR32_LAST REG_ESP
21778 #define REG_EDXEAX 27
21779 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21780 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21781 #define REG_DXAX 28
21782 #define REGC_DIVIDEND32_FIRST REG_DXAX
21783 #define REGC_DIVIDEND32_LAST REG_DXAX
21784 #define REG_MMX0 29
21785 #define REG_MMX1 30
21786 #define REG_MMX2 31
21787 #define REG_MMX3 32
21788 #define REG_MMX4 33
21789 #define REG_MMX5 34
21790 #define REG_MMX6 35
21791 #define REG_MMX7 36
21792 #define REGC_MMX_FIRST REG_MMX0
21793 #define REGC_MMX_LAST REG_MMX7
21794 #define REG_XMM0 37
21795 #define REG_XMM1 38
21796 #define REG_XMM2 39
21797 #define REG_XMM3 40
21798 #define REG_XMM4 41
21799 #define REG_XMM5 42
21800 #define REG_XMM6 43
21801 #define REG_XMM7 44
21802 #define REGC_XMM_FIRST REG_XMM0
21803 #define REGC_XMM_LAST REG_XMM7
21805 #if DEBUG_ROMCC_WARNINGS
21806 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21809 #define LAST_REG REG_XMM7
21811 #define REGC_GPR32_8_FIRST REG_EAX
21812 #define REGC_GPR32_8_LAST REG_EDX
21813 #define REGC_GPR16_8_FIRST REG_AX
21814 #define REGC_GPR16_8_LAST REG_DX
21816 #define REGC_IMM8_FIRST -1
21817 #define REGC_IMM8_LAST -1
21818 #define REGC_IMM16_FIRST -2
21819 #define REGC_IMM16_LAST -1
21820 #define REGC_IMM32_FIRST -4
21821 #define REGC_IMM32_LAST -1
21823 #if LAST_REG >= MAX_REGISTERS
21824 #error "MAX_REGISTERS to low"
21828 static unsigned regc_size[LAST_REGC +1] = {
21829 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21830 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21831 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21832 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21833 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21834 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21835 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21836 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21837 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21838 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21839 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21845 static const struct {
21847 } regcm_bound[LAST_REGC + 1] = {
21848 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21849 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21850 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21851 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21852 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21853 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21854 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21855 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21856 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21857 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21858 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21859 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21860 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21861 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21864 #if ARCH_INPUT_REGS != 4
21865 #error ARCH_INPUT_REGS size mismatch
21867 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21868 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21869 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21870 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21871 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21874 #if ARCH_OUTPUT_REGS != 4
21875 #error ARCH_INPUT_REGS size mismatch
21877 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21878 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21879 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21880 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21881 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21884 static void init_arch_state(struct arch_state *arch)
21886 memset(arch, 0, sizeof(*arch));
21887 arch->features = 0;
21890 static const struct compiler_flag arch_flags[] = {
21891 { "mmx", X86_MMX_REGS },
21892 { "sse", X86_XMM_REGS },
21893 { "noop-copy", X86_NOOP_COPY },
21896 static const struct compiler_flag arch_cpus[] = {
21898 { "p2", X86_MMX_REGS },
21899 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21900 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21901 { "k7", X86_MMX_REGS },
21902 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21903 { "c3", X86_MMX_REGS },
21904 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21907 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21914 if (strncmp(flag, "no-", 3) == 0) {
21918 if (act && strncmp(flag, "cpu=", 4) == 0) {
21920 result = set_flag(arch_cpus, &arch->features, 1, flag);
21923 result = set_flag(arch_flags, &arch->features, act, flag);
21928 static void arch_usage(FILE *fp)
21930 flag_usage(fp, arch_flags, "-m", "-mno-");
21931 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21934 static unsigned arch_regc_size(struct compile_state *state, int class)
21936 if ((class < 0) || (class > LAST_REGC)) {
21939 return regc_size[class];
21942 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21944 /* See if two register classes may have overlapping registers */
21945 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21946 REGCM_GPR32_8 | REGCM_GPR32 |
21947 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21949 /* Special case for the immediates */
21950 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21951 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21952 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21953 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21956 return (regcm1 & regcm2) ||
21957 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21960 static void arch_reg_equivs(
21961 struct compile_state *state, unsigned *equiv, int reg)
21963 if ((reg < 0) || (reg > LAST_REG)) {
21964 internal_error(state, 0, "invalid register");
21969 #if X86_4_8BIT_GPRS
21973 *equiv++ = REG_EAX;
21974 *equiv++ = REG_DXAX;
21975 *equiv++ = REG_EDXEAX;
21978 #if X86_4_8BIT_GPRS
21982 *equiv++ = REG_EAX;
21983 *equiv++ = REG_DXAX;
21984 *equiv++ = REG_EDXEAX;
21987 #if X86_4_8BIT_GPRS
21991 *equiv++ = REG_EBX;
21995 #if X86_4_8BIT_GPRS
21999 *equiv++ = REG_EBX;
22002 #if X86_4_8BIT_GPRS
22006 *equiv++ = REG_ECX;
22010 #if X86_4_8BIT_GPRS
22014 *equiv++ = REG_ECX;
22017 #if X86_4_8BIT_GPRS
22021 *equiv++ = REG_EDX;
22022 *equiv++ = REG_DXAX;
22023 *equiv++ = REG_EDXEAX;
22026 #if X86_4_8BIT_GPRS
22030 *equiv++ = REG_EDX;
22031 *equiv++ = REG_DXAX;
22032 *equiv++ = REG_EDXEAX;
22037 *equiv++ = REG_EAX;
22038 *equiv++ = REG_DXAX;
22039 *equiv++ = REG_EDXEAX;
22044 *equiv++ = REG_EBX;
22049 *equiv++ = REG_ECX;
22054 *equiv++ = REG_EDX;
22055 *equiv++ = REG_DXAX;
22056 *equiv++ = REG_EDXEAX;
22059 *equiv++ = REG_ESI;
22062 *equiv++ = REG_EDI;
22065 *equiv++ = REG_EBP;
22068 *equiv++ = REG_ESP;
22074 *equiv++ = REG_DXAX;
22075 *equiv++ = REG_EDXEAX;
22091 *equiv++ = REG_DXAX;
22092 *equiv++ = REG_EDXEAX;
22113 *equiv++ = REG_EAX;
22114 *equiv++ = REG_EDX;
22115 *equiv++ = REG_EDXEAX;
22124 *equiv++ = REG_EAX;
22125 *equiv++ = REG_EDX;
22126 *equiv++ = REG_DXAX;
22129 *equiv++ = REG_UNSET;
22132 static unsigned arch_avail_mask(struct compile_state *state)
22134 unsigned avail_mask;
22135 /* REGCM_GPR8 is not available */
22136 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22137 REGCM_GPR32 | REGCM_GPR32_8 |
22138 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22139 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22140 if (state->arch->features & X86_MMX_REGS) {
22141 avail_mask |= REGCM_MMX;
22143 if (state->arch->features & X86_XMM_REGS) {
22144 avail_mask |= REGCM_XMM;
22149 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22151 unsigned mask, result;
22155 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22156 if ((result & mask) == 0) {
22159 if (class > LAST_REGC) {
22162 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22163 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22164 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22165 result |= (1 << class2);
22169 result &= arch_avail_mask(state);
22173 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22175 /* Like arch_regcm_normalize except immediate register classes are excluded */
22176 regcm = arch_regcm_normalize(state, regcm);
22177 /* Remove the immediate register classes */
22178 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22183 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22188 for(class = 0; class <= LAST_REGC; class++) {
22189 if ((reg >= regcm_bound[class].first) &&
22190 (reg <= regcm_bound[class].last)) {
22191 mask |= (1 << class);
22195 internal_error(state, 0, "reg %d not in any class", reg);
22200 static struct reg_info arch_reg_constraint(
22201 struct compile_state *state, struct type *type, const char *constraint)
22203 static const struct {
22207 } constraints[] = {
22208 { 'r', REGCM_GPR32, REG_UNSET },
22209 { 'g', REGCM_GPR32, REG_UNSET },
22210 { 'p', REGCM_GPR32, REG_UNSET },
22211 { 'q', REGCM_GPR8_LO, REG_UNSET },
22212 { 'Q', REGCM_GPR32_8, REG_UNSET },
22213 { 'x', REGCM_XMM, REG_UNSET },
22214 { 'y', REGCM_MMX, REG_UNSET },
22215 { 'a', REGCM_GPR32, REG_EAX },
22216 { 'b', REGCM_GPR32, REG_EBX },
22217 { 'c', REGCM_GPR32, REG_ECX },
22218 { 'd', REGCM_GPR32, REG_EDX },
22219 { 'D', REGCM_GPR32, REG_EDI },
22220 { 'S', REGCM_GPR32, REG_ESI },
22221 { '\0', 0, REG_UNSET },
22223 unsigned int regcm;
22224 unsigned int mask, reg;
22225 struct reg_info result;
22227 regcm = arch_type_to_regcm(state, type);
22230 for(ptr = constraint; *ptr; ptr++) {
22235 for(i = 0; constraints[i].class != '\0'; i++) {
22236 if (constraints[i].class == *ptr) {
22240 if (constraints[i].class == '\0') {
22241 error(state, 0, "invalid register constraint ``%c''", *ptr);
22244 if ((constraints[i].mask & regcm) == 0) {
22245 error(state, 0, "invalid register class %c specified",
22248 mask |= constraints[i].mask;
22249 if (constraints[i].reg != REG_UNSET) {
22250 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22251 error(state, 0, "Only one register may be specified");
22253 reg = constraints[i].reg;
22257 result.regcm = mask;
22261 static struct reg_info arch_reg_clobber(
22262 struct compile_state *state, const char *clobber)
22264 struct reg_info result;
22265 if (strcmp(clobber, "memory") == 0) {
22266 result.reg = REG_UNSET;
22269 else if (strcmp(clobber, "eax") == 0) {
22270 result.reg = REG_EAX;
22271 result.regcm = REGCM_GPR32;
22273 else if (strcmp(clobber, "ebx") == 0) {
22274 result.reg = REG_EBX;
22275 result.regcm = REGCM_GPR32;
22277 else if (strcmp(clobber, "ecx") == 0) {
22278 result.reg = REG_ECX;
22279 result.regcm = REGCM_GPR32;
22281 else if (strcmp(clobber, "edx") == 0) {
22282 result.reg = REG_EDX;
22283 result.regcm = REGCM_GPR32;
22285 else if (strcmp(clobber, "esi") == 0) {
22286 result.reg = REG_ESI;
22287 result.regcm = REGCM_GPR32;
22289 else if (strcmp(clobber, "edi") == 0) {
22290 result.reg = REG_EDI;
22291 result.regcm = REGCM_GPR32;
22293 else if (strcmp(clobber, "ebp") == 0) {
22294 result.reg = REG_EBP;
22295 result.regcm = REGCM_GPR32;
22297 else if (strcmp(clobber, "esp") == 0) {
22298 result.reg = REG_ESP;
22299 result.regcm = REGCM_GPR32;
22301 else if (strcmp(clobber, "cc") == 0) {
22302 result.reg = REG_EFLAGS;
22303 result.regcm = REGCM_FLAGS;
22305 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22306 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22307 result.reg = REG_XMM0 + octdigval(clobber[3]);
22308 result.regcm = REGCM_XMM;
22310 else if ((strncmp(clobber, "mm", 2) == 0) &&
22311 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22312 result.reg = REG_MMX0 + octdigval(clobber[3]);
22313 result.regcm = REGCM_MMX;
22316 error(state, 0, "unknown register name `%s' in asm",
22318 result.reg = REG_UNSET;
22324 static int do_select_reg(struct compile_state *state,
22325 char *used, int reg, unsigned classes)
22331 mask = arch_reg_regcm(state, reg);
22332 return (classes & mask) ? reg : REG_UNSET;
22335 static int arch_select_free_register(
22336 struct compile_state *state, char *used, int classes)
22338 /* Live ranges with the most neighbors are colored first.
22340 * Generally it does not matter which colors are given
22341 * as the register allocator attempts to color live ranges
22342 * in an order where you are guaranteed not to run out of colors.
22344 * Occasionally the register allocator cannot find an order
22345 * of register selection that will find a free color. To
22346 * increase the odds the register allocator will work when
22347 * it guesses first give out registers from register classes
22348 * least likely to run out of registers.
22353 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22354 reg = do_select_reg(state, used, i, classes);
22356 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22357 reg = do_select_reg(state, used, i, classes);
22359 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22360 reg = do_select_reg(state, used, i, classes);
22362 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22363 reg = do_select_reg(state, used, i, classes);
22365 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22366 reg = do_select_reg(state, used, i, classes);
22368 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22369 reg = do_select_reg(state, used, i, classes);
22371 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22372 reg = do_select_reg(state, used, i, classes);
22374 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22375 reg = do_select_reg(state, used, i, classes);
22377 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22378 reg = do_select_reg(state, used, i, classes);
22384 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22387 #if DEBUG_ROMCC_WARNINGS
22388 #warning "FIXME force types smaller (if legal) before I get here"
22392 switch(type->type & TYPE_MASK) {
22399 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22400 REGCM_GPR16 | REGCM_GPR16_8 |
22401 REGCM_GPR32 | REGCM_GPR32_8 |
22402 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22403 REGCM_MMX | REGCM_XMM |
22404 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22408 mask = REGCM_GPR16 | REGCM_GPR16_8 |
22409 REGCM_GPR32 | REGCM_GPR32_8 |
22410 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22411 REGCM_MMX | REGCM_XMM |
22412 REGCM_IMM32 | REGCM_IMM16;
22420 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22421 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22422 REGCM_MMX | REGCM_XMM |
22427 mask = arch_type_to_regcm(state, type->left);
22430 mask = arch_type_to_regcm(state, type->left) &
22431 arch_type_to_regcm(state, type->right);
22433 case TYPE_BITFIELD:
22434 mask = arch_type_to_regcm(state, type->left);
22437 fprintf(state->errout, "type: ");
22438 name_of(state->errout, type);
22439 fprintf(state->errout, "\n");
22440 internal_error(state, 0, "no register class for type");
22443 mask = arch_regcm_normalize(state, mask);
22447 static int is_imm32(struct triple *imm)
22449 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22450 (imm->op == OP_ADDRCONST);
22453 static int is_imm16(struct triple *imm)
22455 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22457 static int is_imm8(struct triple *imm)
22459 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22462 static int get_imm32(struct triple *ins, struct triple **expr)
22464 struct triple *imm;
22466 while(imm->op == OP_COPY) {
22469 if (!is_imm32(imm)) {
22472 unuse_triple(*expr, ins);
22473 use_triple(imm, ins);
22478 static int get_imm8(struct triple *ins, struct triple **expr)
22480 struct triple *imm;
22482 while(imm->op == OP_COPY) {
22485 if (!is_imm8(imm)) {
22488 unuse_triple(*expr, ins);
22489 use_triple(imm, ins);
22494 #define TEMPLATE_NOP 0
22495 #define TEMPLATE_INTCONST8 1
22496 #define TEMPLATE_INTCONST32 2
22497 #define TEMPLATE_UNKNOWNVAL 3
22498 #define TEMPLATE_COPY8_REG 5
22499 #define TEMPLATE_COPY16_REG 6
22500 #define TEMPLATE_COPY32_REG 7
22501 #define TEMPLATE_COPY_IMM8 8
22502 #define TEMPLATE_COPY_IMM16 9
22503 #define TEMPLATE_COPY_IMM32 10
22504 #define TEMPLATE_PHI8 11
22505 #define TEMPLATE_PHI16 12
22506 #define TEMPLATE_PHI32 13
22507 #define TEMPLATE_STORE8 14
22508 #define TEMPLATE_STORE16 15
22509 #define TEMPLATE_STORE32 16
22510 #define TEMPLATE_LOAD8 17
22511 #define TEMPLATE_LOAD16 18
22512 #define TEMPLATE_LOAD32 19
22513 #define TEMPLATE_BINARY8_REG 20
22514 #define TEMPLATE_BINARY16_REG 21
22515 #define TEMPLATE_BINARY32_REG 22
22516 #define TEMPLATE_BINARY8_IMM 23
22517 #define TEMPLATE_BINARY16_IMM 24
22518 #define TEMPLATE_BINARY32_IMM 25
22519 #define TEMPLATE_SL8_CL 26
22520 #define TEMPLATE_SL16_CL 27
22521 #define TEMPLATE_SL32_CL 28
22522 #define TEMPLATE_SL8_IMM 29
22523 #define TEMPLATE_SL16_IMM 30
22524 #define TEMPLATE_SL32_IMM 31
22525 #define TEMPLATE_UNARY8 32
22526 #define TEMPLATE_UNARY16 33
22527 #define TEMPLATE_UNARY32 34
22528 #define TEMPLATE_CMP8_REG 35
22529 #define TEMPLATE_CMP16_REG 36
22530 #define TEMPLATE_CMP32_REG 37
22531 #define TEMPLATE_CMP8_IMM 38
22532 #define TEMPLATE_CMP16_IMM 39
22533 #define TEMPLATE_CMP32_IMM 40
22534 #define TEMPLATE_TEST8 41
22535 #define TEMPLATE_TEST16 42
22536 #define TEMPLATE_TEST32 43
22537 #define TEMPLATE_SET 44
22538 #define TEMPLATE_JMP 45
22539 #define TEMPLATE_RET 46
22540 #define TEMPLATE_INB_DX 47
22541 #define TEMPLATE_INB_IMM 48
22542 #define TEMPLATE_INW_DX 49
22543 #define TEMPLATE_INW_IMM 50
22544 #define TEMPLATE_INL_DX 51
22545 #define TEMPLATE_INL_IMM 52
22546 #define TEMPLATE_OUTB_DX 53
22547 #define TEMPLATE_OUTB_IMM 54
22548 #define TEMPLATE_OUTW_DX 55
22549 #define TEMPLATE_OUTW_IMM 56
22550 #define TEMPLATE_OUTL_DX 57
22551 #define TEMPLATE_OUTL_IMM 58
22552 #define TEMPLATE_BSF 59
22553 #define TEMPLATE_RDMSR 60
22554 #define TEMPLATE_WRMSR 61
22555 #define TEMPLATE_UMUL8 62
22556 #define TEMPLATE_UMUL16 63
22557 #define TEMPLATE_UMUL32 64
22558 #define TEMPLATE_DIV8 65
22559 #define TEMPLATE_DIV16 66
22560 #define TEMPLATE_DIV32 67
22561 #define LAST_TEMPLATE TEMPLATE_DIV32
22562 #if LAST_TEMPLATE >= MAX_TEMPLATES
22563 #error "MAX_TEMPLATES to low"
22566 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22567 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22568 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22571 static struct ins_template templates[] = {
22574 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22575 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22576 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22577 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22578 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22579 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22580 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22581 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22582 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22583 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22584 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22585 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22586 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22587 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22588 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22589 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22590 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22591 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22592 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22593 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22594 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22595 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22596 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22597 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22598 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22599 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22600 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22601 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22602 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22603 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22604 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22605 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22606 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22607 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22608 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22609 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22610 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22611 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22612 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22613 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22614 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22615 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22616 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22617 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22618 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22619 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22620 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22621 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22622 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22623 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22624 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22625 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22626 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22627 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22628 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22629 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22630 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22631 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22632 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22633 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22634 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22635 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22636 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22637 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22640 [TEMPLATE_INTCONST8] = {
22641 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22643 [TEMPLATE_INTCONST32] = {
22644 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22646 [TEMPLATE_UNKNOWNVAL] = {
22647 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22649 [TEMPLATE_COPY8_REG] = {
22650 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22651 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22653 [TEMPLATE_COPY16_REG] = {
22654 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22655 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22657 [TEMPLATE_COPY32_REG] = {
22658 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22659 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22661 [TEMPLATE_COPY_IMM8] = {
22662 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22663 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22665 [TEMPLATE_COPY_IMM16] = {
22666 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22667 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22669 [TEMPLATE_COPY_IMM32] = {
22670 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22671 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22673 [TEMPLATE_PHI8] = {
22674 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22675 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22677 [TEMPLATE_PHI16] = {
22678 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22679 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22681 [TEMPLATE_PHI32] = {
22682 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22683 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22685 [TEMPLATE_STORE8] = {
22687 [0] = { REG_UNSET, REGCM_GPR32 },
22688 [1] = { REG_UNSET, REGCM_GPR8_LO },
22691 [TEMPLATE_STORE16] = {
22693 [0] = { REG_UNSET, REGCM_GPR32 },
22694 [1] = { REG_UNSET, REGCM_GPR16 },
22697 [TEMPLATE_STORE32] = {
22699 [0] = { REG_UNSET, REGCM_GPR32 },
22700 [1] = { REG_UNSET, REGCM_GPR32 },
22703 [TEMPLATE_LOAD8] = {
22704 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22705 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22707 [TEMPLATE_LOAD16] = {
22708 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22709 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22711 [TEMPLATE_LOAD32] = {
22712 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22713 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22715 [TEMPLATE_BINARY8_REG] = {
22716 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22718 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22719 [1] = { REG_UNSET, REGCM_GPR8_LO },
22722 [TEMPLATE_BINARY16_REG] = {
22723 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22725 [0] = { REG_VIRT0, REGCM_GPR16 },
22726 [1] = { REG_UNSET, REGCM_GPR16 },
22729 [TEMPLATE_BINARY32_REG] = {
22730 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22732 [0] = { REG_VIRT0, REGCM_GPR32 },
22733 [1] = { REG_UNSET, REGCM_GPR32 },
22736 [TEMPLATE_BINARY8_IMM] = {
22737 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22739 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22740 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22743 [TEMPLATE_BINARY16_IMM] = {
22744 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22746 [0] = { REG_VIRT0, REGCM_GPR16 },
22747 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22750 [TEMPLATE_BINARY32_IMM] = {
22751 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22753 [0] = { REG_VIRT0, REGCM_GPR32 },
22754 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22757 [TEMPLATE_SL8_CL] = {
22758 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22760 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22761 [1] = { REG_CL, REGCM_GPR8_LO },
22764 [TEMPLATE_SL16_CL] = {
22765 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22767 [0] = { REG_VIRT0, REGCM_GPR16 },
22768 [1] = { REG_CL, REGCM_GPR8_LO },
22771 [TEMPLATE_SL32_CL] = {
22772 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22774 [0] = { REG_VIRT0, REGCM_GPR32 },
22775 [1] = { REG_CL, REGCM_GPR8_LO },
22778 [TEMPLATE_SL8_IMM] = {
22779 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22781 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22782 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22785 [TEMPLATE_SL16_IMM] = {
22786 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22788 [0] = { REG_VIRT0, REGCM_GPR16 },
22789 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22792 [TEMPLATE_SL32_IMM] = {
22793 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22795 [0] = { REG_VIRT0, REGCM_GPR32 },
22796 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22799 [TEMPLATE_UNARY8] = {
22800 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22801 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22803 [TEMPLATE_UNARY16] = {
22804 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22805 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22807 [TEMPLATE_UNARY32] = {
22808 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22809 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22811 [TEMPLATE_CMP8_REG] = {
22812 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22814 [0] = { REG_UNSET, REGCM_GPR8_LO },
22815 [1] = { REG_UNSET, REGCM_GPR8_LO },
22818 [TEMPLATE_CMP16_REG] = {
22819 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22821 [0] = { REG_UNSET, REGCM_GPR16 },
22822 [1] = { REG_UNSET, REGCM_GPR16 },
22825 [TEMPLATE_CMP32_REG] = {
22826 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22828 [0] = { REG_UNSET, REGCM_GPR32 },
22829 [1] = { REG_UNSET, REGCM_GPR32 },
22832 [TEMPLATE_CMP8_IMM] = {
22833 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22835 [0] = { REG_UNSET, REGCM_GPR8_LO },
22836 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22839 [TEMPLATE_CMP16_IMM] = {
22840 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22842 [0] = { REG_UNSET, REGCM_GPR16 },
22843 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22846 [TEMPLATE_CMP32_IMM] = {
22847 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22849 [0] = { REG_UNSET, REGCM_GPR32 },
22850 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22853 [TEMPLATE_TEST8] = {
22854 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22855 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22857 [TEMPLATE_TEST16] = {
22858 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22859 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22861 [TEMPLATE_TEST32] = {
22862 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22863 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22866 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22867 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22870 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22873 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22875 [TEMPLATE_INB_DX] = {
22876 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22877 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22879 [TEMPLATE_INB_IMM] = {
22880 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22881 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22883 [TEMPLATE_INW_DX] = {
22884 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22885 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22887 [TEMPLATE_INW_IMM] = {
22888 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22889 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22891 [TEMPLATE_INL_DX] = {
22892 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22893 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22895 [TEMPLATE_INL_IMM] = {
22896 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22897 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22899 [TEMPLATE_OUTB_DX] = {
22901 [0] = { REG_AL, REGCM_GPR8_LO },
22902 [1] = { REG_DX, REGCM_GPR16 },
22905 [TEMPLATE_OUTB_IMM] = {
22907 [0] = { REG_AL, REGCM_GPR8_LO },
22908 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22911 [TEMPLATE_OUTW_DX] = {
22913 [0] = { REG_AX, REGCM_GPR16 },
22914 [1] = { REG_DX, REGCM_GPR16 },
22917 [TEMPLATE_OUTW_IMM] = {
22919 [0] = { REG_AX, REGCM_GPR16 },
22920 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22923 [TEMPLATE_OUTL_DX] = {
22925 [0] = { REG_EAX, REGCM_GPR32 },
22926 [1] = { REG_DX, REGCM_GPR16 },
22929 [TEMPLATE_OUTL_IMM] = {
22931 [0] = { REG_EAX, REGCM_GPR32 },
22932 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22936 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22937 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22939 [TEMPLATE_RDMSR] = {
22941 [0] = { REG_EAX, REGCM_GPR32 },
22942 [1] = { REG_EDX, REGCM_GPR32 },
22944 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22946 [TEMPLATE_WRMSR] = {
22948 [0] = { REG_ECX, REGCM_GPR32 },
22949 [1] = { REG_EAX, REGCM_GPR32 },
22950 [2] = { REG_EDX, REGCM_GPR32 },
22953 [TEMPLATE_UMUL8] = {
22954 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22956 [0] = { REG_AL, REGCM_GPR8_LO },
22957 [1] = { REG_UNSET, REGCM_GPR8_LO },
22960 [TEMPLATE_UMUL16] = {
22961 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22963 [0] = { REG_AX, REGCM_GPR16 },
22964 [1] = { REG_UNSET, REGCM_GPR16 },
22967 [TEMPLATE_UMUL32] = {
22968 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22970 [0] = { REG_EAX, REGCM_GPR32 },
22971 [1] = { REG_UNSET, REGCM_GPR32 },
22974 [TEMPLATE_DIV8] = {
22976 [0] = { REG_AL, REGCM_GPR8_LO },
22977 [1] = { REG_AH, REGCM_GPR8 },
22980 [0] = { REG_AX, REGCM_GPR16 },
22981 [1] = { REG_UNSET, REGCM_GPR8_LO },
22984 [TEMPLATE_DIV16] = {
22986 [0] = { REG_AX, REGCM_GPR16 },
22987 [1] = { REG_DX, REGCM_GPR16 },
22990 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22991 [1] = { REG_UNSET, REGCM_GPR16 },
22994 [TEMPLATE_DIV32] = {
22996 [0] = { REG_EAX, REGCM_GPR32 },
22997 [1] = { REG_EDX, REGCM_GPR32 },
23000 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
23001 [1] = { REG_UNSET, REGCM_GPR32 },
23006 static void fixup_branch(struct compile_state *state,
23007 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23008 struct triple *left, struct triple *right)
23010 struct triple *test;
23012 internal_error(state, branch, "no branch test?");
23014 test = pre_triple(state, branch,
23015 cmp_op, cmp_type, left, right);
23016 test->template_id = TEMPLATE_TEST32;
23017 if (cmp_op == OP_CMP) {
23018 test->template_id = TEMPLATE_CMP32_REG;
23019 if (get_imm32(test, &RHS(test, 1))) {
23020 test->template_id = TEMPLATE_CMP32_IMM;
23023 use_triple(RHS(test, 0), test);
23024 use_triple(RHS(test, 1), test);
23025 unuse_triple(RHS(branch, 0), branch);
23026 RHS(branch, 0) = test;
23027 branch->op = jmp_op;
23028 branch->template_id = TEMPLATE_JMP;
23029 use_triple(RHS(branch, 0), branch);
23032 static void fixup_branches(struct compile_state *state,
23033 struct triple *cmp, struct triple *use, int jmp_op)
23035 struct triple_set *entry, *next;
23036 for(entry = use->use; entry; entry = next) {
23037 next = entry->next;
23038 if (entry->member->op == OP_COPY) {
23039 fixup_branches(state, cmp, entry->member, jmp_op);
23041 else if (entry->member->op == OP_CBRANCH) {
23042 struct triple *branch;
23043 struct triple *left, *right;
23045 left = RHS(cmp, 0);
23046 if (cmp->rhs > 1) {
23047 right = RHS(cmp, 1);
23049 branch = entry->member;
23050 fixup_branch(state, branch, jmp_op,
23051 cmp->op, cmp->type, left, right);
23056 static void bool_cmp(struct compile_state *state,
23057 struct triple *ins, int cmp_op, int jmp_op, int set_op)
23059 struct triple_set *entry, *next;
23060 struct triple *set, *convert;
23062 /* Put a barrier up before the cmp which preceeds the
23063 * copy instruction. If a set actually occurs this gives
23064 * us a chance to move variables in registers out of the way.
23067 /* Modify the comparison operator */
23069 ins->template_id = TEMPLATE_TEST32;
23070 if (cmp_op == OP_CMP) {
23071 ins->template_id = TEMPLATE_CMP32_REG;
23072 if (get_imm32(ins, &RHS(ins, 1))) {
23073 ins->template_id = TEMPLATE_CMP32_IMM;
23076 /* Generate the instruction sequence that will transform the
23077 * result of the comparison into a logical value.
23079 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23080 use_triple(ins, set);
23081 set->template_id = TEMPLATE_SET;
23084 if (!equiv_types(ins->type, set->type)) {
23085 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23086 use_triple(set, convert);
23087 convert->template_id = TEMPLATE_COPY32_REG;
23090 for(entry = ins->use; entry; entry = next) {
23091 next = entry->next;
23092 if (entry->member == set) {
23095 replace_rhs_use(state, ins, convert, entry->member);
23097 fixup_branches(state, ins, convert, jmp_op);
23100 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23102 struct ins_template *template;
23103 struct reg_info result;
23105 if (ins->op == OP_PIECE) {
23106 index = ins->u.cval;
23107 ins = MISC(ins, 0);
23110 if (triple_is_def(state, ins)) {
23113 if (index >= zlhs) {
23114 internal_error(state, ins, "index %d out of range for %s",
23115 index, tops(ins->op));
23119 template = &ins->u.ainfo->tmpl;
23122 if (ins->template_id > LAST_TEMPLATE) {
23123 internal_error(state, ins, "bad template number %d",
23126 template = &templates[ins->template_id];
23129 result = template->lhs[index];
23130 result.regcm = arch_regcm_normalize(state, result.regcm);
23131 if (result.reg != REG_UNNEEDED) {
23132 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23134 if (result.regcm == 0) {
23135 internal_error(state, ins, "lhs %d regcm == 0", index);
23140 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23142 struct reg_info result;
23143 struct ins_template *template;
23144 if ((index > ins->rhs) ||
23145 (ins->op == OP_PIECE)) {
23146 internal_error(state, ins, "index %d out of range for %s\n",
23147 index, tops(ins->op));
23151 template = &ins->u.ainfo->tmpl;
23157 if (ins->template_id > LAST_TEMPLATE) {
23158 internal_error(state, ins, "bad template number %d",
23161 template = &templates[ins->template_id];
23164 result = template->rhs[index];
23165 result.regcm = arch_regcm_normalize(state, result.regcm);
23166 if (result.regcm == 0) {
23167 internal_error(state, ins, "rhs %d regcm == 0", index);
23172 static struct triple *mod_div(struct compile_state *state,
23173 struct triple *ins, int div_op, int index)
23175 struct triple *div, *piece0, *piece1;
23177 /* Generate the appropriate division instruction */
23178 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23179 RHS(div, 0) = RHS(ins, 0);
23180 RHS(div, 1) = RHS(ins, 1);
23181 piece0 = LHS(div, 0);
23182 piece1 = LHS(div, 1);
23183 div->template_id = TEMPLATE_DIV32;
23184 use_triple(RHS(div, 0), div);
23185 use_triple(RHS(div, 1), div);
23186 use_triple(LHS(div, 0), div);
23187 use_triple(LHS(div, 1), div);
23189 /* Replate uses of ins with the appropriate piece of the div */
23190 propogate_use(state, ins, LHS(div, index));
23191 release_triple(state, ins);
23193 /* Return the address of the next instruction */
23194 return piece1->next;
23197 static int noop_adecl(struct triple *adecl)
23199 struct triple_set *use;
23200 /* It's a noop if it doesn't specify stoorage */
23201 if (adecl->lhs == 0) {
23204 /* Is the adecl used? If not it's a noop */
23205 for(use = adecl->use; use ; use = use->next) {
23206 if ((use->member->op != OP_PIECE) ||
23207 (MISC(use->member, 0) != adecl)) {
23214 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23216 struct triple *mask, *nmask, *shift;
23217 struct triple *val, *val_mask, *val_shift;
23218 struct triple *targ, *targ_mask;
23219 struct triple *new;
23220 ulong_t the_mask, the_nmask;
23222 targ = RHS(ins, 0);
23225 /* Get constant for the mask value */
23227 the_mask <<= ins->u.bitfield.size;
23229 the_mask <<= ins->u.bitfield.offset;
23230 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23231 mask->u.cval = the_mask;
23233 /* Get the inverted mask value */
23234 the_nmask = ~the_mask;
23235 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23236 nmask->u.cval = the_nmask;
23238 /* Get constant for the shift value */
23239 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23240 shift->u.cval = ins->u.bitfield.offset;
23242 /* Shift and mask the source value */
23244 if (shift->u.cval != 0) {
23245 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23246 use_triple(val, val_shift);
23247 use_triple(shift, val_shift);
23249 val_mask = val_shift;
23250 if (is_signed(val->type)) {
23251 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23252 use_triple(val_shift, val_mask);
23253 use_triple(mask, val_mask);
23256 /* Mask the target value */
23257 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23258 use_triple(targ, targ_mask);
23259 use_triple(nmask, targ_mask);
23261 /* Now combined them together */
23262 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23263 use_triple(targ_mask, new);
23264 use_triple(val_mask, new);
23266 /* Move all of the users over to the new expression */
23267 propogate_use(state, ins, new);
23269 /* Delete the original triple */
23270 release_triple(state, ins);
23272 /* Restart the transformation at mask */
23276 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23278 struct triple *mask, *shift;
23279 struct triple *val, *val_mask, *val_shift;
23284 /* Get constant for the mask value */
23286 the_mask <<= ins->u.bitfield.size;
23288 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23289 mask->u.cval = the_mask;
23291 /* Get constant for the right shift value */
23292 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23293 shift->u.cval = ins->u.bitfield.offset;
23295 /* Shift arithmetic right, to correct the sign */
23297 if (shift->u.cval != 0) {
23299 if (ins->op == OP_SEXTRACT) {
23304 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23305 use_triple(val, val_shift);
23306 use_triple(shift, val_shift);
23309 /* Finally mask the value */
23310 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23311 use_triple(val_shift, val_mask);
23312 use_triple(mask, val_mask);
23314 /* Move all of the users over to the new expression */
23315 propogate_use(state, ins, val_mask);
23317 /* Release the original instruction */
23318 release_triple(state, ins);
23324 static struct triple *transform_to_arch_instruction(
23325 struct compile_state *state, struct triple *ins)
23327 /* Transform from generic 3 address instructions
23328 * to archtecture specific instructions.
23329 * And apply architecture specific constraints to instructions.
23330 * Copies are inserted to preserve the register flexibility
23331 * of 3 address instructions.
23333 struct triple *next, *value;
23338 ins->template_id = TEMPLATE_INTCONST32;
23339 if (ins->u.cval < 256) {
23340 ins->template_id = TEMPLATE_INTCONST8;
23344 ins->template_id = TEMPLATE_INTCONST32;
23346 case OP_UNKNOWNVAL:
23347 ins->template_id = TEMPLATE_UNKNOWNVAL;
23353 ins->template_id = TEMPLATE_NOP;
23357 size = size_of(state, ins->type);
23358 value = RHS(ins, 0);
23359 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23360 ins->template_id = TEMPLATE_COPY_IMM8;
23362 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23363 ins->template_id = TEMPLATE_COPY_IMM16;
23365 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23366 ins->template_id = TEMPLATE_COPY_IMM32;
23368 else if (is_const(value)) {
23369 internal_error(state, ins, "bad constant passed to copy");
23371 else if (size <= SIZEOF_I8) {
23372 ins->template_id = TEMPLATE_COPY8_REG;
23374 else if (size <= SIZEOF_I16) {
23375 ins->template_id = TEMPLATE_COPY16_REG;
23377 else if (size <= SIZEOF_I32) {
23378 ins->template_id = TEMPLATE_COPY32_REG;
23381 internal_error(state, ins, "bad type passed to copy");
23385 size = size_of(state, ins->type);
23386 if (size <= SIZEOF_I8) {
23387 ins->template_id = TEMPLATE_PHI8;
23389 else if (size <= SIZEOF_I16) {
23390 ins->template_id = TEMPLATE_PHI16;
23392 else if (size <= SIZEOF_I32) {
23393 ins->template_id = TEMPLATE_PHI32;
23396 internal_error(state, ins, "bad type passed to phi");
23400 /* Adecls should always be treated as dead code and
23401 * removed. If we are not optimizing they may linger.
23403 if (!noop_adecl(ins)) {
23404 internal_error(state, ins, "adecl remains?");
23406 ins->template_id = TEMPLATE_NOP;
23407 next = after_lhs(state, ins);
23410 switch(ins->type->type & TYPE_MASK) {
23411 case TYPE_CHAR: case TYPE_UCHAR:
23412 ins->template_id = TEMPLATE_STORE8;
23414 case TYPE_SHORT: case TYPE_USHORT:
23415 ins->template_id = TEMPLATE_STORE16;
23417 case TYPE_INT: case TYPE_UINT:
23418 case TYPE_LONG: case TYPE_ULONG:
23420 ins->template_id = TEMPLATE_STORE32;
23423 internal_error(state, ins, "unknown type in store");
23428 switch(ins->type->type & TYPE_MASK) {
23429 case TYPE_CHAR: case TYPE_UCHAR:
23430 case TYPE_SHORT: case TYPE_USHORT:
23431 case TYPE_INT: case TYPE_UINT:
23432 case TYPE_LONG: case TYPE_ULONG:
23436 internal_error(state, ins, "unknown type in load");
23439 ins->template_id = TEMPLATE_LOAD32;
23447 ins->template_id = TEMPLATE_BINARY32_REG;
23448 if (get_imm32(ins, &RHS(ins, 1))) {
23449 ins->template_id = TEMPLATE_BINARY32_IMM;
23454 ins->template_id = TEMPLATE_DIV32;
23455 next = after_lhs(state, ins);
23458 ins->template_id = TEMPLATE_UMUL32;
23461 next = mod_div(state, ins, OP_UDIVT, 0);
23464 next = mod_div(state, ins, OP_SDIVT, 0);
23467 next = mod_div(state, ins, OP_UDIVT, 1);
23470 next = mod_div(state, ins, OP_SDIVT, 1);
23475 ins->template_id = TEMPLATE_SL32_CL;
23476 if (get_imm8(ins, &RHS(ins, 1))) {
23477 ins->template_id = TEMPLATE_SL32_IMM;
23478 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23479 typed_pre_copy(state, &uchar_type, ins, 1);
23484 ins->template_id = TEMPLATE_UNARY32;
23487 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23490 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23493 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23496 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23499 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23502 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23505 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23508 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23511 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23514 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23517 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23520 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23524 ins->template_id = TEMPLATE_NOP;
23527 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23528 RHS(ins, 0)->type, RHS(ins, 0), 0);
23531 ins->template_id = TEMPLATE_NOP;
23534 ins->template_id = TEMPLATE_RET;
23540 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23541 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23542 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23544 if (get_imm8(ins, &RHS(ins, 0))) {
23545 ins->template_id += 1;
23552 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23553 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23554 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23556 if (get_imm8(ins, &RHS(ins, 1))) {
23557 ins->template_id += 1;
23562 ins->template_id = TEMPLATE_BSF;
23565 ins->template_id = TEMPLATE_RDMSR;
23566 next = after_lhs(state, ins);
23569 ins->template_id = TEMPLATE_WRMSR;
23572 ins->template_id = TEMPLATE_NOP;
23575 ins->template_id = TEMPLATE_NOP;
23576 next = after_lhs(state, ins);
23578 /* Already transformed instructions */
23580 ins->template_id = TEMPLATE_TEST32;
23583 ins->template_id = TEMPLATE_CMP32_REG;
23584 if (get_imm32(ins, &RHS(ins, 1))) {
23585 ins->template_id = TEMPLATE_CMP32_IMM;
23589 ins->template_id = TEMPLATE_NOP;
23591 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23592 case OP_JMP_SLESS: case OP_JMP_ULESS:
23593 case OP_JMP_SMORE: case OP_JMP_UMORE:
23594 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23595 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23596 ins->template_id = TEMPLATE_JMP;
23598 case OP_SET_EQ: case OP_SET_NOTEQ:
23599 case OP_SET_SLESS: case OP_SET_ULESS:
23600 case OP_SET_SMORE: case OP_SET_UMORE:
23601 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23602 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23603 ins->template_id = TEMPLATE_SET;
23606 next = x86_deposit(state, ins);
23610 next = x86_extract(state, ins);
23612 /* Unhandled instructions */
23615 internal_error(state, ins, "unhandled ins: %d %s",
23616 ins->op, tops(ins->op));
23622 static long next_label(struct compile_state *state)
23624 static long label_counter = 1000;
23625 return ++label_counter;
23627 static void generate_local_labels(struct compile_state *state)
23629 struct triple *first, *label;
23630 first = state->first;
23633 if ((label->op == OP_LABEL) ||
23634 (label->op == OP_SDECL)) {
23636 label->u.cval = next_label(state);
23642 label = label->next;
23643 } while(label != first);
23646 static int check_reg(struct compile_state *state,
23647 struct triple *triple, int classes)
23651 reg = ID_REG(triple->id);
23652 if (reg == REG_UNSET) {
23653 internal_error(state, triple, "register not set");
23655 mask = arch_reg_regcm(state, reg);
23656 if (!(classes & mask)) {
23657 internal_error(state, triple, "reg %d in wrong class",
23665 #error "Registers have renumberd fix arch_reg_str"
23667 static const char *arch_regs[] = {
23671 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23672 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23673 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23676 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23677 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23678 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23680 static const char *arch_reg_str(int reg)
23682 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23685 return arch_regs[reg];
23688 static const char *reg(struct compile_state *state, struct triple *triple,
23692 reg = check_reg(state, triple, classes);
23693 return arch_reg_str(reg);
23696 static int arch_reg_size(int reg)
23700 if (reg == REG_EFLAGS) {
23703 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23706 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23709 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23712 else if (reg == REG_EDXEAX) {
23715 else if (reg == REG_DXAX) {
23718 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23721 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23727 static int reg_size(struct compile_state *state, struct triple *ins)
23730 reg = ID_REG(ins->id);
23731 if (reg == REG_UNSET) {
23732 internal_error(state, ins, "register not set");
23734 return arch_reg_size(reg);
23739 const char *type_suffix(struct compile_state *state, struct type *type)
23741 const char *suffix;
23742 switch(size_of(state, type)) {
23743 case SIZEOF_I8: suffix = "b"; break;
23744 case SIZEOF_I16: suffix = "w"; break;
23745 case SIZEOF_I32: suffix = "l"; break;
23747 internal_error(state, 0, "unknown suffix");
23754 static void print_const_val(
23755 struct compile_state *state, struct triple *ins, FILE *fp)
23759 fprintf(fp, " $%ld ",
23760 (long)(ins->u.cval));
23763 if ((MISC(ins, 0)->op != OP_SDECL) &&
23764 (MISC(ins, 0)->op != OP_LABEL))
23766 internal_error(state, ins, "bad base for addrconst");
23768 if (MISC(ins, 0)->u.cval <= 0) {
23769 internal_error(state, ins, "unlabeled constant");
23771 fprintf(fp, " $L%s%lu+%lu ",
23772 state->compiler->label_prefix,
23773 (unsigned long)(MISC(ins, 0)->u.cval),
23774 (unsigned long)(ins->u.cval));
23777 internal_error(state, ins, "unknown constant type");
23782 static void print_const(struct compile_state *state,
23783 struct triple *ins, FILE *fp)
23787 switch(ins->type->type & TYPE_MASK) {
23790 fprintf(fp, ".byte 0x%02lx\n",
23791 (unsigned long)(ins->u.cval));
23795 fprintf(fp, ".short 0x%04lx\n",
23796 (unsigned long)(ins->u.cval));
23803 fprintf(fp, ".int %lu\n",
23804 (unsigned long)(ins->u.cval));
23807 fprintf(state->errout, "type: ");
23808 name_of(state->errout, ins->type);
23809 fprintf(state->errout, "\n");
23810 internal_error(state, ins, "Unknown constant type. Val: %lu",
23811 (unsigned long)(ins->u.cval));
23816 if ((MISC(ins, 0)->op != OP_SDECL) &&
23817 (MISC(ins, 0)->op != OP_LABEL)) {
23818 internal_error(state, ins, "bad base for addrconst");
23820 if (MISC(ins, 0)->u.cval <= 0) {
23821 internal_error(state, ins, "unlabeled constant");
23823 fprintf(fp, ".int L%s%lu+%lu\n",
23824 state->compiler->label_prefix,
23825 (unsigned long)(MISC(ins, 0)->u.cval),
23826 (unsigned long)(ins->u.cval));
23830 unsigned char *blob;
23832 size = size_of_in_bytes(state, ins->type);
23833 blob = ins->u.blob;
23834 for(i = 0; i < size; i++) {
23835 fprintf(fp, ".byte 0x%02x\n",
23841 internal_error(state, ins, "Unknown constant type");
23846 #define TEXT_SECTION ".rom.text"
23847 #define DATA_SECTION ".rom.data"
23849 static long get_const_pool_ref(
23850 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23854 ref = next_label(state);
23855 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23856 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23857 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23858 print_const(state, ins, fp);
23859 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23861 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23863 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23867 static long get_mask_pool_ref(
23868 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23871 if (mask == 0xff) {
23874 else if (mask == 0xffff) {
23879 internal_error(state, ins, "unhandled mask value");
23884 static void print_binary_op(struct compile_state *state,
23885 const char *op, struct triple *ins, FILE *fp)
23888 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23889 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23890 internal_error(state, ins, "invalid register assignment");
23892 if (is_const(RHS(ins, 1))) {
23893 fprintf(fp, "\t%s ", op);
23894 print_const_val(state, RHS(ins, 1), fp);
23895 fprintf(fp, ", %s\n",
23896 reg(state, RHS(ins, 0), mask));
23899 unsigned lmask, rmask;
23901 lreg = check_reg(state, RHS(ins, 0), mask);
23902 rreg = check_reg(state, RHS(ins, 1), mask);
23903 lmask = arch_reg_regcm(state, lreg);
23904 rmask = arch_reg_regcm(state, rreg);
23905 mask = lmask & rmask;
23906 fprintf(fp, "\t%s %s, %s\n",
23908 reg(state, RHS(ins, 1), mask),
23909 reg(state, RHS(ins, 0), mask));
23912 static void print_unary_op(struct compile_state *state,
23913 const char *op, struct triple *ins, FILE *fp)
23916 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23917 fprintf(fp, "\t%s %s\n",
23919 reg(state, RHS(ins, 0), mask));
23922 static void print_op_shift(struct compile_state *state,
23923 const char *op, struct triple *ins, FILE *fp)
23926 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23927 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23928 internal_error(state, ins, "invalid register assignment");
23930 if (is_const(RHS(ins, 1))) {
23931 fprintf(fp, "\t%s ", op);
23932 print_const_val(state, RHS(ins, 1), fp);
23933 fprintf(fp, ", %s\n",
23934 reg(state, RHS(ins, 0), mask));
23937 fprintf(fp, "\t%s %s, %s\n",
23939 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23940 reg(state, RHS(ins, 0), mask));
23944 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23951 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23952 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23953 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23955 internal_error(state, ins, "not an in operation");
23959 dreg = check_reg(state, ins, mask);
23960 if (!reg_is_reg(state, dreg, REG_EAX)) {
23961 internal_error(state, ins, "dst != %%eax");
23963 if (is_const(RHS(ins, 0))) {
23964 fprintf(fp, "\t%s ", op);
23965 print_const_val(state, RHS(ins, 0), fp);
23966 fprintf(fp, ", %s\n",
23967 reg(state, ins, mask));
23971 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23972 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23973 internal_error(state, ins, "src != %%dx");
23975 fprintf(fp, "\t%s %s, %s\n",
23977 reg(state, RHS(ins, 0), REGCM_GPR16),
23978 reg(state, ins, mask));
23982 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23989 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23990 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23991 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23993 internal_error(state, ins, "not an out operation");
23997 lreg = check_reg(state, RHS(ins, 0), mask);
23998 if (!reg_is_reg(state, lreg, REG_EAX)) {
23999 internal_error(state, ins, "src != %%eax");
24001 if (is_const(RHS(ins, 1))) {
24002 fprintf(fp, "\t%s %s,",
24003 op, reg(state, RHS(ins, 0), mask));
24004 print_const_val(state, RHS(ins, 1), fp);
24009 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24010 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24011 internal_error(state, ins, "dst != %%dx");
24013 fprintf(fp, "\t%s %s, %s\n",
24015 reg(state, RHS(ins, 0), mask),
24016 reg(state, RHS(ins, 1), REGCM_GPR16));
24020 static void print_op_move(struct compile_state *state,
24021 struct triple *ins, FILE *fp)
24023 /* op_move is complex because there are many types
24024 * of registers we can move between.
24025 * Because OP_COPY will be introduced in arbitrary locations
24026 * OP_COPY must not affect flags.
24027 * OP_CONVERT can change the flags and it is the only operation
24028 * where it is expected the types in the registers can change.
24030 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24031 struct triple *dst, *src;
24032 if (state->arch->features & X86_NOOP_COPY) {
24035 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24040 internal_error(state, ins, "unknown move operation");
24043 if (reg_size(state, dst) < size_of(state, dst->type)) {
24044 internal_error(state, ins, "Invalid destination register");
24046 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24047 fprintf(state->errout, "src type: ");
24048 name_of(state->errout, src->type);
24049 fprintf(state->errout, "\n");
24050 fprintf(state->errout, "dst type: ");
24051 name_of(state->errout, dst->type);
24052 fprintf(state->errout, "\n");
24053 internal_error(state, ins, "Type mismatch for OP_COPY");
24056 if (!is_const(src)) {
24057 int src_reg, dst_reg;
24058 int src_regcm, dst_regcm;
24059 src_reg = ID_REG(src->id);
24060 dst_reg = ID_REG(dst->id);
24061 src_regcm = arch_reg_regcm(state, src_reg);
24062 dst_regcm = arch_reg_regcm(state, dst_reg);
24063 /* If the class is the same just move the register */
24064 if (src_regcm & dst_regcm &
24065 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24066 if ((src_reg != dst_reg) || !omit_copy) {
24067 fprintf(fp, "\tmov %s, %s\n",
24068 reg(state, src, src_regcm),
24069 reg(state, dst, dst_regcm));
24072 /* Move 32bit to 16bit */
24073 else if ((src_regcm & REGCM_GPR32) &&
24074 (dst_regcm & REGCM_GPR16)) {
24075 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24076 if ((src_reg != dst_reg) || !omit_copy) {
24077 fprintf(fp, "\tmovw %s, %s\n",
24078 arch_reg_str(src_reg),
24079 arch_reg_str(dst_reg));
24082 /* Move from 32bit gprs to 16bit gprs */
24083 else if ((src_regcm & REGCM_GPR32) &&
24084 (dst_regcm & REGCM_GPR16)) {
24085 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24086 if ((src_reg != dst_reg) || !omit_copy) {
24087 fprintf(fp, "\tmov %s, %s\n",
24088 arch_reg_str(src_reg),
24089 arch_reg_str(dst_reg));
24092 /* Move 32bit to 8bit */
24093 else if ((src_regcm & REGCM_GPR32_8) &&
24094 (dst_regcm & REGCM_GPR8_LO))
24096 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24097 if ((src_reg != dst_reg) || !omit_copy) {
24098 fprintf(fp, "\tmovb %s, %s\n",
24099 arch_reg_str(src_reg),
24100 arch_reg_str(dst_reg));
24103 /* Move 16bit to 8bit */
24104 else if ((src_regcm & REGCM_GPR16_8) &&
24105 (dst_regcm & REGCM_GPR8_LO))
24107 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24108 if ((src_reg != dst_reg) || !omit_copy) {
24109 fprintf(fp, "\tmovb %s, %s\n",
24110 arch_reg_str(src_reg),
24111 arch_reg_str(dst_reg));
24114 /* Move 8/16bit to 16/32bit */
24115 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24116 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24118 op = is_signed(src->type)? "movsx": "movzx";
24119 fprintf(fp, "\t%s %s, %s\n",
24121 reg(state, src, src_regcm),
24122 reg(state, dst, dst_regcm));
24124 /* Move between sse registers */
24125 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24126 if ((src_reg != dst_reg) || !omit_copy) {
24127 fprintf(fp, "\tmovdqa %s, %s\n",
24128 reg(state, src, src_regcm),
24129 reg(state, dst, dst_regcm));
24132 /* Move between mmx registers */
24133 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24134 if ((src_reg != dst_reg) || !omit_copy) {
24135 fprintf(fp, "\tmovq %s, %s\n",
24136 reg(state, src, src_regcm),
24137 reg(state, dst, dst_regcm));
24140 /* Move from sse to mmx registers */
24141 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24142 fprintf(fp, "\tmovdq2q %s, %s\n",
24143 reg(state, src, src_regcm),
24144 reg(state, dst, dst_regcm));
24146 /* Move from mmx to sse registers */
24147 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24148 fprintf(fp, "\tmovq2dq %s, %s\n",
24149 reg(state, src, src_regcm),
24150 reg(state, dst, dst_regcm));
24152 /* Move between 32bit gprs & mmx/sse registers */
24153 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24154 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24155 fprintf(fp, "\tmovd %s, %s\n",
24156 reg(state, src, src_regcm),
24157 reg(state, dst, dst_regcm));
24159 /* Move from 16bit gprs & mmx/sse registers */
24160 else if ((src_regcm & REGCM_GPR16) &&
24161 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24164 op = is_signed(src->type)? "movsx":"movzx";
24165 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24166 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24168 arch_reg_str(src_reg),
24169 arch_reg_str(mid_reg),
24170 arch_reg_str(mid_reg),
24171 arch_reg_str(dst_reg));
24173 /* Move from mmx/sse registers to 16bit gprs */
24174 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24175 (dst_regcm & REGCM_GPR16)) {
24176 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24177 fprintf(fp, "\tmovd %s, %s\n",
24178 arch_reg_str(src_reg),
24179 arch_reg_str(dst_reg));
24181 /* Move from gpr to 64bit dividend */
24182 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24183 (dst_regcm & REGCM_DIVIDEND64)) {
24184 const char *extend;
24185 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24186 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24187 arch_reg_str(src_reg),
24190 /* Move from 64bit gpr to gpr */
24191 else if ((src_regcm & REGCM_DIVIDEND64) &&
24192 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24193 if (dst_regcm & REGCM_GPR32) {
24196 else if (dst_regcm & REGCM_GPR16) {
24199 else if (dst_regcm & REGCM_GPR8_LO) {
24202 fprintf(fp, "\tmov %s, %s\n",
24203 arch_reg_str(src_reg),
24204 arch_reg_str(dst_reg));
24206 /* Move from mmx/sse registers to 64bit gpr */
24207 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24208 (dst_regcm & REGCM_DIVIDEND64)) {
24209 const char *extend;
24210 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24211 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24212 arch_reg_str(src_reg),
24215 /* Move from 64bit gpr to mmx/sse register */
24216 else if ((src_regcm & REGCM_DIVIDEND64) &&
24217 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24218 fprintf(fp, "\tmovd %%eax, %s\n",
24219 arch_reg_str(dst_reg));
24221 #if X86_4_8BIT_GPRS
24222 /* Move from 8bit gprs to mmx/sse registers */
24223 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24224 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24227 op = is_signed(src->type)? "movsx":"movzx";
24228 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24229 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24231 reg(state, src, src_regcm),
24232 arch_reg_str(mid_reg),
24233 arch_reg_str(mid_reg),
24234 reg(state, dst, dst_regcm));
24236 /* Move from mmx/sse registers and 8bit gprs */
24237 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24238 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24240 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24241 fprintf(fp, "\tmovd %s, %s\n",
24242 reg(state, src, src_regcm),
24243 arch_reg_str(mid_reg));
24245 /* Move from 32bit gprs to 8bit gprs */
24246 else if ((src_regcm & REGCM_GPR32) &&
24247 (dst_regcm & REGCM_GPR8_LO)) {
24248 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24249 if ((src_reg != dst_reg) || !omit_copy) {
24250 fprintf(fp, "\tmov %s, %s\n",
24251 arch_reg_str(src_reg),
24252 arch_reg_str(dst_reg));
24255 /* Move from 16bit gprs to 8bit gprs */
24256 else if ((src_regcm & REGCM_GPR16) &&
24257 (dst_regcm & REGCM_GPR8_LO)) {
24258 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24259 if ((src_reg != dst_reg) || !omit_copy) {
24260 fprintf(fp, "\tmov %s, %s\n",
24261 arch_reg_str(src_reg),
24262 arch_reg_str(dst_reg));
24265 #endif /* X86_4_8BIT_GPRS */
24266 /* Move from %eax:%edx to %eax:%edx */
24267 else if ((src_regcm & REGCM_DIVIDEND64) &&
24268 (dst_regcm & REGCM_DIVIDEND64) &&
24269 (src_reg == dst_reg)) {
24271 fprintf(fp, "\t/*mov %s, %s*/\n",
24272 arch_reg_str(src_reg),
24273 arch_reg_str(dst_reg));
24277 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24278 internal_error(state, ins, "attempt to copy from %%eflags!");
24280 internal_error(state, ins, "unknown copy type");
24287 dst_size = size_of(state, dst->type);
24288 dst_reg = ID_REG(dst->id);
24289 dst_regcm = arch_reg_regcm(state, dst_reg);
24290 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24291 fprintf(fp, "\tmov ");
24292 print_const_val(state, src, fp);
24293 fprintf(fp, ", %s\n",
24294 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24296 else if (dst_regcm & REGCM_DIVIDEND64) {
24297 if (dst_size > SIZEOF_I32) {
24298 internal_error(state, ins, "%dbit constant...", dst_size);
24300 fprintf(fp, "\tmov $0, %%edx\n");
24301 fprintf(fp, "\tmov ");
24302 print_const_val(state, src, fp);
24303 fprintf(fp, ", %%eax\n");
24305 else if (dst_regcm & REGCM_DIVIDEND32) {
24306 if (dst_size > SIZEOF_I16) {
24307 internal_error(state, ins, "%dbit constant...", dst_size);
24309 fprintf(fp, "\tmov $0, %%dx\n");
24310 fprintf(fp, "\tmov ");
24311 print_const_val(state, src, fp);
24312 fprintf(fp, ", %%ax");
24314 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24316 if (dst_size > SIZEOF_I32) {
24317 internal_error(state, ins, "%d bit constant...", dst_size);
24319 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24320 fprintf(fp, "\tmovd L%s%lu, %s\n",
24321 state->compiler->label_prefix, ref,
24322 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24325 internal_error(state, ins, "unknown copy immediate type");
24328 /* Leave now if this is not a type conversion */
24329 if (ins->op != OP_CONVERT) {
24332 /* Now make certain I have not logically overflowed the destination */
24333 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24334 (size_of(state, dst->type) < reg_size(state, dst)))
24336 unsigned long mask;
24339 if (size_of(state, dst->type) >= 32) {
24340 fprintf(state->errout, "dst type: ");
24341 name_of(state->errout, dst->type);
24342 fprintf(state->errout, "\n");
24343 internal_error(state, dst, "unhandled dst type size");
24346 mask <<= size_of(state, dst->type);
24349 dst_reg = ID_REG(dst->id);
24350 dst_regcm = arch_reg_regcm(state, dst_reg);
24352 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24353 fprintf(fp, "\tand $0x%lx, %s\n",
24354 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24356 else if (dst_regcm & REGCM_MMX) {
24358 ref = get_mask_pool_ref(state, dst, mask, fp);
24359 fprintf(fp, "\tpand L%s%lu, %s\n",
24360 state->compiler->label_prefix, ref,
24361 reg(state, dst, REGCM_MMX));
24363 else if (dst_regcm & REGCM_XMM) {
24365 ref = get_mask_pool_ref(state, dst, mask, fp);
24366 fprintf(fp, "\tpand L%s%lu, %s\n",
24367 state->compiler->label_prefix, ref,
24368 reg(state, dst, REGCM_XMM));
24371 fprintf(state->errout, "dst type: ");
24372 name_of(state->errout, dst->type);
24373 fprintf(state->errout, "\n");
24374 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24375 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24378 /* Make certain I am properly sign extended */
24379 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24380 (is_signed(src->type)))
24382 int bits, reg_bits, shift_bits;
24386 bits = size_of(state, src->type);
24387 reg_bits = reg_size(state, dst);
24388 if (reg_bits > 32) {
24391 shift_bits = reg_bits - size_of(state, src->type);
24392 dst_reg = ID_REG(dst->id);
24393 dst_regcm = arch_reg_regcm(state, dst_reg);
24395 if (shift_bits < 0) {
24396 internal_error(state, dst, "negative shift?");
24399 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24400 fprintf(fp, "\tshl $%d, %s\n",
24402 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24403 fprintf(fp, "\tsar $%d, %s\n",
24405 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24407 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24408 fprintf(fp, "\tpslld $%d, %s\n",
24410 reg(state, dst, REGCM_MMX | REGCM_XMM));
24411 fprintf(fp, "\tpsrad $%d, %s\n",
24413 reg(state, dst, REGCM_MMX | REGCM_XMM));
24416 fprintf(state->errout, "dst type: ");
24417 name_of(state->errout, dst->type);
24418 fprintf(state->errout, "\n");
24419 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24420 internal_error(state, dst, "failed to signed extend value");
24425 static void print_op_load(struct compile_state *state,
24426 struct triple *ins, FILE *fp)
24428 struct triple *dst, *src;
24432 if (is_const(src) || is_const(dst)) {
24433 internal_error(state, ins, "unknown load operation");
24435 switch(ins->type->type & TYPE_MASK) {
24436 case TYPE_CHAR: op = "movsbl"; break;
24437 case TYPE_UCHAR: op = "movzbl"; break;
24438 case TYPE_SHORT: op = "movswl"; break;
24439 case TYPE_USHORT: op = "movzwl"; break;
24440 case TYPE_INT: case TYPE_UINT:
24441 case TYPE_LONG: case TYPE_ULONG:
24446 internal_error(state, ins, "unknown type in load");
24447 op = "<invalid opcode>";
24450 fprintf(fp, "\t%s (%s), %s\n",
24452 reg(state, src, REGCM_GPR32),
24453 reg(state, dst, REGCM_GPR32));
24457 static void print_op_store(struct compile_state *state,
24458 struct triple *ins, FILE *fp)
24460 struct triple *dst, *src;
24463 if (is_const(src) && (src->op == OP_INTCONST)) {
24465 value = (long_t)(src->u.cval);
24466 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24467 type_suffix(state, src->type),
24469 reg(state, dst, REGCM_GPR32));
24471 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24472 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24473 type_suffix(state, src->type),
24474 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24475 (unsigned long)(dst->u.cval));
24478 if (is_const(src) || is_const(dst)) {
24479 internal_error(state, ins, "unknown store operation");
24481 fprintf(fp, "\tmov%s %s, (%s)\n",
24482 type_suffix(state, src->type),
24483 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24484 reg(state, dst, REGCM_GPR32));
24490 static void print_op_smul(struct compile_state *state,
24491 struct triple *ins, FILE *fp)
24493 if (!is_const(RHS(ins, 1))) {
24494 fprintf(fp, "\timul %s, %s\n",
24495 reg(state, RHS(ins, 1), REGCM_GPR32),
24496 reg(state, RHS(ins, 0), REGCM_GPR32));
24499 fprintf(fp, "\timul ");
24500 print_const_val(state, RHS(ins, 1), fp);
24501 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24505 static void print_op_cmp(struct compile_state *state,
24506 struct triple *ins, FILE *fp)
24510 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24511 dreg = check_reg(state, ins, REGCM_FLAGS);
24512 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24513 internal_error(state, ins, "bad dest register for cmp");
24515 if (is_const(RHS(ins, 1))) {
24516 fprintf(fp, "\tcmp ");
24517 print_const_val(state, RHS(ins, 1), fp);
24518 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24521 unsigned lmask, rmask;
24523 lreg = check_reg(state, RHS(ins, 0), mask);
24524 rreg = check_reg(state, RHS(ins, 1), mask);
24525 lmask = arch_reg_regcm(state, lreg);
24526 rmask = arch_reg_regcm(state, rreg);
24527 mask = lmask & rmask;
24528 fprintf(fp, "\tcmp %s, %s\n",
24529 reg(state, RHS(ins, 1), mask),
24530 reg(state, RHS(ins, 0), mask));
24534 static void print_op_test(struct compile_state *state,
24535 struct triple *ins, FILE *fp)
24538 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24539 fprintf(fp, "\ttest %s, %s\n",
24540 reg(state, RHS(ins, 0), mask),
24541 reg(state, RHS(ins, 0), mask));
24544 static void print_op_branch(struct compile_state *state,
24545 struct triple *branch, FILE *fp)
24547 const char *bop = "j";
24548 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24549 if (branch->rhs != 0) {
24550 internal_error(state, branch, "jmp with condition?");
24555 struct triple *ptr;
24556 if (branch->rhs != 1) {
24557 internal_error(state, branch, "jmpcc without condition?");
24559 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24560 if ((RHS(branch, 0)->op != OP_CMP) &&
24561 (RHS(branch, 0)->op != OP_TEST)) {
24562 internal_error(state, branch, "bad branch test");
24564 #if DEBUG_ROMCC_WARNINGS
24565 #warning "FIXME I have observed instructions between the test and branch instructions"
24567 ptr = RHS(branch, 0);
24568 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24569 if (ptr->op != OP_COPY) {
24570 internal_error(state, branch, "branch does not follow test");
24573 switch(branch->op) {
24574 case OP_JMP_EQ: bop = "jz"; break;
24575 case OP_JMP_NOTEQ: bop = "jnz"; break;
24576 case OP_JMP_SLESS: bop = "jl"; break;
24577 case OP_JMP_ULESS: bop = "jb"; break;
24578 case OP_JMP_SMORE: bop = "jg"; break;
24579 case OP_JMP_UMORE: bop = "ja"; break;
24580 case OP_JMP_SLESSEQ: bop = "jle"; break;
24581 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24582 case OP_JMP_SMOREEQ: bop = "jge"; break;
24583 case OP_JMP_UMOREEQ: bop = "jae"; break;
24585 internal_error(state, branch, "Invalid branch op");
24591 if (branch->op == OP_CALL) {
24592 fprintf(fp, "\t/* call */\n");
24595 fprintf(fp, "\t%s L%s%lu\n",
24597 state->compiler->label_prefix,
24598 (unsigned long)(TARG(branch, 0)->u.cval));
24601 static void print_op_ret(struct compile_state *state,
24602 struct triple *branch, FILE *fp)
24604 fprintf(fp, "\tjmp *%s\n",
24605 reg(state, RHS(branch, 0), REGCM_GPR32));
24608 static void print_op_set(struct compile_state *state,
24609 struct triple *set, FILE *fp)
24611 const char *sop = "set";
24612 if (set->rhs != 1) {
24613 internal_error(state, set, "setcc without condition?");
24615 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24616 if ((RHS(set, 0)->op != OP_CMP) &&
24617 (RHS(set, 0)->op != OP_TEST)) {
24618 internal_error(state, set, "bad set test");
24620 if (RHS(set, 0)->next != set) {
24621 internal_error(state, set, "set does not follow test");
24624 case OP_SET_EQ: sop = "setz"; break;
24625 case OP_SET_NOTEQ: sop = "setnz"; break;
24626 case OP_SET_SLESS: sop = "setl"; break;
24627 case OP_SET_ULESS: sop = "setb"; break;
24628 case OP_SET_SMORE: sop = "setg"; break;
24629 case OP_SET_UMORE: sop = "seta"; break;
24630 case OP_SET_SLESSEQ: sop = "setle"; break;
24631 case OP_SET_ULESSEQ: sop = "setbe"; break;
24632 case OP_SET_SMOREEQ: sop = "setge"; break;
24633 case OP_SET_UMOREEQ: sop = "setae"; break;
24635 internal_error(state, set, "Invalid set op");
24638 fprintf(fp, "\t%s %s\n",
24639 sop, reg(state, set, REGCM_GPR8_LO));
24642 static void print_op_bit_scan(struct compile_state *state,
24643 struct triple *ins, FILE *fp)
24647 case OP_BSF: op = "bsf"; break;
24648 case OP_BSR: op = "bsr"; break;
24650 internal_error(state, ins, "unknown bit scan");
24660 reg(state, RHS(ins, 0), REGCM_GPR32),
24661 reg(state, ins, REGCM_GPR32),
24662 reg(state, ins, REGCM_GPR32));
24666 static void print_sdecl(struct compile_state *state,
24667 struct triple *ins, FILE *fp)
24669 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24670 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24671 fprintf(fp, "L%s%lu:\n",
24672 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24673 print_const(state, MISC(ins, 0), fp);
24674 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24678 static void print_instruction(struct compile_state *state,
24679 struct triple *ins, FILE *fp)
24681 /* Assumption: after I have exted the register allocator
24682 * everything is in a valid register.
24686 print_op_asm(state, ins, fp);
24688 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24689 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24690 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24691 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24692 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24693 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24694 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24695 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24696 case OP_POS: break;
24697 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24698 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24703 /* Don't generate anything here for constants */
24705 /* Don't generate anything for variable declarations. */
24707 case OP_UNKNOWNVAL:
24708 fprintf(fp, " /* unknown %s */\n",
24709 reg(state, ins, REGCM_ALL));
24712 print_sdecl(state, ins, fp);
24716 print_op_move(state, ins, fp);
24719 print_op_load(state, ins, fp);
24722 print_op_store(state, ins, fp);
24725 print_op_smul(state, ins, fp);
24727 case OP_CMP: print_op_cmp(state, ins, fp); break;
24728 case OP_TEST: print_op_test(state, ins, fp); break;
24730 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24731 case OP_JMP_SLESS: case OP_JMP_ULESS:
24732 case OP_JMP_SMORE: case OP_JMP_UMORE:
24733 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24734 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24736 print_op_branch(state, ins, fp);
24739 print_op_ret(state, ins, fp);
24741 case OP_SET_EQ: case OP_SET_NOTEQ:
24742 case OP_SET_SLESS: case OP_SET_ULESS:
24743 case OP_SET_SMORE: case OP_SET_UMORE:
24744 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24745 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24746 print_op_set(state, ins, fp);
24748 case OP_INB: case OP_INW: case OP_INL:
24749 print_op_in(state, ins, fp);
24751 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24752 print_op_out(state, ins, fp);
24756 print_op_bit_scan(state, ins, fp);
24759 after_lhs(state, ins);
24760 fprintf(fp, "\trdmsr\n");
24763 fprintf(fp, "\twrmsr\n");
24766 fprintf(fp, "\thlt\n");
24769 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24772 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24775 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24781 fprintf(fp, "L%s%lu:\n",
24782 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24785 /* Ignore adecls with no registers error otherwise */
24786 if (!noop_adecl(ins)) {
24787 internal_error(state, ins, "adecl remains?");
24790 /* Ignore OP_PIECE */
24793 /* Operations that should never get here */
24794 case OP_SDIV: case OP_UDIV:
24795 case OP_SMOD: case OP_UMOD:
24796 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24797 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24798 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24800 internal_error(state, ins, "unknown op: %d %s",
24801 ins->op, tops(ins->op));
24806 static void print_instructions(struct compile_state *state)
24808 struct triple *first, *ins;
24809 int print_location;
24810 struct occurance *last_occurance;
24812 int max_inline_depth;
24813 max_inline_depth = 0;
24814 print_location = 1;
24815 last_occurance = 0;
24816 fp = state->output;
24817 /* Masks for common sizes */
24818 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24819 fprintf(fp, ".balign 16\n");
24820 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24821 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24822 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24823 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24824 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24825 first = state->first;
24828 if (print_location &&
24829 last_occurance != ins->occurance) {
24830 if (!ins->occurance->parent) {
24831 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24832 ins->occurance->function?ins->occurance->function:"(null)",
24833 ins->occurance->filename?ins->occurance->filename:"(null)",
24834 ins->occurance->line,
24835 ins->occurance->col);
24838 struct occurance *ptr;
24840 fprintf(fp, "\t/*\n");
24842 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24844 fprintf(fp, "\t * %s,%s:%d.%d\n",
24850 fprintf(fp, "\t */\n");
24851 if (inline_depth > max_inline_depth) {
24852 max_inline_depth = inline_depth;
24855 if (last_occurance) {
24856 put_occurance(last_occurance);
24858 get_occurance(ins->occurance);
24859 last_occurance = ins->occurance;
24862 print_instruction(state, ins, fp);
24864 } while(ins != first);
24865 if (print_location) {
24866 fprintf(fp, "/* max inline depth %d */\n",
24871 static void generate_code(struct compile_state *state)
24873 generate_local_labels(state);
24874 print_instructions(state);
24878 static void print_preprocessed_tokens(struct compile_state *state)
24883 const char *filename;
24884 fp = state->output;
24888 struct file_state *file;
24890 const char *token_str;
24892 if (tok == TOK_EOF) {
24895 tk = eat(state, tok);
24897 tk->ident ? tk->ident->name :
24898 tk->str_len ? tk->val.str :
24901 file = state->file;
24902 while(file->macro && file->prev) {
24905 if (!file->macro &&
24906 ((file->line != line) || (file->basename != filename)))
24909 if ((file->basename == filename) &&
24910 (line < file->line)) {
24911 while(line < file->line) {
24917 fprintf(fp, "\n#line %d \"%s\"\n",
24918 file->line, file->basename);
24921 filename = file->basename;
24922 col = get_col(file) - strlen(token_str);
24923 for(i = 0; i < col; i++) {
24928 fprintf(fp, "%s ", token_str);
24930 if (state->compiler->debug & DEBUG_TOKENS) {
24931 loc(state->dbgout, state, 0);
24932 fprintf(state->dbgout, "%s <- `%s'\n",
24933 tokens[tok], token_str);
24938 static void compile(const char *filename,
24939 struct compiler_state *compiler, struct arch_state *arch)
24942 struct compile_state state;
24943 struct triple *ptr;
24944 struct filelist *includes = include_filelist;
24945 memset(&state, 0, sizeof(state));
24946 state.compiler = compiler;
24949 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24950 memset(&state.token[i], 0, sizeof(state.token[i]));
24951 state.token[i].tok = -1;
24953 /* Remember the output descriptors */
24954 state.errout = stderr;
24955 state.dbgout = stdout;
24956 /* Remember the output filename */
24957 state.output = fopen(state.compiler->ofilename, "w");
24958 if (!state.output) {
24959 error(&state, 0, "Cannot open output file %s\n",
24960 state.compiler->ofilename);
24962 /* Make certain a good cleanup happens */
24963 exit_state = &state;
24964 atexit(exit_cleanup);
24966 /* Prep the preprocessor */
24967 state.if_depth = 0;
24968 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24969 /* register the C keywords */
24970 register_keywords(&state);
24971 /* register the keywords the macro preprocessor knows */
24972 register_macro_keywords(&state);
24973 /* generate some builtin macros */
24974 register_builtin_macros(&state);
24975 /* Memorize where some special keywords are. */
24976 state.i_switch = lookup(&state, "switch", 6);
24977 state.i_case = lookup(&state, "case", 4);
24978 state.i_continue = lookup(&state, "continue", 8);
24979 state.i_break = lookup(&state, "break", 5);
24980 state.i_default = lookup(&state, "default", 7);
24981 state.i_return = lookup(&state, "return", 6);
24982 /* Memorize where predefined macros are. */
24983 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24984 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24985 state.i___LINE__ = lookup(&state, "__LINE__", 8);
24986 /* Memorize where predefined identifiers are. */
24987 state.i___func__ = lookup(&state, "__func__", 8);
24988 /* Memorize where some attribute keywords are. */
24989 state.i_noinline = lookup(&state, "noinline", 8);
24990 state.i_always_inline = lookup(&state, "always_inline", 13);
24992 /* Process the command line macros */
24993 process_cmdline_macros(&state);
24995 /* Allocate beginning bounding labels for the function list */
24996 state.first = label(&state);
24997 state.first->id |= TRIPLE_FLAG_VOLATILE;
24998 use_triple(state.first, state.first);
24999 ptr = label(&state);
25000 ptr->id |= TRIPLE_FLAG_VOLATILE;
25001 use_triple(ptr, ptr);
25002 flatten(&state, state.first, ptr);
25004 /* Allocate a label for the pool of global variables */
25005 state.global_pool = label(&state);
25006 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
25007 flatten(&state, state.first, state.global_pool);
25009 /* Enter the globl definition scope */
25010 start_scope(&state);
25011 register_builtins(&state);
25013 compile_file(&state, filename, 1);
25016 compile_file(&state, includes->filename, 1);
25017 includes=includes->next;
25020 /* Stop if all we want is preprocessor output */
25021 if (state.compiler->flags & COMPILER_PP_ONLY) {
25022 print_preprocessed_tokens(&state);
25028 /* Exit the global definition scope */
25031 /* Now that basic compilation has happened
25032 * optimize the intermediate code
25036 generate_code(&state);
25037 if (state.compiler->debug) {
25038 fprintf(state.errout, "done\n");
25043 static void version(FILE *fp)
25045 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25048 static void usage(void)
25053 "\nUsage: romcc [options] <source>.c\n"
25054 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25056 "-o <output file name>\n"
25057 "-f<option> Specify a generic compiler option\n"
25058 "-m<option> Specify a arch dependent option\n"
25059 "-- Specify this is the last option\n"
25060 "\nGeneric compiler options:\n"
25062 compiler_usage(fp);
25064 "\nArchitecture compiler options:\n"
25072 static void arg_error(char *fmt, ...)
25075 va_start(args, fmt);
25076 vfprintf(stderr, fmt, args);
25082 int main(int argc, char **argv)
25084 const char *filename;
25085 struct compiler_state compiler;
25086 struct arch_state arch;
25090 /* I don't want any surprises */
25091 setlocale(LC_ALL, "C");
25093 init_compiler_state(&compiler);
25094 init_arch_state(&arch);
25098 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25099 compiler.ofilename = argv[2];
25103 else if (!all_opts && argv[1][0] == '-') {
25106 if (strcmp(argv[1], "--") == 0) {
25110 else if (strncmp(argv[1], "-E", 2) == 0) {
25111 result = compiler_encode_flag(&compiler, argv[1]);
25113 else if (strncmp(argv[1], "-O", 2) == 0) {
25114 result = compiler_encode_flag(&compiler, argv[1]);
25116 else if (strncmp(argv[1], "-I", 2) == 0) {
25117 result = compiler_encode_flag(&compiler, argv[1]);
25119 else if (strncmp(argv[1], "-D", 2) == 0) {
25120 result = compiler_encode_flag(&compiler, argv[1]);
25122 else if (strncmp(argv[1], "-U", 2) == 0) {
25123 result = compiler_encode_flag(&compiler, argv[1]);
25125 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25126 result = compiler_encode_flag(&compiler, argv[1]+2);
25128 else if (strncmp(argv[1], "-f", 2) == 0) {
25129 result = compiler_encode_flag(&compiler, argv[1]+2);
25131 else if (strncmp(argv[1], "-m", 2) == 0) {
25132 result = arch_encode_flag(&arch, argv[1]+2);
25134 else if (strncmp(argv[1], "-include", 10) == 0) {
25135 struct filelist *old_head = include_filelist;
25136 include_filelist = malloc(sizeof(struct filelist));
25137 if (!include_filelist) {
25138 die("Out of memory.\n");
25142 include_filelist->filename = argv[1];
25143 include_filelist->next = old_head;
25147 arg_error("Invalid option specified: %s\n",
25155 arg_error("Only one filename may be specified\n");
25157 filename = argv[1];
25163 arg_error("No filename specified\n");
25165 compile(filename, &compiler, &arch);