5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "71"
7 #define RELEASE_DATE "03 April 2009"
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.
130 static void die(char *fmt, ...)
135 vfprintf(stderr, fmt, args);
142 static void *xmalloc(size_t size, const char *name)
147 die("Cannot malloc %ld bytes to hold %s: %s\n",
148 size + 0UL, name, strerror(errno));
153 static void *xcmalloc(size_t size, const char *name)
156 buf = xmalloc(size, name);
157 memset(buf, 0, size);
161 static void *xrealloc(void *ptr, size_t size, const char *name)
164 buf = realloc(ptr, size);
166 die("Cannot realloc %ld bytes to hold %s: %s\n",
167 size + 0UL, name, strerror(errno));
172 static void xfree(const void *ptr)
177 static char *xstrdup(const char *str)
182 new = xmalloc(len + 1, "xstrdup string");
183 memcpy(new, str, len);
188 static void xchdir(const char *path)
190 if (chdir(path) != 0) {
191 die("chdir to `%s' failed: %s\n",
192 path, strerror(errno));
196 static int exists(const char *dirname, const char *filename)
198 char cwd[MAX_CWD_SIZE];
201 if (getcwd(cwd, sizeof(cwd)) == 0) {
202 die("cwd buffer to small");
206 if (chdir(dirname) != 0) {
209 if (does_exist && (access(filename, O_RDONLY) < 0)) {
210 if ((errno != EACCES) && (errno != EROFS)) {
219 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
221 char cwd[MAX_CWD_SIZE];
223 off_t size, progress;
231 if (getcwd(cwd, sizeof(cwd)) == 0) {
232 die("cwd buffer to small");
235 file = fopen(filename, "rb");
238 die("Cannot open '%s' : %s\n",
239 filename, strerror(errno));
241 fseek(file, 0, SEEK_END);
243 fseek(file, 0, SEEK_SET);
245 buf = xmalloc(size +2, filename);
246 buf[size] = '\n'; /* Make certain the file is newline terminated */
247 buf[size+1] = '\0'; /* Null terminate the file for good measure */
249 while(progress < size) {
250 result = fread(buf + progress, 1, size - progress, file);
252 if ((errno == EINTR) || (errno == EAGAIN))
254 die("read on %s of %ld bytes failed: %s\n",
255 filename, (size - progress)+ 0UL, strerror(errno));
263 /* Types on the destination platform */
264 #if DEBUG_ROMCC_WARNINGS
265 #warning "FIXME this assumes 32bit x86 is the destination"
267 typedef int8_t schar_t;
268 typedef uint8_t uchar_t;
269 typedef int8_t char_t;
270 typedef int16_t short_t;
271 typedef uint16_t ushort_t;
272 typedef int32_t int_t;
273 typedef uint32_t uint_t;
274 typedef int32_t long_t;
275 #define ulong_t uint32_t
277 #define SCHAR_T_MIN (-128)
278 #define SCHAR_T_MAX 127
279 #define UCHAR_T_MAX 255
280 #define CHAR_T_MIN SCHAR_T_MIN
281 #define CHAR_T_MAX SCHAR_T_MAX
282 #define SHRT_T_MIN (-32768)
283 #define SHRT_T_MAX 32767
284 #define USHRT_T_MAX 65535
285 #define INT_T_MIN (-LONG_T_MAX - 1)
286 #define INT_T_MAX 2147483647
287 #define UINT_T_MAX 4294967295U
288 #define LONG_T_MIN (-LONG_T_MAX - 1)
289 #define LONG_T_MAX 2147483647
290 #define ULONG_T_MAX 4294967295U
293 #define SIZEOF_I16 16
294 #define SIZEOF_I32 32
295 #define SIZEOF_I64 64
297 #define SIZEOF_CHAR 8
298 #define SIZEOF_SHORT 16
299 #define SIZEOF_INT 32
300 #define SIZEOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
303 #define ALIGNOF_CHAR 8
304 #define ALIGNOF_SHORT 16
305 #define ALIGNOF_INT 32
306 #define ALIGNOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
308 #define REG_SIZEOF_REG 32
309 #define REG_SIZEOF_CHAR REG_SIZEOF_REG
310 #define REG_SIZEOF_SHORT REG_SIZEOF_REG
311 #define REG_SIZEOF_INT REG_SIZEOF_REG
312 #define REG_SIZEOF_LONG REG_SIZEOF_REG
314 #define REG_ALIGNOF_REG REG_SIZEOF_REG
315 #define REG_ALIGNOF_CHAR REG_SIZEOF_REG
316 #define REG_ALIGNOF_SHORT REG_SIZEOF_REG
317 #define REG_ALIGNOF_INT REG_SIZEOF_REG
318 #define REG_ALIGNOF_LONG REG_SIZEOF_REG
320 /* Additional definitions for clarity.
321 * I currently assume a long is the largest native
322 * machine word and that a pointer fits into it.
324 #define SIZEOF_WORD SIZEOF_LONG
325 #define SIZEOF_POINTER SIZEOF_LONG
326 #define ALIGNOF_WORD ALIGNOF_LONG
327 #define ALIGNOF_POINTER ALIGNOF_LONG
328 #define REG_SIZEOF_POINTER REG_SIZEOF_LONG
329 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
332 struct file_state *prev;
333 const char *basename;
339 const char *line_start;
341 const char *report_name;
342 const char *report_dir;
350 struct hash_entry *ident;
360 /* I have two classes of types:
362 * Logical types. (The type the C standard says the operation is of)
364 * The operational types are:
379 * No memory is useable by the compiler.
380 * There is no floating point support.
381 * All operations take place in general purpose registers.
382 * There is one type of general purpose register.
383 * Unsigned longs are stored in that general purpose register.
386 /* Operations on general purpose registers.
405 #define OP_POS 16 /* Dummy positive operator don't use it */
415 #define OP_SLESSEQ 26
416 #define OP_ULESSEQ 27
417 #define OP_SMOREEQ 28
418 #define OP_UMOREEQ 29
420 #define OP_LFALSE 30 /* Test if the expression is logically false */
421 #define OP_LTRUE 31 /* Test if the expression is logcially true */
425 /* For OP_STORE ->type holds the type
426 * RHS(0) holds the destination address
427 * RHS(1) holds the value to store.
430 #define OP_UEXTRACT 34
431 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
432 * RHS(0) holds the psuedo register to extract from
433 * ->type holds the size of the bitfield.
434 * ->u.bitfield.size holds the size of the bitfield.
435 * ->u.bitfield.offset holds the offset to extract from
437 #define OP_SEXTRACT 35
438 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
439 * RHS(0) holds the psuedo register to extract from
440 * ->type holds the size of the bitfield.
441 * ->u.bitfield.size holds the size of the bitfield.
442 * ->u.bitfield.offset holds the offset to extract from
444 #define OP_DEPOSIT 36
445 /* OP_DEPOSIT replaces a bitfield with a new value.
446 * RHS(0) holds the value to replace a bitifield in.
447 * RHS(1) holds the replacement value
448 * ->u.bitfield.size holds the size of the bitfield.
449 * ->u.bitfield.offset holds the deposit into
454 #define OP_MIN_CONST 50
455 #define OP_MAX_CONST 58
456 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
457 #define OP_INTCONST 50
458 /* For OP_INTCONST ->type holds the type.
459 * ->u.cval holds the constant value.
461 #define OP_BLOBCONST 51
462 /* For OP_BLOBCONST ->type holds the layout and size
463 * information. u.blob holds a pointer to the raw binary
464 * data for the constant initializer.
466 #define OP_ADDRCONST 52
467 /* For OP_ADDRCONST ->type holds the type.
468 * MISC(0) holds the reference to the static variable.
469 * ->u.cval holds an offset from that value.
471 #define OP_UNKNOWNVAL 59
472 /* For OP_UNKNOWNAL ->type holds the type.
473 * For some reason we don't know what value this type has.
474 * This allows for variables that have don't have values
475 * assigned yet, or variables whose value we simply do not know.
479 /* OP_WRITE moves one pseudo register to another.
480 * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
481 * RHS(0) holds the psuedo to move.
485 /* OP_READ reads the value of a variable and makes
486 * it available for the pseudo operation.
487 * Useful for things like def-use chains.
488 * RHS(0) holds points to the triple to read from.
491 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
493 #define OP_CONVERT 63
494 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
495 * And then the type is converted appropriately.
498 /* OP_PIECE returns one piece of a instruction that returns a structure.
499 * MISC(0) is the instruction
500 * u.cval is the LHS piece of the instruction to return.
503 /* OP_ASM holds a sequence of assembly instructions, the result
504 * of a C asm directive.
505 * RHS(x) holds input value x to the assembly sequence.
506 * LHS(x) holds the output value x from the assembly sequence.
507 * u.blob holds the string of assembly instructions.
511 /* OP_DEREF generates an lvalue from a pointer.
512 * RHS(0) holds the pointer value.
513 * OP_DEREF serves as a place holder to indicate all necessary
514 * checks have been done to indicate a value is an lvalue.
517 /* OP_DOT references a submember of a structure lvalue.
518 * MISC(0) holds the lvalue.
519 * ->u.field holds the name of the field we want.
521 * Not seen after structures are flattened.
524 /* OP_INDEX references a submember of a tuple or array lvalue.
525 * MISC(0) holds the lvalue.
526 * ->u.cval holds the index into the lvalue.
528 * Not seen after structures are flattened.
531 /* OP_VAL returns the value of a subexpression of the current expression.
532 * Useful for operators that have side effects.
533 * RHS(0) holds the expression.
534 * MISC(0) holds the subexpression of RHS(0) that is the
535 * value of the expression.
537 * Not seen outside of expressions.
541 /* OP_TUPLE is an array of triples that are either variable
542 * or values for a structure or an array. It is used as
543 * a place holder when flattening compound types.
544 * The value represented by an OP_TUPLE is held in N registers.
545 * LHS(0..N-1) refer to those registers.
546 * ->use is a list of statements that use the value.
548 * Although OP_TUPLE always has register sized pieces they are not
549 * used until structures are flattened/decomposed into their register
551 * ???? registers ????
555 /* OP_BITREF describes a bitfield as an lvalue.
556 * RHS(0) holds the register value.
557 * ->type holds the type of the bitfield.
558 * ->u.bitfield.size holds the size of the bitfield.
559 * ->u.bitfield.offset holds the offset of the bitfield in the register
564 /* OP_FCALL performs a procedure call.
565 * MISC(0) holds a pointer to the OP_LIST of a function
566 * RHS(x) holds argument x of a function
568 * Currently not seen outside of expressions.
571 /* OP_PROG is an expression that holds a list of statements, or
572 * expressions. The final expression is the value of the expression.
573 * RHS(0) holds the start of the list.
578 /* OP_LIST Holds a list of statements that compose a function, and a result value.
579 * RHS(0) holds the list of statements.
580 * A list of all functions is maintained.
583 #define OP_BRANCH 81 /* an unconditional branch */
584 /* For branch instructions
585 * TARG(0) holds the branch target.
586 * ->next holds where to branch to if the branch is not taken.
587 * The branch target can only be a label
590 #define OP_CBRANCH 82 /* a conditional branch */
591 /* For conditional branch instructions
592 * RHS(0) holds the branch condition.
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_CALL 83 /* an uncontional branch that will return */
599 /* For call instructions
600 * MISC(0) holds the OP_RET that returns from the branch
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_RET 84 /* an uncontinonal branch through a variable back to an OP_CALL */
607 /* For call instructions
608 * RHS(0) holds the variable with the return address
609 * The branch target can only be a label
613 /* OP_LABEL is a triple that establishes an target for branches.
614 * ->use is the list of all branches that use this label.
618 /* OP_ADECL is a triple that establishes an lvalue for assignments.
619 * A variable takes N registers to contain.
620 * LHS(0..N-1) refer to an OP_PIECE triple that represents
621 * the Xth register that the variable is stored in.
622 * ->use is a list of statements that use the variable.
624 * Although OP_ADECL always has register sized pieces they are not
625 * used until structures are flattened/decomposed into their register
630 /* OP_SDECL is a triple that establishes a variable of static
632 * ->use is a list of statements that use the variable.
633 * MISC(0) holds the initializer expression.
638 /* OP_PHI is a triple used in SSA form code.
639 * It is used when multiple code paths merge and a variable needs
640 * a single assignment from any of those code paths.
641 * The operation is a cross between OP_DECL and OP_WRITE, which
642 * is what OP_PHI is generated from.
644 * RHS(x) points to the value from code path x
645 * The number of RHS entries is the number of control paths into the block
646 * in which OP_PHI resides. The elements of the array point to point
647 * to the variables OP_PHI is derived from.
649 * MISC(0) holds a pointer to the orginal OP_DECL node.
653 /* continuation helpers
655 #define OP_CPS_BRANCH 90 /* an unconditional branch */
656 /* OP_CPS_BRANCH calls a continuation
657 * RHS(x) holds argument x of the function
658 * TARG(0) holds OP_CPS_START target
660 #define OP_CPS_CBRANCH 91 /* a conditional branch */
661 /* OP_CPS_CBRANCH conditionally calls one of two continuations
662 * RHS(0) holds the branch condition
663 * RHS(x + 1) holds argument x of the function
664 * TARG(0) holds the OP_CPS_START to jump to when true
665 * ->next holds the OP_CPS_START to jump to when false
667 #define OP_CPS_CALL 92 /* an uncontional branch that will return */
668 /* For OP_CPS_CALL instructions
669 * RHS(x) holds argument x of the function
670 * MISC(0) holds the OP_CPS_RET that returns from the branch
671 * TARG(0) holds the branch target.
672 * ->next holds where the OP_CPS_RET will return to.
674 #define OP_CPS_RET 93
675 /* OP_CPS_RET conditionally calls one of two continuations
676 * RHS(0) holds the variable with the return function address
677 * RHS(x + 1) holds argument x of the function
678 * The branch target may be any OP_CPS_START
680 #define OP_CPS_END 94
681 /* OP_CPS_END is the triple at the end of the program.
682 * For most practical purposes it is a branch.
684 #define OP_CPS_START 95
685 /* OP_CPS_START is a triple at the start of a continuation
686 * The arguments variables takes N registers to contain.
687 * LHS(0..N-1) refer to an OP_PIECE triple that represents
688 * the Xth register that the arguments are stored in.
692 /* Architecture specific instructions */
695 #define OP_SET_EQ 102
696 #define OP_SET_NOTEQ 103
697 #define OP_SET_SLESS 104
698 #define OP_SET_ULESS 105
699 #define OP_SET_SMORE 106
700 #define OP_SET_UMORE 107
701 #define OP_SET_SLESSEQ 108
702 #define OP_SET_ULESSEQ 109
703 #define OP_SET_SMOREEQ 110
704 #define OP_SET_UMOREEQ 111
707 #define OP_JMP_EQ 113
708 #define OP_JMP_NOTEQ 114
709 #define OP_JMP_SLESS 115
710 #define OP_JMP_ULESS 116
711 #define OP_JMP_SMORE 117
712 #define OP_JMP_UMORE 118
713 #define OP_JMP_SLESSEQ 119
714 #define OP_JMP_ULESSEQ 120
715 #define OP_JMP_SMOREEQ 121
716 #define OP_JMP_UMOREEQ 122
718 /* Builtin operators that it is just simpler to use the compiler for */
734 #define PURE 0x001 /* Triple has no side effects */
735 #define IMPURE 0x002 /* Triple has side effects */
736 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
737 #define DEF 0x004 /* Triple is a variable definition */
738 #define BLOCK 0x008 /* Triple stores the current block */
739 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
740 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
741 #define UBRANCH 0x020 /* Triple is an unconditional branch instruction */
742 #define CBRANCH 0x040 /* Triple is a conditional branch instruction */
743 #define RETBRANCH 0x060 /* Triple is a return instruction */
744 #define CALLBRANCH 0x080 /* Triple is a call instruction */
745 #define ENDBRANCH 0x0a0 /* Triple is an end instruction */
746 #define PART 0x100 /* Triple is really part of another triple */
747 #define BITFIELD 0x200 /* Triple manipulates a bitfield */
748 signed char lhs, rhs, misc, targ;
751 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
759 static const struct op_info table_ops[] = {
760 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
761 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
762 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
763 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
764 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
765 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
766 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
767 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
768 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
769 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
770 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
771 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
772 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
773 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
774 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
775 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
776 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
777 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
778 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
780 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
781 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
782 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
783 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
784 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
785 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
786 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
787 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
788 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
789 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
790 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
791 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
793 [OP_LOAD ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "load"),
794 [OP_STORE ] = OP( 0, 2, 0, 0, PURE | BLOCK , "store"),
796 [OP_UEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
797 [OP_SEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
798 [OP_DEPOSIT ] = OP( 0, 2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
800 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
802 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
803 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE , "blobconst"),
804 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
805 [OP_UNKNOWNVAL ] = OP( 0, 0, 0, 0, PURE | DEF, "unknown"),
807 #if DEBUG_ROMCC_WARNINGS
808 #warning "FIXME is it correct for OP_WRITE to be a def? I currently use it as one..."
810 [OP_WRITE ] = OP( 0, 1, 1, 0, PURE | DEF | BLOCK, "write"),
811 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
812 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
813 [OP_CONVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "convert"),
814 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
815 [OP_ASM ] = OP(-1, -1, 0, 0, PURE, "asm"),
816 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
817 [OP_DOT ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "dot"),
818 [OP_INDEX ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "index"),
820 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
821 [OP_TUPLE ] = OP(-1, 0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
822 [OP_BITREF ] = OP( 0, 1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
823 /* Call is special most it can stand in for anything so it depends on context */
824 [OP_FCALL ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
825 [OP_PROG ] = OP( 0, 1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
826 /* The sizes of OP_FCALL depends upon context */
828 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
829 [OP_BRANCH ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
830 [OP_CBRANCH ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
831 [OP_CALL ] = OP( 0, 0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
832 [OP_RET ] = OP( 0, 1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
833 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
834 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
835 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
836 /* The number of RHS elements of OP_PHI depend upon context */
837 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
840 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH, "cps_branch"),
841 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH, "cps_cbranch"),
842 [OP_CPS_CALL ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH, "cps_call"),
843 [OP_CPS_RET ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH, "cps_ret"),
844 [OP_CPS_END ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
845 [OP_CPS_START ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "cps_start"),
848 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
849 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
850 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
851 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
852 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
853 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
854 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
855 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
856 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
857 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
858 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
859 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
860 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
861 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
862 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
863 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
864 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
865 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
866 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
867 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
868 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
869 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
870 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
872 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
873 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
874 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
875 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
876 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
877 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
878 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
879 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
880 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
881 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
882 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
885 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
887 static const char *tops(int index)
889 static const char unknown[] = "unknown op";
893 if (index > OP_MAX) {
896 return table_ops[index].name;
903 struct triple_set *next;
904 struct triple *member;
914 const char *filename;
915 const char *function;
918 struct occurance *parent;
925 struct triple *next, *prev;
926 struct triple_set *use;
929 unsigned int template_id : 7;
930 unsigned int lhs : 6;
931 unsigned int rhs : 7;
932 unsigned int misc : 2;
933 unsigned int targ : 1;
934 #define TRIPLE_SIZE(TRIPLE) \
935 ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
936 #define TRIPLE_LHS_OFF(PTR) (0)
937 #define TRIPLE_RHS_OFF(PTR) (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
938 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
939 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
940 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
941 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
942 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
943 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
944 unsigned id; /* A scratch value and finally the register */
945 #define TRIPLE_FLAG_FLATTENED (1 << 31)
946 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
947 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
948 #define TRIPLE_FLAG_VOLATILE (1 << 28)
949 #define TRIPLE_FLAG_INLINE (1 << 27) /* ???? */
950 #define TRIPLE_FLAG_LOCAL (1 << 26)
952 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
953 struct occurance *occurance;
956 struct bitfield bitfield;
959 struct hash_entry *field;
960 struct asm_info *ainfo;
962 struct symbol *symbol;
964 struct triple *param[2];
971 struct ins_template {
972 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
976 struct ins_template tmpl;
981 struct block_set *next;
982 struct block *member;
985 struct block *work_next;
986 struct triple *first, *last;
988 struct block_set *edges;
990 struct block_set *use;
991 struct block_set *idominates;
992 struct block_set *domfrontier;
994 struct block_set *ipdominates;
995 struct block_set *ipdomfrontier;
1002 struct symbol *next;
1003 struct hash_entry *ident;
1010 struct macro_arg *next;
1011 struct hash_entry *ident;
1014 struct hash_entry *ident;
1017 struct macro_arg *args;
1022 struct hash_entry *next;
1026 struct macro *sym_define;
1027 struct symbol *sym_label;
1028 struct symbol *sym_tag;
1029 struct symbol *sym_ident;
1032 #define HASH_TABLE_SIZE 2048
1034 struct compiler_state {
1035 const char *label_prefix;
1036 const char *ofilename;
1037 unsigned long flags;
1038 unsigned long debug;
1039 unsigned long max_allocation_passes;
1041 size_t include_path_count;
1042 const char **include_paths;
1044 size_t define_count;
1045 const char **defines;
1048 const char **undefs;
1051 unsigned long features;
1053 struct basic_blocks {
1054 struct triple *func;
1055 struct triple *first;
1056 struct block *first_block, *last_block;
1059 #define MAX_PP_IF_DEPTH 63
1060 struct compile_state {
1061 struct compiler_state *compiler;
1062 struct arch_state *arch;
1066 struct file_state *file;
1067 struct occurance *last_occurance;
1068 const char *function;
1070 struct token token[6];
1071 struct hash_entry *hash_table[HASH_TABLE_SIZE];
1072 struct hash_entry *i_switch;
1073 struct hash_entry *i_case;
1074 struct hash_entry *i_continue;
1075 struct hash_entry *i_break;
1076 struct hash_entry *i_default;
1077 struct hash_entry *i_return;
1078 /* Additional hash entries for predefined macros */
1079 struct hash_entry *i_defined;
1080 struct hash_entry *i___VA_ARGS__;
1081 struct hash_entry *i___FILE__;
1082 struct hash_entry *i___LINE__;
1083 /* Additional hash entries for predefined identifiers */
1084 struct hash_entry *i___func__;
1085 /* Additional hash entries for attributes */
1086 struct hash_entry *i_noinline;
1087 struct hash_entry *i_always_inline;
1089 unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1091 int eat_depth, eat_targ;
1092 struct file_state *macro_file;
1093 struct triple *functions;
1094 struct triple *main_function;
1095 struct triple *first;
1096 struct triple *global_pool;
1097 struct basic_blocks bb;
1098 int functions_joined;
1101 /* visibility global/local */
1102 /* static/auto duration */
1103 /* typedef, register, inline */
1104 #define STOR_SHIFT 0
1105 #define STOR_MASK 0x001f
1107 #define STOR_GLOBAL 0x0001
1109 #define STOR_PERM 0x0002
1110 /* Definition locality */
1111 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1112 /* Storage specifiers */
1113 #define STOR_AUTO 0x0000
1114 #define STOR_STATIC 0x0002
1115 #define STOR_LOCAL 0x0003
1116 #define STOR_EXTERN 0x0007
1117 #define STOR_INLINE 0x0008
1118 #define STOR_REGISTER 0x0010
1119 #define STOR_TYPEDEF 0x0018
1121 #define QUAL_SHIFT 5
1122 #define QUAL_MASK 0x00e0
1123 #define QUAL_NONE 0x0000
1124 #define QUAL_CONST 0x0020
1125 #define QUAL_VOLATILE 0x0040
1126 #define QUAL_RESTRICT 0x0080
1128 #define TYPE_SHIFT 8
1129 #define TYPE_MASK 0x1f00
1130 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1131 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1132 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1133 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1134 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1135 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1136 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1137 #define TYPE_DEFAULT 0x0000
1138 #define TYPE_VOID 0x0100
1139 #define TYPE_CHAR 0x0200
1140 #define TYPE_UCHAR 0x0300
1141 #define TYPE_SHORT 0x0400
1142 #define TYPE_USHORT 0x0500
1143 #define TYPE_INT 0x0600
1144 #define TYPE_UINT 0x0700
1145 #define TYPE_LONG 0x0800
1146 #define TYPE_ULONG 0x0900
1147 #define TYPE_LLONG 0x0a00 /* long long */
1148 #define TYPE_ULLONG 0x0b00
1149 #define TYPE_FLOAT 0x0c00
1150 #define TYPE_DOUBLE 0x0d00
1151 #define TYPE_LDOUBLE 0x0e00 /* long double */
1153 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1154 #define TYPE_ENUM 0x1600
1155 #define TYPE_LIST 0x1700
1156 /* TYPE_LIST is a basic building block when defining enumerations
1157 * type->field_ident holds the name of this enumeration entry.
1158 * type->right holds the entry in the list.
1161 #define TYPE_STRUCT 0x1000
1163 * type->left holds the link list of TYPE_PRODUCT entries that
1164 * make up the structure.
1165 * type->elements hold the length of the linked list
1167 #define TYPE_UNION 0x1100
1169 * type->left holds the link list of TYPE_OVERLAP entries that
1170 * make up the union.
1171 * type->elements hold the length of the linked list
1173 #define TYPE_POINTER 0x1200
1174 /* For TYPE_POINTER:
1175 * type->left holds the type pointed to.
1177 #define TYPE_FUNCTION 0x1300
1178 /* For TYPE_FUNCTION:
1179 * type->left holds the return type.
1180 * type->right holds the type of the arguments
1181 * type->elements holds the count of the arguments
1183 #define TYPE_PRODUCT 0x1400
1184 /* TYPE_PRODUCT is a basic building block when defining structures
1185 * type->left holds the type that appears first in memory.
1186 * type->right holds the type that appears next in memory.
1188 #define TYPE_OVERLAP 0x1500
1189 /* TYPE_OVERLAP is a basic building block when defining unions
1190 * type->left and type->right holds to types that overlap
1191 * each other in memory.
1193 #define TYPE_ARRAY 0x1800
1194 /* TYPE_ARRAY is a basic building block when definitng arrays.
1195 * type->left holds the type we are an array of.
1196 * type->elements holds the number of elements.
1198 #define TYPE_TUPLE 0x1900
1199 /* TYPE_TUPLE is a basic building block when defining
1200 * positionally reference type conglomerations. (i.e. closures)
1201 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1202 * except it has no field names.
1203 * type->left holds the liked list of TYPE_PRODUCT entries that
1204 * make up the closure type.
1205 * type->elements hold the number of elements in the closure.
1207 #define TYPE_JOIN 0x1a00
1208 /* TYPE_JOIN is a basic building block when defining
1209 * positionally reference type conglomerations. (i.e. closures)
1210 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1211 * except it has no field names.
1212 * type->left holds the liked list of TYPE_OVERLAP entries that
1213 * make up the closure type.
1214 * type->elements hold the number of elements in the closure.
1216 #define TYPE_BITFIELD 0x1b00
1217 /* TYPE_BITFIED is the type of a bitfield.
1218 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1219 * type->elements holds the number of bits in the bitfield.
1221 #define TYPE_UNKNOWN 0x1c00
1222 /* TYPE_UNKNOWN is the type of an unknown value.
1223 * Used on unknown consts and other places where I don't know the type.
1226 #define ATTRIB_SHIFT 16
1227 #define ATTRIB_MASK 0xffff0000
1228 #define ATTRIB_NOINLINE 0x00010000
1229 #define ATTRIB_ALWAYS_INLINE 0x00020000
1231 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1235 struct type *left, *right;
1237 struct hash_entry *field_ident;
1238 struct hash_entry *type_ident;
1241 #define TEMPLATE_BITS 7
1242 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1243 #define MAX_REG_EQUIVS 16
1245 #define MAX_REGISTERS 75
1246 #define REGISTER_BITS 7
1247 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1250 #define REG_UNNEEDED 2
1251 #define REG_VIRT0 (MAX_REGISTERS + 0)
1252 #define REG_VIRT1 (MAX_REGISTERS + 1)
1253 #define REG_VIRT2 (MAX_REGISTERS + 2)
1254 #define REG_VIRT3 (MAX_REGISTERS + 3)
1255 #define REG_VIRT4 (MAX_REGISTERS + 4)
1256 #define REG_VIRT5 (MAX_REGISTERS + 5)
1257 #define REG_VIRT6 (MAX_REGISTERS + 6)
1258 #define REG_VIRT7 (MAX_REGISTERS + 7)
1259 #define REG_VIRT8 (MAX_REGISTERS + 8)
1260 #define REG_VIRT9 (MAX_REGISTERS + 9)
1262 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1263 #error "MAX_VIRT_REGISTERS to small"
1265 #if (MAX_REGC + REGISTER_BITS) >= 26
1266 #error "Too many id bits used"
1269 /* Provision for 8 register classes */
1271 #define REGC_SHIFT REGISTER_BITS
1272 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1273 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1274 #define ID_REG(ID) ((ID) & REG_MASK)
1275 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1276 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1277 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1278 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1279 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1281 #define ARCH_INPUT_REGS 4
1282 #define ARCH_OUTPUT_REGS 4
1284 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1285 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1286 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1287 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1288 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1289 static void arch_reg_equivs(
1290 struct compile_state *state, unsigned *equiv, int reg);
1291 static int arch_select_free_register(
1292 struct compile_state *state, char *used, int classes);
1293 static unsigned arch_regc_size(struct compile_state *state, int class);
1294 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1295 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1296 static const char *arch_reg_str(int reg);
1297 static struct reg_info arch_reg_constraint(
1298 struct compile_state *state, struct type *type, const char *constraint);
1299 static struct reg_info arch_reg_clobber(
1300 struct compile_state *state, const char *clobber);
1301 static struct reg_info arch_reg_lhs(struct compile_state *state,
1302 struct triple *ins, int index);
1303 static struct reg_info arch_reg_rhs(struct compile_state *state,
1304 struct triple *ins, int index);
1305 static int arch_reg_size(int reg);
1306 static struct triple *transform_to_arch_instruction(
1307 struct compile_state *state, struct triple *ins);
1308 static struct triple *flatten(
1309 struct compile_state *state, struct triple *first, struct triple *ptr);
1310 static void print_dominators(struct compile_state *state,
1311 FILE *fp, struct basic_blocks *bb);
1312 static void print_dominance_frontiers(struct compile_state *state,
1313 FILE *fp, struct basic_blocks *bb);
1317 #define DEBUG_ABORT_ON_ERROR 0x00000001
1318 #define DEBUG_BASIC_BLOCKS 0x00000002
1319 #define DEBUG_FDOMINATORS 0x00000004
1320 #define DEBUG_RDOMINATORS 0x00000008
1321 #define DEBUG_TRIPLES 0x00000010
1322 #define DEBUG_INTERFERENCE 0x00000020
1323 #define DEBUG_SCC_TRANSFORM 0x00000040
1324 #define DEBUG_SCC_TRANSFORM2 0x00000080
1325 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1326 #define DEBUG_INLINE 0x00000200
1327 #define DEBUG_RANGE_CONFLICTS 0x00000400
1328 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1329 #define DEBUG_COLOR_GRAPH 0x00001000
1330 #define DEBUG_COLOR_GRAPH2 0x00002000
1331 #define DEBUG_COALESCING 0x00004000
1332 #define DEBUG_COALESCING2 0x00008000
1333 #define DEBUG_VERIFICATION 0x00010000
1334 #define DEBUG_CALLS 0x00020000
1335 #define DEBUG_CALLS2 0x00040000
1336 #define DEBUG_TOKENS 0x80000000
1338 #define DEBUG_DEFAULT ( \
1339 DEBUG_ABORT_ON_ERROR | \
1340 DEBUG_BASIC_BLOCKS | \
1341 DEBUG_FDOMINATORS | \
1342 DEBUG_RDOMINATORS | \
1346 #define DEBUG_ALL ( \
1347 DEBUG_ABORT_ON_ERROR | \
1348 DEBUG_BASIC_BLOCKS | \
1349 DEBUG_FDOMINATORS | \
1350 DEBUG_RDOMINATORS | \
1352 DEBUG_INTERFERENCE | \
1353 DEBUG_SCC_TRANSFORM | \
1354 DEBUG_SCC_TRANSFORM2 | \
1355 DEBUG_REBUILD_SSA_FORM | \
1357 DEBUG_RANGE_CONFLICTS | \
1358 DEBUG_RANGE_CONFLICTS2 | \
1359 DEBUG_COLOR_GRAPH | \
1360 DEBUG_COLOR_GRAPH2 | \
1361 DEBUG_COALESCING | \
1362 DEBUG_COALESCING2 | \
1363 DEBUG_VERIFICATION | \
1369 #define COMPILER_INLINE_MASK 0x00000007
1370 #define COMPILER_INLINE_ALWAYS 0x00000000
1371 #define COMPILER_INLINE_NEVER 0x00000001
1372 #define COMPILER_INLINE_DEFAULTON 0x00000002
1373 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1374 #define COMPILER_INLINE_NOPENALTY 0x00000004
1375 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1376 #define COMPILER_SIMPLIFY 0x00000010
1377 #define COMPILER_SCC_TRANSFORM 0x00000020
1378 #define COMPILER_SIMPLIFY_OP 0x00000040
1379 #define COMPILER_SIMPLIFY_PHI 0x00000080
1380 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1381 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1382 #define COMPILER_SIMPLIFY_COPY 0x00000400
1383 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1384 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1385 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1386 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1387 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1389 #define COMPILER_TRIGRAPHS 0x40000000
1390 #define COMPILER_PP_ONLY 0x80000000
1392 #define COMPILER_DEFAULT_FLAGS ( \
1393 COMPILER_TRIGRAPHS | \
1394 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1395 COMPILER_INLINE_DEFAULTON | \
1396 COMPILER_SIMPLIFY_OP | \
1397 COMPILER_SIMPLIFY_PHI | \
1398 COMPILER_SIMPLIFY_LABEL | \
1399 COMPILER_SIMPLIFY_BRANCH | \
1400 COMPILER_SIMPLIFY_COPY | \
1401 COMPILER_SIMPLIFY_ARITH | \
1402 COMPILER_SIMPLIFY_SHIFT | \
1403 COMPILER_SIMPLIFY_BITWISE | \
1404 COMPILER_SIMPLIFY_LOGICAL | \
1405 COMPILER_SIMPLIFY_BITFIELD | \
1408 #define GLOBAL_SCOPE_DEPTH 1
1409 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1411 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1415 static void init_compiler_state(struct compiler_state *compiler)
1417 memset(compiler, 0, sizeof(*compiler));
1418 compiler->label_prefix = "";
1419 compiler->ofilename = "auto.inc";
1420 compiler->flags = COMPILER_DEFAULT_FLAGS;
1421 compiler->debug = 0;
1422 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1423 compiler->include_path_count = 1;
1424 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1425 compiler->define_count = 1;
1426 compiler->defines = xcmalloc(sizeof(char *), "defines");
1427 compiler->undef_count = 1;
1428 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1431 struct compiler_flag {
1436 struct compiler_arg {
1439 struct compiler_flag flags[16];
1442 static int set_flag(
1443 const struct compiler_flag *ptr, unsigned long *flags,
1444 int act, const char *flag)
1447 for(; ptr->name; ptr++) {
1448 if (strcmp(ptr->name, flag) == 0) {
1454 *flags &= ~(ptr->flag);
1456 *flags |= ptr->flag;
1463 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1468 val = strchr(arg, '=');
1472 for(; ptr->name; ptr++) {
1473 if (strncmp(ptr->name, arg, len) == 0) {
1478 *flags &= ~ptr->mask;
1479 result = set_flag(&ptr->flags[0], flags, 1, val);
1486 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1487 const char *prefix, const char *invert_prefix)
1489 for(;ptr->name; ptr++) {
1490 fprintf(fp, "%s%s\n", prefix, ptr->name);
1491 if (invert_prefix) {
1492 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1497 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1500 for(;ptr->name; ptr++) {
1501 const struct compiler_flag *flag;
1502 for(flag = &ptr->flags[0]; flag->name; flag++) {
1503 fprintf(fp, "%s%s=%s\n",
1504 prefix, ptr->name, flag->name);
1509 static int append_string(size_t *max, const char ***vec, const char *str,
1514 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1515 (*vec)[count -1] = 0;
1516 (*vec)[count -2] = str;
1520 static void arg_error(char *fmt, ...);
1521 static const char *identifier(const char *str, const char *end);
1523 static int append_include_path(struct compiler_state *compiler, const char *str)
1526 if (!exists(str, ".")) {
1527 arg_error("Nonexistent include path: `%s'\n",
1530 result = append_string(&compiler->include_path_count,
1531 &compiler->include_paths, str, "include_paths");
1535 static int append_define(struct compiler_state *compiler, const char *str)
1537 const char *end, *rest;
1540 end = strchr(str, '=');
1542 end = str + strlen(str);
1544 rest = identifier(str, end);
1546 int len = end - str - 1;
1547 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1550 result = append_string(&compiler->define_count,
1551 &compiler->defines, str, "defines");
1555 static int append_undef(struct compiler_state *compiler, const char *str)
1557 const char *end, *rest;
1560 end = str + strlen(str);
1561 rest = identifier(str, end);
1563 int len = end - str - 1;
1564 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1567 result = append_string(&compiler->undef_count,
1568 &compiler->undefs, str, "undefs");
1572 static const struct compiler_flag romcc_flags[] = {
1573 { "trigraphs", COMPILER_TRIGRAPHS },
1574 { "pp-only", COMPILER_PP_ONLY },
1575 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1576 { "simplify", COMPILER_SIMPLIFY },
1577 { "scc-transform", COMPILER_SCC_TRANSFORM },
1578 { "simplify-op", COMPILER_SIMPLIFY_OP },
1579 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1580 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1581 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1582 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1583 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1584 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1585 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1586 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1587 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1590 static const struct compiler_arg romcc_args[] = {
1591 { "inline-policy", COMPILER_INLINE_MASK,
1593 { "always", COMPILER_INLINE_ALWAYS, },
1594 { "never", COMPILER_INLINE_NEVER, },
1595 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1596 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1597 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1603 static const struct compiler_flag romcc_opt_flags[] = {
1604 { "-O", COMPILER_SIMPLIFY },
1605 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1606 { "-E", COMPILER_PP_ONLY },
1609 static const struct compiler_flag romcc_debug_flags[] = {
1610 { "all", DEBUG_ALL },
1611 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1612 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1613 { "fdominators", DEBUG_FDOMINATORS },
1614 { "rdominators", DEBUG_RDOMINATORS },
1615 { "triples", DEBUG_TRIPLES },
1616 { "interference", DEBUG_INTERFERENCE },
1617 { "scc-transform", DEBUG_SCC_TRANSFORM },
1618 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1619 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1620 { "inline", DEBUG_INLINE },
1621 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1622 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1623 { "color-graph", DEBUG_COLOR_GRAPH },
1624 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1625 { "coalescing", DEBUG_COALESCING },
1626 { "coalescing2", DEBUG_COALESCING2 },
1627 { "verification", DEBUG_VERIFICATION },
1628 { "calls", DEBUG_CALLS },
1629 { "calls2", DEBUG_CALLS2 },
1630 { "tokens", DEBUG_TOKENS },
1634 static int compiler_encode_flag(
1635 struct compiler_state *compiler, const char *flag)
1642 if (strncmp(flag, "no-", 3) == 0) {
1646 if (strncmp(flag, "-O", 2) == 0) {
1647 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1649 else if (strncmp(flag, "-E", 2) == 0) {
1650 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1652 else if (strncmp(flag, "-I", 2) == 0) {
1653 result = append_include_path(compiler, flag + 2);
1655 else if (strncmp(flag, "-D", 2) == 0) {
1656 result = append_define(compiler, flag + 2);
1658 else if (strncmp(flag, "-U", 2) == 0) {
1659 result = append_undef(compiler, flag + 2);
1661 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1663 compiler->label_prefix = flag + 13;
1665 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1666 unsigned long max_passes;
1668 max_passes = strtoul(flag + 22, &end, 10);
1669 if (end[0] == '\0') {
1671 compiler->max_allocation_passes = max_passes;
1674 else if (act && strcmp(flag, "debug") == 0) {
1676 compiler->debug |= DEBUG_DEFAULT;
1678 else if (strncmp(flag, "debug-", 6) == 0) {
1680 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1683 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1685 result = set_arg(romcc_args, &compiler->flags, flag);
1691 static void compiler_usage(FILE *fp)
1693 flag_usage(fp, romcc_opt_flags, "", 0);
1694 flag_usage(fp, romcc_flags, "-f", "-fno-");
1695 arg_usage(fp, romcc_args, "-f");
1696 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1697 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1698 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1699 fprintf(fp, "-I<include path>\n");
1700 fprintf(fp, "-D<macro>[=defn]\n");
1701 fprintf(fp, "-U<macro>\n");
1704 static void do_cleanup(struct compile_state *state)
1706 if (state->output) {
1707 fclose(state->output);
1708 unlink(state->compiler->ofilename);
1711 if (state->dbgout) {
1712 fflush(state->dbgout);
1714 if (state->errout) {
1715 fflush(state->errout);
1719 static struct compile_state *exit_state;
1720 static void exit_cleanup(void)
1723 do_cleanup(exit_state);
1727 static int get_col(struct file_state *file)
1730 const char *ptr, *end;
1731 ptr = file->line_start;
1733 for(col = 0; ptr < end; ptr++) {
1738 col = (col & ~7) + 8;
1744 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1747 if (triple && triple->occurance) {
1748 struct occurance *spot;
1749 for(spot = triple->occurance; spot; spot = spot->parent) {
1750 fprintf(fp, "%s:%d.%d: ",
1751 spot->filename, spot->line, spot->col);
1758 col = get_col(state->file);
1759 fprintf(fp, "%s:%d.%d: ",
1760 state->file->report_name, state->file->report_line, col);
1763 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr,
1764 const char *fmt, ...)
1766 FILE *fp = state->errout;
1768 va_start(args, fmt);
1769 loc(fp, state, ptr);
1772 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1774 fprintf(fp, "Internal compiler error: ");
1775 vfprintf(fp, fmt, args);
1783 static void internal_warning(struct compile_state *state, struct triple *ptr,
1784 const char *fmt, ...)
1786 FILE *fp = state->errout;
1788 va_start(args, fmt);
1789 loc(fp, state, ptr);
1791 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1793 fprintf(fp, "Internal compiler warning: ");
1794 vfprintf(fp, fmt, args);
1801 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr,
1802 const char *fmt, ...)
1804 FILE *fp = state->errout;
1806 va_start(args, fmt);
1807 loc(fp, state, ptr);
1809 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1810 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1812 vfprintf(fp, fmt, args);
1816 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1822 static void warning(struct compile_state *state, struct triple *ptr,
1823 const char *fmt, ...)
1825 FILE *fp = state->errout;
1827 va_start(args, fmt);
1828 loc(fp, state, ptr);
1829 fprintf(fp, "warning: ");
1830 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1831 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1833 vfprintf(fp, fmt, args);
1838 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1840 static void valid_op(struct compile_state *state, int op)
1842 char *fmt = "invalid op: %d";
1844 internal_error(state, 0, fmt, op);
1847 internal_error(state, 0, fmt, op);
1851 static void valid_ins(struct compile_state *state, struct triple *ptr)
1853 valid_op(state, ptr->op);
1856 #if DEBUG_ROMCC_WARNING
1857 static void valid_param_count(struct compile_state *state, struct triple *ins)
1859 int lhs, rhs, misc, targ;
1860 valid_ins(state, ins);
1861 lhs = table_ops[ins->op].lhs;
1862 rhs = table_ops[ins->op].rhs;
1863 misc = table_ops[ins->op].misc;
1864 targ = table_ops[ins->op].targ;
1866 if ((lhs >= 0) && (ins->lhs != lhs)) {
1867 internal_error(state, ins, "Bad lhs count");
1869 if ((rhs >= 0) && (ins->rhs != rhs)) {
1870 internal_error(state, ins, "Bad rhs count");
1872 if ((misc >= 0) && (ins->misc != misc)) {
1873 internal_error(state, ins, "Bad misc count");
1875 if ((targ >= 0) && (ins->targ != targ)) {
1876 internal_error(state, ins, "Bad targ count");
1881 static struct type void_type;
1882 static struct type unknown_type;
1883 static void use_triple(struct triple *used, struct triple *user)
1885 struct triple_set **ptr, *new;
1892 if ((*ptr)->member == user) {
1895 ptr = &(*ptr)->next;
1897 /* Append new to the head of the list,
1898 * copy_func and rename_block_variables
1901 new = xcmalloc(sizeof(*new), "triple_set");
1903 new->next = used->use;
1907 static void unuse_triple(struct triple *used, struct triple *unuser)
1909 struct triple_set *use, **ptr;
1916 if (use->member == unuser) {
1926 static void put_occurance(struct occurance *occurance)
1929 occurance->count -= 1;
1930 if (occurance->count <= 0) {
1931 if (occurance->parent) {
1932 put_occurance(occurance->parent);
1939 static void get_occurance(struct occurance *occurance)
1942 occurance->count += 1;
1947 static struct occurance *new_occurance(struct compile_state *state)
1949 struct occurance *result, *last;
1950 const char *filename;
1951 const char *function;
1959 filename = state->file->report_name;
1960 line = state->file->report_line;
1961 col = get_col(state->file);
1963 if (state->function) {
1964 function = state->function;
1966 last = state->last_occurance;
1968 (last->col == col) &&
1969 (last->line == line) &&
1970 (last->function == function) &&
1971 ((last->filename == filename) ||
1972 (strcmp(last->filename, filename) == 0)))
1974 get_occurance(last);
1978 state->last_occurance = 0;
1979 put_occurance(last);
1981 result = xmalloc(sizeof(*result), "occurance");
1983 result->filename = filename;
1984 result->function = function;
1985 result->line = line;
1988 state->last_occurance = result;
1992 static struct occurance *inline_occurance(struct compile_state *state,
1993 struct occurance *base, struct occurance *top)
1995 struct occurance *result, *last;
1997 internal_error(state, 0, "inlining an already inlined function?");
1999 /* If I have a null base treat it that way */
2000 if ((base->parent == 0) &&
2002 (base->line == 0) &&
2003 (base->function[0] == '\0') &&
2004 (base->filename[0] == '\0')) {
2007 /* See if I can reuse the last occurance I had */
2008 last = state->last_occurance;
2010 (last->parent == base) &&
2011 (last->col == top->col) &&
2012 (last->line == top->line) &&
2013 (last->function == top->function) &&
2014 (last->filename == top->filename)) {
2015 get_occurance(last);
2018 /* I can't reuse the last occurance so free it */
2020 state->last_occurance = 0;
2021 put_occurance(last);
2023 /* Generate a new occurance structure */
2024 get_occurance(base);
2025 result = xmalloc(sizeof(*result), "occurance");
2027 result->filename = top->filename;
2028 result->function = top->function;
2029 result->line = top->line;
2030 result->col = top->col;
2031 result->parent = base;
2032 state->last_occurance = result;
2036 static struct occurance dummy_occurance = {
2038 .filename = __FILE__,
2045 /* The undef triple is used as a place holder when we are removing pointers
2046 * from a triple. Having allows certain sanity checks to pass even
2047 * when the original triple that was pointed to is gone.
2049 static struct triple unknown_triple = {
2050 .next = &unknown_triple,
2051 .prev = &unknown_triple,
2053 .op = OP_UNKNOWNVAL,
2058 .type = &unknown_type,
2059 .id = -1, /* An invalid id */
2060 .u = { .cval = 0, },
2061 .occurance = &dummy_occurance,
2062 .param = { [0] = 0, [1] = 0, },
2066 static size_t registers_of(struct compile_state *state, struct type *type);
2068 static struct triple *alloc_triple(struct compile_state *state,
2069 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2070 struct occurance *occurance)
2072 size_t size, extra_count, min_count;
2073 int lhs, rhs, misc, targ;
2074 struct triple *ret, dummy;
2076 dummy.occurance = occurance;
2077 valid_op(state, op);
2078 lhs = table_ops[op].lhs;
2079 rhs = table_ops[op].rhs;
2080 misc = table_ops[op].misc;
2081 targ = table_ops[op].targ;
2091 lhs = registers_of(state, type);
2094 lhs = registers_of(state, type);
2101 if ((rhs < 0) || (rhs > MAX_RHS)) {
2102 internal_error(state, &dummy, "bad rhs count %d", rhs);
2104 if ((lhs < 0) || (lhs > MAX_LHS)) {
2105 internal_error(state, &dummy, "bad lhs count %d", lhs);
2107 if ((misc < 0) || (misc > MAX_MISC)) {
2108 internal_error(state, &dummy, "bad misc count %d", misc);
2110 if ((targ < 0) || (targ > MAX_TARG)) {
2111 internal_error(state, &dummy, "bad targs count %d", targ);
2114 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2115 extra_count = lhs + rhs + misc + targ;
2116 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2118 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2119 ret = xcmalloc(size, "tripple");
2128 ret->occurance = occurance;
2129 /* A simple sanity check */
2130 if ((ret->op != op) ||
2131 (ret->lhs != lhs) ||
2132 (ret->rhs != rhs) ||
2133 (ret->misc != misc) ||
2134 (ret->targ != targ) ||
2135 (ret->type != type) ||
2136 (ret->next != ret) ||
2137 (ret->prev != ret) ||
2138 (ret->occurance != occurance)) {
2139 internal_error(state, ret, "huh?");
2144 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2147 int src_lhs, src_rhs, src_size;
2150 src_size = TRIPLE_SIZE(src);
2151 get_occurance(src->occurance);
2152 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2154 memcpy(dup, src, sizeof(*src));
2155 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2159 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2161 struct triple *copy;
2162 copy = dup_triple(state, src);
2164 copy->next = copy->prev = copy;
2168 static struct triple *new_triple(struct compile_state *state,
2169 int op, struct type *type, int lhs, int rhs)
2172 struct occurance *occurance;
2173 occurance = new_occurance(state);
2174 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2178 static struct triple *build_triple(struct compile_state *state,
2179 int op, struct type *type, struct triple *left, struct triple *right,
2180 struct occurance *occurance)
2184 ret = alloc_triple(state, op, type, -1, -1, occurance);
2185 count = TRIPLE_SIZE(ret);
2187 ret->param[0] = left;
2190 ret->param[1] = right;
2195 static struct triple *triple(struct compile_state *state,
2196 int op, struct type *type, struct triple *left, struct triple *right)
2200 ret = new_triple(state, op, type, -1, -1);
2201 count = TRIPLE_SIZE(ret);
2203 ret->param[0] = left;
2206 ret->param[1] = right;
2211 static struct triple *branch(struct compile_state *state,
2212 struct triple *targ, struct triple *test)
2216 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2219 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2221 TARG(ret, 0) = targ;
2222 /* record the branch target was used */
2223 if (!targ || (targ->op != OP_LABEL)) {
2224 internal_error(state, 0, "branch not to label");
2229 static int triple_is_label(struct compile_state *state, struct triple *ins);
2230 static int triple_is_call(struct compile_state *state, struct triple *ins);
2231 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2232 static void insert_triple(struct compile_state *state,
2233 struct triple *first, struct triple *ptr)
2236 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2237 internal_error(state, ptr, "expression already used");
2240 ptr->prev = first->prev;
2241 ptr->prev->next = ptr;
2242 ptr->next->prev = ptr;
2244 if (triple_is_cbranch(state, ptr->prev) ||
2245 triple_is_call(state, ptr->prev)) {
2246 unuse_triple(first, ptr->prev);
2247 use_triple(ptr, ptr->prev);
2252 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2254 /* This function is used to determine if u.block
2255 * is utilized to store the current block number.
2258 valid_ins(state, ins);
2259 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2260 return stores_block;
2263 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2264 static struct block *block_of_triple(struct compile_state *state,
2267 struct triple *first;
2268 if (!ins || ins == &unknown_triple) {
2271 first = state->first;
2272 while(ins != first && !triple_is_branch(state, ins->prev) &&
2273 !triple_stores_block(state, ins))
2275 if (ins == ins->prev) {
2276 internal_error(state, ins, "ins == ins->prev?");
2280 return triple_stores_block(state, ins)? ins->u.block: 0;
2283 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2284 static struct triple *pre_triple(struct compile_state *state,
2285 struct triple *base,
2286 int op, struct type *type, struct triple *left, struct triple *right)
2288 struct block *block;
2291 /* If I am an OP_PIECE jump to the real instruction */
2292 if (base->op == OP_PIECE) {
2293 base = MISC(base, 0);
2295 block = block_of_triple(state, base);
2296 get_occurance(base->occurance);
2297 ret = build_triple(state, op, type, left, right, base->occurance);
2298 generate_lhs_pieces(state, ret);
2299 if (triple_stores_block(state, ret)) {
2300 ret->u.block = block;
2302 insert_triple(state, base, ret);
2303 for(i = 0; i < ret->lhs; i++) {
2304 struct triple *piece;
2305 piece = LHS(ret, i);
2306 insert_triple(state, base, piece);
2307 use_triple(ret, piece);
2308 use_triple(piece, ret);
2310 if (block && (block->first == base)) {
2316 static struct triple *post_triple(struct compile_state *state,
2317 struct triple *base,
2318 int op, struct type *type, struct triple *left, struct triple *right)
2320 struct block *block;
2321 struct triple *ret, *next;
2323 /* If I am an OP_PIECE jump to the real instruction */
2324 if (base->op == OP_PIECE) {
2325 base = MISC(base, 0);
2327 /* If I have a left hand side skip over it */
2330 base = LHS(base, zlhs - 1);
2333 block = block_of_triple(state, base);
2334 get_occurance(base->occurance);
2335 ret = build_triple(state, op, type, left, right, base->occurance);
2336 generate_lhs_pieces(state, ret);
2337 if (triple_stores_block(state, ret)) {
2338 ret->u.block = block;
2341 insert_triple(state, next, ret);
2343 for(i = 0; i < zlhs; i++) {
2344 struct triple *piece;
2345 piece = LHS(ret, i);
2346 insert_triple(state, next, piece);
2347 use_triple(ret, piece);
2348 use_triple(piece, ret);
2350 if (block && (block->last == base)) {
2353 block->last = LHS(ret, zlhs - 1);
2359 static struct type *reg_type(
2360 struct compile_state *state, struct type *type, int reg);
2362 static void generate_lhs_piece(
2363 struct compile_state *state, struct triple *ins, int index)
2365 struct type *piece_type;
2366 struct triple *piece;
2367 get_occurance(ins->occurance);
2368 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2370 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2371 piece_type = piece_type->left;
2375 static void name_of(FILE *fp, struct type *type);
2376 FILE * fp = state->errout;
2377 fprintf(fp, "piece_type(%d): ", index);
2378 name_of(fp, piece_type);
2382 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2383 piece->u.cval = index;
2384 LHS(ins, piece->u.cval) = piece;
2385 MISC(piece, 0) = ins;
2388 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2392 for(i = 0; i < zlhs; i++) {
2393 generate_lhs_piece(state, ins, i);
2397 static struct triple *label(struct compile_state *state)
2399 /* Labels don't get a type */
2400 struct triple *result;
2401 result = triple(state, OP_LABEL, &void_type, 0, 0);
2405 static struct triple *mkprog(struct compile_state *state, ...)
2407 struct triple *prog, *head, *arg;
2411 head = label(state);
2412 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2413 RHS(prog, 0) = head;
2414 va_start(args, state);
2416 while((arg = va_arg(args, struct triple *)) != 0) {
2418 internal_error(state, 0, "too many arguments to mkprog");
2420 flatten(state, head, arg);
2423 prog->type = head->prev->type;
2426 static void name_of(FILE *fp, struct type *type);
2427 static void display_triple(FILE *fp, struct triple *ins)
2429 struct occurance *ptr;
2431 char pre, post, vol;
2432 pre = post = vol = ' ';
2434 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2437 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2440 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2443 reg = arch_reg_str(ID_REG(ins->id));
2446 fprintf(fp, "(%p) <nothing> ", ins);
2448 else if (ins->op == OP_INTCONST) {
2449 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2450 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2451 (unsigned long)(ins->u.cval));
2453 else if (ins->op == OP_ADDRCONST) {
2454 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2455 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2456 MISC(ins, 0), (unsigned long)(ins->u.cval));
2458 else if (ins->op == OP_INDEX) {
2459 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2460 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2461 RHS(ins, 0), (unsigned long)(ins->u.cval));
2463 else if (ins->op == OP_PIECE) {
2464 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2465 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2466 MISC(ins, 0), (unsigned long)(ins->u.cval));
2470 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2471 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2472 if (table_ops[ins->op].flags & BITFIELD) {
2473 fprintf(fp, " <%2d-%2d:%2d>",
2474 ins->u.bitfield.offset,
2475 ins->u.bitfield.offset + ins->u.bitfield.size,
2476 ins->u.bitfield.size);
2478 count = TRIPLE_SIZE(ins);
2479 for(i = 0; i < count; i++) {
2480 fprintf(fp, " %-10p", ins->param[i]);
2487 struct triple_set *user;
2488 #if DEBUG_DISPLAY_TYPES
2490 name_of(fp, ins->type);
2493 #if DEBUG_DISPLAY_USES
2495 for(user = ins->use; user; user = user->next) {
2496 fprintf(fp, " %-10p", user->member);
2501 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2502 fprintf(fp, " %s,%s:%d.%d",
2508 if (ins->op == OP_ASM) {
2509 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2516 static int equiv_types(struct type *left, struct type *right);
2517 static void display_triple_changes(
2518 FILE *fp, const struct triple *new, const struct triple *orig)
2521 int new_count, orig_count;
2522 new_count = TRIPLE_SIZE(new);
2523 orig_count = TRIPLE_SIZE(orig);
2524 if ((new->op != orig->op) ||
2525 (new_count != orig_count) ||
2526 (memcmp(orig->param, new->param,
2527 orig_count * sizeof(orig->param[0])) != 0) ||
2528 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2530 struct occurance *ptr;
2531 int i, min_count, indent;
2532 fprintf(fp, "(%p %p)", new, orig);
2533 if (orig->op == new->op) {
2534 fprintf(fp, " %-11s", tops(orig->op));
2536 fprintf(fp, " [%-10s %-10s]",
2537 tops(new->op), tops(orig->op));
2539 min_count = new_count;
2540 if (min_count > orig_count) {
2541 min_count = orig_count;
2543 for(indent = i = 0; i < min_count; i++) {
2544 if (orig->param[i] == new->param[i]) {
2545 fprintf(fp, " %-11p",
2549 fprintf(fp, " [%-10p %-10p]",
2555 for(; i < orig_count; i++) {
2556 fprintf(fp, " [%-9p]", orig->param[i]);
2559 for(; i < new_count; i++) {
2560 fprintf(fp, " [%-9p]", new->param[i]);
2563 if ((new->op == OP_INTCONST)||
2564 (new->op == OP_ADDRCONST)) {
2565 fprintf(fp, " <0x%08lx>",
2566 (unsigned long)(new->u.cval));
2569 for(;indent < 36; indent++) {
2573 #if DEBUG_DISPLAY_TYPES
2575 name_of(fp, new->type);
2576 if (!equiv_types(new->type, orig->type)) {
2577 fprintf(fp, " -- ");
2578 name_of(fp, orig->type);
2584 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2585 fprintf(fp, " %s,%s:%d.%d",
2597 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2599 /* Does the triple have no side effects.
2600 * I.e. Rexecuting the triple with the same arguments
2601 * gives the same value.
2604 valid_ins(state, ins);
2605 pure = PURE_BITS(table_ops[ins->op].flags);
2606 if ((pure != PURE) && (pure != IMPURE)) {
2607 internal_error(state, 0, "Purity of %s not known",
2610 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2613 static int triple_is_branch_type(struct compile_state *state,
2614 struct triple *ins, unsigned type)
2616 /* Is this one of the passed branch types? */
2617 valid_ins(state, ins);
2618 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2621 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2623 /* Is this triple a branch instruction? */
2624 valid_ins(state, ins);
2625 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2628 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2630 /* Is this triple a conditional branch instruction? */
2631 return triple_is_branch_type(state, ins, CBRANCH);
2634 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2636 /* Is this triple a unconditional branch instruction? */
2638 valid_ins(state, ins);
2639 type = BRANCH_BITS(table_ops[ins->op].flags);
2640 return (type != 0) && (type != CBRANCH);
2643 static int triple_is_call(struct compile_state *state, struct triple *ins)
2645 /* Is this triple a call instruction? */
2646 return triple_is_branch_type(state, ins, CALLBRANCH);
2649 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2651 /* Is this triple a return instruction? */
2652 return triple_is_branch_type(state, ins, RETBRANCH);
2655 #if DEBUG_ROMCC_WARNING
2656 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2658 /* Is this triple an unconditional branch and not a call or a
2660 return triple_is_branch_type(state, ins, UBRANCH);
2664 static int triple_is_end(struct compile_state *state, struct triple *ins)
2666 return triple_is_branch_type(state, ins, ENDBRANCH);
2669 static int triple_is_label(struct compile_state *state, struct triple *ins)
2671 valid_ins(state, ins);
2672 return (ins->op == OP_LABEL);
2675 static struct triple *triple_to_block_start(
2676 struct compile_state *state, struct triple *start)
2678 while(!triple_is_branch(state, start->prev) &&
2679 (!triple_is_label(state, start) || !start->use)) {
2680 start = start->prev;
2685 static int triple_is_def(struct compile_state *state, struct triple *ins)
2687 /* This function is used to determine which triples need
2691 valid_ins(state, ins);
2692 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2693 if (ins->lhs >= 1) {
2699 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2702 valid_ins(state, ins);
2703 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2704 return is_structural;
2707 static int triple_is_part(struct compile_state *state, struct triple *ins)
2710 valid_ins(state, ins);
2711 is_part = (table_ops[ins->op].flags & PART) == PART;
2715 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2717 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2720 static struct triple **triple_iter(struct compile_state *state,
2721 size_t count, struct triple **vector,
2722 struct triple *ins, struct triple **last)
2724 struct triple **ret;
2730 else if ((last >= vector) && (last < (vector + count - 1))) {
2738 static struct triple **triple_lhs(struct compile_state *state,
2739 struct triple *ins, struct triple **last)
2741 return triple_iter(state, ins->lhs, &LHS(ins,0),
2745 static struct triple **triple_rhs(struct compile_state *state,
2746 struct triple *ins, struct triple **last)
2748 return triple_iter(state, ins->rhs, &RHS(ins,0),
2752 static struct triple **triple_misc(struct compile_state *state,
2753 struct triple *ins, struct triple **last)
2755 return triple_iter(state, ins->misc, &MISC(ins,0),
2759 static struct triple **do_triple_targ(struct compile_state *state,
2760 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2763 struct triple **ret, **vector;
2768 if (triple_is_cbranch(state, ins)) {
2771 if (!call_edges && triple_is_call(state, ins)) {
2774 if (next_edges && triple_is_call(state, ins)) {
2777 vector = &TARG(ins, 0);
2778 if (!ret && next_is_targ) {
2781 } else if (last == &ins->next) {
2785 if (!ret && count) {
2789 else if ((last >= vector) && (last < (vector + count - 1))) {
2792 else if (last == vector + count - 1) {
2796 if (!ret && triple_is_ret(state, ins) && call_edges) {
2797 struct triple_set *use;
2798 for(use = ins->use; use; use = use->next) {
2799 if (!triple_is_call(state, use->member)) {
2803 ret = &use->member->next;
2806 else if (last == &use->member->next) {
2814 static struct triple **triple_targ(struct compile_state *state,
2815 struct triple *ins, struct triple **last)
2817 return do_triple_targ(state, ins, last, 1, 1);
2820 static struct triple **triple_edge_targ(struct compile_state *state,
2821 struct triple *ins, struct triple **last)
2823 return do_triple_targ(state, ins, last,
2824 state->functions_joined, !state->functions_joined);
2827 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2829 struct triple *next;
2833 for(i = 0; i < lhs; i++) {
2834 struct triple *piece;
2835 piece = LHS(ins, i);
2836 if (next != piece) {
2837 internal_error(state, ins, "malformed lhs on %s",
2840 if (next->op != OP_PIECE) {
2841 internal_error(state, ins, "bad lhs op %s at %d on %s",
2842 tops(next->op), i, tops(ins->op));
2844 if (next->u.cval != i) {
2845 internal_error(state, ins, "bad u.cval of %d %d expected",
2853 /* Function piece accessor functions */
2854 static struct triple *do_farg(struct compile_state *state,
2855 struct triple *func, unsigned index)
2858 struct triple *first, *arg;
2862 if((index < 0) || (index >= (ftype->elements + 2))) {
2863 internal_error(state, func, "bad argument index: %d", index);
2865 first = RHS(func, 0);
2867 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2870 if (arg->op != OP_ADECL) {
2871 internal_error(state, 0, "arg not adecl?");
2875 static struct triple *fresult(struct compile_state *state, struct triple *func)
2877 return do_farg(state, func, 0);
2879 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2881 return do_farg(state, func, 1);
2883 static struct triple *farg(struct compile_state *state,
2884 struct triple *func, unsigned index)
2886 return do_farg(state, func, index + 2);
2890 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2892 struct triple *first, *ins;
2893 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2894 first = ins = RHS(func, 0);
2896 if (triple_is_label(state, ins) && ins->use) {
2897 fprintf(fp, "%p:\n", ins);
2899 display_triple(fp, ins);
2901 if (triple_is_branch(state, ins)) {
2904 if (ins->next->prev != ins) {
2905 internal_error(state, ins->next, "bad prev");
2908 } while(ins != first);
2911 static void verify_use(struct compile_state *state,
2912 struct triple *user, struct triple *used)
2915 size = TRIPLE_SIZE(user);
2916 for(i = 0; i < size; i++) {
2917 if (user->param[i] == used) {
2921 if (triple_is_branch(state, user)) {
2922 if (user->next == used) {
2927 internal_error(state, user, "%s(%p) does not use %s(%p)",
2928 tops(user->op), user, tops(used->op), used);
2932 static int find_rhs_use(struct compile_state *state,
2933 struct triple *user, struct triple *used)
2935 struct triple **param;
2937 verify_use(state, user, used);
2939 #if DEBUG_ROMCC_WARNINGS
2940 #warning "AUDIT ME ->rhs"
2943 param = &RHS(user, 0);
2944 for(i = 0; i < size; i++) {
2945 if (param[i] == used) {
2952 static void free_triple(struct compile_state *state, struct triple *ptr)
2955 size = sizeof(*ptr) - sizeof(ptr->param) +
2956 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2957 ptr->prev->next = ptr->next;
2958 ptr->next->prev = ptr->prev;
2960 internal_error(state, ptr, "ptr->use != 0");
2962 put_occurance(ptr->occurance);
2963 memset(ptr, -1, size);
2967 static void release_triple(struct compile_state *state, struct triple *ptr)
2969 struct triple_set *set, *next;
2970 struct triple **expr;
2971 struct block *block;
2972 if (ptr == &unknown_triple) {
2975 valid_ins(state, ptr);
2976 /* Make certain the we are not the first or last element of a block */
2977 block = block_of_triple(state, ptr);
2979 if ((block->last == ptr) && (block->first == ptr)) {
2980 block->last = block->first = 0;
2982 else if (block->last == ptr) {
2983 block->last = ptr->prev;
2985 else if (block->first == ptr) {
2986 block->first = ptr->next;
2989 /* Remove ptr from use chains where it is the user */
2990 expr = triple_rhs(state, ptr, 0);
2991 for(; expr; expr = triple_rhs(state, ptr, expr)) {
2993 unuse_triple(*expr, ptr);
2996 expr = triple_lhs(state, ptr, 0);
2997 for(; expr; expr = triple_lhs(state, ptr, expr)) {
2999 unuse_triple(*expr, ptr);
3002 expr = triple_misc(state, ptr, 0);
3003 for(; expr; expr = triple_misc(state, ptr, expr)) {
3005 unuse_triple(*expr, ptr);
3008 expr = triple_targ(state, ptr, 0);
3009 for(; expr; expr = triple_targ(state, ptr, expr)) {
3011 unuse_triple(*expr, ptr);
3014 /* Reomve ptr from use chains where it is used */
3015 for(set = ptr->use; set; set = next) {
3017 valid_ins(state, set->member);
3018 expr = triple_rhs(state, set->member, 0);
3019 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3021 *expr = &unknown_triple;
3024 expr = triple_lhs(state, set->member, 0);
3025 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3027 *expr = &unknown_triple;
3030 expr = triple_misc(state, set->member, 0);
3031 for(; expr; expr = triple_misc(state, set->member, expr)) {
3033 *expr = &unknown_triple;
3036 expr = triple_targ(state, set->member, 0);
3037 for(; expr; expr = triple_targ(state, set->member, expr)) {
3039 *expr = &unknown_triple;
3042 unuse_triple(ptr, set->member);
3044 free_triple(state, ptr);
3047 static void print_triples(struct compile_state *state);
3048 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3050 #define TOK_UNKNOWN 0
3053 #define TOK_LBRACE 3
3054 #define TOK_RBRACE 4
3058 #define TOK_LBRACKET 8
3059 #define TOK_RBRACKET 9
3060 #define TOK_LPAREN 10
3061 #define TOK_RPAREN 11
3066 #define TOK_TIMESEQ 16
3067 #define TOK_DIVEQ 17
3068 #define TOK_MODEQ 18
3069 #define TOK_PLUSEQ 19
3070 #define TOK_MINUSEQ 20
3073 #define TOK_ANDEQ 23
3074 #define TOK_XOREQ 24
3077 #define TOK_NOTEQ 27
3078 #define TOK_QUEST 28
3079 #define TOK_LOGOR 29
3080 #define TOK_LOGAND 30
3084 #define TOK_LESSEQ 34
3085 #define TOK_MOREEQ 35
3089 #define TOK_MINUS 39
3092 #define TOK_PLUSPLUS 42
3093 #define TOK_MINUSMINUS 43
3095 #define TOK_ARROW 45
3097 #define TOK_TILDE 47
3098 #define TOK_LIT_STRING 48
3099 #define TOK_LIT_CHAR 49
3100 #define TOK_LIT_INT 50
3101 #define TOK_LIT_FLOAT 51
3102 #define TOK_MACRO 52
3103 #define TOK_CONCATENATE 53
3105 #define TOK_IDENT 54
3106 #define TOK_STRUCT_NAME 55
3107 #define TOK_ENUM_CONST 56
3108 #define TOK_TYPE_NAME 57
3111 #define TOK_BREAK 59
3114 #define TOK_CONST 62
3115 #define TOK_CONTINUE 63
3116 #define TOK_DEFAULT 64
3118 #define TOK_DOUBLE 66
3121 #define TOK_EXTERN 69
3122 #define TOK_FLOAT 70
3126 #define TOK_INLINE 74
3129 #define TOK_REGISTER 77
3130 #define TOK_RESTRICT 78
3131 #define TOK_RETURN 79
3132 #define TOK_SHORT 80
3133 #define TOK_SIGNED 81
3134 #define TOK_SIZEOF 82
3135 #define TOK_STATIC 83
3136 #define TOK_STRUCT 84
3137 #define TOK_SWITCH 85
3138 #define TOK_TYPEDEF 86
3139 #define TOK_UNION 87
3140 #define TOK_UNSIGNED 88
3142 #define TOK_VOLATILE 90
3143 #define TOK_WHILE 91
3145 #define TOK_ATTRIBUTE 93
3146 #define TOK_ALIGNOF 94
3147 #define TOK_FIRST_KEYWORD TOK_AUTO
3148 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3150 #define TOK_MDEFINE 100
3151 #define TOK_MDEFINED 101
3152 #define TOK_MUNDEF 102
3153 #define TOK_MINCLUDE 103
3154 #define TOK_MLINE 104
3155 #define TOK_MERROR 105
3156 #define TOK_MWARNING 106
3157 #define TOK_MPRAGMA 107
3158 #define TOK_MIFDEF 108
3159 #define TOK_MIFNDEF 109
3160 #define TOK_MELIF 110
3161 #define TOK_MENDIF 111
3163 #define TOK_FIRST_MACRO TOK_MDEFINE
3164 #define TOK_LAST_MACRO TOK_MENDIF
3167 #define TOK_MELSE 113
3168 #define TOK_MIDENT 114
3173 static const char *tokens[] = {
3174 [TOK_UNKNOWN ] = ":unknown:",
3175 [TOK_SPACE ] = ":space:",
3177 [TOK_LBRACE ] = "{",
3178 [TOK_RBRACE ] = "}",
3182 [TOK_LBRACKET ] = "[",
3183 [TOK_RBRACKET ] = "]",
3184 [TOK_LPAREN ] = "(",
3185 [TOK_RPAREN ] = ")",
3187 [TOK_DOTS ] = "...",
3190 [TOK_TIMESEQ ] = "*=",
3191 [TOK_DIVEQ ] = "/=",
3192 [TOK_MODEQ ] = "%=",
3193 [TOK_PLUSEQ ] = "+=",
3194 [TOK_MINUSEQ ] = "-=",
3195 [TOK_SLEQ ] = "<<=",
3196 [TOK_SREQ ] = ">>=",
3197 [TOK_ANDEQ ] = "&=",
3198 [TOK_XOREQ ] = "^=",
3201 [TOK_NOTEQ ] = "!=",
3203 [TOK_LOGOR ] = "||",
3204 [TOK_LOGAND ] = "&&",
3208 [TOK_LESSEQ ] = "<=",
3209 [TOK_MOREEQ ] = ">=",
3216 [TOK_PLUSPLUS ] = "++",
3217 [TOK_MINUSMINUS ] = "--",
3219 [TOK_ARROW ] = "->",
3222 [TOK_LIT_STRING ] = ":string:",
3223 [TOK_IDENT ] = ":ident:",
3224 [TOK_TYPE_NAME ] = ":typename:",
3225 [TOK_LIT_CHAR ] = ":char:",
3226 [TOK_LIT_INT ] = ":integer:",
3227 [TOK_LIT_FLOAT ] = ":float:",
3229 [TOK_CONCATENATE ] = "##",
3231 [TOK_AUTO ] = "auto",
3232 [TOK_BREAK ] = "break",
3233 [TOK_CASE ] = "case",
3234 [TOK_CHAR ] = "char",
3235 [TOK_CONST ] = "const",
3236 [TOK_CONTINUE ] = "continue",
3237 [TOK_DEFAULT ] = "default",
3239 [TOK_DOUBLE ] = "double",
3240 [TOK_ELSE ] = "else",
3241 [TOK_ENUM ] = "enum",
3242 [TOK_EXTERN ] = "extern",
3243 [TOK_FLOAT ] = "float",
3245 [TOK_GOTO ] = "goto",
3247 [TOK_INLINE ] = "inline",
3249 [TOK_LONG ] = "long",
3250 [TOK_REGISTER ] = "register",
3251 [TOK_RESTRICT ] = "restrict",
3252 [TOK_RETURN ] = "return",
3253 [TOK_SHORT ] = "short",
3254 [TOK_SIGNED ] = "signed",
3255 [TOK_SIZEOF ] = "sizeof",
3256 [TOK_STATIC ] = "static",
3257 [TOK_STRUCT ] = "struct",
3258 [TOK_SWITCH ] = "switch",
3259 [TOK_TYPEDEF ] = "typedef",
3260 [TOK_UNION ] = "union",
3261 [TOK_UNSIGNED ] = "unsigned",
3262 [TOK_VOID ] = "void",
3263 [TOK_VOLATILE ] = "volatile",
3264 [TOK_WHILE ] = "while",
3266 [TOK_ATTRIBUTE ] = "__attribute__",
3267 [TOK_ALIGNOF ] = "__alignof__",
3269 [TOK_MDEFINE ] = "#define",
3270 [TOK_MDEFINED ] = "#defined",
3271 [TOK_MUNDEF ] = "#undef",
3272 [TOK_MINCLUDE ] = "#include",
3273 [TOK_MLINE ] = "#line",
3274 [TOK_MERROR ] = "#error",
3275 [TOK_MWARNING ] = "#warning",
3276 [TOK_MPRAGMA ] = "#pragma",
3277 [TOK_MIFDEF ] = "#ifdef",
3278 [TOK_MIFNDEF ] = "#ifndef",
3279 [TOK_MELIF ] = "#elif",
3280 [TOK_MENDIF ] = "#endif",
3283 [TOK_MELSE ] = "#else",
3284 [TOK_MIDENT ] = "#:ident:",
3289 static unsigned int hash(const char *str, int str_len)
3293 end = str + str_len;
3295 for(; str < end; str++) {
3296 hash = (hash *263) + *str;
3298 hash = hash & (HASH_TABLE_SIZE -1);
3302 static struct hash_entry *lookup(
3303 struct compile_state *state, const char *name, int name_len)
3305 struct hash_entry *entry;
3307 index = hash(name, name_len);
3308 entry = state->hash_table[index];
3310 ((entry->name_len != name_len) ||
3311 (memcmp(entry->name, name, name_len) != 0))) {
3312 entry = entry->next;
3316 /* Get a private copy of the name */
3317 new_name = xmalloc(name_len + 1, "hash_name");
3318 memcpy(new_name, name, name_len);
3319 new_name[name_len] = '\0';
3321 /* Create a new hash entry */
3322 entry = xcmalloc(sizeof(*entry), "hash_entry");
3323 entry->next = state->hash_table[index];
3324 entry->name = new_name;
3325 entry->name_len = name_len;
3327 /* Place the new entry in the hash table */
3328 state->hash_table[index] = entry;
3333 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3335 struct hash_entry *entry;
3337 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3338 (entry->tok == TOK_ENUM_CONST) ||
3339 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3340 (entry->tok <= TOK_LAST_KEYWORD)))) {
3341 tk->tok = entry->tok;
3345 static void ident_to_macro(struct compile_state *state, struct token *tk)
3347 struct hash_entry *entry;
3351 if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3352 tk->tok = entry->tok;
3354 else if (entry->tok == TOK_IF) {
3357 else if (entry->tok == TOK_ELSE) {
3358 tk->tok = TOK_MELSE;
3361 tk->tok = TOK_MIDENT;
3365 static void hash_keyword(
3366 struct compile_state *state, const char *keyword, int tok)
3368 struct hash_entry *entry;
3369 entry = lookup(state, keyword, strlen(keyword));
3370 if (entry && entry->tok != TOK_UNKNOWN) {
3371 die("keyword %s already hashed", keyword);
3376 static void romcc_symbol(
3377 struct compile_state *state, struct hash_entry *ident,
3378 struct symbol **chain, struct triple *def, struct type *type, int depth)
3381 if (*chain && ((*chain)->scope_depth >= depth)) {
3382 error(state, 0, "%s already defined", ident->name);
3384 sym = xcmalloc(sizeof(*sym), "symbol");
3388 sym->scope_depth = depth;
3394 struct compile_state *state, struct hash_entry *ident,
3395 struct symbol **chain, struct triple *def, struct type *type)
3397 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3400 static void var_symbol(struct compile_state *state,
3401 struct hash_entry *ident, struct triple *def)
3403 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3404 internal_error(state, 0, "bad var type");
3406 symbol(state, ident, &ident->sym_ident, def, def->type);
3409 static void label_symbol(struct compile_state *state,
3410 struct hash_entry *ident, struct triple *label, int depth)
3412 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3415 static void start_scope(struct compile_state *state)
3417 state->scope_depth++;
3420 static void end_scope_syms(struct compile_state *state,
3421 struct symbol **chain, int depth)
3423 struct symbol *sym, *next;
3425 while(sym && (sym->scope_depth == depth)) {
3433 static void end_scope(struct compile_state *state)
3437 /* Walk through the hash table and remove all symbols
3438 * in the current scope.
3440 depth = state->scope_depth;
3441 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3442 struct hash_entry *entry;
3443 entry = state->hash_table[i];
3445 end_scope_syms(state, &entry->sym_label, depth);
3446 end_scope_syms(state, &entry->sym_tag, depth);
3447 end_scope_syms(state, &entry->sym_ident, depth);
3448 entry = entry->next;
3451 state->scope_depth = depth - 1;
3454 static void register_keywords(struct compile_state *state)
3456 hash_keyword(state, "auto", TOK_AUTO);
3457 hash_keyword(state, "break", TOK_BREAK);
3458 hash_keyword(state, "case", TOK_CASE);
3459 hash_keyword(state, "char", TOK_CHAR);
3460 hash_keyword(state, "const", TOK_CONST);
3461 hash_keyword(state, "continue", TOK_CONTINUE);
3462 hash_keyword(state, "default", TOK_DEFAULT);
3463 hash_keyword(state, "do", TOK_DO);
3464 hash_keyword(state, "double", TOK_DOUBLE);
3465 hash_keyword(state, "else", TOK_ELSE);
3466 hash_keyword(state, "enum", TOK_ENUM);
3467 hash_keyword(state, "extern", TOK_EXTERN);
3468 hash_keyword(state, "float", TOK_FLOAT);
3469 hash_keyword(state, "for", TOK_FOR);
3470 hash_keyword(state, "goto", TOK_GOTO);
3471 hash_keyword(state, "if", TOK_IF);
3472 hash_keyword(state, "inline", TOK_INLINE);
3473 hash_keyword(state, "int", TOK_INT);
3474 hash_keyword(state, "long", TOK_LONG);
3475 hash_keyword(state, "register", TOK_REGISTER);
3476 hash_keyword(state, "restrict", TOK_RESTRICT);
3477 hash_keyword(state, "return", TOK_RETURN);
3478 hash_keyword(state, "short", TOK_SHORT);
3479 hash_keyword(state, "signed", TOK_SIGNED);
3480 hash_keyword(state, "sizeof", TOK_SIZEOF);
3481 hash_keyword(state, "static", TOK_STATIC);
3482 hash_keyword(state, "struct", TOK_STRUCT);
3483 hash_keyword(state, "switch", TOK_SWITCH);
3484 hash_keyword(state, "typedef", TOK_TYPEDEF);
3485 hash_keyword(state, "union", TOK_UNION);
3486 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3487 hash_keyword(state, "void", TOK_VOID);
3488 hash_keyword(state, "volatile", TOK_VOLATILE);
3489 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3490 hash_keyword(state, "while", TOK_WHILE);
3491 hash_keyword(state, "asm", TOK_ASM);
3492 hash_keyword(state, "__asm__", TOK_ASM);
3493 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3494 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3497 static void register_macro_keywords(struct compile_state *state)
3499 hash_keyword(state, "define", TOK_MDEFINE);
3500 hash_keyword(state, "defined", TOK_MDEFINED);
3501 hash_keyword(state, "undef", TOK_MUNDEF);
3502 hash_keyword(state, "include", TOK_MINCLUDE);
3503 hash_keyword(state, "line", TOK_MLINE);
3504 hash_keyword(state, "error", TOK_MERROR);
3505 hash_keyword(state, "warning", TOK_MWARNING);
3506 hash_keyword(state, "pragma", TOK_MPRAGMA);
3507 hash_keyword(state, "ifdef", TOK_MIFDEF);
3508 hash_keyword(state, "ifndef", TOK_MIFNDEF);
3509 hash_keyword(state, "elif", TOK_MELIF);
3510 hash_keyword(state, "endif", TOK_MENDIF);
3514 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3516 if (ident->sym_define != 0) {
3517 struct macro *macro;
3518 struct macro_arg *arg, *anext;
3519 macro = ident->sym_define;
3520 ident->sym_define = 0;
3522 /* Free the macro arguments... */
3523 anext = macro->args;
3530 /* Free the macro buffer */
3533 /* Now free the macro itself */
3538 static void do_define_macro(struct compile_state *state,
3539 struct hash_entry *ident, const char *body,
3540 int argc, struct macro_arg *args)
3542 struct macro *macro;
3543 struct macro_arg *arg;
3546 /* Find the length of the body */
3547 body_len = strlen(body);
3548 macro = ident->sym_define;
3550 int identical_bodies, identical_args;
3551 struct macro_arg *oarg;
3552 /* Explicitly allow identical redfinitions of the same macro */
3554 (macro->buf_len == body_len) &&
3555 (memcmp(macro->buf, body, body_len) == 0);
3556 identical_args = macro->argc == argc;
3559 while(identical_args && arg) {
3560 identical_args = oarg->ident == arg->ident;
3564 if (identical_bodies && identical_args) {
3568 error(state, 0, "macro %s already defined\n", ident->name);
3571 fprintf(state->errout, "#define %s: `%*.*s'\n",
3572 ident->name, body_len, body_len, body);
3574 macro = xmalloc(sizeof(*macro), "macro");
3575 macro->ident = ident;
3577 macro->buf_len = body_len;
3581 ident->sym_define = macro;
3584 static void define_macro(
3585 struct compile_state *state,
3586 struct hash_entry *ident,
3587 const char *body, int body_len,
3588 int argc, struct macro_arg *args)
3591 buf = xmalloc(body_len + 1, "macro buf");
3592 memcpy(buf, body, body_len);
3593 buf[body_len] = '\0';
3594 do_define_macro(state, ident, buf, argc, args);
3597 static void register_builtin_macro(struct compile_state *state,
3598 const char *name, const char *value)
3600 struct hash_entry *ident;
3602 if (value[0] == '(') {
3603 internal_error(state, 0, "Builtin macros with arguments not supported");
3605 ident = lookup(state, name, strlen(name));
3606 define_macro(state, ident, value, strlen(value), -1, 0);
3609 static void register_builtin_macros(struct compile_state *state)
3616 tm = localtime(&now);
3618 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3619 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3620 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3621 register_builtin_macro(state, "__LINE__", "54321");
3623 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3624 sprintf(buf, "\"%s\"", scratch);
3625 register_builtin_macro(state, "__DATE__", buf);
3627 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3628 sprintf(buf, "\"%s\"", scratch);
3629 register_builtin_macro(state, "__TIME__", buf);
3631 /* I can't be a conforming implementation of C :( */
3632 register_builtin_macro(state, "__STDC__", "0");
3633 /* In particular I don't conform to C99 */
3634 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3638 static void process_cmdline_macros(struct compile_state *state)
3640 const char **macro, *name;
3641 struct hash_entry *ident;
3642 for(macro = state->compiler->defines; (name = *macro); macro++) {
3646 name_len = strlen(name);
3647 body = strchr(name, '=');
3651 name_len = body - name;
3654 ident = lookup(state, name, name_len);
3655 define_macro(state, ident, body, strlen(body), -1, 0);
3657 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3658 ident = lookup(state, name, strlen(name));
3659 undef_macro(state, ident);
3663 static int spacep(int c)
3678 static int digitp(int c)
3682 case '0': case '1': case '2': case '3': case '4':
3683 case '5': case '6': case '7': case '8': case '9':
3689 static int digval(int c)
3692 if ((c >= '0') && (c <= '9')) {
3698 static int hexdigitp(int c)
3702 case '0': case '1': case '2': case '3': case '4':
3703 case '5': case '6': case '7': case '8': case '9':
3704 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3705 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3711 static int hexdigval(int c)
3714 if ((c >= '0') && (c <= '9')) {
3717 else if ((c >= 'A') && (c <= 'F')) {
3718 val = 10 + (c - 'A');
3720 else if ((c >= 'a') && (c <= 'f')) {
3721 val = 10 + (c - 'a');
3726 static int octdigitp(int c)
3730 case '0': case '1': case '2': case '3':
3731 case '4': case '5': case '6': case '7':
3737 static int octdigval(int c)
3740 if ((c >= '0') && (c <= '7')) {
3746 static int letterp(int c)
3750 case 'a': case 'b': case 'c': case 'd': case 'e':
3751 case 'f': case 'g': case 'h': case 'i': case 'j':
3752 case 'k': case 'l': case 'm': case 'n': case 'o':
3753 case 'p': case 'q': case 'r': case 's': case 't':
3754 case 'u': case 'v': case 'w': case 'x': case 'y':
3756 case 'A': case 'B': case 'C': case 'D': case 'E':
3757 case 'F': case 'G': case 'H': case 'I': case 'J':
3758 case 'K': case 'L': case 'M': case 'N': case 'O':
3759 case 'P': case 'Q': case 'R': case 'S': case 'T':
3760 case 'U': case 'V': case 'W': case 'X': case 'Y':
3769 static const char *identifier(const char *str, const char *end)
3771 if (letterp(*str)) {
3772 for(; str < end; str++) {
3775 if (!letterp(c) && !digitp(c)) {
3783 static int char_value(struct compile_state *state,
3784 const signed char **strp, const signed char *end)
3786 const signed char *str;
3790 if ((c == '\\') && (str < end)) {
3792 case 'n': c = '\n'; str++; break;
3793 case 't': c = '\t'; str++; break;
3794 case 'v': c = '\v'; str++; break;
3795 case 'b': c = '\b'; str++; break;
3796 case 'r': c = '\r'; str++; break;
3797 case 'f': c = '\f'; str++; break;
3798 case 'a': c = '\a'; str++; break;
3799 case '\\': c = '\\'; str++; break;
3800 case '?': c = '?'; str++; break;
3801 case '\'': c = '\''; str++; break;
3802 case '"': c = '"'; str++; break;
3806 while((str < end) && hexdigitp(*str)) {
3808 c += hexdigval(*str);
3812 case '0': case '1': case '2': case '3':
3813 case '4': case '5': case '6': case '7':
3815 while((str < end) && octdigitp(*str)) {
3817 c += octdigval(*str);
3822 error(state, 0, "Invalid character constant");
3830 static const char *next_char(struct file_state *file, const char *pos, int index)
3832 const char *end = file->buf + file->size;
3834 /* Lookup the character */
3837 /* Is this a trigraph? */
3838 if (file->trigraphs &&
3839 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3842 case '=': c = '#'; break;
3843 case '/': c = '\\'; break;
3844 case '\'': c = '^'; break;
3845 case '(': c = '['; break;
3846 case ')': c = ']'; break;
3847 case '!': c = '!'; break;
3848 case '<': c = '{'; break;
3849 case '>': c = '}'; break;
3850 case '-': c = '~'; break;
3856 /* Is this an escaped newline? */
3857 if (file->join_lines &&
3858 (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3860 int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3861 /* At the start of a line just eat it */
3862 if (pos == file->pos) {
3864 file->report_line++;
3865 file->line_start = pos + size + 1 + cr_offset;
3867 pos += size + 1 + cr_offset;
3869 /* Do I need to ga any farther? */
3870 else if (index == 0) {
3873 /* Process a normal character */
3882 static int get_char(struct file_state *file, const char *pos)
3884 const char *end = file->buf + file->size;
3887 pos = next_char(file, pos, 0);
3889 /* Lookup the character */
3891 /* If it is a trigraph get the trigraph value */
3892 if (file->trigraphs &&
3893 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3896 case '=': c = '#'; break;
3897 case '/': c = '\\'; break;
3898 case '\'': c = '^'; break;
3899 case '(': c = '['; break;
3900 case ')': c = ']'; break;
3901 case '!': c = '!'; break;
3902 case '<': c = '{'; break;
3903 case '>': c = '}'; break;
3904 case '-': c = '~'; break;
3911 static void eat_chars(struct file_state *file, const char *targ)
3913 const char *pos = file->pos;
3915 /* Do we have a newline? */
3916 if (pos[0] == '\n') {
3918 file->report_line++;
3919 file->line_start = pos + 1;
3927 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3932 src = next_char(file, src, 1);
3938 static void char_strcpy(char *dest,
3939 struct file_state *file, const char *src, const char *end)
3943 c = get_char(file, src);
3944 src = next_char(file, src, 1);
3949 static char *char_strdup(struct file_state *file,
3950 const char *start, const char *end, const char *id)
3954 str_len = char_strlen(file, start, end);
3955 str = xcmalloc(str_len + 1, id);
3956 char_strcpy(str, file, start, end);
3957 str[str_len] = '\0';
3961 static const char *after_digits(struct file_state *file, const char *ptr)
3963 while(digitp(get_char(file, ptr))) {
3964 ptr = next_char(file, ptr, 1);
3969 static const char *after_octdigits(struct file_state *file, const char *ptr)
3971 while(octdigitp(get_char(file, ptr))) {
3972 ptr = next_char(file, ptr, 1);
3977 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3979 while(hexdigitp(get_char(file, ptr))) {
3980 ptr = next_char(file, ptr, 1);
3985 static const char *after_alnums(struct file_state *file, const char *ptr)
3988 c = get_char(file, ptr);
3989 while(letterp(c) || digitp(c)) {
3990 ptr = next_char(file, ptr, 1);
3991 c = get_char(file, ptr);
3996 static void save_string(struct file_state *file,
3997 struct token *tk, const char *start, const char *end, const char *id)
4001 /* Create a private copy of the string */
4002 str = char_strdup(file, start, end, id);
4004 /* Store the copy in the token */
4006 tk->str_len = strlen(str);
4009 static void raw_next_token(struct compile_state *state,
4010 struct file_state *file, struct token *tk)
4020 token = tokp = next_char(file, file->pos, 0);
4022 c = get_char(file, tokp);
4023 tokp = next_char(file, tokp, 1);
4025 c1 = get_char(file, tokp);
4026 c2 = get_char(file, next_char(file, tokp, 1));
4027 c3 = get_char(file, next_char(file, tokp, 2));
4029 /* The end of the file */
4034 else if (spacep(c)) {
4036 while (spacep(get_char(file, tokp))) {
4037 tokp = next_char(file, tokp, 1);
4041 else if ((c == '/') && (c1 == '/')) {
4043 tokp = next_char(file, tokp, 1);
4044 while((c = get_char(file, tokp)) != -1) {
4045 /* Advance to the next character only after we verify
4046 * the current character is not a newline.
4047 * EOL is special to the preprocessor so we don't
4048 * want to loose any.
4053 tokp = next_char(file, tokp, 1);
4057 else if ((c == '/') && (c1 == '*')) {
4058 tokp = next_char(file, tokp, 2);
4060 while((c1 = get_char(file, tokp)) != -1) {
4061 tokp = next_char(file, tokp, 1);
4062 if ((c == '*') && (c1 == '/')) {
4068 if (tok == TOK_UNKNOWN) {
4069 error(state, 0, "unterminated comment");
4072 /* string constants */
4073 else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4074 int wchar, multiline;
4080 tokp = next_char(file, tokp, 1);
4082 while((c = get_char(file, tokp)) != -1) {
4083 tokp = next_char(file, tokp, 1);
4087 else if (c == '\\') {
4088 tokp = next_char(file, tokp, 1);
4090 else if (c == '"') {
4091 tok = TOK_LIT_STRING;
4095 if (tok == TOK_UNKNOWN) {
4096 error(state, 0, "unterminated string constant");
4099 warning(state, 0, "multiline string constant");
4102 /* Save the string value */
4103 save_string(file, tk, token, tokp, "literal string");
4105 /* character constants */
4106 else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4107 int wchar, multiline;
4113 tokp = next_char(file, tokp, 1);
4115 while((c = get_char(file, tokp)) != -1) {
4116 tokp = next_char(file, tokp, 1);
4120 else if (c == '\\') {
4121 tokp = next_char(file, tokp, 1);
4123 else if (c == '\'') {
4128 if (tok == TOK_UNKNOWN) {
4129 error(state, 0, "unterminated character constant");
4132 warning(state, 0, "multiline character constant");
4135 /* Save the character value */
4136 save_string(file, tk, token, tokp, "literal character");
4138 /* integer and floating constants
4144 * Floating constants
4145 * {digits}.{digits}[Ee][+-]?{digits}
4147 * {digits}[Ee][+-]?{digits}
4148 * .{digits}[Ee][+-]?{digits}
4151 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4157 next = after_digits(file, tokp);
4162 cn = get_char(file, next);
4164 next = next_char(file, next, 1);
4165 next = after_digits(file, next);
4168 cn = get_char(file, next);
4169 if ((cn == 'e') || (cn == 'E')) {
4171 next = next_char(file, next, 1);
4172 cn = get_char(file, next);
4173 if ((cn == '+') || (cn == '-')) {
4174 next = next_char(file, next, 1);
4176 new = after_digits(file, next);
4177 is_float |= (new != next);
4181 tok = TOK_LIT_FLOAT;
4182 cn = get_char(file, next);
4183 if ((cn == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4184 next = next_char(file, next, 1);
4187 if (!is_float && digitp(c)) {
4189 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4190 next = next_char(file, tokp, 1);
4191 next = after_hexdigits(file, next);
4193 else if (c == '0') {
4194 next = after_octdigits(file, tokp);
4197 next = after_digits(file, tokp);
4199 /* crazy integer suffixes */
4200 cn = get_char(file, next);
4201 if ((cn == 'u') || (cn == 'U')) {
4202 next = next_char(file, next, 1);
4203 cn = get_char(file, next);
4204 if ((cn == 'l') || (cn == 'L')) {
4205 next = next_char(file, next, 1);
4206 cn = get_char(file, next);
4208 if ((cn == 'l') || (cn == 'L')) {
4209 next = next_char(file, next, 1);
4212 else if ((cn == 'l') || (cn == 'L')) {
4213 next = next_char(file, next, 1);
4214 cn = get_char(file, next);
4215 if ((cn == 'l') || (cn == 'L')) {
4216 next = next_char(file, next, 1);
4217 cn = get_char(file, next);
4219 if ((cn == 'u') || (cn == 'U')) {
4220 next = next_char(file, next, 1);
4226 /* Save the integer/floating point value */
4227 save_string(file, tk, token, tokp, "literal number");
4230 else if (letterp(c)) {
4233 /* Find and save the identifier string */
4234 tokp = after_alnums(file, tokp);
4235 save_string(file, tk, token, tokp, "identifier");
4237 /* Look up to see which identifier it is */
4238 tk->ident = lookup(state, tk->val.str, tk->str_len);
4240 /* Free the identifier string */
4244 /* See if this identifier can be macro expanded */
4245 tk->val.notmacro = 0;
4246 c = get_char(file, tokp);
4248 tokp = next_char(file, tokp, 1);
4249 tk->val.notmacro = 1;
4252 /* C99 alternate macro characters */
4253 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4255 tok = TOK_CONCATENATE;
4257 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4258 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4259 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4260 else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4261 else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4262 else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4263 else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4264 else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4265 else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4266 else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4267 else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4268 else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4269 else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4270 else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4271 else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4272 else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4273 else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4274 else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4275 else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4276 else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4277 else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4278 else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4279 else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4280 else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4281 else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4282 else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4283 else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4284 else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4285 else if (c == ';') { tok = TOK_SEMI; }
4286 else if (c == '{') { tok = TOK_LBRACE; }
4287 else if (c == '}') { tok = TOK_RBRACE; }
4288 else if (c == ',') { tok = TOK_COMMA; }
4289 else if (c == '=') { tok = TOK_EQ; }
4290 else if (c == ':') { tok = TOK_COLON; }
4291 else if (c == '[') { tok = TOK_LBRACKET; }
4292 else if (c == ']') { tok = TOK_RBRACKET; }
4293 else if (c == '(') { tok = TOK_LPAREN; }
4294 else if (c == ')') { tok = TOK_RPAREN; }
4295 else if (c == '*') { tok = TOK_STAR; }
4296 else if (c == '>') { tok = TOK_MORE; }
4297 else if (c == '<') { tok = TOK_LESS; }
4298 else if (c == '?') { tok = TOK_QUEST; }
4299 else if (c == '|') { tok = TOK_OR; }
4300 else if (c == '&') { tok = TOK_AND; }
4301 else if (c == '^') { tok = TOK_XOR; }
4302 else if (c == '+') { tok = TOK_PLUS; }
4303 else if (c == '-') { tok = TOK_MINUS; }
4304 else if (c == '/') { tok = TOK_DIV; }
4305 else if (c == '%') { tok = TOK_MOD; }
4306 else if (c == '!') { tok = TOK_BANG; }
4307 else if (c == '.') { tok = TOK_DOT; }
4308 else if (c == '~') { tok = TOK_TILDE; }
4309 else if (c == '#') { tok = TOK_MACRO; }
4310 else if (c == '\n') { tok = TOK_EOL; }
4312 tokp = next_char(file, tokp, eat);
4313 eat_chars(file, tokp);
4318 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4320 if (tk->tok != tok) {
4321 const char *name1, *name2;
4322 name1 = tokens[tk->tok];
4324 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4325 name2 = tk->ident->name;
4327 error(state, 0, "\tfound %s %s expected %s",
4328 name1, name2, tokens[tok]);
4332 struct macro_arg_value {
4333 struct hash_entry *ident;
4337 static struct macro_arg_value *read_macro_args(
4338 struct compile_state *state, struct macro *macro,
4339 struct file_state *file, struct token *tk)
4341 struct macro_arg_value *argv;
4342 struct macro_arg *arg;
4346 if (macro->argc == 0) {
4348 raw_next_token(state, file, tk);
4349 } while(tk->tok == TOK_SPACE);
4352 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4353 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4356 argv[i].ident = arg->ident;
4365 raw_next_token(state, file, tk);
4367 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4368 (argv[i].ident != state->i___VA_ARGS__))
4371 if (i >= macro->argc) {
4372 error(state, 0, "too many args to %s\n",
4373 macro->ident->name);
4378 if (tk->tok == TOK_LPAREN) {
4382 if (tk->tok == TOK_RPAREN) {
4383 if (paren_depth == 0) {
4388 if (tk->tok == TOK_EOF) {
4389 error(state, 0, "End of file encountered while parsing macro arguments");
4392 len = char_strlen(file, start, file->pos);
4393 argv[i].value = xrealloc(
4394 argv[i].value, argv[i].len + len, "macro args");
4395 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4398 if (i != macro->argc -1) {
4399 error(state, 0, "missing %s arg %d\n",
4400 macro->ident->name, i +2);
4406 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4409 for(i = 0; i < macro->argc; i++) {
4410 xfree(argv[i].value);
4420 static void grow_macro_buf(struct compile_state *state,
4421 const char *id, struct macro_buf *buf,
4424 if ((buf->pos + grow) >= buf->len) {
4425 buf->str = xrealloc(buf->str, buf->len + grow, id);
4430 static void append_macro_text(struct compile_state *state,
4431 const char *id, struct macro_buf *buf,
4432 const char *fstart, size_t flen)
4434 grow_macro_buf(state, id, buf, flen);
4435 memcpy(buf->str + buf->pos, fstart, flen);
4437 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4438 buf->pos, buf->pos, buf->str,
4439 flen, flen, buf->str + buf->pos);
4445 static void append_macro_chars(struct compile_state *state,
4446 const char *id, struct macro_buf *buf,
4447 struct file_state *file, const char *start, const char *end)
4450 flen = char_strlen(file, start, end);
4451 grow_macro_buf(state, id, buf, flen);
4452 char_strcpy(buf->str + buf->pos, file, start, end);
4454 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4455 buf->pos, buf->pos, buf->str,
4456 flen, flen, buf->str + buf->pos);
4461 static int compile_macro(struct compile_state *state,
4462 struct file_state **filep, struct token *tk);
4464 static void macro_expand_args(struct compile_state *state,
4465 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4469 for(i = 0; i < macro->argc; i++) {
4470 struct file_state fmacro, *file;
4471 struct macro_buf buf;
4474 fmacro.basename = argv[i].ident->name;
4475 fmacro.dirname = "";
4476 fmacro.buf = (char *)argv[i].value;
4477 fmacro.size = argv[i].len;
4478 fmacro.pos = fmacro.buf;
4480 fmacro.line_start = fmacro.buf;
4481 fmacro.report_line = 1;
4482 fmacro.report_name = fmacro.basename;
4483 fmacro.report_dir = fmacro.dirname;
4485 fmacro.trigraphs = 0;
4486 fmacro.join_lines = 0;
4488 buf.len = argv[i].len;
4489 buf.str = xmalloc(buf.len, argv[i].ident->name);
4494 raw_next_token(state, file, tk);
4496 /* If we have recursed into another macro body
4499 if (tk->tok == TOK_EOF) {
4500 struct file_state *old;
4506 /* old->basename is used keep it */
4507 xfree(old->dirname);
4512 else if (tk->ident && tk->ident->sym_define) {
4513 if (compile_macro(state, &file, tk)) {
4518 append_macro_chars(state, macro->ident->name, &buf,
4519 file, tk->pos, file->pos);
4522 xfree(argv[i].value);
4523 argv[i].value = buf.str;
4524 argv[i].len = buf.pos;
4529 static void expand_macro(struct compile_state *state,
4530 struct macro *macro, struct macro_buf *buf,
4531 struct macro_arg_value *argv, struct token *tk)
4533 struct file_state fmacro;
4534 const char space[] = " ";
4539 /* Place the macro body in a dummy file */
4541 fmacro.basename = macro->ident->name;
4542 fmacro.dirname = "";
4543 fmacro.buf = macro->buf;
4544 fmacro.size = macro->buf_len;
4545 fmacro.pos = fmacro.buf;
4547 fmacro.line_start = fmacro.buf;
4548 fmacro.report_line = 1;
4549 fmacro.report_name = fmacro.basename;
4550 fmacro.report_dir = fmacro.dirname;
4552 fmacro.trigraphs = 0;
4553 fmacro.join_lines = 0;
4555 /* Allocate a buffer to hold the macro expansion */
4556 buf->len = macro->buf_len + 3;
4557 buf->str = xmalloc(buf->len, macro->ident->name);
4560 fstart = fmacro.pos;
4561 raw_next_token(state, &fmacro, tk);
4562 while(tk->tok != TOK_EOF) {
4563 flen = fmacro.pos - fstart;
4566 for(i = 0; i < macro->argc; i++) {
4567 if (argv[i].ident == tk->ident) {
4571 if (i >= macro->argc) {
4574 /* Substitute macro parameter */
4575 fstart = argv[i].value;
4579 if (macro->argc < 0) {
4583 raw_next_token(state, &fmacro, tk);
4584 } while(tk->tok == TOK_SPACE);
4585 check_tok(state, tk, TOK_IDENT);
4586 for(i = 0; i < macro->argc; i++) {
4587 if (argv[i].ident == tk->ident) {
4591 if (i >= macro->argc) {
4592 error(state, 0, "parameter `%s' not found",
4595 /* Stringize token */
4596 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4597 for(j = 0; j < argv[i].len; j++) {
4598 char *str = argv[i].value + j;
4604 else if (*str == '"') {
4608 append_macro_text(state, macro->ident->name, buf, str, len);
4610 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4614 case TOK_CONCATENATE:
4615 /* Concatenate tokens */
4616 /* Delete the previous whitespace token */
4617 if (buf->str[buf->pos - 1] == ' ') {
4620 /* Skip the next sequence of whitspace tokens */
4622 fstart = fmacro.pos;
4623 raw_next_token(state, &fmacro, tk);
4624 } while(tk->tok == TOK_SPACE);
4625 /* Restart at the top of the loop.
4626 * I need to process the non white space token.
4631 /* Collapse multiple spaces into one */
4632 if (buf->str[buf->pos - 1] != ' ') {
4644 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4646 fstart = fmacro.pos;
4647 raw_next_token(state, &fmacro, tk);
4651 static void tag_macro_name(struct compile_state *state,
4652 struct macro *macro, struct macro_buf *buf,
4655 /* Guard all instances of the macro name in the replacement
4656 * text from further macro expansion.
4658 struct file_state fmacro;
4662 /* Put the old macro expansion buffer in a file */
4664 fmacro.basename = macro->ident->name;
4665 fmacro.dirname = "";
4666 fmacro.buf = buf->str;
4667 fmacro.size = buf->pos;
4668 fmacro.pos = fmacro.buf;
4670 fmacro.line_start = fmacro.buf;
4671 fmacro.report_line = 1;
4672 fmacro.report_name = fmacro.basename;
4673 fmacro.report_dir = fmacro.dirname;
4675 fmacro.trigraphs = 0;
4676 fmacro.join_lines = 0;
4678 /* Allocate a new macro expansion buffer */
4679 buf->len = macro->buf_len + 3;
4680 buf->str = xmalloc(buf->len, macro->ident->name);
4683 fstart = fmacro.pos;
4684 raw_next_token(state, &fmacro, tk);
4685 while(tk->tok != TOK_EOF) {
4686 flen = fmacro.pos - fstart;
4687 if ((tk->tok == TOK_IDENT) &&
4688 (tk->ident == macro->ident) &&
4689 (tk->val.notmacro == 0))
4691 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4696 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4698 fstart = fmacro.pos;
4699 raw_next_token(state, &fmacro, tk);
4704 static int compile_macro(struct compile_state *state,
4705 struct file_state **filep, struct token *tk)
4707 struct file_state *file;
4708 struct hash_entry *ident;
4709 struct macro *macro;
4710 struct macro_arg_value *argv;
4711 struct macro_buf buf;
4714 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4717 macro = ident->sym_define;
4719 /* If this token comes from a macro expansion ignore it */
4720 if (tk->val.notmacro) {
4723 /* If I am a function like macro and the identifier is not followed
4724 * by a left parenthesis, do nothing.
4726 if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4730 /* Read in the macro arguments */
4732 if (macro->argc >= 0) {
4733 raw_next_token(state, *filep, tk);
4734 check_tok(state, tk, TOK_LPAREN);
4736 argv = read_macro_args(state, macro, *filep, tk);
4738 check_tok(state, tk, TOK_RPAREN);
4740 /* Macro expand the macro arguments */
4741 macro_expand_args(state, macro, argv, tk);
4746 if (ident == state->i___FILE__) {
4747 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4748 buf.str = xmalloc(buf.len, ident->name);
4749 sprintf(buf.str, "\"%s\"", state->file->basename);
4750 buf.pos = strlen(buf.str);
4752 else if (ident == state->i___LINE__) {
4754 buf.str = xmalloc(buf.len, ident->name);
4755 sprintf(buf.str, "%d", state->file->line);
4756 buf.pos = strlen(buf.str);
4759 expand_macro(state, macro, &buf, argv, tk);
4761 /* Tag the macro name with a $ so it will no longer
4762 * be regonized as a canidate for macro expansion.
4764 tag_macro_name(state, macro, &buf, tk);
4767 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4768 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4771 free_macro_args(macro, argv);
4773 file = xmalloc(sizeof(*file), "file_state");
4774 file->prev = *filep;
4775 file->basename = xstrdup(ident->name);
4776 file->dirname = xstrdup("");
4777 file->buf = buf.str;
4778 file->size = buf.pos;
4779 file->pos = file->buf;
4781 file->line_start = file->pos;
4782 file->report_line = 1;
4783 file->report_name = file->basename;
4784 file->report_dir = file->dirname;
4786 file->trigraphs = 0;
4787 file->join_lines = 0;
4792 static void eat_tokens(struct compile_state *state, int targ_tok)
4794 if (state->eat_depth > 0) {
4795 internal_error(state, 0, "Already eating...");
4797 state->eat_depth = state->if_depth;
4798 state->eat_targ = targ_tok;
4800 static int if_eat(struct compile_state *state)
4802 return state->eat_depth > 0;
4804 static int if_value(struct compile_state *state)
4807 index = state->if_depth / CHAR_BIT;
4808 offset = state->if_depth % CHAR_BIT;
4809 return !!(state->if_bytes[index] & (1 << (offset)));
4811 static void set_if_value(struct compile_state *state, int value)
4814 index = state->if_depth / CHAR_BIT;
4815 offset = state->if_depth % CHAR_BIT;
4817 state->if_bytes[index] &= ~(1 << offset);
4819 state->if_bytes[index] |= (1 << offset);
4822 static void in_if(struct compile_state *state, const char *name)
4824 if (state->if_depth <= 0) {
4825 error(state, 0, "%s without #if", name);
4828 static void enter_if(struct compile_state *state)
4830 state->if_depth += 1;
4831 if (state->if_depth > MAX_PP_IF_DEPTH) {
4832 error(state, 0, "#if depth too great");
4835 static void reenter_if(struct compile_state *state, const char *name)
4838 if ((state->eat_depth == state->if_depth) &&
4839 (state->eat_targ == TOK_MELSE)) {
4840 state->eat_depth = 0;
4841 state->eat_targ = 0;
4844 static void enter_else(struct compile_state *state, const char *name)
4847 if ((state->eat_depth == state->if_depth) &&
4848 (state->eat_targ == TOK_MELSE)) {
4849 state->eat_depth = 0;
4850 state->eat_targ = 0;
4853 static void exit_if(struct compile_state *state, const char *name)
4856 if (state->eat_depth == state->if_depth) {
4857 state->eat_depth = 0;
4858 state->eat_targ = 0;
4860 state->if_depth -= 1;
4863 static void raw_token(struct compile_state *state, struct token *tk)
4865 struct file_state *file;
4869 raw_next_token(state, file, tk);
4873 /* Exit out of an include directive or macro call */
4874 if ((tk->tok == TOK_EOF) &&
4875 (file != state->macro_file) && file->prev)
4877 state->file = file->prev;
4878 /* file->basename is used keep it */
4879 xfree(file->dirname);
4883 raw_next_token(state, state->file, tk);
4889 static void pp_token(struct compile_state *state, struct token *tk)
4891 struct file_state *file;
4894 raw_token(state, tk);
4898 if (tk->tok == TOK_SPACE) {
4899 raw_token(state, tk);
4902 else if (tk->tok == TOK_IDENT) {
4903 if (state->token_base == 0) {
4904 ident_to_keyword(state, tk);
4906 ident_to_macro(state, tk);
4912 static void preprocess(struct compile_state *state, struct token *tk);
4914 static void token(struct compile_state *state, struct token *tk)
4917 pp_token(state, tk);
4920 /* Process a macro directive */
4921 if (tk->tok == TOK_MACRO) {
4922 /* Only match preprocessor directives at the start of a line */
4924 ptr = state->file->line_start;
4925 while((ptr < tk->pos)
4926 && spacep(get_char(state->file, ptr)))
4928 ptr = next_char(state->file, ptr, 1);
4930 if (ptr == tk->pos) {
4931 preprocess(state, tk);
4935 /* Expand a macro call */
4936 else if (tk->ident && tk->ident->sym_define) {
4937 rescan = compile_macro(state, &state->file, tk);
4939 pp_token(state, tk);
4942 /* Eat tokens disabled by the preprocessor
4943 * (Unless we are parsing a preprocessor directive
4945 else if (if_eat(state) && (state->token_base == 0)) {
4946 pp_token(state, tk);
4949 /* Make certain EOL only shows up in preprocessor directives */
4950 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4951 pp_token(state, tk);
4954 /* Error on unknown tokens */
4955 else if (tk->tok == TOK_UNKNOWN) {
4956 error(state, 0, "unknown token");
4962 static inline struct token *get_token(struct compile_state *state, int offset)
4965 index = state->token_base + offset;
4966 if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4967 internal_error(state, 0, "token array to small");
4969 return &state->token[index];
4972 static struct token *do_eat_token(struct compile_state *state, int tok)
4976 check_tok(state, get_token(state, 1), tok);
4978 /* Free the old token value */
4979 tk = get_token(state, 0);
4981 memset((void *)tk->val.str, -1, tk->str_len);
4984 /* Overwrite the old token with newer tokens */
4985 for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4986 state->token[i] = state->token[i + 1];
4988 /* Clear the last token */
4989 memset(&state->token[i], 0, sizeof(state->token[i]));
4990 state->token[i].tok = -1;
4992 /* Return the token */
4996 static int raw_peek(struct compile_state *state)
4999 tk1 = get_token(state, 1);
5000 if (tk1->tok == -1) {
5001 raw_token(state, tk1);
5006 static struct token *raw_eat(struct compile_state *state, int tok)
5009 return do_eat_token(state, tok);
5012 static int pp_peek(struct compile_state *state)
5015 tk1 = get_token(state, 1);
5016 if (tk1->tok == -1) {
5017 pp_token(state, tk1);
5022 static struct token *pp_eat(struct compile_state *state, int tok)
5025 return do_eat_token(state, tok);
5028 static int peek(struct compile_state *state)
5031 tk1 = get_token(state, 1);
5032 if (tk1->tok == -1) {
5038 static int peek2(struct compile_state *state)
5040 struct token *tk1, *tk2;
5041 tk1 = get_token(state, 1);
5042 tk2 = get_token(state, 2);
5043 if (tk1->tok == -1) {
5046 if (tk2->tok == -1) {
5052 static struct token *eat(struct compile_state *state, int tok)
5055 return do_eat_token(state, tok);
5058 static void compile_file(struct compile_state *state, const char *filename, int local)
5060 char cwd[MAX_CWD_SIZE];
5061 const char *subdir, *base;
5063 struct file_state *file;
5065 file = xmalloc(sizeof(*file), "file_state");
5067 base = strrchr(filename, '/');
5070 subdir_len = base - filename;
5077 basename = xmalloc(strlen(base) +1, "basename");
5078 strcpy(basename, base);
5079 file->basename = basename;
5081 if (getcwd(cwd, sizeof(cwd)) == 0) {
5082 die("cwd buffer to small");
5084 if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5085 file->dirname = xmalloc(subdir_len + 1, "dirname");
5086 memcpy(file->dirname, subdir, subdir_len);
5087 file->dirname[subdir_len] = '\0';
5093 /* Find the appropriate directory... */
5095 if (!state->file && exists(cwd, filename)) {
5098 if (local && state->file && exists(state->file->dirname, filename)) {
5099 dir = state->file->dirname;
5101 for(path = state->compiler->include_paths; !dir && *path; path++) {
5102 if (exists(*path, filename)) {
5107 error(state, 0, "Cannot open `%s'\n", filename);
5109 dirlen = strlen(dir);
5110 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5111 memcpy(file->dirname, dir, dirlen);
5112 file->dirname[dirlen] = '/';
5113 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5114 file->dirname[dirlen + 1 + subdir_len] = '\0';
5116 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5118 file->pos = file->buf;
5119 file->line_start = file->pos;
5122 file->report_line = 1;
5123 file->report_name = file->basename;
5124 file->report_dir = file->dirname;
5126 file->trigraphs = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5127 file->join_lines = 1;
5129 file->prev = state->file;
5133 static struct triple *constant_expr(struct compile_state *state);
5134 static void integral(struct compile_state *state, struct triple *def);
5136 static int mcexpr(struct compile_state *state)
5138 struct triple *cvalue;
5139 cvalue = constant_expr(state);
5140 integral(state, cvalue);
5141 if (cvalue->op != OP_INTCONST) {
5142 error(state, 0, "integer constant expected");
5144 return cvalue->u.cval != 0;
5147 static void preprocess(struct compile_state *state, struct token *current_token)
5149 /* Doing much more with the preprocessor would require
5150 * a parser and a major restructuring.
5151 * Postpone that for later.
5156 state->macro_file = state->file;
5158 old_token_base = state->token_base;
5159 state->token_base = current_token - state->token;
5161 tok = pp_peek(state);
5167 tk = pp_eat(state, TOK_LIT_INT);
5168 override_line = strtoul(tk->val.str, 0, 10);
5169 /* I have a preprocessor line marker parse it */
5170 if (pp_peek(state) == TOK_LIT_STRING) {
5171 const char *token, *base;
5173 int name_len, dir_len;
5174 tk = pp_eat(state, TOK_LIT_STRING);
5175 name = xmalloc(tk->str_len, "report_name");
5176 token = tk->val.str + 1;
5177 base = strrchr(token, '/');
5178 name_len = tk->str_len -2;
5180 dir_len = base - token;
5182 name_len -= base - token;
5187 memcpy(name, base, name_len);
5188 name[name_len] = '\0';
5189 dir = xmalloc(dir_len + 1, "report_dir");
5190 memcpy(dir, token, dir_len);
5191 dir[dir_len] = '\0';
5192 state->file->report_line = override_line - 1;
5193 state->file->report_name = name;
5194 state->file->report_dir = dir;
5195 state->file->macro = 0;
5202 pp_eat(state, TOK_MLINE);
5203 tk = eat(state, TOK_LIT_INT);
5204 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5205 if (pp_peek(state) == TOK_LIT_STRING) {
5206 const char *token, *base;
5208 int name_len, dir_len;
5209 tk = pp_eat(state, TOK_LIT_STRING);
5210 name = xmalloc(tk->str_len, "report_name");
5211 token = tk->val.str + 1;
5212 base = strrchr(token, '/');
5213 name_len = tk->str_len - 2;
5215 dir_len = base - token;
5217 name_len -= base - token;
5222 memcpy(name, base, name_len);
5223 name[name_len] = '\0';
5224 dir = xmalloc(dir_len + 1, "report_dir");
5225 memcpy(dir, token, dir_len);
5226 dir[dir_len] = '\0';
5227 state->file->report_name = name;
5228 state->file->report_dir = dir;
5229 state->file->macro = 0;
5235 struct hash_entry *ident;
5236 pp_eat(state, TOK_MUNDEF);
5237 if (if_eat(state)) /* quit early when #if'd out */
5240 ident = pp_eat(state, TOK_MIDENT)->ident;
5242 undef_macro(state, ident);
5246 pp_eat(state, TOK_MPRAGMA);
5247 if (if_eat(state)) /* quit early when #if'd out */
5249 warning(state, 0, "Ignoring pragma");
5252 pp_eat(state, TOK_MELIF);
5253 reenter_if(state, "#elif");
5254 if (if_eat(state)) /* quit early when #if'd out */
5256 /* If the #if was taken the #elif just disables the following code */
5257 if (if_value(state)) {
5258 eat_tokens(state, TOK_MENDIF);
5260 /* If the previous #if was not taken see if the #elif enables the
5264 set_if_value(state, mcexpr(state));
5265 if (!if_value(state)) {
5266 eat_tokens(state, TOK_MELSE);
5271 pp_eat(state, TOK_MIF);
5273 if (if_eat(state)) /* quit early when #if'd out */
5275 set_if_value(state, mcexpr(state));
5276 if (!if_value(state)) {
5277 eat_tokens(state, TOK_MELSE);
5282 struct hash_entry *ident;
5284 pp_eat(state, TOK_MIFNDEF);
5286 if (if_eat(state)) /* quit early when #if'd out */
5288 ident = pp_eat(state, TOK_MIDENT)->ident;
5289 set_if_value(state, ident->sym_define == 0);
5290 if (!if_value(state)) {
5291 eat_tokens(state, TOK_MELSE);
5297 struct hash_entry *ident;
5298 pp_eat(state, TOK_MIFDEF);
5300 if (if_eat(state)) /* quit early when #if'd out */
5302 ident = pp_eat(state, TOK_MIDENT)->ident;
5303 set_if_value(state, ident->sym_define != 0);
5304 if (!if_value(state)) {
5305 eat_tokens(state, TOK_MELSE);
5310 pp_eat(state, TOK_MELSE);
5311 enter_else(state, "#else");
5312 if (!if_eat(state) && if_value(state)) {
5313 eat_tokens(state, TOK_MENDIF);
5317 pp_eat(state, TOK_MENDIF);
5318 exit_if(state, "#endif");
5322 struct hash_entry *ident;
5323 struct macro_arg *args, **larg;
5324 const char *mstart, *mend;
5327 pp_eat(state, TOK_MDEFINE);
5328 if (if_eat(state)) /* quit early when #if'd out */
5330 ident = pp_eat(state, TOK_MIDENT)->ident;
5335 /* Parse macro parameters */
5336 if (raw_peek(state) == TOK_LPAREN) {
5337 raw_eat(state, TOK_LPAREN);
5341 struct macro_arg *narg, *arg;
5342 struct hash_entry *aident;
5345 tok = pp_peek(state);
5346 if (!args && (tok == TOK_RPAREN)) {
5349 else if (tok == TOK_DOTS) {
5350 pp_eat(state, TOK_DOTS);
5351 aident = state->i___VA_ARGS__;
5354 aident = pp_eat(state, TOK_MIDENT)->ident;
5357 narg = xcmalloc(sizeof(*arg), "macro arg");
5358 narg->ident = aident;
5360 /* Verify I don't have a duplicate identifier */
5361 for(arg = args; arg; arg = arg->next) {
5362 if (arg->ident == narg->ident) {
5363 error(state, 0, "Duplicate macro arg `%s'",
5367 /* Add the new argument to the end of the list */
5372 if ((aident == state->i___VA_ARGS__) ||
5373 (pp_peek(state) != TOK_COMMA)) {
5376 pp_eat(state, TOK_COMMA);
5378 pp_eat(state, TOK_RPAREN);
5380 /* Remove leading whitespace */
5381 while(raw_peek(state) == TOK_SPACE) {
5382 raw_eat(state, TOK_SPACE);
5385 /* Remember the start of the macro body */
5386 tok = raw_peek(state);
5387 mend = mstart = get_token(state, 1)->pos;
5389 /* Find the end of the macro */
5390 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5391 raw_eat(state, tok);
5392 /* Remember the end of the last non space token */
5394 if (tok != TOK_SPACE) {
5395 mend = get_token(state, 1)->pos;
5399 /* Now that I have found the body defined the token */
5400 do_define_macro(state, ident,
5401 char_strdup(state->file, mstart, mend, "macro buf"),
5407 const char *start, *end;
5410 pp_eat(state, TOK_MERROR);
5411 /* Find the start of the line */
5413 start = get_token(state, 1)->pos;
5415 /* Find the end of the line */
5416 while((tok = raw_peek(state)) != TOK_EOL) {
5417 raw_eat(state, tok);
5419 end = get_token(state, 1)->pos;
5421 if (!if_eat(state)) {
5422 error(state, 0, "%*.*s", len, len, start);
5428 const char *start, *end;
5431 pp_eat(state, TOK_MWARNING);
5433 /* Find the start of the line */
5435 start = get_token(state, 1)->pos;
5437 /* Find the end of the line */
5438 while((tok = raw_peek(state)) != TOK_EOL) {
5439 raw_eat(state, tok);
5441 end = get_token(state, 1)->pos;
5443 if (!if_eat(state)) {
5444 warning(state, 0, "%*.*s", len, len, start);
5455 pp_eat(state, TOK_MINCLUDE);
5456 if (if_eat(state)) {
5457 /* Find the end of the line */
5458 while((tok = raw_peek(state)) != TOK_EOL) {
5459 raw_eat(state, tok);
5464 if (tok == TOK_LIT_STRING) {
5468 tk = eat(state, TOK_LIT_STRING);
5469 name = xmalloc(tk->str_len, "include");
5470 token = tk->val.str +1;
5471 name_len = tk->str_len -2;
5472 if (*token == '"') {
5476 memcpy(name, token, name_len);
5477 name[name_len] = '\0';
5480 else if (tok == TOK_LESS) {
5481 struct macro_buf buf;
5482 eat(state, TOK_LESS);
5485 buf.str = xmalloc(buf.len, "include");
5489 while((tok != TOK_MORE) &&
5490 (tok != TOK_EOL) && (tok != TOK_EOF))
5493 tk = eat(state, tok);
5494 append_macro_chars(state, "include", &buf,
5495 state->file, tk->pos, state->file->pos);
5498 append_macro_text(state, "include", &buf, "\0", 1);
5499 if (peek(state) != TOK_MORE) {
5500 error(state, 0, "Unterminated include directive");
5502 eat(state, TOK_MORE);
5507 error(state, 0, "Invalid include directive");
5509 /* Error if there are any tokens after the include */
5510 if (pp_peek(state) != TOK_EOL) {
5511 error(state, 0, "garbage after include directive");
5513 if (!if_eat(state)) {
5514 compile_file(state, name, local);
5520 /* Ignore # without a follwing ident */
5524 const char *name1, *name2;
5525 name1 = tokens[tok];
5527 if (tok == TOK_MIDENT) {
5528 name2 = get_token(state, 1)->ident->name;
5530 error(state, 0, "Invalid preprocessor directive: %s %s",
5535 /* Consume the rest of the macro line */
5537 tok = pp_peek(state);
5539 } while((tok != TOK_EOF) && (tok != TOK_EOL));
5540 state->token_base = old_token_base;
5541 state->macro_file = NULL;
5545 /* Type helper functions */
5547 static struct type *new_type(
5548 unsigned int type, struct type *left, struct type *right)
5550 struct type *result;
5551 result = xmalloc(sizeof(*result), "type");
5552 result->type = type;
5553 result->left = left;
5554 result->right = right;
5555 result->field_ident = 0;
5556 result->type_ident = 0;
5557 result->elements = 0;
5561 static struct type *clone_type(unsigned int specifiers, struct type *old)
5563 struct type *result;
5564 result = xmalloc(sizeof(*result), "type");
5565 memcpy(result, old, sizeof(*result));
5566 result->type &= TYPE_MASK;
5567 result->type |= specifiers;
5571 static struct type *dup_type(struct compile_state *state, struct type *orig)
5574 new = xcmalloc(sizeof(*new), "type");
5575 new->type = orig->type;
5576 new->field_ident = orig->field_ident;
5577 new->type_ident = orig->type_ident;
5578 new->elements = orig->elements;
5580 new->left = dup_type(state, orig->left);
5583 new->right = dup_type(state, orig->right);
5589 static struct type *invalid_type(struct compile_state *state, struct type *type)
5591 struct type *invalid, *member;
5594 internal_error(state, 0, "type missing?");
5596 switch(type->type & TYPE_MASK) {
5598 case TYPE_CHAR: case TYPE_UCHAR:
5599 case TYPE_SHORT: case TYPE_USHORT:
5600 case TYPE_INT: case TYPE_UINT:
5601 case TYPE_LONG: case TYPE_ULONG:
5602 case TYPE_LLONG: case TYPE_ULLONG:
5607 invalid = invalid_type(state, type->left);
5610 invalid = invalid_type(state, type->left);
5614 member = type->left;
5615 while(member && (invalid == 0) &&
5616 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5617 invalid = invalid_type(state, member->left);
5618 member = member->right;
5621 invalid = invalid_type(state, member);
5626 member = type->left;
5627 while(member && (invalid == 0) &&
5628 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5629 invalid = invalid_type(state, member->left);
5630 member = member->right;
5633 invalid = invalid_type(state, member);
5644 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5645 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5646 static inline ulong_t mask_uint(ulong_t x)
5648 if (SIZEOF_INT < SIZEOF_LONG) {
5649 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5654 #define MASK_UINT(X) (mask_uint(X))
5655 #define MASK_ULONG(X) (X)
5657 static struct type void_type = { .type = TYPE_VOID };
5658 static struct type char_type = { .type = TYPE_CHAR };
5659 static struct type uchar_type = { .type = TYPE_UCHAR };
5660 #if DEBUG_ROMCC_WARNING
5661 static struct type short_type = { .type = TYPE_SHORT };
5663 static struct type ushort_type = { .type = TYPE_USHORT };
5664 static struct type int_type = { .type = TYPE_INT };
5665 static struct type uint_type = { .type = TYPE_UINT };
5666 static struct type long_type = { .type = TYPE_LONG };
5667 static struct type ulong_type = { .type = TYPE_ULONG };
5668 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5670 static struct type void_ptr_type = {
5671 .type = TYPE_POINTER,
5675 #if DEBUG_ROMCC_WARNING
5676 static struct type void_func_type = {
5677 .type = TYPE_FUNCTION,
5679 .right = &void_type,
5683 static size_t bits_to_bytes(size_t size)
5685 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5688 static struct triple *variable(struct compile_state *state, struct type *type)
5690 struct triple *result;
5691 if ((type->type & STOR_MASK) != STOR_PERM) {
5692 result = triple(state, OP_ADECL, type, 0, 0);
5693 generate_lhs_pieces(state, result);
5696 result = triple(state, OP_SDECL, type, 0, 0);
5701 static void stor_of(FILE *fp, struct type *type)
5703 switch(type->type & STOR_MASK) {
5705 fprintf(fp, "auto ");
5708 fprintf(fp, "static ");
5711 fprintf(fp, "local ");
5714 fprintf(fp, "extern ");
5717 fprintf(fp, "register ");
5720 fprintf(fp, "typedef ");
5722 case STOR_INLINE | STOR_LOCAL:
5723 fprintf(fp, "inline ");
5725 case STOR_INLINE | STOR_STATIC:
5726 fprintf(fp, "static inline");
5728 case STOR_INLINE | STOR_EXTERN:
5729 fprintf(fp, "extern inline");
5732 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5736 static void qual_of(FILE *fp, struct type *type)
5738 if (type->type & QUAL_CONST) {
5739 fprintf(fp, " const");
5741 if (type->type & QUAL_VOLATILE) {
5742 fprintf(fp, " volatile");
5744 if (type->type & QUAL_RESTRICT) {
5745 fprintf(fp, " restrict");
5749 static void name_of(FILE *fp, struct type *type)
5751 unsigned int base_type;
5752 base_type = type->type & TYPE_MASK;
5753 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5758 fprintf(fp, "void");
5762 fprintf(fp, "signed char");
5766 fprintf(fp, "unsigned char");
5770 fprintf(fp, "signed short");
5774 fprintf(fp, "unsigned short");
5778 fprintf(fp, "signed int");
5782 fprintf(fp, "unsigned int");
5786 fprintf(fp, "signed long");
5790 fprintf(fp, "unsigned long");
5794 name_of(fp, type->left);
5799 name_of(fp, type->left);
5801 name_of(fp, type->right);
5804 name_of(fp, type->left);
5806 name_of(fp, type->right);
5809 fprintf(fp, "enum %s",
5810 (type->type_ident)? type->type_ident->name : "");
5814 fprintf(fp, "struct %s { ",
5815 (type->type_ident)? type->type_ident->name : "");
5816 name_of(fp, type->left);
5821 fprintf(fp, "union %s { ",
5822 (type->type_ident)? type->type_ident->name : "");
5823 name_of(fp, type->left);
5828 name_of(fp, type->left);
5829 fprintf(fp, " (*)(");
5830 name_of(fp, type->right);
5834 name_of(fp, type->left);
5835 fprintf(fp, " [%ld]", (long)(type->elements));
5838 fprintf(fp, "tuple { ");
5839 name_of(fp, type->left);
5844 fprintf(fp, "join { ");
5845 name_of(fp, type->left);
5850 name_of(fp, type->left);
5851 fprintf(fp, " : %d ", type->elements);
5855 fprintf(fp, "unknown_t");
5858 fprintf(fp, "????: %x", base_type);
5861 if (type->field_ident && type->field_ident->name) {
5862 fprintf(fp, " .%s", type->field_ident->name);
5866 static size_t align_of(struct compile_state *state, struct type *type)
5870 switch(type->type & TYPE_MASK) {
5879 align = ALIGNOF_CHAR;
5883 align = ALIGNOF_SHORT;
5888 align = ALIGNOF_INT;
5892 align = ALIGNOF_LONG;
5895 align = ALIGNOF_POINTER;
5900 size_t left_align, right_align;
5901 left_align = align_of(state, type->left);
5902 right_align = align_of(state, type->right);
5903 align = (left_align >= right_align) ? left_align : right_align;
5907 align = align_of(state, type->left);
5913 align = align_of(state, type->left);
5916 error(state, 0, "alignof not yet defined for type\n");
5922 static size_t reg_align_of(struct compile_state *state, struct type *type)
5926 switch(type->type & TYPE_MASK) {
5935 align = REG_ALIGNOF_CHAR;
5939 align = REG_ALIGNOF_SHORT;
5944 align = REG_ALIGNOF_INT;
5948 align = REG_ALIGNOF_LONG;
5951 align = REG_ALIGNOF_POINTER;
5956 size_t left_align, right_align;
5957 left_align = reg_align_of(state, type->left);
5958 right_align = reg_align_of(state, type->right);
5959 align = (left_align >= right_align) ? left_align : right_align;
5963 align = reg_align_of(state, type->left);
5969 align = reg_align_of(state, type->left);
5972 error(state, 0, "alignof not yet defined for type\n");
5978 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5980 return bits_to_bytes(align_of(state, type));
5982 static size_t size_of(struct compile_state *state, struct type *type);
5983 static size_t reg_size_of(struct compile_state *state, struct type *type);
5985 static size_t needed_padding(struct compile_state *state,
5986 struct type *type, size_t offset)
5988 size_t padding, align;
5989 align = align_of(state, type);
5990 /* Align to the next machine word if the bitfield does completely
5991 * fit into the current word.
5993 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
5995 size = size_of(state, type);
5996 if ((offset + type->elements)/size != offset/size) {
6001 if (offset % align) {
6002 padding = align - (offset % align);
6007 static size_t reg_needed_padding(struct compile_state *state,
6008 struct type *type, size_t offset)
6010 size_t padding, align;
6011 align = reg_align_of(state, type);
6012 /* Align to the next register word if the bitfield does completely
6013 * fit into the current register.
6015 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6016 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6018 align = REG_SIZEOF_REG;
6021 if (offset % align) {
6022 padding = align - (offset % align);
6027 static size_t size_of(struct compile_state *state, struct type *type)
6031 switch(type->type & TYPE_MASK) {
6036 size = type->elements;
6044 size = SIZEOF_SHORT;
6056 size = SIZEOF_POINTER;
6062 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6063 pad = needed_padding(state, type->left, size);
6064 size = size + pad + size_of(state, type->left);
6067 pad = needed_padding(state, type, size);
6068 size = size + pad + size_of(state, type);
6073 size_t size_left, size_right;
6074 size_left = size_of(state, type->left);
6075 size_right = size_of(state, type->right);
6076 size = (size_left >= size_right)? size_left : size_right;
6080 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6081 internal_error(state, 0, "Invalid array type");
6083 size = size_of(state, type->left) * type->elements;
6090 size = size_of(state, type->left);
6091 /* Pad structures so their size is a multiples of their alignment */
6092 pad = needed_padding(state, type, size);
6100 size = size_of(state, type->left);
6101 /* Pad unions so their size is a multiple of their alignment */
6102 pad = needed_padding(state, type, size);
6107 internal_error(state, 0, "sizeof not yet defined for type");
6113 static size_t reg_size_of(struct compile_state *state, struct type *type)
6117 switch(type->type & TYPE_MASK) {
6122 size = type->elements;
6126 size = REG_SIZEOF_CHAR;
6130 size = REG_SIZEOF_SHORT;
6135 size = REG_SIZEOF_INT;
6139 size = REG_SIZEOF_LONG;
6142 size = REG_SIZEOF_POINTER;
6148 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6149 pad = reg_needed_padding(state, type->left, size);
6150 size = size + pad + reg_size_of(state, type->left);
6153 pad = reg_needed_padding(state, type, size);
6154 size = size + pad + reg_size_of(state, type);
6159 size_t size_left, size_right;
6160 size_left = reg_size_of(state, type->left);
6161 size_right = reg_size_of(state, type->right);
6162 size = (size_left >= size_right)? size_left : size_right;
6166 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6167 internal_error(state, 0, "Invalid array type");
6169 size = reg_size_of(state, type->left) * type->elements;
6176 size = reg_size_of(state, type->left);
6177 /* Pad structures so their size is a multiples of their alignment */
6178 pad = reg_needed_padding(state, type, size);
6186 size = reg_size_of(state, type->left);
6187 /* Pad unions so their size is a multiple of their alignment */
6188 pad = reg_needed_padding(state, type, size);
6193 internal_error(state, 0, "sizeof not yet defined for type");
6199 static size_t registers_of(struct compile_state *state, struct type *type)
6202 registers = reg_size_of(state, type);
6203 registers += REG_SIZEOF_REG - 1;
6204 registers /= REG_SIZEOF_REG;
6208 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6210 return bits_to_bytes(size_of(state, type));
6213 static size_t field_offset(struct compile_state *state,
6214 struct type *type, struct hash_entry *field)
6216 struct type *member;
6221 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6222 member = type->left;
6223 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6224 size += needed_padding(state, member->left, size);
6225 if (member->left->field_ident == field) {
6226 member = member->left;
6229 size += size_of(state, member->left);
6230 member = member->right;
6232 size += needed_padding(state, member, size);
6234 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6235 member = type->left;
6236 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6237 if (member->left->field_ident == field) {
6238 member = member->left;
6241 member = member->right;
6245 internal_error(state, 0, "field_offset only works on structures and unions");
6248 if (!member || (member->field_ident != field)) {
6249 error(state, 0, "member %s not present", field->name);
6254 static size_t field_reg_offset(struct compile_state *state,
6255 struct type *type, struct hash_entry *field)
6257 struct type *member;
6262 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6263 member = type->left;
6264 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6265 size += reg_needed_padding(state, member->left, size);
6266 if (member->left->field_ident == field) {
6267 member = member->left;
6270 size += reg_size_of(state, member->left);
6271 member = member->right;
6274 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6275 member = type->left;
6276 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6277 if (member->left->field_ident == field) {
6278 member = member->left;
6281 member = member->right;
6285 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6288 size += reg_needed_padding(state, member, size);
6289 if (!member || (member->field_ident != field)) {
6290 error(state, 0, "member %s not present", field->name);
6295 static struct type *field_type(struct compile_state *state,
6296 struct type *type, struct hash_entry *field)
6298 struct type *member;
6301 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6302 member = type->left;
6303 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6304 if (member->left->field_ident == field) {
6305 member = member->left;
6308 member = member->right;
6311 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6312 member = type->left;
6313 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6314 if (member->left->field_ident == field) {
6315 member = member->left;
6318 member = member->right;
6322 internal_error(state, 0, "field_type only works on structures and unions");
6325 if (!member || (member->field_ident != field)) {
6326 error(state, 0, "member %s not present", field->name);
6331 static size_t index_offset(struct compile_state *state,
6332 struct type *type, ulong_t index)
6334 struct type *member;
6337 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6338 size = size_of(state, type->left) * index;
6340 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6342 member = type->left;
6344 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6345 size += needed_padding(state, member->left, size);
6347 member = member->left;
6350 size += size_of(state, member->left);
6352 member = member->right;
6354 size += needed_padding(state, member, size);
6356 internal_error(state, 0, "Missing member index: %u", index);
6359 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6362 member = type->left;
6364 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6366 member = member->left;
6370 member = member->right;
6373 internal_error(state, 0, "Missing member index: %u", index);
6377 internal_error(state, 0,
6378 "request for index %u in something not an array, tuple or join",
6384 static size_t index_reg_offset(struct compile_state *state,
6385 struct type *type, ulong_t index)
6387 struct type *member;
6390 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6391 size = reg_size_of(state, type->left) * index;
6393 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6395 member = type->left;
6397 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6398 size += reg_needed_padding(state, member->left, size);
6400 member = member->left;
6403 size += reg_size_of(state, member->left);
6405 member = member->right;
6407 size += reg_needed_padding(state, member, size);
6409 internal_error(state, 0, "Missing member index: %u", index);
6413 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6416 member = type->left;
6418 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6420 member = member->left;
6424 member = member->right;
6427 internal_error(state, 0, "Missing member index: %u", index);
6431 internal_error(state, 0,
6432 "request for index %u in something not an array, tuple or join",
6438 static struct type *index_type(struct compile_state *state,
6439 struct type *type, ulong_t index)
6441 struct type *member;
6442 if (index >= type->elements) {
6443 internal_error(state, 0, "Invalid element %u requested", index);
6445 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6446 member = type->left;
6448 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6450 member = type->left;
6452 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6454 member = member->left;
6458 member = member->right;
6461 internal_error(state, 0, "Missing member index: %u", index);
6464 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6466 member = type->left;
6468 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6470 member = member->left;
6474 member = member->right;
6477 internal_error(state, 0, "Missing member index: %u", index);
6482 internal_error(state, 0,
6483 "request for index %u in something not an array, tuple or join",
6489 static struct type *unpack_type(struct compile_state *state, struct type *type)
6491 /* If I have a single register compound type not a bit-field
6492 * find the real type.
6494 struct type *start_type;
6496 /* Get out early if I need multiple registers for this type */
6497 size = reg_size_of(state, type);
6498 if (size > REG_SIZEOF_REG) {
6501 /* Get out early if I don't need any registers for this type */
6505 /* Loop until I have no more layers I can remove */
6508 switch(type->type & TYPE_MASK) {
6510 /* If I have a single element the unpacked type
6513 if (type->elements == 1) {
6519 /* If I have a single element the unpacked type
6522 if (type->elements == 1) {
6525 /* If I have multiple elements the unpacked
6526 * type is the non-void element.
6529 struct type *next, *member;
6530 struct type *sub_type;
6536 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6537 next = member->right;
6538 member = member->left;
6540 if (reg_size_of(state, member) > 0) {
6542 internal_error(state, 0, "true compound type in a register");
6555 /* If I have a single element the unpacked type
6558 if (type->elements == 1) {
6561 /* I can't in general unpack union types */
6564 /* If I'm not a compound type I can't unpack it */
6567 } while(start_type != type);
6568 switch(type->type & TYPE_MASK) {
6572 internal_error(state, 0, "irredicible type?");
6578 static int equiv_types(struct type *left, struct type *right);
6579 static int is_compound_type(struct type *type);
6581 static struct type *reg_type(
6582 struct compile_state *state, struct type *type, int reg_offset)
6584 struct type *member;
6587 struct type *invalid;
6588 invalid = invalid_type(state, type);
6590 fprintf(state->errout, "type: ");
6591 name_of(state->errout, type);
6592 fprintf(state->errout, "\n");
6593 fprintf(state->errout, "invalid: ");
6594 name_of(state->errout, invalid);
6595 fprintf(state->errout, "\n");
6596 internal_error(state, 0, "bad input type?");
6600 size = reg_size_of(state, type);
6601 if (reg_offset > size) {
6603 fprintf(state->errout, "type: ");
6604 name_of(state->errout, type);
6605 fprintf(state->errout, "\n");
6606 internal_error(state, 0, "offset outside of type");
6609 switch(type->type & TYPE_MASK) {
6610 /* Don't do anything with the basic types */
6612 case TYPE_CHAR: case TYPE_UCHAR:
6613 case TYPE_SHORT: case TYPE_USHORT:
6614 case TYPE_INT: case TYPE_UINT:
6615 case TYPE_LONG: case TYPE_ULONG:
6616 case TYPE_LLONG: case TYPE_ULLONG:
6617 case TYPE_FLOAT: case TYPE_DOUBLE:
6625 member = type->left;
6626 size = reg_size_of(state, member);
6627 if (size > REG_SIZEOF_REG) {
6628 member = reg_type(state, member, reg_offset % size);
6636 member = type->left;
6637 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6638 size = reg_size_of(state, member->left);
6639 offset += reg_needed_padding(state, member->left, offset);
6640 if ((offset + size) > reg_offset) {
6641 member = member->left;
6645 member = member->right;
6647 offset += reg_needed_padding(state, member, offset);
6648 member = reg_type(state, member, reg_offset - offset);
6654 struct type *join, **jnext, *mnext;
6655 join = new_type(TYPE_JOIN, 0, 0);
6656 jnext = &join->left;
6662 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6663 mnext = member->right;
6664 member = member->left;
6666 size = reg_size_of(state, member);
6667 if (size > reg_offset) {
6668 struct type *part, *hunt;
6669 part = reg_type(state, member, reg_offset);
6670 /* See if this type is already in the union */
6673 struct type *test = hunt;
6675 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6679 if (equiv_types(part, test)) {
6687 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6688 jnext = &(*jnext)->right;
6695 if (join->elements == 0) {
6696 internal_error(state, 0, "No elements?");
6703 fprintf(state->errout, "type: ");
6704 name_of(state->errout, type);
6705 fprintf(state->errout, "\n");
6706 internal_error(state, 0, "reg_type not yet defined for type");
6710 /* If I have a single register compound type not a bit-field
6711 * find the real type.
6713 member = unpack_type(state, member);
6715 size = reg_size_of(state, member);
6716 if (size > REG_SIZEOF_REG) {
6717 internal_error(state, 0, "Cannot find type of single register");
6720 invalid = invalid_type(state, member);
6722 fprintf(state->errout, "type: ");
6723 name_of(state->errout, member);
6724 fprintf(state->errout, "\n");
6725 fprintf(state->errout, "invalid: ");
6726 name_of(state->errout, invalid);
6727 fprintf(state->errout, "\n");
6728 internal_error(state, 0, "returning bad type?");
6734 static struct type *next_field(struct compile_state *state,
6735 struct type *type, struct type *prev_member)
6737 struct type *member;
6738 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6739 internal_error(state, 0, "next_field only works on structures");
6741 member = type->left;
6742 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6744 member = member->left;
6747 if (member->left == prev_member) {
6750 member = member->right;
6752 if (member == prev_member) {
6756 internal_error(state, 0, "prev_member %s not present",
6757 prev_member->field_ident->name);
6762 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6763 size_t ret_offset, size_t mem_offset, void *arg);
6765 static void walk_type_fields(struct compile_state *state,
6766 struct type *type, size_t reg_offset, size_t mem_offset,
6767 walk_type_fields_cb_t cb, void *arg);
6769 static void walk_struct_fields(struct compile_state *state,
6770 struct type *type, size_t reg_offset, size_t mem_offset,
6771 walk_type_fields_cb_t cb, void *arg)
6775 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6776 internal_error(state, 0, "walk_struct_fields only works on structures");
6779 for(i = 0; i < type->elements; i++) {
6782 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6783 mtype = mtype->left;
6785 walk_type_fields(state, mtype,
6787 field_reg_offset(state, type, mtype->field_ident),
6789 field_offset(state, type, mtype->field_ident),
6796 static void walk_type_fields(struct compile_state *state,
6797 struct type *type, size_t reg_offset, size_t mem_offset,
6798 walk_type_fields_cb_t cb, void *arg)
6800 switch(type->type & TYPE_MASK) {
6802 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6812 cb(state, type, reg_offset, mem_offset, arg);
6817 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6821 static void arrays_complete(struct compile_state *state, struct type *type)
6823 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6824 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6825 error(state, 0, "array size not specified");
6827 arrays_complete(state, type->left);
6831 static unsigned int get_basic_type(struct type *type)
6834 basic = type->type & TYPE_MASK;
6835 /* Convert enums to ints */
6836 if (basic == TYPE_ENUM) {
6839 /* Convert bitfields to standard types */
6840 else if (basic == TYPE_BITFIELD) {
6841 if (type->elements <= SIZEOF_CHAR) {
6844 else if (type->elements <= SIZEOF_SHORT) {
6847 else if (type->elements <= SIZEOF_INT) {
6850 else if (type->elements <= SIZEOF_LONG) {
6853 if (!TYPE_SIGNED(type->left->type)) {
6860 static unsigned int do_integral_promotion(unsigned int type)
6862 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6868 static unsigned int do_arithmetic_conversion(
6869 unsigned int left, unsigned int right)
6871 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6872 return TYPE_LDOUBLE;
6874 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6877 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6880 left = do_integral_promotion(left);
6881 right = do_integral_promotion(right);
6882 /* If both operands have the same size done */
6883 if (left == right) {
6886 /* If both operands have the same signedness pick the larger */
6887 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6888 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6890 /* If the signed type can hold everything use it */
6891 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6894 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6897 /* Convert to the unsigned type with the same rank as the signed type */
6898 else if (TYPE_SIGNED(left)) {
6899 return TYPE_MKUNSIGNED(left);
6902 return TYPE_MKUNSIGNED(right);
6906 /* see if two types are the same except for qualifiers */
6907 static int equiv_types(struct type *left, struct type *right)
6910 /* Error if the basic types do not match */
6911 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6914 type = left->type & TYPE_MASK;
6915 /* If the basic types match and it is a void type we are done */
6916 if (type == TYPE_VOID) {
6919 /* For bitfields we need to compare the sizes */
6920 else if (type == TYPE_BITFIELD) {
6921 return (left->elements == right->elements) &&
6922 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6924 /* if the basic types match and it is an arithmetic type we are done */
6925 else if (TYPE_ARITHMETIC(type)) {
6928 /* If it is a pointer type recurse and keep testing */
6929 else if (type == TYPE_POINTER) {
6930 return equiv_types(left->left, right->left);
6932 else if (type == TYPE_ARRAY) {
6933 return (left->elements == right->elements) &&
6934 equiv_types(left->left, right->left);
6936 /* test for struct equality */
6937 else if (type == TYPE_STRUCT) {
6938 return left->type_ident == right->type_ident;
6940 /* test for union equality */
6941 else if (type == TYPE_UNION) {
6942 return left->type_ident == right->type_ident;
6944 /* Test for equivalent functions */
6945 else if (type == TYPE_FUNCTION) {
6946 return equiv_types(left->left, right->left) &&
6947 equiv_types(left->right, right->right);
6949 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6950 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6951 else if (type == TYPE_PRODUCT) {
6952 return equiv_types(left->left, right->left) &&
6953 equiv_types(left->right, right->right);
6955 /* We should see TYPE_OVERLAP when comparing joins */
6956 else if (type == TYPE_OVERLAP) {
6957 return equiv_types(left->left, right->left) &&
6958 equiv_types(left->right, right->right);
6960 /* Test for equivalence of tuples */
6961 else if (type == TYPE_TUPLE) {
6962 return (left->elements == right->elements) &&
6963 equiv_types(left->left, right->left);
6965 /* Test for equivalence of joins */
6966 else if (type == TYPE_JOIN) {
6967 return (left->elements == right->elements) &&
6968 equiv_types(left->left, right->left);
6975 static int equiv_ptrs(struct type *left, struct type *right)
6977 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6978 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6981 return equiv_types(left->left, right->left);
6984 static struct type *compatible_types(struct type *left, struct type *right)
6986 struct type *result;
6987 unsigned int type, qual_type;
6988 /* Error if the basic types do not match */
6989 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6992 type = left->type & TYPE_MASK;
6993 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
6995 /* if the basic types match and it is an arithmetic type we are done */
6996 if (TYPE_ARITHMETIC(type)) {
6997 result = new_type(qual_type, 0, 0);
6999 /* If it is a pointer type recurse and keep testing */
7000 else if (type == TYPE_POINTER) {
7001 result = compatible_types(left->left, right->left);
7003 result = new_type(qual_type, result, 0);
7006 /* test for struct equality */
7007 else if (type == TYPE_STRUCT) {
7008 if (left->type_ident == right->type_ident) {
7012 /* test for union equality */
7013 else if (type == TYPE_UNION) {
7014 if (left->type_ident == right->type_ident) {
7018 /* Test for equivalent functions */
7019 else if (type == TYPE_FUNCTION) {
7020 struct type *lf, *rf;
7021 lf = compatible_types(left->left, right->left);
7022 rf = compatible_types(left->right, right->right);
7024 result = new_type(qual_type, lf, rf);
7027 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7028 else if (type == TYPE_PRODUCT) {
7029 struct type *lf, *rf;
7030 lf = compatible_types(left->left, right->left);
7031 rf = compatible_types(left->right, right->right);
7033 result = new_type(qual_type, lf, rf);
7037 /* Nothing else is compatible */
7042 /* See if left is a equivalent to right or right is a union member of left */
7043 static int is_subset_type(struct type *left, struct type *right)
7045 if (equiv_types(left, right)) {
7048 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7049 struct type *member, *mnext;
7054 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7055 mnext = member->right;
7056 member = member->left;
7058 if (is_subset_type( member, right)) {
7066 static struct type *compatible_ptrs(struct type *left, struct type *right)
7068 struct type *result;
7069 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7070 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7073 result = compatible_types(left->left, right->left);
7075 unsigned int qual_type;
7076 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7077 result = new_type(qual_type, result, 0);
7082 static struct triple *integral_promotion(
7083 struct compile_state *state, struct triple *def)
7087 /* As all operations are carried out in registers
7088 * the values are converted on load I just convert
7089 * logical type of the operand.
7091 if (TYPE_INTEGER(type->type)) {
7092 unsigned int int_type;
7093 int_type = type->type & ~TYPE_MASK;
7094 int_type |= do_integral_promotion(get_basic_type(type));
7095 if (int_type != type->type) {
7096 if (def->op != OP_LOAD) {
7097 def->type = new_type(int_type, 0, 0);
7100 def = triple(state, OP_CONVERT,
7101 new_type(int_type, 0, 0), def, 0);
7109 static void arithmetic(struct compile_state *state, struct triple *def)
7111 if (!TYPE_ARITHMETIC(def->type->type)) {
7112 error(state, 0, "arithmetic type expexted");
7116 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7118 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7119 error(state, def, "pointer or arithmetic type expected");
7123 static int is_integral(struct triple *ins)
7125 return TYPE_INTEGER(ins->type->type);
7128 static void integral(struct compile_state *state, struct triple *def)
7130 if (!is_integral(def)) {
7131 error(state, 0, "integral type expected");
7136 static void bool(struct compile_state *state, struct triple *def)
7138 if (!TYPE_ARITHMETIC(def->type->type) &&
7139 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7140 error(state, 0, "arithmetic or pointer type expected");
7144 static int is_signed(struct type *type)
7146 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7149 return !!TYPE_SIGNED(type->type);
7151 static int is_compound_type(struct type *type)
7154 switch((type->type & TYPE_MASK)) {
7169 /* Is this value located in a register otherwise it must be in memory */
7170 static int is_in_reg(struct compile_state *state, struct triple *def)
7173 if (def->op == OP_ADECL) {
7176 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7179 else if (triple_is_part(state, def)) {
7180 in_reg = is_in_reg(state, MISC(def, 0));
7183 internal_error(state, def, "unknown expr storage location");
7189 /* Is this an auto or static variable location? Something that can
7190 * be assigned to. Otherwise it must must be a pure value, a temporary.
7192 static int is_lvalue(struct compile_state *state, struct triple *def)
7199 if ((def->op == OP_ADECL) ||
7200 (def->op == OP_SDECL) ||
7201 (def->op == OP_DEREF) ||
7202 (def->op == OP_BLOBCONST) ||
7203 (def->op == OP_LIST)) {
7206 else if (triple_is_part(state, def)) {
7207 ret = is_lvalue(state, MISC(def, 0));
7212 static void clvalue(struct compile_state *state, struct triple *def)
7215 internal_error(state, def, "nothing where lvalue expected?");
7217 if (!is_lvalue(state, def)) {
7218 error(state, def, "lvalue expected");
7221 static void lvalue(struct compile_state *state, struct triple *def)
7223 clvalue(state, def);
7224 if (def->type->type & QUAL_CONST) {
7225 error(state, def, "modifable lvalue expected");
7229 static int is_pointer(struct triple *def)
7231 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7234 static void pointer(struct compile_state *state, struct triple *def)
7236 if (!is_pointer(def)) {
7237 error(state, def, "pointer expected");
7241 static struct triple *int_const(
7242 struct compile_state *state, struct type *type, ulong_t value)
7244 struct triple *result;
7245 switch(type->type & TYPE_MASK) {
7247 case TYPE_INT: case TYPE_UINT:
7248 case TYPE_LONG: case TYPE_ULONG:
7251 internal_error(state, 0, "constant for unknown type");
7253 result = triple(state, OP_INTCONST, type, 0, 0);
7254 result->u.cval = value;
7259 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7261 static struct triple *do_mk_addr_expr(struct compile_state *state,
7262 struct triple *expr, struct type *type, ulong_t offset)
7264 struct triple *result;
7265 struct type *ptr_type;
7266 clvalue(state, expr);
7268 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7272 if (expr->op == OP_ADECL) {
7273 error(state, expr, "address of auto variables not supported");
7275 else if (expr->op == OP_SDECL) {
7276 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7277 MISC(result, 0) = expr;
7278 result->u.cval = offset;
7280 else if (expr->op == OP_DEREF) {
7281 result = triple(state, OP_ADD, ptr_type,
7283 int_const(state, &ulong_type, offset));
7285 else if (expr->op == OP_BLOBCONST) {
7287 internal_error(state, expr, "not yet implemented");
7289 else if (expr->op == OP_LIST) {
7290 error(state, 0, "Function addresses not supported");
7292 else if (triple_is_part(state, expr)) {
7293 struct triple *part;
7295 expr = MISC(expr, 0);
7296 if (part->op == OP_DOT) {
7297 offset += bits_to_bytes(
7298 field_offset(state, expr->type, part->u.field));
7300 else if (part->op == OP_INDEX) {
7301 offset += bits_to_bytes(
7302 index_offset(state, expr->type, part->u.cval));
7305 internal_error(state, part, "unhandled part type");
7307 result = do_mk_addr_expr(state, expr, type, offset);
7310 internal_error(state, expr, "cannot take address of expression");
7315 static struct triple *mk_addr_expr(
7316 struct compile_state *state, struct triple *expr, ulong_t offset)
7318 return do_mk_addr_expr(state, expr, expr->type, offset);
7321 static struct triple *mk_deref_expr(
7322 struct compile_state *state, struct triple *expr)
7324 struct type *base_type;
7325 pointer(state, expr);
7326 base_type = expr->type->left;
7327 return triple(state, OP_DEREF, base_type, expr, 0);
7330 /* lvalue conversions always apply except when certain operators
7331 * are applied. So I apply apply it when I know no more
7332 * operators will be applied.
7334 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7336 /* Tranform an array to a pointer to the first element */
7337 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7340 TYPE_POINTER | (def->type->type & QUAL_MASK),
7341 def->type->left, 0);
7342 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7343 struct triple *addrconst;
7344 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7345 internal_error(state, def, "bad array constant");
7347 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7348 MISC(addrconst, 0) = def;
7352 def = triple(state, OP_CONVERT, type, def, 0);
7355 /* Transform a function to a pointer to it */
7356 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7357 def = mk_addr_expr(state, def, 0);
7362 static struct triple *deref_field(
7363 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7365 struct triple *result;
7366 struct type *type, *member;
7369 internal_error(state, 0, "No field passed to deref_field");
7373 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7374 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7375 error(state, 0, "request for member %s in something not a struct or union",
7378 member = field_type(state, type, field);
7379 if ((type->type & STOR_MASK) == STOR_PERM) {
7380 /* Do the pointer arithmetic to get a deref the field */
7381 offset = bits_to_bytes(field_offset(state, type, field));
7382 result = do_mk_addr_expr(state, expr, member, offset);
7383 result = mk_deref_expr(state, result);
7386 /* Find the variable for the field I want. */
7387 result = triple(state, OP_DOT, member, expr, 0);
7388 result->u.field = field;
7393 static struct triple *deref_index(
7394 struct compile_state *state, struct triple *expr, size_t index)
7396 struct triple *result;
7397 struct type *type, *member;
7402 member = index_type(state, type, index);
7404 if ((type->type & STOR_MASK) == STOR_PERM) {
7405 offset = bits_to_bytes(index_offset(state, type, index));
7406 result = do_mk_addr_expr(state, expr, member, offset);
7407 result = mk_deref_expr(state, result);
7410 result = triple(state, OP_INDEX, member, expr, 0);
7411 result->u.cval = index;
7416 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7422 #if DEBUG_ROMCC_WARNINGS
7423 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7425 /* Transform lvalues into something we can read */
7426 def = lvalue_conversion(state, def);
7427 if (!is_lvalue(state, def)) {
7430 if (is_in_reg(state, def)) {
7433 if (def->op == OP_SDECL) {
7434 def = mk_addr_expr(state, def, 0);
7435 def = mk_deref_expr(state, def);
7439 def = triple(state, op, def->type, def, 0);
7440 if (def->type->type & QUAL_VOLATILE) {
7441 def->id |= TRIPLE_FLAG_VOLATILE;
7446 int is_write_compatible(struct compile_state *state,
7447 struct type *dest, struct type *rval)
7450 /* Both operands have arithmetic type */
7451 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7454 /* One operand is a pointer and the other is a pointer to void */
7455 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7456 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7457 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7458 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7461 /* If both types are the same without qualifiers we are good */
7462 else if (equiv_ptrs(dest, rval)) {
7465 /* test for struct/union equality */
7466 else if (equiv_types(dest, rval)) {
7472 static void write_compatible(struct compile_state *state,
7473 struct type *dest, struct type *rval)
7475 if (!is_write_compatible(state, dest, rval)) {
7476 FILE *fp = state->errout;
7477 fprintf(fp, "dest: ");
7479 fprintf(fp,"\nrval: ");
7482 error(state, 0, "Incompatible types in assignment");
7486 static int is_init_compatible(struct compile_state *state,
7487 struct type *dest, struct type *rval)
7490 if (is_write_compatible(state, dest, rval)) {
7493 else if (equiv_types(dest, rval)) {
7499 static struct triple *write_expr(
7500 struct compile_state *state, struct triple *dest, struct triple *rval)
7507 internal_error(state, 0, "missing rval");
7510 if (rval->op == OP_LIST) {
7511 internal_error(state, 0, "expression of type OP_LIST?");
7513 if (!is_lvalue(state, dest)) {
7514 internal_error(state, 0, "writing to a non lvalue?");
7516 if (dest->type->type & QUAL_CONST) {
7517 internal_error(state, 0, "modifable lvalue expexted");
7520 write_compatible(state, dest->type, rval->type);
7521 if (!equiv_types(dest->type, rval->type)) {
7522 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7525 /* Now figure out which assignment operator to use */
7527 if (is_in_reg(state, dest)) {
7528 def = triple(state, OP_WRITE, dest->type, rval, dest);
7529 if (MISC(def, 0) != dest) {
7530 internal_error(state, def, "huh?");
7532 if (RHS(def, 0) != rval) {
7533 internal_error(state, def, "huh?");
7536 def = triple(state, OP_STORE, dest->type, dest, rval);
7538 if (def->type->type & QUAL_VOLATILE) {
7539 def->id |= TRIPLE_FLAG_VOLATILE;
7544 static struct triple *init_expr(
7545 struct compile_state *state, struct triple *dest, struct triple *rval)
7551 internal_error(state, 0, "missing rval");
7553 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7554 rval = read_expr(state, rval);
7555 def = write_expr(state, dest, rval);
7558 /* Fill in the array size if necessary */
7559 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7560 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7561 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7562 dest->type->elements = rval->type->elements;
7565 if (!equiv_types(dest->type, rval->type)) {
7566 error(state, 0, "Incompatible types in inializer");
7568 MISC(dest, 0) = rval;
7569 insert_triple(state, dest, rval);
7570 rval->id |= TRIPLE_FLAG_FLATTENED;
7571 use_triple(MISC(dest, 0), dest);
7576 struct type *arithmetic_result(
7577 struct compile_state *state, struct triple *left, struct triple *right)
7580 /* Sanity checks to ensure I am working with arithmetic types */
7581 arithmetic(state, left);
7582 arithmetic(state, right);
7584 do_arithmetic_conversion(
7585 get_basic_type(left->type),
7586 get_basic_type(right->type)),
7591 struct type *ptr_arithmetic_result(
7592 struct compile_state *state, struct triple *left, struct triple *right)
7595 /* Sanity checks to ensure I am working with the proper types */
7596 ptr_arithmetic(state, left);
7597 arithmetic(state, right);
7598 if (TYPE_ARITHMETIC(left->type->type) &&
7599 TYPE_ARITHMETIC(right->type->type)) {
7600 type = arithmetic_result(state, left, right);
7602 else if (TYPE_PTR(left->type->type)) {
7606 internal_error(state, 0, "huh?");
7612 /* boolean helper function */
7614 static struct triple *ltrue_expr(struct compile_state *state,
7615 struct triple *expr)
7618 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7619 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7620 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7621 /* If the expression is already boolean do nothing */
7624 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7630 static struct triple *lfalse_expr(struct compile_state *state,
7631 struct triple *expr)
7633 return triple(state, OP_LFALSE, &int_type, expr, 0);
7636 static struct triple *mkland_expr(
7637 struct compile_state *state,
7638 struct triple *left, struct triple *right)
7640 struct triple *def, *val, *var, *jmp, *mid, *end;
7641 struct triple *lstore, *rstore;
7643 /* Generate some intermediate triples */
7645 var = variable(state, &int_type);
7647 /* Store the left hand side value */
7648 lstore = write_expr(state, var, left);
7650 /* Jump if the value is false */
7651 jmp = branch(state, end,
7652 lfalse_expr(state, read_expr(state, var)));
7655 /* Store the right hand side value */
7656 rstore = write_expr(state, var, right);
7658 /* An expression for the computed value */
7659 val = read_expr(state, var);
7661 /* Generate the prog for a logical and */
7662 def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0UL);
7667 static struct triple *mklor_expr(
7668 struct compile_state *state,
7669 struct triple *left, struct triple *right)
7671 struct triple *def, *val, *var, *jmp, *mid, *end;
7673 /* Generate some intermediate triples */
7675 var = variable(state, &int_type);
7677 /* Store the left hand side value */
7678 left = write_expr(state, var, left);
7680 /* Jump if the value is true */
7681 jmp = branch(state, end, read_expr(state, var));
7684 /* Store the right hand side value */
7685 right = write_expr(state, var, right);
7687 /* An expression for the computed value*/
7688 val = read_expr(state, var);
7690 /* Generate the prog for a logical or */
7691 def = mkprog(state, var, left, jmp, mid, right, end, val, 0UL);
7696 static struct triple *mkcond_expr(
7697 struct compile_state *state,
7698 struct triple *test, struct triple *left, struct triple *right)
7700 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7701 struct type *result_type;
7702 unsigned int left_type, right_type;
7704 left_type = left->type->type;
7705 right_type = right->type->type;
7707 /* Both operands have arithmetic type */
7708 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7709 result_type = arithmetic_result(state, left, right);
7711 /* Both operands have void type */
7712 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7713 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7714 result_type = &void_type;
7716 /* pointers to the same type... */
7717 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7720 /* Both operands are pointers and left is a pointer to void */
7721 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7722 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7723 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7724 result_type = right->type;
7726 /* Both operands are pointers and right is a pointer to void */
7727 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7728 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7729 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7730 result_type = left->type;
7733 error(state, 0, "Incompatible types in conditional expression");
7735 /* Generate some intermediate triples */
7738 var = variable(state, result_type);
7740 /* Branch if the test is false */
7741 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7744 /* Store the left hand side value */
7745 left = write_expr(state, var, left);
7747 /* Branch to the end */
7748 jmp2 = branch(state, end, 0);
7750 /* Store the right hand side value */
7751 right = write_expr(state, var, right);
7753 /* An expression for the computed value */
7754 val = read_expr(state, var);
7756 /* Generate the prog for a conditional expression */
7757 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0UL);
7763 static int expr_depth(struct compile_state *state, struct triple *ins)
7765 #if DEBUG_ROMCC_WARNINGS
7766 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7770 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7773 else if (ins->op == OP_DEREF) {
7774 count = expr_depth(state, RHS(ins, 0)) - 1;
7776 else if (ins->op == OP_VAL) {
7777 count = expr_depth(state, RHS(ins, 0)) - 1;
7779 else if (ins->op == OP_FCALL) {
7780 /* Don't figure the depth of a call just guess it is huge */
7784 struct triple **expr;
7785 expr = triple_rhs(state, ins, 0);
7786 for(;expr; expr = triple_rhs(state, ins, expr)) {
7789 depth = expr_depth(state, *expr);
7790 if (depth > count) {
7799 static struct triple *flatten_generic(
7800 struct compile_state *state, struct triple *first, struct triple *ptr,
7805 struct triple **ins;
7808 /* Only operations with just a rhs and a lhs should come here */
7811 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7812 internal_error(state, ptr, "unexpected args for: %d %s",
7813 ptr->op, tops(ptr->op));
7815 /* Find the depth of the rhs elements */
7816 for(i = 0; i < rhs; i++) {
7817 vector[i].ins = &RHS(ptr, i);
7818 vector[i].depth = expr_depth(state, *vector[i].ins);
7820 /* Selection sort the rhs */
7821 for(i = 0; i < rhs; i++) {
7823 for(j = i + 1; j < rhs; j++ ) {
7824 if (vector[j].depth > vector[max].depth) {
7829 struct rhs_vector tmp;
7831 vector[i] = vector[max];
7835 /* Now flatten the rhs elements */
7836 for(i = 0; i < rhs; i++) {
7837 *vector[i].ins = flatten(state, first, *vector[i].ins);
7838 use_triple(*vector[i].ins, ptr);
7841 insert_triple(state, first, ptr);
7842 ptr->id |= TRIPLE_FLAG_FLATTENED;
7843 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7845 /* Now flatten the lhs elements */
7846 for(i = 0; i < lhs; i++) {
7847 struct triple **ins = &LHS(ptr, i);
7848 *ins = flatten(state, first, *ins);
7849 use_triple(*ins, ptr);
7855 static struct triple *flatten_prog(
7856 struct compile_state *state, struct triple *first, struct triple *ptr)
7858 struct triple *head, *body, *val;
7863 release_triple(state, head);
7864 release_triple(state, ptr);
7866 body->prev = first->prev;
7867 body->prev->next = body;
7868 val->next->prev = val;
7870 if (triple_is_cbranch(state, body->prev) ||
7871 triple_is_call(state, body->prev)) {
7872 unuse_triple(first, body->prev);
7873 use_triple(body, body->prev);
7876 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7877 internal_error(state, val, "val not flattened?");
7884 static struct triple *flatten_part(
7885 struct compile_state *state, struct triple *first, struct triple *ptr)
7887 if (!triple_is_part(state, ptr)) {
7888 internal_error(state, ptr, "not a part");
7890 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7891 internal_error(state, ptr, "unexpected args for: %d %s",
7892 ptr->op, tops(ptr->op));
7894 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7895 use_triple(MISC(ptr, 0), ptr);
7896 return flatten_generic(state, first, ptr, 1);
7899 static struct triple *flatten(
7900 struct compile_state *state, struct triple *first, struct triple *ptr)
7902 struct triple *orig_ptr;
7907 /* Only flatten triples once */
7908 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7913 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7914 return MISC(ptr, 0);
7917 ptr = flatten_prog(state, first, ptr);
7920 ptr = flatten_generic(state, first, ptr, 1);
7921 insert_triple(state, first, ptr);
7922 ptr->id |= TRIPLE_FLAG_FLATTENED;
7923 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7924 if (ptr->next != ptr) {
7925 use_triple(ptr->next, ptr);
7930 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7931 use_triple(RHS(ptr, 0), ptr);
7934 ptr = flatten_generic(state, first, ptr, 1);
7935 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7936 use_triple(MISC(ptr, 0), ptr);
7939 use_triple(TARG(ptr, 0), ptr);
7942 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7943 use_triple(RHS(ptr, 0), ptr);
7944 use_triple(TARG(ptr, 0), ptr);
7945 insert_triple(state, first, ptr);
7946 ptr->id |= TRIPLE_FLAG_FLATTENED;
7947 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7948 if (ptr->next != ptr) {
7949 use_triple(ptr->next, ptr);
7953 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7954 use_triple(MISC(ptr, 0), ptr);
7955 use_triple(TARG(ptr, 0), ptr);
7956 insert_triple(state, first, ptr);
7957 ptr->id |= TRIPLE_FLAG_FLATTENED;
7958 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7959 if (ptr->next != ptr) {
7960 use_triple(ptr->next, ptr);
7964 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7965 use_triple(RHS(ptr, 0), ptr);
7968 insert_triple(state, state->global_pool, ptr);
7969 ptr->id |= TRIPLE_FLAG_FLATTENED;
7970 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7971 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7972 use_triple(MISC(ptr, 0), ptr);
7975 /* Since OP_DEREF is just a marker delete it when I flatten it */
7977 RHS(orig_ptr, 0) = 0;
7978 free_triple(state, orig_ptr);
7981 if (RHS(ptr, 0)->op == OP_DEREF) {
7982 struct triple *base, *left;
7984 base = MISC(ptr, 0);
7985 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7986 left = RHS(base, 0);
7987 ptr = triple(state, OP_ADD, left->type,
7988 read_expr(state, left),
7989 int_const(state, &ulong_type, offset));
7990 free_triple(state, base);
7993 ptr = flatten_part(state, first, ptr);
7997 if (RHS(ptr, 0)->op == OP_DEREF) {
7998 struct triple *base, *left;
8000 base = MISC(ptr, 0);
8001 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8002 left = RHS(base, 0);
8003 ptr = triple(state, OP_ADD, left->type,
8004 read_expr(state, left),
8005 int_const(state, &long_type, offset));
8006 free_triple(state, base);
8009 ptr = flatten_part(state, first, ptr);
8013 ptr = flatten_part(state, first, ptr);
8014 use_triple(ptr, MISC(ptr, 0));
8017 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8018 use_triple(MISC(ptr, 0), ptr);
8021 first = state->global_pool;
8022 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8023 use_triple(MISC(ptr, 0), ptr);
8024 insert_triple(state, first, ptr);
8025 ptr->id |= TRIPLE_FLAG_FLATTENED;
8026 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8029 ptr = flatten_generic(state, first, ptr, 0);
8032 /* Flatten the easy cases we don't override */
8033 ptr = flatten_generic(state, first, ptr, 0);
8036 } while(ptr && (ptr != orig_ptr));
8037 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8038 insert_triple(state, first, ptr);
8039 ptr->id |= TRIPLE_FLAG_FLATTENED;
8040 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8045 static void release_expr(struct compile_state *state, struct triple *expr)
8047 struct triple *head;
8048 head = label(state);
8049 flatten(state, head, expr);
8050 while(head->next != head) {
8051 release_triple(state, head->next);
8053 free_triple(state, head);
8056 static int replace_rhs_use(struct compile_state *state,
8057 struct triple *orig, struct triple *new, struct triple *use)
8059 struct triple **expr;
8062 expr = triple_rhs(state, use, 0);
8063 for(;expr; expr = triple_rhs(state, use, expr)) {
8064 if (*expr == orig) {
8070 unuse_triple(orig, use);
8071 use_triple(new, use);
8076 static int replace_lhs_use(struct compile_state *state,
8077 struct triple *orig, struct triple *new, struct triple *use)
8079 struct triple **expr;
8082 expr = triple_lhs(state, use, 0);
8083 for(;expr; expr = triple_lhs(state, use, expr)) {
8084 if (*expr == orig) {
8090 unuse_triple(orig, use);
8091 use_triple(new, use);
8096 static int replace_misc_use(struct compile_state *state,
8097 struct triple *orig, struct triple *new, struct triple *use)
8099 struct triple **expr;
8102 expr = triple_misc(state, use, 0);
8103 for(;expr; expr = triple_misc(state, use, expr)) {
8104 if (*expr == orig) {
8110 unuse_triple(orig, use);
8111 use_triple(new, use);
8116 static int replace_targ_use(struct compile_state *state,
8117 struct triple *orig, struct triple *new, struct triple *use)
8119 struct triple **expr;
8122 expr = triple_targ(state, use, 0);
8123 for(;expr; expr = triple_targ(state, use, expr)) {
8124 if (*expr == orig) {
8130 unuse_triple(orig, use);
8131 use_triple(new, use);
8136 static void replace_use(struct compile_state *state,
8137 struct triple *orig, struct triple *new, struct triple *use)
8141 found |= replace_rhs_use(state, orig, new, use);
8142 found |= replace_lhs_use(state, orig, new, use);
8143 found |= replace_misc_use(state, orig, new, use);
8144 found |= replace_targ_use(state, orig, new, use);
8146 internal_error(state, use, "use without use");
8150 static void propogate_use(struct compile_state *state,
8151 struct triple *orig, struct triple *new)
8153 struct triple_set *user, *next;
8154 for(user = orig->use; user; user = next) {
8155 /* Careful replace_use modifies the use chain and
8156 * removes use. So we must get a copy of the next
8160 replace_use(state, orig, new, user->member);
8163 internal_error(state, orig, "used after propogate_use");
8169 * ===========================
8172 static struct triple *mk_cast_expr(
8173 struct compile_state *state, struct type *type, struct triple *expr)
8176 def = read_expr(state, expr);
8177 def = triple(state, OP_CONVERT, type, def, 0);
8181 static struct triple *mk_add_expr(
8182 struct compile_state *state, struct triple *left, struct triple *right)
8184 struct type *result_type;
8185 /* Put pointer operands on the left */
8186 if (is_pointer(right)) {
8192 left = read_expr(state, left);
8193 right = read_expr(state, right);
8194 result_type = ptr_arithmetic_result(state, left, right);
8195 if (is_pointer(left)) {
8196 struct type *ptr_math;
8198 if (is_signed(right->type)) {
8199 ptr_math = &long_type;
8202 ptr_math = &ulong_type;
8205 if (!equiv_types(right->type, ptr_math)) {
8206 right = mk_cast_expr(state, ptr_math, right);
8208 right = triple(state, op, ptr_math, right,
8209 int_const(state, ptr_math,
8210 size_of_in_bytes(state, left->type->left)));
8212 return triple(state, OP_ADD, result_type, left, right);
8215 static struct triple *mk_sub_expr(
8216 struct compile_state *state, struct triple *left, struct triple *right)
8218 struct type *result_type;
8219 result_type = ptr_arithmetic_result(state, left, right);
8220 left = read_expr(state, left);
8221 right = read_expr(state, right);
8222 if (is_pointer(left)) {
8223 struct type *ptr_math;
8225 if (is_signed(right->type)) {
8226 ptr_math = &long_type;
8229 ptr_math = &ulong_type;
8232 if (!equiv_types(right->type, ptr_math)) {
8233 right = mk_cast_expr(state, ptr_math, right);
8235 right = triple(state, op, ptr_math, right,
8236 int_const(state, ptr_math,
8237 size_of_in_bytes(state, left->type->left)));
8239 return triple(state, OP_SUB, result_type, left, right);
8242 static struct triple *mk_pre_inc_expr(
8243 struct compile_state *state, struct triple *def)
8247 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8248 return triple(state, OP_VAL, def->type,
8249 write_expr(state, def, val),
8253 static struct triple *mk_pre_dec_expr(
8254 struct compile_state *state, struct triple *def)
8258 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8259 return triple(state, OP_VAL, def->type,
8260 write_expr(state, def, val),
8264 static struct triple *mk_post_inc_expr(
8265 struct compile_state *state, struct triple *def)
8269 val = read_expr(state, def);
8270 return triple(state, OP_VAL, def->type,
8271 write_expr(state, def,
8272 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8276 static struct triple *mk_post_dec_expr(
8277 struct compile_state *state, struct triple *def)
8281 val = read_expr(state, def);
8282 return triple(state, OP_VAL, def->type,
8283 write_expr(state, def,
8284 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8288 static struct triple *mk_subscript_expr(
8289 struct compile_state *state, struct triple *left, struct triple *right)
8291 left = read_expr(state, left);
8292 right = read_expr(state, right);
8293 if (!is_pointer(left) && !is_pointer(right)) {
8294 error(state, left, "subscripted value is not a pointer");
8296 return mk_deref_expr(state, mk_add_expr(state, left, right));
8301 * Compile time evaluation
8302 * ===========================
8304 static int is_const(struct triple *ins)
8306 return IS_CONST_OP(ins->op);
8309 static int is_simple_const(struct triple *ins)
8311 /* Is this a constant that u.cval has the value.
8312 * Or equivalently is this a constant that read_const
8314 * So far only OP_INTCONST qualifies.
8316 return (ins->op == OP_INTCONST);
8319 static int constants_equal(struct compile_state *state,
8320 struct triple *left, struct triple *right)
8323 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8326 else if (!is_const(left) || !is_const(right)) {
8329 else if (left->op != right->op) {
8332 else if (!equiv_types(left->type, right->type)) {
8339 if (left->u.cval == right->u.cval) {
8345 size_t lsize, rsize, bytes;
8346 lsize = size_of(state, left->type);
8347 rsize = size_of(state, right->type);
8348 if (lsize != rsize) {
8351 bytes = bits_to_bytes(lsize);
8352 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8358 if ((MISC(left, 0) == MISC(right, 0)) &&
8359 (left->u.cval == right->u.cval)) {
8364 internal_error(state, left, "uknown constant type");
8371 static int is_zero(struct triple *ins)
8373 return is_simple_const(ins) && (ins->u.cval == 0);
8376 static int is_one(struct triple *ins)
8378 return is_simple_const(ins) && (ins->u.cval == 1);
8381 #if DEBUG_ROMCC_WARNING
8382 static long_t bit_count(ulong_t value)
8387 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8400 static long_t bsr(ulong_t value)
8403 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8414 static long_t bsf(ulong_t value)
8417 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8428 static long_t ilog2(ulong_t value)
8433 static long_t tlog2(struct triple *ins)
8435 return ilog2(ins->u.cval);
8438 static int is_pow2(struct triple *ins)
8440 ulong_t value, mask;
8442 if (!is_const(ins)) {
8445 value = ins->u.cval;
8452 return ((value & mask) == value);
8455 static ulong_t read_const(struct compile_state *state,
8456 struct triple *ins, struct triple *rhs)
8458 switch(rhs->type->type &TYPE_MASK) {
8471 fprintf(state->errout, "type: ");
8472 name_of(state->errout, rhs->type);
8473 fprintf(state->errout, "\n");
8474 internal_warning(state, rhs, "bad type to read_const");
8477 if (!is_simple_const(rhs)) {
8478 internal_error(state, rhs, "bad op to read_const");
8483 static long_t read_sconst(struct compile_state *state,
8484 struct triple *ins, struct triple *rhs)
8486 return (long_t)(rhs->u.cval);
8489 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8491 if (!is_const(rhs)) {
8492 internal_error(state, 0, "non const passed to const_true");
8494 return !is_zero(rhs);
8497 int const_eq(struct compile_state *state, struct triple *ins,
8498 struct triple *left, struct triple *right)
8501 if (!is_const(left) || !is_const(right)) {
8502 internal_warning(state, ins, "non const passed to const_eq");
8505 else if (left == right) {
8508 else if (is_simple_const(left) && is_simple_const(right)) {
8510 lval = read_const(state, ins, left);
8511 rval = read_const(state, ins, right);
8512 result = (lval == rval);
8514 else if ((left->op == OP_ADDRCONST) &&
8515 (right->op == OP_ADDRCONST)) {
8516 result = (MISC(left, 0) == MISC(right, 0)) &&
8517 (left->u.cval == right->u.cval);
8520 internal_warning(state, ins, "incomparable constants passed to const_eq");
8527 int const_ucmp(struct compile_state *state, struct triple *ins,
8528 struct triple *left, struct triple *right)
8531 if (!is_const(left) || !is_const(right)) {
8532 internal_warning(state, ins, "non const past to const_ucmp");
8535 else if (left == right) {
8538 else if (is_simple_const(left) && is_simple_const(right)) {
8540 lval = read_const(state, ins, left);
8541 rval = read_const(state, ins, right);
8545 } else if (rval > lval) {
8549 else if ((left->op == OP_ADDRCONST) &&
8550 (right->op == OP_ADDRCONST) &&
8551 (MISC(left, 0) == MISC(right, 0))) {
8553 if (left->u.cval > right->u.cval) {
8555 } else if (left->u.cval < right->u.cval) {
8560 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8566 int const_scmp(struct compile_state *state, struct triple *ins,
8567 struct triple *left, struct triple *right)
8570 if (!is_const(left) || !is_const(right)) {
8571 internal_warning(state, ins, "non const past to ucmp_const");
8574 else if (left == right) {
8577 else if (is_simple_const(left) && is_simple_const(right)) {
8579 lval = read_sconst(state, ins, left);
8580 rval = read_sconst(state, ins, right);
8584 } else if (rval > lval) {
8589 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8595 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8597 struct triple **expr;
8598 expr = triple_rhs(state, ins, 0);
8599 for(;expr;expr = triple_rhs(state, ins, expr)) {
8601 unuse_triple(*expr, ins);
8607 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8609 struct triple **expr;
8610 expr = triple_lhs(state, ins, 0);
8611 for(;expr;expr = triple_lhs(state, ins, expr)) {
8612 unuse_triple(*expr, ins);
8617 #if DEBUG_ROMCC_WARNING
8618 static void unuse_misc(struct compile_state *state, struct triple *ins)
8620 struct triple **expr;
8621 expr = triple_misc(state, ins, 0);
8622 for(;expr;expr = triple_misc(state, ins, expr)) {
8623 unuse_triple(*expr, ins);
8628 static void unuse_targ(struct compile_state *state, struct triple *ins)
8631 struct triple **slot;
8632 slot = &TARG(ins, 0);
8633 for(i = 0; i < ins->targ; i++) {
8634 unuse_triple(slot[i], ins);
8639 static void check_lhs(struct compile_state *state, struct triple *ins)
8641 struct triple **expr;
8642 expr = triple_lhs(state, ins, 0);
8643 for(;expr;expr = triple_lhs(state, ins, expr)) {
8644 internal_error(state, ins, "unexpected lhs");
8650 static void check_misc(struct compile_state *state, struct triple *ins)
8652 struct triple **expr;
8653 expr = triple_misc(state, ins, 0);
8654 for(;expr;expr = triple_misc(state, ins, expr)) {
8656 internal_error(state, ins, "unexpected misc");
8661 static void check_targ(struct compile_state *state, struct triple *ins)
8663 struct triple **expr;
8664 expr = triple_targ(state, ins, 0);
8665 for(;expr;expr = triple_targ(state, ins, expr)) {
8666 internal_error(state, ins, "unexpected targ");
8670 static void wipe_ins(struct compile_state *state, struct triple *ins)
8672 /* Becareful which instructions you replace the wiped
8673 * instruction with, as there are not enough slots
8674 * in all instructions to hold all others.
8676 check_targ(state, ins);
8677 check_misc(state, ins);
8678 unuse_rhs(state, ins);
8679 unuse_lhs(state, ins);
8686 #if DEBUG_ROMCC_WARNING
8687 static void wipe_branch(struct compile_state *state, struct triple *ins)
8689 /* Becareful which instructions you replace the wiped
8690 * instruction with, as there are not enough slots
8691 * in all instructions to hold all others.
8693 unuse_rhs(state, ins);
8694 unuse_lhs(state, ins);
8695 unuse_misc(state, ins);
8696 unuse_targ(state, ins);
8704 static void mkcopy(struct compile_state *state,
8705 struct triple *ins, struct triple *rhs)
8707 struct block *block;
8708 if (!equiv_types(ins->type, rhs->type)) {
8709 FILE *fp = state->errout;
8710 fprintf(fp, "src type: ");
8711 name_of(fp, rhs->type);
8712 fprintf(fp, "\ndst type: ");
8713 name_of(fp, ins->type);
8715 internal_error(state, ins, "mkcopy type mismatch");
8717 block = block_of_triple(state, ins);
8718 wipe_ins(state, ins);
8721 ins->u.block = block;
8723 use_triple(RHS(ins, 0), ins);
8726 static void mkconst(struct compile_state *state,
8727 struct triple *ins, ulong_t value)
8729 if (!is_integral(ins) && !is_pointer(ins)) {
8730 fprintf(state->errout, "type: ");
8731 name_of(state->errout, ins->type);
8732 fprintf(state->errout, "\n");
8733 internal_error(state, ins, "unknown type to make constant value: %ld",
8736 wipe_ins(state, ins);
8737 ins->op = OP_INTCONST;
8738 ins->u.cval = value;
8741 static void mkaddr_const(struct compile_state *state,
8742 struct triple *ins, struct triple *sdecl, ulong_t value)
8744 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8745 internal_error(state, ins, "bad base for addrconst");
8747 wipe_ins(state, ins);
8748 ins->op = OP_ADDRCONST;
8750 MISC(ins, 0) = sdecl;
8751 ins->u.cval = value;
8752 use_triple(sdecl, ins);
8755 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8756 static void print_tuple(struct compile_state *state,
8757 struct triple *ins, struct triple *tuple)
8759 FILE *fp = state->dbgout;
8760 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8761 name_of(fp, tuple->type);
8762 if (tuple->lhs > 0) {
8763 fprintf(fp, " lhs: ");
8764 name_of(fp, LHS(tuple, 0)->type);
8771 static struct triple *decompose_with_tuple(struct compile_state *state,
8772 struct triple *ins, struct triple *tuple)
8774 struct triple *next;
8776 flatten(state, next, tuple);
8777 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8778 print_tuple(state, ins, tuple);
8781 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8783 if (tuple->lhs != 1) {
8784 internal_error(state, tuple, "plain type in multiple registers?");
8786 tmp = LHS(tuple, 0);
8787 release_triple(state, tuple);
8791 propogate_use(state, ins, tuple);
8792 release_triple(state, ins);
8797 static struct triple *decompose_unknownval(struct compile_state *state,
8800 struct triple *tuple;
8803 #if DEBUG_DECOMPOSE_HIRES
8804 FILE *fp = state->dbgout;
8805 fprintf(fp, "unknown type: ");
8806 name_of(fp, ins->type);
8810 get_occurance(ins->occurance);
8811 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8814 for(i = 0; i < tuple->lhs; i++) {
8815 struct type *piece_type;
8816 struct triple *unknown;
8818 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8819 get_occurance(tuple->occurance);
8820 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8822 LHS(tuple, i) = unknown;
8824 return decompose_with_tuple(state, ins, tuple);
8828 static struct triple *decompose_read(struct compile_state *state,
8831 struct triple *tuple, *lval;
8836 if (lval->op == OP_PIECE) {
8839 get_occurance(ins->occurance);
8840 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8843 if ((tuple->lhs != lval->lhs) &&
8844 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8846 internal_error(state, ins, "lhs size inconsistency?");
8848 for(i = 0; i < tuple->lhs; i++) {
8849 struct triple *piece, *read, *bitref;
8850 if ((i != 0) || !triple_is_def(state, lval)) {
8851 piece = LHS(lval, i);
8856 /* See if the piece is really a bitref */
8858 if (piece->op == OP_BITREF) {
8860 piece = RHS(bitref, 0);
8863 get_occurance(tuple->occurance);
8864 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8866 RHS(read, 0) = piece;
8869 struct triple *extract;
8871 if (is_signed(bitref->type->left)) {
8876 get_occurance(tuple->occurance);
8877 extract = alloc_triple(state, op, bitref->type, -1, -1,
8879 RHS(extract, 0) = read;
8880 extract->u.bitfield.size = bitref->u.bitfield.size;
8881 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8886 LHS(tuple, i) = read;
8888 return decompose_with_tuple(state, ins, tuple);
8891 static struct triple *decompose_write(struct compile_state *state,
8894 struct triple *tuple, *lval, *val;
8897 lval = MISC(ins, 0);
8899 get_occurance(ins->occurance);
8900 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8903 if ((tuple->lhs != lval->lhs) &&
8904 (!triple_is_def(state, lval) || tuple->lhs != 1))
8906 internal_error(state, ins, "lhs size inconsistency?");
8908 for(i = 0; i < tuple->lhs; i++) {
8909 struct triple *piece, *write, *pval, *bitref;
8910 if ((i != 0) || !triple_is_def(state, lval)) {
8911 piece = LHS(lval, i);
8915 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8920 internal_error(state, ins, "lhs size inconsistency?");
8925 /* See if the piece is really a bitref */
8927 if (piece->op == OP_BITREF) {
8928 struct triple *read, *deposit;
8930 piece = RHS(bitref, 0);
8932 /* Read the destination register */
8933 get_occurance(tuple->occurance);
8934 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8936 RHS(read, 0) = piece;
8938 /* Deposit the new bitfield value */
8939 get_occurance(tuple->occurance);
8940 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8942 RHS(deposit, 0) = read;
8943 RHS(deposit, 1) = pval;
8944 deposit->u.bitfield.size = bitref->u.bitfield.size;
8945 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8947 /* Now write the newly generated value */
8951 get_occurance(tuple->occurance);
8952 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
8954 MISC(write, 0) = piece;
8955 RHS(write, 0) = pval;
8956 LHS(tuple, i) = write;
8958 return decompose_with_tuple(state, ins, tuple);
8961 struct decompose_load_info {
8962 struct occurance *occurance;
8963 struct triple *lval;
8964 struct triple *tuple;
8966 static void decompose_load_cb(struct compile_state *state,
8967 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8969 struct decompose_load_info *info = arg;
8970 struct triple *load;
8972 if (reg_offset > info->tuple->lhs) {
8973 internal_error(state, info->tuple, "lhs to small?");
8975 get_occurance(info->occurance);
8976 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8977 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8978 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8981 static struct triple *decompose_load(struct compile_state *state,
8984 struct triple *tuple;
8985 struct decompose_load_info info;
8987 if (!is_compound_type(ins->type)) {
8990 get_occurance(ins->occurance);
8991 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8994 info.occurance = ins->occurance;
8995 info.lval = RHS(ins, 0);
8997 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
8999 return decompose_with_tuple(state, ins, tuple);
9003 struct decompose_store_info {
9004 struct occurance *occurance;
9005 struct triple *lval;
9007 struct triple *tuple;
9009 static void decompose_store_cb(struct compile_state *state,
9010 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9012 struct decompose_store_info *info = arg;
9013 struct triple *store;
9015 if (reg_offset > info->tuple->lhs) {
9016 internal_error(state, info->tuple, "lhs to small?");
9018 get_occurance(info->occurance);
9019 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9020 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9021 RHS(store, 1) = LHS(info->val, reg_offset);
9022 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9025 static struct triple *decompose_store(struct compile_state *state,
9028 struct triple *tuple;
9029 struct decompose_store_info info;
9031 if (!is_compound_type(ins->type)) {
9034 get_occurance(ins->occurance);
9035 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9038 info.occurance = ins->occurance;
9039 info.lval = RHS(ins, 0);
9040 info.val = RHS(ins, 1);
9042 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9044 return decompose_with_tuple(state, ins, tuple);
9047 static struct triple *decompose_dot(struct compile_state *state,
9050 struct triple *tuple, *lval;
9055 lval = MISC(ins, 0);
9056 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9057 idx = reg_offset/REG_SIZEOF_REG;
9058 type = field_type(state, lval->type, ins->u.field);
9059 #if DEBUG_DECOMPOSE_HIRES
9061 FILE *fp = state->dbgout;
9062 fprintf(fp, "field type: ");
9068 get_occurance(ins->occurance);
9069 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9072 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9075 internal_error(state, ins, "multi register bitfield?");
9078 for(i = 0; i < tuple->lhs; i++, idx++) {
9079 struct triple *piece;
9080 if (!triple_is_def(state, lval)) {
9081 if (idx > lval->lhs) {
9082 internal_error(state, ins, "inconsistent lhs count");
9084 piece = LHS(lval, idx);
9087 internal_error(state, ins, "bad reg_offset into def");
9090 internal_error(state, ins, "bad reg count from def");
9095 /* Remember the offset of the bitfield */
9096 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9097 get_occurance(ins->occurance);
9098 piece = build_triple(state, OP_BITREF, type, piece, 0,
9100 piece->u.bitfield.size = size_of(state, type);
9101 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9103 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9104 internal_error(state, ins,
9105 "request for a nonbitfield sub register?");
9108 LHS(tuple, i) = piece;
9111 return decompose_with_tuple(state, ins, tuple);
9114 static struct triple *decompose_index(struct compile_state *state,
9117 struct triple *tuple, *lval;
9121 lval = MISC(ins, 0);
9122 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9123 type = index_type(state, lval->type, ins->u.cval);
9124 #if DEBUG_DECOMPOSE_HIRES
9126 FILE *fp = state->dbgout;
9127 fprintf(fp, "index type: ");
9133 get_occurance(ins->occurance);
9134 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9137 for(i = 0; i < tuple->lhs; i++, idx++) {
9138 struct triple *piece;
9139 if (!triple_is_def(state, lval)) {
9140 if (idx > lval->lhs) {
9141 internal_error(state, ins, "inconsistent lhs count");
9143 piece = LHS(lval, idx);
9146 internal_error(state, ins, "bad reg_offset into def");
9149 internal_error(state, ins, "bad reg count from def");
9153 LHS(tuple, i) = piece;
9156 return decompose_with_tuple(state, ins, tuple);
9159 static void decompose_compound_types(struct compile_state *state)
9161 struct triple *ins, *next, *first;
9164 first = state->first;
9167 /* Pass one expand compound values into pseudo registers.
9175 next = decompose_unknownval(state, ins);
9179 next = decompose_read(state, ins);
9183 next = decompose_write(state, ins);
9187 /* Be very careful with the load/store logic. These
9188 * operations must convert from the in register layout
9189 * to the in memory layout, which is nontrivial.
9192 next = decompose_load(state, ins);
9195 next = decompose_store(state, ins);
9199 next = decompose_dot(state, ins);
9202 next = decompose_index(state, ins);
9206 #if DEBUG_DECOMPOSE_HIRES
9207 fprintf(fp, "decompose next: %p \n", next);
9209 fprintf(fp, "next->op: %d %s\n",
9210 next->op, tops(next->op));
9211 /* High resolution debugging mode */
9212 print_triples(state);
9214 } while (next != first);
9216 /* Pass two remove the tuples.
9221 if (ins->op == OP_TUPLE) {
9223 internal_error(state, ins, "tuple used");
9226 release_triple(state, ins);
9230 } while(ins != first);
9234 if (ins->op == OP_BITREF) {
9236 internal_error(state, ins, "bitref used");
9239 release_triple(state, ins);
9243 } while(ins != first);
9245 /* Pass three verify the state and set ->id to 0.
9251 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9252 if (triple_stores_block(state, ins)) {
9255 if (triple_is_def(state, ins)) {
9256 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9257 internal_error(state, ins, "multi register value remains?");
9260 if (ins->op == OP_DOT) {
9261 internal_error(state, ins, "OP_DOT remains?");
9263 if (ins->op == OP_INDEX) {
9264 internal_error(state, ins, "OP_INDEX remains?");
9266 if (ins->op == OP_BITREF) {
9267 internal_error(state, ins, "OP_BITREF remains?");
9269 if (ins->op == OP_TUPLE) {
9270 internal_error(state, ins, "OP_TUPLE remains?");
9272 } while(next != first);
9275 /* For those operations that cannot be simplified */
9276 static void simplify_noop(struct compile_state *state, struct triple *ins)
9281 static void simplify_smul(struct compile_state *state, struct triple *ins)
9283 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9286 RHS(ins, 0) = RHS(ins, 1);
9289 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9291 left = read_sconst(state, ins, RHS(ins, 0));
9292 right = read_sconst(state, ins, RHS(ins, 1));
9293 mkconst(state, ins, left * right);
9295 else if (is_zero(RHS(ins, 1))) {
9296 mkconst(state, ins, 0);
9298 else if (is_one(RHS(ins, 1))) {
9299 mkcopy(state, ins, RHS(ins, 0));
9301 else if (is_pow2(RHS(ins, 1))) {
9303 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9305 insert_triple(state, state->global_pool, val);
9306 unuse_triple(RHS(ins, 1), ins);
9307 use_triple(val, ins);
9312 static void simplify_umul(struct compile_state *state, struct triple *ins)
9314 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9317 RHS(ins, 0) = RHS(ins, 1);
9320 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9321 ulong_t left, right;
9322 left = read_const(state, ins, RHS(ins, 0));
9323 right = read_const(state, ins, RHS(ins, 1));
9324 mkconst(state, ins, left * right);
9326 else if (is_zero(RHS(ins, 1))) {
9327 mkconst(state, ins, 0);
9329 else if (is_one(RHS(ins, 1))) {
9330 mkcopy(state, ins, RHS(ins, 0));
9332 else if (is_pow2(RHS(ins, 1))) {
9334 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9336 insert_triple(state, state->global_pool, val);
9337 unuse_triple(RHS(ins, 1), ins);
9338 use_triple(val, ins);
9343 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9345 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9347 left = read_sconst(state, ins, RHS(ins, 0));
9348 right = read_sconst(state, ins, RHS(ins, 1));
9349 mkconst(state, ins, left / right);
9351 else if (is_zero(RHS(ins, 0))) {
9352 mkconst(state, ins, 0);
9354 else if (is_zero(RHS(ins, 1))) {
9355 error(state, ins, "division by zero");
9357 else if (is_one(RHS(ins, 1))) {
9358 mkcopy(state, ins, RHS(ins, 0));
9360 else if (is_pow2(RHS(ins, 1))) {
9362 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9364 insert_triple(state, state->global_pool, val);
9365 unuse_triple(RHS(ins, 1), ins);
9366 use_triple(val, ins);
9371 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9373 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9374 ulong_t left, right;
9375 left = read_const(state, ins, RHS(ins, 0));
9376 right = read_const(state, ins, RHS(ins, 1));
9377 mkconst(state, ins, left / right);
9379 else if (is_zero(RHS(ins, 0))) {
9380 mkconst(state, ins, 0);
9382 else if (is_zero(RHS(ins, 1))) {
9383 error(state, ins, "division by zero");
9385 else if (is_one(RHS(ins, 1))) {
9386 mkcopy(state, ins, RHS(ins, 0));
9388 else if (is_pow2(RHS(ins, 1))) {
9390 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9392 insert_triple(state, state->global_pool, val);
9393 unuse_triple(RHS(ins, 1), ins);
9394 use_triple(val, ins);
9399 static void simplify_smod(struct compile_state *state, struct triple *ins)
9401 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9403 left = read_const(state, ins, RHS(ins, 0));
9404 right = read_const(state, ins, RHS(ins, 1));
9405 mkconst(state, ins, left % right);
9407 else if (is_zero(RHS(ins, 0))) {
9408 mkconst(state, ins, 0);
9410 else if (is_zero(RHS(ins, 1))) {
9411 error(state, ins, "division by zero");
9413 else if (is_one(RHS(ins, 1))) {
9414 mkconst(state, ins, 0);
9416 else if (is_pow2(RHS(ins, 1))) {
9418 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9420 insert_triple(state, state->global_pool, val);
9421 unuse_triple(RHS(ins, 1), ins);
9422 use_triple(val, ins);
9427 static void simplify_umod(struct compile_state *state, struct triple *ins)
9429 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9430 ulong_t left, right;
9431 left = read_const(state, ins, RHS(ins, 0));
9432 right = read_const(state, ins, RHS(ins, 1));
9433 mkconst(state, ins, left % right);
9435 else if (is_zero(RHS(ins, 0))) {
9436 mkconst(state, ins, 0);
9438 else if (is_zero(RHS(ins, 1))) {
9439 error(state, ins, "division by zero");
9441 else if (is_one(RHS(ins, 1))) {
9442 mkconst(state, ins, 0);
9444 else if (is_pow2(RHS(ins, 1))) {
9446 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9448 insert_triple(state, state->global_pool, val);
9449 unuse_triple(RHS(ins, 1), ins);
9450 use_triple(val, ins);
9455 static void simplify_add(struct compile_state *state, struct triple *ins)
9457 /* start with the pointer on the left */
9458 if (is_pointer(RHS(ins, 1))) {
9461 RHS(ins, 0) = RHS(ins, 1);
9464 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9465 if (RHS(ins, 0)->op == OP_INTCONST) {
9466 ulong_t left, right;
9467 left = read_const(state, ins, RHS(ins, 0));
9468 right = read_const(state, ins, RHS(ins, 1));
9469 mkconst(state, ins, left + right);
9471 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9472 struct triple *sdecl;
9473 ulong_t left, right;
9474 sdecl = MISC(RHS(ins, 0), 0);
9475 left = RHS(ins, 0)->u.cval;
9476 right = RHS(ins, 1)->u.cval;
9477 mkaddr_const(state, ins, sdecl, left + right);
9480 internal_warning(state, ins, "Optimize me!");
9483 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9486 RHS(ins, 1) = RHS(ins, 0);
9491 static void simplify_sub(struct compile_state *state, struct triple *ins)
9493 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9494 if (RHS(ins, 0)->op == OP_INTCONST) {
9495 ulong_t left, right;
9496 left = read_const(state, ins, RHS(ins, 0));
9497 right = read_const(state, ins, RHS(ins, 1));
9498 mkconst(state, ins, left - right);
9500 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9501 struct triple *sdecl;
9502 ulong_t left, right;
9503 sdecl = MISC(RHS(ins, 0), 0);
9504 left = RHS(ins, 0)->u.cval;
9505 right = RHS(ins, 1)->u.cval;
9506 mkaddr_const(state, ins, sdecl, left - right);
9509 internal_warning(state, ins, "Optimize me!");
9514 static void simplify_sl(struct compile_state *state, struct triple *ins)
9516 if (is_simple_const(RHS(ins, 1))) {
9518 right = read_const(state, ins, RHS(ins, 1));
9519 if (right >= (size_of(state, ins->type))) {
9520 warning(state, ins, "left shift count >= width of type");
9523 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9524 ulong_t left, right;
9525 left = read_const(state, ins, RHS(ins, 0));
9526 right = read_const(state, ins, RHS(ins, 1));
9527 mkconst(state, ins, left << right);
9531 static void simplify_usr(struct compile_state *state, struct triple *ins)
9533 if (is_simple_const(RHS(ins, 1))) {
9535 right = read_const(state, ins, RHS(ins, 1));
9536 if (right >= (size_of(state, ins->type))) {
9537 warning(state, ins, "right shift count >= width of type");
9540 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9541 ulong_t left, right;
9542 left = read_const(state, ins, RHS(ins, 0));
9543 right = read_const(state, ins, RHS(ins, 1));
9544 mkconst(state, ins, left >> right);
9548 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9550 if (is_simple_const(RHS(ins, 1))) {
9552 right = read_const(state, ins, RHS(ins, 1));
9553 if (right >= (size_of(state, ins->type))) {
9554 warning(state, ins, "right shift count >= width of type");
9557 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9559 left = read_sconst(state, ins, RHS(ins, 0));
9560 right = read_sconst(state, ins, RHS(ins, 1));
9561 mkconst(state, ins, left >> right);
9565 static void simplify_and(struct compile_state *state, struct triple *ins)
9567 struct triple *left, *right;
9569 right = RHS(ins, 1);
9571 if (is_simple_const(left) && is_simple_const(right)) {
9573 lval = read_const(state, ins, left);
9574 rval = read_const(state, ins, right);
9575 mkconst(state, ins, lval & rval);
9577 else if (is_zero(right) || is_zero(left)) {
9578 mkconst(state, ins, 0);
9582 static void simplify_or(struct compile_state *state, struct triple *ins)
9584 struct triple *left, *right;
9586 right = RHS(ins, 1);
9588 if (is_simple_const(left) && is_simple_const(right)) {
9590 lval = read_const(state, ins, left);
9591 rval = read_const(state, ins, right);
9592 mkconst(state, ins, lval | rval);
9594 #if 0 /* I need to handle type mismatches here... */
9595 else if (is_zero(right)) {
9596 mkcopy(state, ins, left);
9598 else if (is_zero(left)) {
9599 mkcopy(state, ins, right);
9604 static void simplify_xor(struct compile_state *state, struct triple *ins)
9606 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9607 ulong_t left, right;
9608 left = read_const(state, ins, RHS(ins, 0));
9609 right = read_const(state, ins, RHS(ins, 1));
9610 mkconst(state, ins, left ^ right);
9614 static void simplify_pos(struct compile_state *state, struct triple *ins)
9616 if (is_const(RHS(ins, 0))) {
9617 mkconst(state, ins, RHS(ins, 0)->u.cval);
9620 mkcopy(state, ins, RHS(ins, 0));
9624 static void simplify_neg(struct compile_state *state, struct triple *ins)
9626 if (is_simple_const(RHS(ins, 0))) {
9628 left = read_const(state, ins, RHS(ins, 0));
9629 mkconst(state, ins, -left);
9631 else if (RHS(ins, 0)->op == OP_NEG) {
9632 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9636 static void simplify_invert(struct compile_state *state, struct triple *ins)
9638 if (is_simple_const(RHS(ins, 0))) {
9640 left = read_const(state, ins, RHS(ins, 0));
9641 mkconst(state, ins, ~left);
9645 static void simplify_eq(struct compile_state *state, struct triple *ins)
9647 struct triple *left, *right;
9649 right = RHS(ins, 1);
9651 if (is_const(left) && is_const(right)) {
9653 val = const_eq(state, ins, left, right);
9655 mkconst(state, ins, val == 1);
9658 else if (left == right) {
9659 mkconst(state, ins, 1);
9663 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9665 struct triple *left, *right;
9667 right = RHS(ins, 1);
9669 if (is_const(left) && is_const(right)) {
9671 val = const_eq(state, ins, left, right);
9673 mkconst(state, ins, val != 1);
9676 if (left == right) {
9677 mkconst(state, ins, 0);
9681 static void simplify_sless(struct compile_state *state, struct triple *ins)
9683 struct triple *left, *right;
9685 right = RHS(ins, 1);
9687 if (is_const(left) && is_const(right)) {
9689 val = const_scmp(state, ins, left, right);
9690 if ((val >= -1) && (val <= 1)) {
9691 mkconst(state, ins, val < 0);
9694 else if (left == right) {
9695 mkconst(state, ins, 0);
9699 static void simplify_uless(struct compile_state *state, struct triple *ins)
9701 struct triple *left, *right;
9703 right = RHS(ins, 1);
9705 if (is_const(left) && is_const(right)) {
9707 val = const_ucmp(state, ins, left, right);
9708 if ((val >= -1) && (val <= 1)) {
9709 mkconst(state, ins, val < 0);
9712 else if (is_zero(right)) {
9713 mkconst(state, ins, 0);
9715 else if (left == right) {
9716 mkconst(state, ins, 0);
9720 static void simplify_smore(struct compile_state *state, struct triple *ins)
9722 struct triple *left, *right;
9724 right = RHS(ins, 1);
9726 if (is_const(left) && is_const(right)) {
9728 val = const_scmp(state, ins, left, right);
9729 if ((val >= -1) && (val <= 1)) {
9730 mkconst(state, ins, val > 0);
9733 else if (left == right) {
9734 mkconst(state, ins, 0);
9738 static void simplify_umore(struct compile_state *state, struct triple *ins)
9740 struct triple *left, *right;
9742 right = RHS(ins, 1);
9744 if (is_const(left) && is_const(right)) {
9746 val = const_ucmp(state, ins, left, right);
9747 if ((val >= -1) && (val <= 1)) {
9748 mkconst(state, ins, val > 0);
9751 else if (is_zero(left)) {
9752 mkconst(state, ins, 0);
9754 else if (left == right) {
9755 mkconst(state, ins, 0);
9760 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9762 struct triple *left, *right;
9764 right = RHS(ins, 1);
9766 if (is_const(left) && is_const(right)) {
9768 val = const_scmp(state, ins, left, right);
9769 if ((val >= -1) && (val <= 1)) {
9770 mkconst(state, ins, val <= 0);
9773 else if (left == right) {
9774 mkconst(state, ins, 1);
9778 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9780 struct triple *left, *right;
9782 right = RHS(ins, 1);
9784 if (is_const(left) && is_const(right)) {
9786 val = const_ucmp(state, ins, left, right);
9787 if ((val >= -1) && (val <= 1)) {
9788 mkconst(state, ins, val <= 0);
9791 else if (is_zero(left)) {
9792 mkconst(state, ins, 1);
9794 else if (left == right) {
9795 mkconst(state, ins, 1);
9799 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9801 struct triple *left, *right;
9803 right = RHS(ins, 1);
9805 if (is_const(left) && is_const(right)) {
9807 val = const_scmp(state, ins, left, right);
9808 if ((val >= -1) && (val <= 1)) {
9809 mkconst(state, ins, val >= 0);
9812 else if (left == right) {
9813 mkconst(state, ins, 1);
9817 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9819 struct triple *left, *right;
9821 right = RHS(ins, 1);
9823 if (is_const(left) && is_const(right)) {
9825 val = const_ucmp(state, ins, left, right);
9826 if ((val >= -1) && (val <= 1)) {
9827 mkconst(state, ins, val >= 0);
9830 else if (is_zero(right)) {
9831 mkconst(state, ins, 1);
9833 else if (left == right) {
9834 mkconst(state, ins, 1);
9838 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9843 if (is_const(rhs)) {
9844 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9846 /* Otherwise if I am the only user... */
9847 else if ((rhs->use) &&
9848 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9850 /* Invert a boolean operation */
9852 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9853 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9854 case OP_EQ: rhs->op = OP_NOTEQ; break;
9855 case OP_NOTEQ: rhs->op = OP_EQ; break;
9856 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9857 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9858 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9859 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9860 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9861 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9862 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9863 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9869 mkcopy(state, ins, rhs);
9874 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9879 if (is_const(rhs)) {
9880 mkconst(state, ins, const_ltrue(state, ins, rhs));
9882 else switch(rhs->op) {
9883 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9884 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9885 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9886 mkcopy(state, ins, rhs);
9891 static void simplify_load(struct compile_state *state, struct triple *ins)
9893 struct triple *addr, *sdecl, *blob;
9895 /* If I am doing a load with a constant pointer from a constant
9896 * table get the value.
9899 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9900 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9901 (blob->op == OP_BLOBCONST)) {
9902 unsigned char buffer[SIZEOF_WORD];
9903 size_t reg_size, mem_size;
9904 const char *src, *end;
9906 reg_size = reg_size_of(state, ins->type);
9907 if (reg_size > REG_SIZEOF_REG) {
9908 internal_error(state, ins, "load size greater than register");
9910 mem_size = size_of(state, ins->type);
9912 end += bits_to_bytes(size_of(state, sdecl->type));
9914 src += addr->u.cval;
9917 error(state, ins, "Load address out of bounds");
9920 memset(buffer, 0, sizeof(buffer));
9921 memcpy(buffer, src, bits_to_bytes(mem_size));
9924 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
9925 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9926 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9927 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9929 internal_error(state, ins, "mem_size: %d not handled",
9934 mkconst(state, ins, val);
9938 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9940 if (is_simple_const(RHS(ins, 0))) {
9943 val = read_const(state, ins, RHS(ins, 0));
9945 mask <<= ins->u.bitfield.size;
9947 val >>= ins->u.bitfield.offset;
9949 mkconst(state, ins, val);
9953 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9955 if (is_simple_const(RHS(ins, 0))) {
9959 val = read_const(state, ins, RHS(ins, 0));
9961 mask <<= ins->u.bitfield.size;
9963 val >>= ins->u.bitfield.offset;
9965 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9967 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9968 mkconst(state, ins, sval);
9972 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9974 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9977 targ = read_const(state, ins, RHS(ins, 0));
9978 val = read_const(state, ins, RHS(ins, 1));
9980 mask <<= ins->u.bitfield.size;
9982 mask <<= ins->u.bitfield.offset;
9984 val <<= ins->u.bitfield.offset;
9987 mkconst(state, ins, targ);
9991 static void simplify_copy(struct compile_state *state, struct triple *ins)
9993 struct triple *right;
9994 right = RHS(ins, 0);
9995 if (is_subset_type(ins->type, right->type)) {
9996 ins->type = right->type;
9998 if (equiv_types(ins->type, right->type)) {
9999 ins->op = OP_COPY;/* I don't need to convert if the types match */
10001 if (ins->op == OP_COPY) {
10002 internal_error(state, ins, "type mismatch on copy");
10005 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10006 struct triple *sdecl;
10008 sdecl = MISC(right, 0);
10009 offset = right->u.cval;
10010 mkaddr_const(state, ins, sdecl, offset);
10012 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10013 switch(right->op) {
10017 left = read_const(state, ins, right);
10018 /* Ensure I have not overflowed the destination. */
10019 if (size_of(state, right->type) > size_of(state, ins->type)) {
10022 mask <<= size_of(state, ins->type);
10026 /* Ensure I am properly sign extended */
10027 if (size_of(state, right->type) < size_of(state, ins->type) &&
10028 is_signed(right->type)) {
10031 shift = SIZEOF_LONG - size_of(state, right->type);
10037 mkconst(state, ins, left);
10041 internal_error(state, ins, "uknown constant");
10047 static int phi_present(struct block *block)
10049 struct triple *ptr;
10053 ptr = block->first;
10055 if (ptr->op == OP_PHI) {
10059 } while(ptr != block->last);
10063 static int phi_dependency(struct block *block)
10065 /* A block has a phi dependency if a phi function
10066 * depends on that block to exist, and makes a block
10067 * that is otherwise useless unsafe to remove.
10070 struct block_set *edge;
10071 for(edge = block->edges; edge; edge = edge->next) {
10072 if (phi_present(edge->member)) {
10080 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10082 struct triple *targ;
10083 targ = TARG(ins, 0);
10084 /* During scc_transform temporary triples are allocated that
10085 * loop back onto themselves. If I see one don't advance the
10088 while(triple_is_structural(state, targ) &&
10089 (targ->next != targ) && (targ->next != state->first)) {
10096 static void simplify_branch(struct compile_state *state, struct triple *ins)
10098 int simplified, loops;
10099 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10100 internal_error(state, ins, "not branch");
10102 if (ins->use != 0) {
10103 internal_error(state, ins, "branch use");
10105 /* The challenge here with simplify branch is that I need to
10106 * make modifications to the control flow graph as well
10107 * as to the branch instruction itself. That is handled
10108 * by rebuilding the basic blocks after simplify all is called.
10111 /* If we have a branch to an unconditional branch update
10112 * our target. But watch out for dependencies from phi
10114 * Also only do this a limited number of times so
10115 * we don't get into an infinite loop.
10119 struct triple *targ;
10121 targ = branch_target(state, ins);
10122 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10123 !phi_dependency(targ->u.block))
10125 unuse_triple(TARG(ins, 0), ins);
10126 TARG(ins, 0) = TARG(targ, 0);
10127 use_triple(TARG(ins, 0), ins);
10130 } while(simplified && (++loops < 20));
10132 /* If we have a conditional branch with a constant condition
10133 * make it an unconditional branch.
10135 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10136 struct triple *targ;
10138 value = read_const(state, ins, RHS(ins, 0));
10139 unuse_triple(RHS(ins, 0), ins);
10140 targ = TARG(ins, 0);
10143 ins->op = OP_BRANCH;
10145 unuse_triple(ins->next, ins);
10146 TARG(ins, 0) = targ;
10149 unuse_triple(targ, ins);
10150 TARG(ins, 0) = ins->next;
10154 /* If we have a branch to the next instruction,
10157 if (TARG(ins, 0) == ins->next) {
10158 unuse_triple(TARG(ins, 0), ins);
10159 if (ins->op == OP_CBRANCH) {
10160 unuse_triple(RHS(ins, 0), ins);
10161 unuse_triple(ins->next, ins);
10169 internal_error(state, ins, "noop use != 0");
10174 static void simplify_label(struct compile_state *state, struct triple *ins)
10176 /* Ignore volatile labels */
10177 if (!triple_is_pure(state, ins, ins->id)) {
10180 if (ins->use == 0) {
10183 else if (ins->prev->op == OP_LABEL) {
10184 /* In general it is not safe to merge one label that
10185 * imediately follows another. The problem is that the empty
10186 * looking block may have phi functions that depend on it.
10188 if (!phi_dependency(ins->prev->u.block)) {
10189 struct triple_set *user, *next;
10191 for(user = ins->use; user; user = next) {
10192 struct triple *use, **expr;
10194 use = user->member;
10195 expr = triple_targ(state, use, 0);
10196 for(;expr; expr = triple_targ(state, use, expr)) {
10197 if (*expr == ins) {
10199 unuse_triple(ins, use);
10200 use_triple(ins->prev, use);
10206 internal_error(state, ins, "noop use != 0");
10212 static void simplify_phi(struct compile_state *state, struct triple *ins)
10214 struct triple **slot;
10215 struct triple *value;
10218 slot = &RHS(ins, 0);
10223 /* See if all of the rhs members of a phi have the same value */
10224 if (slot[0] && is_simple_const(slot[0])) {
10225 cvalue = read_const(state, ins, slot[0]);
10226 for(i = 1; i < zrhs; i++) {
10228 !is_simple_const(slot[i]) ||
10229 !equiv_types(slot[0]->type, slot[i]->type) ||
10230 (cvalue != read_const(state, ins, slot[i]))) {
10235 mkconst(state, ins, cvalue);
10240 /* See if all of rhs members of a phi are the same */
10242 for(i = 1; i < zrhs; i++) {
10243 if (slot[i] != value) {
10248 /* If the phi has a single value just copy it */
10249 if (!is_subset_type(ins->type, value->type)) {
10250 internal_error(state, ins, "bad input type to phi");
10252 /* Make the types match */
10253 if (!equiv_types(ins->type, value->type)) {
10254 ins->type = value->type;
10256 /* Now make the actual copy */
10257 mkcopy(state, ins, value);
10263 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10265 if (is_simple_const(RHS(ins, 0))) {
10267 left = read_const(state, ins, RHS(ins, 0));
10268 mkconst(state, ins, bsf(left));
10272 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10274 if (is_simple_const(RHS(ins, 0))) {
10276 left = read_const(state, ins, RHS(ins, 0));
10277 mkconst(state, ins, bsr(left));
10282 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10283 static const struct simplify_table {
10285 unsigned long flag;
10286 } table_simplify[] = {
10287 #define simplify_sdivt simplify_noop
10288 #define simplify_udivt simplify_noop
10289 #define simplify_piece simplify_noop
10291 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10292 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10293 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10294 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10295 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10296 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10297 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10298 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10299 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10300 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10301 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10302 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10303 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10304 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10305 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10306 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10307 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10308 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10309 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10311 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10312 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10313 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10314 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10315 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10316 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10317 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10318 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10319 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10320 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10321 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10322 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10324 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10325 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10327 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10328 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10329 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10331 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10333 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10334 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10335 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10336 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10338 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10339 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10340 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10341 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10342 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10343 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10345 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10346 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10348 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10349 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10350 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10351 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10352 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10353 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10354 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10355 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10356 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10358 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10359 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10360 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10361 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10362 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10363 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10364 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10365 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10366 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10367 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10368 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10371 static inline void debug_simplify(struct compile_state *state,
10372 simplify_t do_simplify, struct triple *ins)
10374 #if DEBUG_SIMPLIFY_HIRES
10375 if (state->functions_joined && (do_simplify != simplify_noop)) {
10376 /* High resolution debugging mode */
10377 fprintf(state->dbgout, "simplifing: ");
10378 display_triple(state->dbgout, ins);
10381 do_simplify(state, ins);
10382 #if DEBUG_SIMPLIFY_HIRES
10383 if (state->functions_joined && (do_simplify != simplify_noop)) {
10384 /* High resolution debugging mode */
10385 fprintf(state->dbgout, "simplified: ");
10386 display_triple(state->dbgout, ins);
10390 static void simplify(struct compile_state *state, struct triple *ins)
10393 simplify_t do_simplify;
10394 if (ins == &unknown_triple) {
10395 internal_error(state, ins, "simplifying the unknown triple?");
10400 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10404 do_simplify = table_simplify[op].func;
10407 !(state->compiler->flags & table_simplify[op].flag)) {
10408 do_simplify = simplify_noop;
10410 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10411 do_simplify = simplify_noop;
10414 if (!do_simplify) {
10415 internal_error(state, ins, "cannot simplify op: %d %s",
10419 debug_simplify(state, do_simplify, ins);
10420 } while(ins->op != op);
10423 static void rebuild_ssa_form(struct compile_state *state);
10425 static void simplify_all(struct compile_state *state)
10427 struct triple *ins, *first;
10428 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10431 first = state->first;
10434 simplify(state, ins);
10436 } while(ins != first->prev);
10439 simplify(state, ins);
10441 }while(ins != first);
10442 rebuild_ssa_form(state);
10444 print_blocks(state, __func__, state->dbgout);
10449 * ============================
10452 static void register_builtin_function(struct compile_state *state,
10453 const char *name, int op, struct type *rtype, ...)
10455 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10456 struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10457 struct hash_entry *ident;
10458 struct file_state file;
10464 /* Dummy file state to get debug handling right */
10465 memset(&file, 0, sizeof(file));
10466 file.basename = "<built-in>";
10468 file.report_line = 1;
10469 file.report_name = file.basename;
10470 file.prev = state->file;
10471 state->file = &file;
10472 state->function = name;
10474 /* Find the Parameter count */
10475 valid_op(state, op);
10476 parameters = table_ops[op].rhs;
10477 if (parameters < 0 ) {
10478 internal_error(state, 0, "Invalid builtin parameter count");
10481 /* Find the function type */
10482 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10483 ftype->elements = parameters;
10484 next = &ftype->right;
10485 va_start(args, rtype);
10486 for(i = 0; i < parameters; i++) {
10487 atype = va_arg(args, struct type *);
10491 *next = new_type(TYPE_PRODUCT, *next, atype);
10492 next = &((*next)->right);
10496 *next = &void_type;
10500 /* Get the initial closure type */
10501 ctype = new_type(TYPE_JOIN, &void_type, 0);
10502 ctype->elements = 1;
10504 /* Get the return type */
10505 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10506 crtype->elements = 2;
10508 /* Generate the needed triples */
10509 def = triple(state, OP_LIST, ftype, 0, 0);
10510 first = label(state);
10511 RHS(def, 0) = first;
10512 result = flatten(state, first, variable(state, crtype));
10513 retvar = flatten(state, first, variable(state, &void_ptr_type));
10514 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10516 /* Now string them together */
10517 param = ftype->right;
10518 for(i = 0; i < parameters; i++) {
10519 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10520 atype = param->left;
10524 arg = flatten(state, first, variable(state, atype));
10525 param = param->right;
10527 work = new_triple(state, op, rtype, -1, parameters);
10528 generate_lhs_pieces(state, work);
10529 for(i = 0; i < parameters; i++) {
10530 RHS(work, i) = read_expr(state, farg(state, def, i));
10532 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10533 work = write_expr(state, deref_index(state, result, 1), work);
10535 work = flatten(state, first, work);
10536 last = flatten(state, first, label(state));
10537 ret = flatten(state, first, ret);
10538 name_len = strlen(name);
10539 ident = lookup(state, name, name_len);
10540 ftype->type_ident = ident;
10541 symbol(state, ident, &ident->sym_ident, def, ftype);
10543 state->file = file.prev;
10544 state->function = 0;
10545 state->main_function = 0;
10547 if (!state->functions) {
10548 state->functions = def;
10550 insert_triple(state, state->functions, def);
10552 if (state->compiler->debug & DEBUG_INLINE) {
10553 FILE *fp = state->dbgout;
10556 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10557 display_func(state, fp, def);
10558 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10562 static struct type *partial_struct(struct compile_state *state,
10563 const char *field_name, struct type *type, struct type *rest)
10565 struct hash_entry *field_ident;
10566 struct type *result;
10567 int field_name_len;
10569 field_name_len = strlen(field_name);
10570 field_ident = lookup(state, field_name, field_name_len);
10572 result = clone_type(0, type);
10573 result->field_ident = field_ident;
10576 result = new_type(TYPE_PRODUCT, result, rest);
10581 static struct type *register_builtin_type(struct compile_state *state,
10582 const char *name, struct type *type)
10584 struct hash_entry *ident;
10587 name_len = strlen(name);
10588 ident = lookup(state, name, name_len);
10590 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10591 ulong_t elements = 0;
10592 struct type *field;
10593 type = new_type(TYPE_STRUCT, type, 0);
10594 field = type->left;
10595 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10597 field = field->right;
10600 symbol(state, ident, &ident->sym_tag, 0, type);
10601 type->type_ident = ident;
10602 type->elements = elements;
10604 symbol(state, ident, &ident->sym_ident, 0, type);
10605 ident->tok = TOK_TYPE_NAME;
10610 static void register_builtins(struct compile_state *state)
10612 struct type *div_type, *ldiv_type;
10613 struct type *udiv_type, *uldiv_type;
10614 struct type *msr_type;
10616 div_type = register_builtin_type(state, "__builtin_div_t",
10617 partial_struct(state, "quot", &int_type,
10618 partial_struct(state, "rem", &int_type, 0)));
10619 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10620 partial_struct(state, "quot", &long_type,
10621 partial_struct(state, "rem", &long_type, 0)));
10622 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10623 partial_struct(state, "quot", &uint_type,
10624 partial_struct(state, "rem", &uint_type, 0)));
10625 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10626 partial_struct(state, "quot", &ulong_type,
10627 partial_struct(state, "rem", &ulong_type, 0)));
10629 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10630 &int_type, &int_type);
10631 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10632 &long_type, &long_type);
10633 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10634 &uint_type, &uint_type);
10635 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10636 &ulong_type, &ulong_type);
10638 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10640 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10642 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10645 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10646 &uchar_type, &ushort_type);
10647 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10648 &ushort_type, &ushort_type);
10649 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10650 &uint_type, &ushort_type);
10652 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10654 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10657 msr_type = register_builtin_type(state, "__builtin_msr_t",
10658 partial_struct(state, "lo", &ulong_type,
10659 partial_struct(state, "hi", &ulong_type, 0)));
10661 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10663 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10664 &ulong_type, &ulong_type, &ulong_type);
10666 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10670 static struct type *declarator(
10671 struct compile_state *state, struct type *type,
10672 struct hash_entry **ident, int need_ident);
10673 static void decl(struct compile_state *state, struct triple *first);
10674 static struct type *specifier_qualifier_list(struct compile_state *state);
10675 #if DEBUG_ROMCC_WARNING
10676 static int isdecl_specifier(int tok);
10678 static struct type *decl_specifiers(struct compile_state *state);
10679 static int istype(int tok);
10680 static struct triple *expr(struct compile_state *state);
10681 static struct triple *assignment_expr(struct compile_state *state);
10682 static struct type *type_name(struct compile_state *state);
10683 static void statement(struct compile_state *state, struct triple *first);
10685 static struct triple *call_expr(
10686 struct compile_state *state, struct triple *func)
10688 struct triple *def;
10689 struct type *param, *type;
10690 ulong_t pvals, index;
10692 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10693 error(state, 0, "Called object is not a function");
10695 if (func->op != OP_LIST) {
10696 internal_error(state, 0, "improper function");
10698 eat(state, TOK_LPAREN);
10699 /* Find the return type without any specifiers */
10700 type = clone_type(0, func->type->left);
10701 /* Count the number of rhs entries for OP_FCALL */
10702 param = func->type->right;
10704 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10706 param = param->right;
10708 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10711 def = new_triple(state, OP_FCALL, type, -1, pvals);
10712 MISC(def, 0) = func;
10714 param = func->type->right;
10715 for(index = 0; index < pvals; index++) {
10716 struct triple *val;
10717 struct type *arg_type;
10718 val = read_expr(state, assignment_expr(state));
10720 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10721 arg_type = param->left;
10723 write_compatible(state, arg_type, val->type);
10724 RHS(def, index) = val;
10725 if (index != (pvals - 1)) {
10726 eat(state, TOK_COMMA);
10727 param = param->right;
10730 eat(state, TOK_RPAREN);
10735 static struct triple *character_constant(struct compile_state *state)
10737 struct triple *def;
10739 const signed char *str, *end;
10742 tk = eat(state, TOK_LIT_CHAR);
10743 str = (signed char *)tk->val.str + 1;
10744 str_len = tk->str_len - 2;
10745 if (str_len <= 0) {
10746 error(state, 0, "empty character constant");
10748 end = str + str_len;
10749 c = char_value(state, &str, end);
10751 error(state, 0, "multibyte character constant not supported");
10753 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10757 static struct triple *string_constant(struct compile_state *state)
10759 struct triple *def;
10762 const signed char *str, *end;
10763 signed char *buf, *ptr;
10767 type = new_type(TYPE_ARRAY, &char_type, 0);
10768 type->elements = 0;
10769 /* The while loop handles string concatenation */
10771 tk = eat(state, TOK_LIT_STRING);
10772 str = (signed char *)tk->val.str + 1;
10773 str_len = tk->str_len - 2;
10775 error(state, 0, "negative string constant length");
10777 end = str + str_len;
10779 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10780 memcpy(buf, ptr, type->elements);
10781 ptr = buf + type->elements;
10783 *ptr++ = char_value(state, &str, end);
10784 } while(str < end);
10785 type->elements = ptr - buf;
10786 } while(peek(state) == TOK_LIT_STRING);
10788 type->elements += 1;
10789 def = triple(state, OP_BLOBCONST, type, 0, 0);
10796 static struct triple *integer_constant(struct compile_state *state)
10798 struct triple *def;
10805 tk = eat(state, TOK_LIT_INT);
10807 decimal = (tk->val.str[0] != '0');
10808 val = strtoul(tk->val.str, &end, 0);
10809 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10810 error(state, 0, "Integer constant to large");
10813 if ((*end == 'u') || (*end == 'U')) {
10817 if ((*end == 'l') || (*end == 'L')) {
10821 if ((*end == 'u') || (*end == 'U')) {
10826 error(state, 0, "Junk at end of integer constant");
10829 type = &ulong_type;
10833 if (!decimal && (val > LONG_T_MAX)) {
10834 type = &ulong_type;
10839 if (val > UINT_T_MAX) {
10840 type = &ulong_type;
10845 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10848 else if (!decimal && (val > LONG_T_MAX)) {
10849 type = &ulong_type;
10851 else if (val > INT_T_MAX) {
10855 def = int_const(state, type, val);
10859 static struct triple *primary_expr(struct compile_state *state)
10861 struct triple *def;
10867 struct hash_entry *ident;
10868 /* Here ident is either:
10872 ident = eat(state, TOK_IDENT)->ident;
10873 if (!ident->sym_ident) {
10874 error(state, 0, "%s undeclared", ident->name);
10876 def = ident->sym_ident->def;
10879 case TOK_ENUM_CONST:
10881 struct hash_entry *ident;
10882 /* Here ident is an enumeration constant */
10883 ident = eat(state, TOK_ENUM_CONST)->ident;
10884 if (!ident->sym_ident) {
10885 error(state, 0, "%s undeclared", ident->name);
10887 def = ident->sym_ident->def;
10892 struct hash_entry *ident;
10893 ident = eat(state, TOK_MIDENT)->ident;
10894 warning(state, 0, "Replacing undefined macro: %s with 0",
10896 def = int_const(state, &int_type, 0);
10900 eat(state, TOK_LPAREN);
10902 eat(state, TOK_RPAREN);
10905 def = integer_constant(state);
10907 case TOK_LIT_FLOAT:
10908 eat(state, TOK_LIT_FLOAT);
10909 error(state, 0, "Floating point constants not supported");
10914 def = character_constant(state);
10916 case TOK_LIT_STRING:
10917 def = string_constant(state);
10921 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10926 static struct triple *postfix_expr(struct compile_state *state)
10928 struct triple *def;
10930 def = primary_expr(state);
10932 struct triple *left;
10936 switch((tok = peek(state))) {
10938 eat(state, TOK_LBRACKET);
10939 def = mk_subscript_expr(state, left, expr(state));
10940 eat(state, TOK_RBRACKET);
10943 def = call_expr(state, def);
10947 struct hash_entry *field;
10948 eat(state, TOK_DOT);
10949 field = eat(state, TOK_IDENT)->ident;
10950 def = deref_field(state, def, field);
10955 struct hash_entry *field;
10956 eat(state, TOK_ARROW);
10957 field = eat(state, TOK_IDENT)->ident;
10958 def = mk_deref_expr(state, read_expr(state, def));
10959 def = deref_field(state, def, field);
10963 eat(state, TOK_PLUSPLUS);
10964 def = mk_post_inc_expr(state, left);
10966 case TOK_MINUSMINUS:
10967 eat(state, TOK_MINUSMINUS);
10968 def = mk_post_dec_expr(state, left);
10978 static struct triple *cast_expr(struct compile_state *state);
10980 static struct triple *unary_expr(struct compile_state *state)
10982 struct triple *def, *right;
10984 switch((tok = peek(state))) {
10986 eat(state, TOK_PLUSPLUS);
10987 def = mk_pre_inc_expr(state, unary_expr(state));
10989 case TOK_MINUSMINUS:
10990 eat(state, TOK_MINUSMINUS);
10991 def = mk_pre_dec_expr(state, unary_expr(state));
10994 eat(state, TOK_AND);
10995 def = mk_addr_expr(state, cast_expr(state), 0);
10998 eat(state, TOK_STAR);
10999 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11002 eat(state, TOK_PLUS);
11003 right = read_expr(state, cast_expr(state));
11004 arithmetic(state, right);
11005 def = integral_promotion(state, right);
11008 eat(state, TOK_MINUS);
11009 right = read_expr(state, cast_expr(state));
11010 arithmetic(state, right);
11011 def = integral_promotion(state, right);
11012 def = triple(state, OP_NEG, def->type, def, 0);
11015 eat(state, TOK_TILDE);
11016 right = read_expr(state, cast_expr(state));
11017 integral(state, right);
11018 def = integral_promotion(state, right);
11019 def = triple(state, OP_INVERT, def->type, def, 0);
11022 eat(state, TOK_BANG);
11023 right = read_expr(state, cast_expr(state));
11024 bool(state, right);
11025 def = lfalse_expr(state, right);
11031 eat(state, TOK_SIZEOF);
11032 tok1 = peek(state);
11033 tok2 = peek2(state);
11034 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11035 eat(state, TOK_LPAREN);
11036 type = type_name(state);
11037 eat(state, TOK_RPAREN);
11040 struct triple *expr;
11041 expr = unary_expr(state);
11043 release_expr(state, expr);
11045 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11052 eat(state, TOK_ALIGNOF);
11053 tok1 = peek(state);
11054 tok2 = peek2(state);
11055 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11056 eat(state, TOK_LPAREN);
11057 type = type_name(state);
11058 eat(state, TOK_RPAREN);
11061 struct triple *expr;
11062 expr = unary_expr(state);
11064 release_expr(state, expr);
11066 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11071 /* We only come here if we are called from the preprocessor */
11072 struct hash_entry *ident;
11074 eat(state, TOK_MDEFINED);
11076 if (pp_peek(state) == TOK_LPAREN) {
11077 pp_eat(state, TOK_LPAREN);
11080 ident = pp_eat(state, TOK_MIDENT)->ident;
11082 eat(state, TOK_RPAREN);
11084 def = int_const(state, &int_type, ident->sym_define != 0);
11088 def = postfix_expr(state);
11094 static struct triple *cast_expr(struct compile_state *state)
11096 struct triple *def;
11098 tok1 = peek(state);
11099 tok2 = peek2(state);
11100 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11102 eat(state, TOK_LPAREN);
11103 type = type_name(state);
11104 eat(state, TOK_RPAREN);
11105 def = mk_cast_expr(state, type, cast_expr(state));
11108 def = unary_expr(state);
11113 static struct triple *mult_expr(struct compile_state *state)
11115 struct triple *def;
11117 def = cast_expr(state);
11119 struct triple *left, *right;
11120 struct type *result_type;
11128 left = read_expr(state, def);
11129 arithmetic(state, left);
11133 right = read_expr(state, cast_expr(state));
11134 arithmetic(state, right);
11136 result_type = arithmetic_result(state, left, right);
11137 sign = is_signed(result_type);
11140 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11141 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11142 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11144 def = triple(state, op, result_type, left, right);
11154 static struct triple *add_expr(struct compile_state *state)
11156 struct triple *def;
11158 def = mult_expr(state);
11161 switch( peek(state)) {
11163 eat(state, TOK_PLUS);
11164 def = mk_add_expr(state, def, mult_expr(state));
11167 eat(state, TOK_MINUS);
11168 def = mk_sub_expr(state, def, mult_expr(state));
11178 static struct triple *shift_expr(struct compile_state *state)
11180 struct triple *def;
11182 def = add_expr(state);
11184 struct triple *left, *right;
11187 switch((tok = peek(state))) {
11190 left = read_expr(state, def);
11191 integral(state, left);
11192 left = integral_promotion(state, left);
11196 right = read_expr(state, add_expr(state));
11197 integral(state, right);
11198 right = integral_promotion(state, right);
11200 op = (tok == TOK_SL)? OP_SL :
11201 is_signed(left->type)? OP_SSR: OP_USR;
11203 def = triple(state, op, left->type, left, right);
11213 static struct triple *relational_expr(struct compile_state *state)
11215 #if DEBUG_ROMCC_WARNINGS
11216 #warning "Extend relational exprs to work on more than arithmetic types"
11218 struct triple *def;
11220 def = shift_expr(state);
11222 struct triple *left, *right;
11223 struct type *arg_type;
11226 switch((tok = peek(state))) {
11231 left = read_expr(state, def);
11232 arithmetic(state, left);
11236 right = read_expr(state, shift_expr(state));
11237 arithmetic(state, right);
11239 arg_type = arithmetic_result(state, left, right);
11240 sign = is_signed(arg_type);
11243 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11244 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11245 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11246 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11248 def = triple(state, op, &int_type, left, right);
11258 static struct triple *equality_expr(struct compile_state *state)
11260 #if DEBUG_ROMCC_WARNINGS
11261 #warning "Extend equality exprs to work on more than arithmetic types"
11263 struct triple *def;
11265 def = relational_expr(state);
11267 struct triple *left, *right;
11270 switch((tok = peek(state))) {
11273 left = read_expr(state, def);
11274 arithmetic(state, left);
11276 right = read_expr(state, relational_expr(state));
11277 arithmetic(state, right);
11278 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11279 def = triple(state, op, &int_type, left, right);
11289 static struct triple *and_expr(struct compile_state *state)
11291 struct triple *def;
11292 def = equality_expr(state);
11293 while(peek(state) == TOK_AND) {
11294 struct triple *left, *right;
11295 struct type *result_type;
11296 left = read_expr(state, def);
11297 integral(state, left);
11298 eat(state, TOK_AND);
11299 right = read_expr(state, equality_expr(state));
11300 integral(state, right);
11301 result_type = arithmetic_result(state, left, right);
11302 def = triple(state, OP_AND, result_type, left, right);
11307 static struct triple *xor_expr(struct compile_state *state)
11309 struct triple *def;
11310 def = and_expr(state);
11311 while(peek(state) == TOK_XOR) {
11312 struct triple *left, *right;
11313 struct type *result_type;
11314 left = read_expr(state, def);
11315 integral(state, left);
11316 eat(state, TOK_XOR);
11317 right = read_expr(state, and_expr(state));
11318 integral(state, right);
11319 result_type = arithmetic_result(state, left, right);
11320 def = triple(state, OP_XOR, result_type, left, right);
11325 static struct triple *or_expr(struct compile_state *state)
11327 struct triple *def;
11328 def = xor_expr(state);
11329 while(peek(state) == TOK_OR) {
11330 struct triple *left, *right;
11331 struct type *result_type;
11332 left = read_expr(state, def);
11333 integral(state, left);
11334 eat(state, TOK_OR);
11335 right = read_expr(state, xor_expr(state));
11336 integral(state, right);
11337 result_type = arithmetic_result(state, left, right);
11338 def = triple(state, OP_OR, result_type, left, right);
11343 static struct triple *land_expr(struct compile_state *state)
11345 struct triple *def;
11346 def = or_expr(state);
11347 while(peek(state) == TOK_LOGAND) {
11348 struct triple *left, *right;
11349 left = read_expr(state, def);
11351 eat(state, TOK_LOGAND);
11352 right = read_expr(state, or_expr(state));
11353 bool(state, right);
11355 def = mkland_expr(state,
11356 ltrue_expr(state, left),
11357 ltrue_expr(state, right));
11362 static struct triple *lor_expr(struct compile_state *state)
11364 struct triple *def;
11365 def = land_expr(state);
11366 while(peek(state) == TOK_LOGOR) {
11367 struct triple *left, *right;
11368 left = read_expr(state, def);
11370 eat(state, TOK_LOGOR);
11371 right = read_expr(state, land_expr(state));
11372 bool(state, right);
11374 def = mklor_expr(state,
11375 ltrue_expr(state, left),
11376 ltrue_expr(state, right));
11381 static struct triple *conditional_expr(struct compile_state *state)
11383 struct triple *def;
11384 def = lor_expr(state);
11385 if (peek(state) == TOK_QUEST) {
11386 struct triple *test, *left, *right;
11388 test = ltrue_expr(state, read_expr(state, def));
11389 eat(state, TOK_QUEST);
11390 left = read_expr(state, expr(state));
11391 eat(state, TOK_COLON);
11392 right = read_expr(state, conditional_expr(state));
11394 def = mkcond_expr(state, test, left, right);
11400 struct triple *val;
11404 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11405 struct triple *dest, struct triple *val)
11407 if (cv[dest->id].val) {
11408 free_triple(state, cv[dest->id].val);
11410 cv[dest->id].val = val;
11412 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11413 struct triple *src)
11415 return cv[src->id].val;
11418 static struct triple *eval_const_expr(
11419 struct compile_state *state, struct triple *expr)
11421 struct triple *def;
11422 if (is_const(expr)) {
11426 /* If we don't start out as a constant simplify into one */
11427 struct triple *head, *ptr;
11428 struct cv_triple *cv;
11430 head = label(state); /* dummy initial triple */
11431 flatten(state, head, expr);
11433 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11436 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11438 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11440 cv[i].id = ptr->id;
11446 valid_ins(state, ptr);
11447 if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11448 internal_error(state, ptr,
11449 "unexpected %s in constant expression",
11452 else if (ptr->op == OP_LIST) {
11454 else if (triple_is_structural(state, ptr)) {
11457 else if (triple_is_ubranch(state, ptr)) {
11458 ptr = TARG(ptr, 0);
11460 else if (triple_is_cbranch(state, ptr)) {
11461 struct triple *cond_val;
11462 cond_val = get_cv(state, cv, RHS(ptr, 0));
11463 if (!cond_val || !is_const(cond_val) ||
11464 (cond_val->op != OP_INTCONST))
11466 internal_error(state, ptr, "bad branch condition");
11468 if (cond_val->u.cval == 0) {
11471 ptr = TARG(ptr, 0);
11474 else if (triple_is_branch(state, ptr)) {
11475 error(state, ptr, "bad branch type in constant expression");
11477 else if (ptr->op == OP_WRITE) {
11478 struct triple *val;
11479 val = get_cv(state, cv, RHS(ptr, 0));
11481 set_cv(state, cv, MISC(ptr, 0),
11482 copy_triple(state, val));
11483 set_cv(state, cv, ptr,
11484 copy_triple(state, val));
11487 else if (ptr->op == OP_READ) {
11488 set_cv(state, cv, ptr,
11490 get_cv(state, cv, RHS(ptr, 0))));
11493 else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11494 struct triple *val, **rhs;
11495 val = copy_triple(state, ptr);
11496 rhs = triple_rhs(state, val, 0);
11497 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11499 internal_error(state, ptr, "Missing rhs");
11501 *rhs = get_cv(state, cv, *rhs);
11503 simplify(state, val);
11504 set_cv(state, cv, ptr, val);
11508 error(state, ptr, "impure operation in constant expression");
11511 } while(ptr != head);
11513 /* Get the result value */
11514 def = get_cv(state, cv, head->prev);
11515 cv[head->prev->id].val = 0;
11517 /* Free the temporary values */
11518 for(i = 0; i < count; i++) {
11520 free_triple(state, cv[i].val);
11525 /* Free the intermediate expressions */
11526 while(head->next != head) {
11527 release_triple(state, head->next);
11529 free_triple(state, head);
11531 if (!is_const(def)) {
11532 error(state, expr, "Not a constant expression");
11537 static struct triple *constant_expr(struct compile_state *state)
11539 return eval_const_expr(state, conditional_expr(state));
11542 static struct triple *assignment_expr(struct compile_state *state)
11544 struct triple *def, *left, *right;
11546 /* The C grammer in K&R shows assignment expressions
11547 * only taking unary expressions as input on their
11548 * left hand side. But specifies the precedence of
11549 * assignemnt as the lowest operator except for comma.
11551 * Allowing conditional expressions on the left hand side
11552 * of an assignement results in a grammar that accepts
11553 * a larger set of statements than standard C. As long
11554 * as the subset of the grammar that is standard C behaves
11555 * correctly this should cause no problems.
11557 * For the extra token strings accepted by the grammar
11558 * none of them should produce a valid lvalue, so they
11559 * should not produce functioning programs.
11561 * GCC has this bug as well, so surprises should be minimal.
11563 def = conditional_expr(state);
11565 switch((tok = peek(state))) {
11567 lvalue(state, left);
11568 eat(state, TOK_EQ);
11569 def = write_expr(state, left,
11570 read_expr(state, assignment_expr(state)));
11575 lvalue(state, left);
11576 arithmetic(state, left);
11578 right = read_expr(state, assignment_expr(state));
11579 arithmetic(state, right);
11581 sign = is_signed(left->type);
11584 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11585 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11586 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11588 def = write_expr(state, left,
11589 triple(state, op, left->type,
11590 read_expr(state, left), right));
11593 lvalue(state, left);
11594 eat(state, TOK_PLUSEQ);
11595 def = write_expr(state, left,
11596 mk_add_expr(state, left, assignment_expr(state)));
11599 lvalue(state, left);
11600 eat(state, TOK_MINUSEQ);
11601 def = write_expr(state, left,
11602 mk_sub_expr(state, left, assignment_expr(state)));
11609 lvalue(state, left);
11610 integral(state, left);
11612 right = read_expr(state, assignment_expr(state));
11613 integral(state, right);
11614 right = integral_promotion(state, right);
11615 sign = is_signed(left->type);
11618 case TOK_SLEQ: op = OP_SL; break;
11619 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11620 case TOK_ANDEQ: op = OP_AND; break;
11621 case TOK_XOREQ: op = OP_XOR; break;
11622 case TOK_OREQ: op = OP_OR; break;
11624 def = write_expr(state, left,
11625 triple(state, op, left->type,
11626 read_expr(state, left), right));
11632 static struct triple *expr(struct compile_state *state)
11634 struct triple *def;
11635 def = assignment_expr(state);
11636 while(peek(state) == TOK_COMMA) {
11637 eat(state, TOK_COMMA);
11638 def = mkprog(state, def, assignment_expr(state), 0UL);
11643 static void expr_statement(struct compile_state *state, struct triple *first)
11645 if (peek(state) != TOK_SEMI) {
11646 /* lvalue conversions always apply except when certian operators
11647 * are applied. I apply the lvalue conversions here
11648 * as I know no more operators will be applied.
11650 flatten(state, first, lvalue_conversion(state, expr(state)));
11652 eat(state, TOK_SEMI);
11655 static void if_statement(struct compile_state *state, struct triple *first)
11657 struct triple *test, *jmp1, *jmp2, *middle, *end;
11659 jmp1 = jmp2 = middle = 0;
11660 eat(state, TOK_IF);
11661 eat(state, TOK_LPAREN);
11662 test = expr(state);
11664 /* Cleanup and invert the test */
11665 test = lfalse_expr(state, read_expr(state, test));
11666 eat(state, TOK_RPAREN);
11667 /* Generate the needed pieces */
11668 middle = label(state);
11669 jmp1 = branch(state, middle, test);
11670 /* Thread the pieces together */
11671 flatten(state, first, test);
11672 flatten(state, first, jmp1);
11673 flatten(state, first, label(state));
11674 statement(state, first);
11675 if (peek(state) == TOK_ELSE) {
11676 eat(state, TOK_ELSE);
11677 /* Generate the rest of the pieces */
11678 end = label(state);
11679 jmp2 = branch(state, end, 0);
11680 /* Thread them together */
11681 flatten(state, first, jmp2);
11682 flatten(state, first, middle);
11683 statement(state, first);
11684 flatten(state, first, end);
11687 flatten(state, first, middle);
11691 static void for_statement(struct compile_state *state, struct triple *first)
11693 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11694 struct triple *label1, *label2, *label3;
11695 struct hash_entry *ident;
11697 eat(state, TOK_FOR);
11698 eat(state, TOK_LPAREN);
11699 head = test = tail = jmp1 = jmp2 = 0;
11700 if (peek(state) != TOK_SEMI) {
11701 head = expr(state);
11703 eat(state, TOK_SEMI);
11704 if (peek(state) != TOK_SEMI) {
11705 test = expr(state);
11707 test = ltrue_expr(state, read_expr(state, test));
11709 eat(state, TOK_SEMI);
11710 if (peek(state) != TOK_RPAREN) {
11711 tail = expr(state);
11713 eat(state, TOK_RPAREN);
11714 /* Generate the needed pieces */
11715 label1 = label(state);
11716 label2 = label(state);
11717 label3 = label(state);
11719 jmp1 = branch(state, label3, 0);
11720 jmp2 = branch(state, label1, test);
11723 jmp2 = branch(state, label1, 0);
11725 end = label(state);
11726 /* Remember where break and continue go */
11727 start_scope(state);
11728 ident = state->i_break;
11729 symbol(state, ident, &ident->sym_ident, end, end->type);
11730 ident = state->i_continue;
11731 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11732 /* Now include the body */
11733 flatten(state, first, head);
11734 flatten(state, first, jmp1);
11735 flatten(state, first, label1);
11736 statement(state, first);
11737 flatten(state, first, label2);
11738 flatten(state, first, tail);
11739 flatten(state, first, label3);
11740 flatten(state, first, test);
11741 flatten(state, first, jmp2);
11742 flatten(state, first, end);
11743 /* Cleanup the break/continue scope */
11747 static void while_statement(struct compile_state *state, struct triple *first)
11749 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11750 struct hash_entry *ident;
11751 eat(state, TOK_WHILE);
11752 eat(state, TOK_LPAREN);
11753 test = expr(state);
11755 test = ltrue_expr(state, read_expr(state, test));
11756 eat(state, TOK_RPAREN);
11757 /* Generate the needed pieces */
11758 label1 = label(state);
11759 label2 = label(state);
11760 jmp1 = branch(state, label2, 0);
11761 jmp2 = branch(state, label1, test);
11762 end = label(state);
11763 /* Remember where break and continue go */
11764 start_scope(state);
11765 ident = state->i_break;
11766 symbol(state, ident, &ident->sym_ident, end, end->type);
11767 ident = state->i_continue;
11768 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11769 /* Thread them together */
11770 flatten(state, first, jmp1);
11771 flatten(state, first, label1);
11772 statement(state, first);
11773 flatten(state, first, label2);
11774 flatten(state, first, test);
11775 flatten(state, first, jmp2);
11776 flatten(state, first, end);
11777 /* Cleanup the break/continue scope */
11781 static void do_statement(struct compile_state *state, struct triple *first)
11783 struct triple *label1, *label2, *test, *end;
11784 struct hash_entry *ident;
11785 eat(state, TOK_DO);
11786 /* Generate the needed pieces */
11787 label1 = label(state);
11788 label2 = label(state);
11789 end = label(state);
11790 /* Remember where break and continue go */
11791 start_scope(state);
11792 ident = state->i_break;
11793 symbol(state, ident, &ident->sym_ident, end, end->type);
11794 ident = state->i_continue;
11795 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11796 /* Now include the body */
11797 flatten(state, first, label1);
11798 statement(state, first);
11799 /* Cleanup the break/continue scope */
11801 /* Eat the rest of the loop */
11802 eat(state, TOK_WHILE);
11803 eat(state, TOK_LPAREN);
11804 test = read_expr(state, expr(state));
11806 eat(state, TOK_RPAREN);
11807 eat(state, TOK_SEMI);
11808 /* Thread the pieces together */
11809 test = ltrue_expr(state, test);
11810 flatten(state, first, label2);
11811 flatten(state, first, test);
11812 flatten(state, first, branch(state, label1, test));
11813 flatten(state, first, end);
11817 static void return_statement(struct compile_state *state, struct triple *first)
11819 struct triple *jmp, *mv, *dest, *var, *val;
11821 eat(state, TOK_RETURN);
11823 #if DEBUG_ROMCC_WARNINGS
11824 #warning "FIXME implement a more general excess branch elimination"
11827 /* If we have a return value do some more work */
11828 if (peek(state) != TOK_SEMI) {
11829 val = read_expr(state, expr(state));
11831 eat(state, TOK_SEMI);
11833 /* See if this last statement in a function */
11834 last = ((peek(state) == TOK_RBRACE) &&
11835 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11837 /* Find the return variable */
11838 var = fresult(state, state->main_function);
11840 /* Find the return destination */
11841 dest = state->i_return->sym_ident->def;
11843 /* If needed generate a jump instruction */
11845 jmp = branch(state, dest, 0);
11847 /* If needed generate an assignment instruction */
11849 mv = write_expr(state, deref_index(state, var, 1), val);
11851 /* Now put the code together */
11853 flatten(state, first, mv);
11854 flatten(state, first, jmp);
11857 flatten(state, first, jmp);
11861 static void break_statement(struct compile_state *state, struct triple *first)
11863 struct triple *dest;
11864 eat(state, TOK_BREAK);
11865 eat(state, TOK_SEMI);
11866 if (!state->i_break->sym_ident) {
11867 error(state, 0, "break statement not within loop or switch");
11869 dest = state->i_break->sym_ident->def;
11870 flatten(state, first, branch(state, dest, 0));
11873 static void continue_statement(struct compile_state *state, struct triple *first)
11875 struct triple *dest;
11876 eat(state, TOK_CONTINUE);
11877 eat(state, TOK_SEMI);
11878 if (!state->i_continue->sym_ident) {
11879 error(state, 0, "continue statement outside of a loop");
11881 dest = state->i_continue->sym_ident->def;
11882 flatten(state, first, branch(state, dest, 0));
11885 static void goto_statement(struct compile_state *state, struct triple *first)
11887 struct hash_entry *ident;
11888 eat(state, TOK_GOTO);
11889 ident = eat(state, TOK_IDENT)->ident;
11890 if (!ident->sym_label) {
11891 /* If this is a forward branch allocate the label now,
11892 * it will be flattend in the appropriate location later.
11894 struct triple *ins;
11895 ins = label(state);
11896 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11898 eat(state, TOK_SEMI);
11900 flatten(state, first, branch(state, ident->sym_label->def, 0));
11903 static void labeled_statement(struct compile_state *state, struct triple *first)
11905 struct triple *ins;
11906 struct hash_entry *ident;
11908 ident = eat(state, TOK_IDENT)->ident;
11909 if (ident->sym_label && ident->sym_label->def) {
11910 ins = ident->sym_label->def;
11911 put_occurance(ins->occurance);
11912 ins->occurance = new_occurance(state);
11915 ins = label(state);
11916 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11918 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11919 error(state, 0, "label %s already defined", ident->name);
11921 flatten(state, first, ins);
11923 eat(state, TOK_COLON);
11924 statement(state, first);
11927 static void switch_statement(struct compile_state *state, struct triple *first)
11929 struct triple *value, *top, *end, *dbranch;
11930 struct hash_entry *ident;
11932 /* See if we have a valid switch statement */
11933 eat(state, TOK_SWITCH);
11934 eat(state, TOK_LPAREN);
11935 value = expr(state);
11936 integral(state, value);
11937 value = read_expr(state, value);
11938 eat(state, TOK_RPAREN);
11939 /* Generate the needed pieces */
11940 top = label(state);
11941 end = label(state);
11942 dbranch = branch(state, end, 0);
11943 /* Remember where case branches and break goes */
11944 start_scope(state);
11945 ident = state->i_switch;
11946 symbol(state, ident, &ident->sym_ident, value, value->type);
11947 ident = state->i_case;
11948 symbol(state, ident, &ident->sym_ident, top, top->type);
11949 ident = state->i_break;
11950 symbol(state, ident, &ident->sym_ident, end, end->type);
11951 ident = state->i_default;
11952 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11953 /* Thread them together */
11954 flatten(state, first, value);
11955 flatten(state, first, top);
11956 flatten(state, first, dbranch);
11957 statement(state, first);
11958 flatten(state, first, end);
11959 /* Cleanup the switch scope */
11963 static void case_statement(struct compile_state *state, struct triple *first)
11965 struct triple *cvalue, *dest, *test, *jmp;
11966 struct triple *ptr, *value, *top, *dbranch;
11968 /* See if w have a valid case statement */
11969 eat(state, TOK_CASE);
11970 cvalue = constant_expr(state);
11971 integral(state, cvalue);
11972 if (cvalue->op != OP_INTCONST) {
11973 error(state, 0, "integer constant expected");
11975 eat(state, TOK_COLON);
11976 if (!state->i_case->sym_ident) {
11977 error(state, 0, "case statement not within a switch");
11980 /* Lookup the interesting pieces */
11981 top = state->i_case->sym_ident->def;
11982 value = state->i_switch->sym_ident->def;
11983 dbranch = state->i_default->sym_ident->def;
11985 /* See if this case label has already been used */
11986 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11987 if (ptr->op != OP_EQ) {
11990 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11991 error(state, 0, "duplicate case %d statement",
11995 /* Generate the needed pieces */
11996 dest = label(state);
11997 test = triple(state, OP_EQ, &int_type, value, cvalue);
11998 jmp = branch(state, dest, test);
11999 /* Thread the pieces together */
12000 flatten(state, dbranch, test);
12001 flatten(state, dbranch, jmp);
12002 flatten(state, dbranch, label(state));
12003 flatten(state, first, dest);
12004 statement(state, first);
12007 static void default_statement(struct compile_state *state, struct triple *first)
12009 struct triple *dest;
12010 struct triple *dbranch, *end;
12012 /* See if we have a valid default statement */
12013 eat(state, TOK_DEFAULT);
12014 eat(state, TOK_COLON);
12016 if (!state->i_case->sym_ident) {
12017 error(state, 0, "default statement not within a switch");
12020 /* Lookup the interesting pieces */
12021 dbranch = state->i_default->sym_ident->def;
12022 end = state->i_break->sym_ident->def;
12024 /* See if a default statement has already happened */
12025 if (TARG(dbranch, 0) != end) {
12026 error(state, 0, "duplicate default statement");
12029 /* Generate the needed pieces */
12030 dest = label(state);
12032 /* Blame the branch on the default statement */
12033 put_occurance(dbranch->occurance);
12034 dbranch->occurance = new_occurance(state);
12036 /* Thread the pieces together */
12037 TARG(dbranch, 0) = dest;
12038 use_triple(dest, dbranch);
12039 flatten(state, first, dest);
12040 statement(state, first);
12043 static void asm_statement(struct compile_state *state, struct triple *first)
12045 struct asm_info *info;
12047 struct triple *constraint;
12048 struct triple *expr;
12049 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12050 struct triple *def, *asm_str;
12051 int out, in, clobbers, more, colons, i;
12055 eat(state, TOK_ASM);
12056 /* For now ignore the qualifiers */
12057 switch(peek(state)) {
12059 eat(state, TOK_CONST);
12062 eat(state, TOK_VOLATILE);
12063 flags |= TRIPLE_FLAG_VOLATILE;
12066 eat(state, TOK_LPAREN);
12067 asm_str = string_constant(state);
12070 out = in = clobbers = 0;
12072 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12073 eat(state, TOK_COLON);
12075 more = (peek(state) == TOK_LIT_STRING);
12077 struct triple *var;
12078 struct triple *constraint;
12081 if (out > MAX_LHS) {
12082 error(state, 0, "Maximum output count exceeded.");
12084 constraint = string_constant(state);
12085 str = constraint->u.blob;
12086 if (str[0] != '=') {
12087 error(state, 0, "Output constraint does not start with =");
12089 constraint->u.blob = str + 1;
12090 eat(state, TOK_LPAREN);
12091 var = conditional_expr(state);
12092 eat(state, TOK_RPAREN);
12094 lvalue(state, var);
12095 out_param[out].constraint = constraint;
12096 out_param[out].expr = var;
12097 if (peek(state) == TOK_COMMA) {
12098 eat(state, TOK_COMMA);
12105 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12106 eat(state, TOK_COLON);
12108 more = (peek(state) == TOK_LIT_STRING);
12110 struct triple *val;
12111 struct triple *constraint;
12114 if (in > MAX_RHS) {
12115 error(state, 0, "Maximum input count exceeded.");
12117 constraint = string_constant(state);
12118 str = constraint->u.blob;
12119 if (digitp(str[0] && str[1] == '\0')) {
12121 val = digval(str[0]);
12122 if ((val < 0) || (val >= out)) {
12123 error(state, 0, "Invalid input constraint %d", val);
12126 eat(state, TOK_LPAREN);
12127 val = conditional_expr(state);
12128 eat(state, TOK_RPAREN);
12130 in_param[in].constraint = constraint;
12131 in_param[in].expr = val;
12132 if (peek(state) == TOK_COMMA) {
12133 eat(state, TOK_COMMA);
12141 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12142 eat(state, TOK_COLON);
12144 more = (peek(state) == TOK_LIT_STRING);
12146 struct triple *clobber;
12148 if ((clobbers + out) > MAX_LHS) {
12149 error(state, 0, "Maximum clobber limit exceeded.");
12151 clobber = string_constant(state);
12153 clob_param[clobbers].constraint = clobber;
12154 if (peek(state) == TOK_COMMA) {
12155 eat(state, TOK_COMMA);
12161 eat(state, TOK_RPAREN);
12162 eat(state, TOK_SEMI);
12165 info = xcmalloc(sizeof(*info), "asm_info");
12166 info->str = asm_str->u.blob;
12167 free_triple(state, asm_str);
12169 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12170 def->u.ainfo = info;
12173 /* Find the register constraints */
12174 for(i = 0; i < out; i++) {
12175 struct triple *constraint;
12176 constraint = out_param[i].constraint;
12177 info->tmpl.lhs[i] = arch_reg_constraint(state,
12178 out_param[i].expr->type, constraint->u.blob);
12179 free_triple(state, constraint);
12181 for(; i - out < clobbers; i++) {
12182 struct triple *constraint;
12183 constraint = clob_param[i - out].constraint;
12184 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12185 free_triple(state, constraint);
12187 for(i = 0; i < in; i++) {
12188 struct triple *constraint;
12190 constraint = in_param[i].constraint;
12191 str = constraint->u.blob;
12192 if (digitp(str[0]) && str[1] == '\0') {
12193 struct reg_info cinfo;
12195 val = digval(str[0]);
12196 cinfo.reg = info->tmpl.lhs[val].reg;
12197 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12198 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12199 if (cinfo.reg == REG_UNSET) {
12200 cinfo.reg = REG_VIRT0 + val;
12202 if (cinfo.regcm == 0) {
12203 error(state, 0, "No registers for %d", val);
12205 info->tmpl.lhs[val] = cinfo;
12206 info->tmpl.rhs[i] = cinfo;
12209 info->tmpl.rhs[i] = arch_reg_constraint(state,
12210 in_param[i].expr->type, str);
12212 free_triple(state, constraint);
12215 /* Now build the helper expressions */
12216 for(i = 0; i < in; i++) {
12217 RHS(def, i) = read_expr(state, in_param[i].expr);
12219 flatten(state, first, def);
12220 for(i = 0; i < (out + clobbers); i++) {
12222 struct triple *piece;
12224 type = out_param[i].expr->type;
12226 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12227 if (size >= SIZEOF_LONG) {
12228 type = &ulong_type;
12230 else if (size >= SIZEOF_INT) {
12233 else if (size >= SIZEOF_SHORT) {
12234 type = &ushort_type;
12237 type = &uchar_type;
12240 piece = triple(state, OP_PIECE, type, def, 0);
12242 LHS(def, i) = piece;
12243 flatten(state, first, piece);
12245 /* And write the helpers to their destinations */
12246 for(i = 0; i < out; i++) {
12247 struct triple *piece;
12248 piece = LHS(def, i);
12249 flatten(state, first,
12250 write_expr(state, out_param[i].expr, piece));
12255 static int isdecl(int tok)
12278 case TOK_TYPE_NAME: /* typedef name */
12285 static void compound_statement(struct compile_state *state, struct triple *first)
12287 eat(state, TOK_LBRACE);
12288 start_scope(state);
12290 /* statement-list opt */
12291 while (peek(state) != TOK_RBRACE) {
12292 statement(state, first);
12295 eat(state, TOK_RBRACE);
12298 static void statement(struct compile_state *state, struct triple *first)
12302 if (tok == TOK_LBRACE) {
12303 compound_statement(state, first);
12305 else if (tok == TOK_IF) {
12306 if_statement(state, first);
12308 else if (tok == TOK_FOR) {
12309 for_statement(state, first);
12311 else if (tok == TOK_WHILE) {
12312 while_statement(state, first);
12314 else if (tok == TOK_DO) {
12315 do_statement(state, first);
12317 else if (tok == TOK_RETURN) {
12318 return_statement(state, first);
12320 else if (tok == TOK_BREAK) {
12321 break_statement(state, first);
12323 else if (tok == TOK_CONTINUE) {
12324 continue_statement(state, first);
12326 else if (tok == TOK_GOTO) {
12327 goto_statement(state, first);
12329 else if (tok == TOK_SWITCH) {
12330 switch_statement(state, first);
12332 else if (tok == TOK_ASM) {
12333 asm_statement(state, first);
12335 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12336 labeled_statement(state, first);
12338 else if (tok == TOK_CASE) {
12339 case_statement(state, first);
12341 else if (tok == TOK_DEFAULT) {
12342 default_statement(state, first);
12344 else if (isdecl(tok)) {
12345 /* This handles C99 intermixing of statements and decls */
12346 decl(state, first);
12349 expr_statement(state, first);
12353 static struct type *param_decl(struct compile_state *state)
12356 struct hash_entry *ident;
12357 /* Cheat so the declarator will know we are not global */
12358 start_scope(state);
12360 type = decl_specifiers(state);
12361 type = declarator(state, type, &ident, 0);
12362 type->field_ident = ident;
12367 static struct type *param_type_list(struct compile_state *state, struct type *type)
12369 struct type *ftype, **next;
12370 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12371 next = &ftype->right;
12372 ftype->elements = 1;
12373 while(peek(state) == TOK_COMMA) {
12374 eat(state, TOK_COMMA);
12375 if (peek(state) == TOK_DOTS) {
12376 eat(state, TOK_DOTS);
12377 error(state, 0, "variadic functions not supported");
12380 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12381 next = &((*next)->right);
12388 static struct type *type_name(struct compile_state *state)
12391 type = specifier_qualifier_list(state);
12392 /* abstract-declarator (may consume no tokens) */
12393 type = declarator(state, type, 0, 0);
12397 static struct type *direct_declarator(
12398 struct compile_state *state, struct type *type,
12399 struct hash_entry **pident, int need_ident)
12401 struct hash_entry *ident;
12402 struct type *outer;
12405 arrays_complete(state, type);
12406 switch(peek(state)) {
12408 ident = eat(state, TOK_IDENT)->ident;
12410 error(state, 0, "Unexpected identifier found");
12412 /* The name of what we are declaring */
12416 eat(state, TOK_LPAREN);
12417 outer = declarator(state, type, pident, need_ident);
12418 eat(state, TOK_RPAREN);
12422 error(state, 0, "Identifier expected");
12428 arrays_complete(state, type);
12429 switch(peek(state)) {
12431 eat(state, TOK_LPAREN);
12432 type = param_type_list(state, type);
12433 eat(state, TOK_RPAREN);
12437 unsigned int qualifiers;
12438 struct triple *value;
12440 eat(state, TOK_LBRACKET);
12441 if (peek(state) != TOK_RBRACKET) {
12442 value = constant_expr(state);
12443 integral(state, value);
12445 eat(state, TOK_RBRACKET);
12447 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12448 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12450 type->elements = value->u.cval;
12451 free_triple(state, value);
12453 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12464 struct type *inner;
12465 arrays_complete(state, type);
12467 for(inner = outer; inner->left; inner = inner->left)
12469 inner->left = type;
12475 static struct type *declarator(
12476 struct compile_state *state, struct type *type,
12477 struct hash_entry **pident, int need_ident)
12479 while(peek(state) == TOK_STAR) {
12480 eat(state, TOK_STAR);
12481 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12483 type = direct_declarator(state, type, pident, need_ident);
12487 static struct type *typedef_name(
12488 struct compile_state *state, unsigned int specifiers)
12490 struct hash_entry *ident;
12492 ident = eat(state, TOK_TYPE_NAME)->ident;
12493 type = ident->sym_ident->type;
12494 specifiers |= type->type & QUAL_MASK;
12495 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12496 (type->type & (STOR_MASK | QUAL_MASK))) {
12497 type = clone_type(specifiers, type);
12502 static struct type *enum_specifier(
12503 struct compile_state *state, unsigned int spec)
12505 struct hash_entry *ident;
12508 struct type *enum_type;
12511 eat(state, TOK_ENUM);
12513 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12514 ident = eat(state, tok)->ident;
12517 if (!ident || (peek(state) == TOK_LBRACE)) {
12518 struct type **next;
12519 eat(state, TOK_LBRACE);
12520 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12521 enum_type->type_ident = ident;
12522 next = &enum_type->right;
12524 struct hash_entry *eident;
12525 struct triple *value;
12526 struct type *entry;
12527 eident = eat(state, TOK_IDENT)->ident;
12528 if (eident->sym_ident) {
12529 error(state, 0, "%s already declared",
12532 eident->tok = TOK_ENUM_CONST;
12533 if (peek(state) == TOK_EQ) {
12534 struct triple *val;
12535 eat(state, TOK_EQ);
12536 val = constant_expr(state);
12537 integral(state, val);
12538 base = val->u.cval;
12540 value = int_const(state, &int_type, base);
12541 symbol(state, eident, &eident->sym_ident, value, &int_type);
12542 entry = new_type(TYPE_LIST, 0, 0);
12543 entry->field_ident = eident;
12545 next = &entry->right;
12547 if (peek(state) == TOK_COMMA) {
12548 eat(state, TOK_COMMA);
12550 } while(peek(state) != TOK_RBRACE);
12551 eat(state, TOK_RBRACE);
12553 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12556 if (ident && ident->sym_tag &&
12557 ident->sym_tag->type &&
12558 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12559 enum_type = clone_type(spec, ident->sym_tag->type);
12561 else if (ident && !enum_type) {
12562 error(state, 0, "enum %s undeclared", ident->name);
12567 static struct type *struct_declarator(
12568 struct compile_state *state, struct type *type, struct hash_entry **ident)
12570 if (peek(state) != TOK_COLON) {
12571 type = declarator(state, type, ident, 1);
12573 if (peek(state) == TOK_COLON) {
12574 struct triple *value;
12575 eat(state, TOK_COLON);
12576 value = constant_expr(state);
12577 if (value->op != OP_INTCONST) {
12578 error(state, 0, "Invalid constant expression");
12580 if (value->u.cval > size_of(state, type)) {
12581 error(state, 0, "bitfield larger than base type");
12583 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12584 error(state, 0, "bitfield base not an integer type");
12586 type = new_type(TYPE_BITFIELD, type, 0);
12587 type->elements = value->u.cval;
12592 static struct type *struct_or_union_specifier(
12593 struct compile_state *state, unsigned int spec)
12595 struct type *struct_type;
12596 struct hash_entry *ident;
12597 unsigned int type_main;
12598 unsigned int type_join;
12602 switch(peek(state)) {
12604 eat(state, TOK_STRUCT);
12605 type_main = TYPE_STRUCT;
12606 type_join = TYPE_PRODUCT;
12609 eat(state, TOK_UNION);
12610 type_main = TYPE_UNION;
12611 type_join = TYPE_OVERLAP;
12614 eat(state, TOK_STRUCT);
12615 type_main = TYPE_STRUCT;
12616 type_join = TYPE_PRODUCT;
12620 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12621 ident = eat(state, tok)->ident;
12623 if (!ident || (peek(state) == TOK_LBRACE)) {
12625 struct type **next;
12627 eat(state, TOK_LBRACE);
12628 next = &struct_type;
12630 struct type *base_type;
12632 base_type = specifier_qualifier_list(state);
12635 struct hash_entry *fident;
12637 type = struct_declarator(state, base_type, &fident);
12639 if (peek(state) == TOK_COMMA) {
12641 eat(state, TOK_COMMA);
12643 type = clone_type(0, type);
12644 type->field_ident = fident;
12646 *next = new_type(type_join, *next, type);
12647 next = &((*next)->right);
12652 eat(state, TOK_SEMI);
12653 } while(peek(state) != TOK_RBRACE);
12654 eat(state, TOK_RBRACE);
12655 struct_type = new_type(type_main | spec, struct_type, 0);
12656 struct_type->type_ident = ident;
12657 struct_type->elements = elements;
12659 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12662 if (ident && ident->sym_tag &&
12663 ident->sym_tag->type &&
12664 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12665 struct_type = clone_type(spec, ident->sym_tag->type);
12667 else if (ident && !struct_type) {
12668 error(state, 0, "%s %s undeclared",
12669 (type_main == TYPE_STRUCT)?"struct" : "union",
12672 return struct_type;
12675 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12677 unsigned int specifiers;
12678 switch(peek(state)) {
12680 eat(state, TOK_AUTO);
12681 specifiers = STOR_AUTO;
12684 eat(state, TOK_REGISTER);
12685 specifiers = STOR_REGISTER;
12688 eat(state, TOK_STATIC);
12689 specifiers = STOR_STATIC;
12692 eat(state, TOK_EXTERN);
12693 specifiers = STOR_EXTERN;
12696 eat(state, TOK_TYPEDEF);
12697 specifiers = STOR_TYPEDEF;
12700 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12701 specifiers = STOR_LOCAL;
12704 specifiers = STOR_AUTO;
12710 static unsigned int function_specifier_opt(struct compile_state *state)
12712 /* Ignore the inline keyword */
12713 unsigned int specifiers;
12715 switch(peek(state)) {
12717 eat(state, TOK_INLINE);
12718 specifiers = STOR_INLINE;
12723 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12725 int tok = peek(state);
12729 /* The empty attribute ignore it */
12732 case TOK_ENUM_CONST:
12733 case TOK_TYPE_NAME:
12735 struct hash_entry *ident;
12736 ident = eat(state, TOK_IDENT)->ident;
12738 if (ident == state->i_noinline) {
12739 if (attributes & ATTRIB_ALWAYS_INLINE) {
12740 error(state, 0, "both always_inline and noinline attribtes");
12742 attributes |= ATTRIB_NOINLINE;
12744 else if (ident == state->i_always_inline) {
12745 if (attributes & ATTRIB_NOINLINE) {
12746 error(state, 0, "both noinline and always_inline attribtes");
12748 attributes |= ATTRIB_ALWAYS_INLINE;
12751 error(state, 0, "Unknown attribute:%s", ident->name);
12756 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12762 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12764 type = attrib(state, type);
12765 while(peek(state) == TOK_COMMA) {
12766 eat(state, TOK_COMMA);
12767 type = attrib(state, type);
12772 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12774 if (peek(state) == TOK_ATTRIBUTE) {
12775 eat(state, TOK_ATTRIBUTE);
12776 eat(state, TOK_LPAREN);
12777 eat(state, TOK_LPAREN);
12778 type = attribute_list(state, type);
12779 eat(state, TOK_RPAREN);
12780 eat(state, TOK_RPAREN);
12785 static unsigned int type_qualifiers(struct compile_state *state)
12787 unsigned int specifiers;
12790 specifiers = QUAL_NONE;
12792 switch(peek(state)) {
12794 eat(state, TOK_CONST);
12795 specifiers |= QUAL_CONST;
12798 eat(state, TOK_VOLATILE);
12799 specifiers |= QUAL_VOLATILE;
12802 eat(state, TOK_RESTRICT);
12803 specifiers |= QUAL_RESTRICT;
12813 static struct type *type_specifier(
12814 struct compile_state *state, unsigned int spec)
12819 switch((tok = peek(state))) {
12821 eat(state, TOK_VOID);
12822 type = new_type(TYPE_VOID | spec, 0, 0);
12825 eat(state, TOK_CHAR);
12826 type = new_type(TYPE_CHAR | spec, 0, 0);
12829 eat(state, TOK_SHORT);
12830 if (peek(state) == TOK_INT) {
12831 eat(state, TOK_INT);
12833 type = new_type(TYPE_SHORT | spec, 0, 0);
12836 eat(state, TOK_INT);
12837 type = new_type(TYPE_INT | spec, 0, 0);
12840 eat(state, TOK_LONG);
12841 switch(peek(state)) {
12843 eat(state, TOK_LONG);
12844 error(state, 0, "long long not supported");
12847 eat(state, TOK_DOUBLE);
12848 error(state, 0, "long double not supported");
12851 eat(state, TOK_INT);
12852 type = new_type(TYPE_LONG | spec, 0, 0);
12855 type = new_type(TYPE_LONG | spec, 0, 0);
12860 eat(state, TOK_FLOAT);
12861 error(state, 0, "type float not supported");
12864 eat(state, TOK_DOUBLE);
12865 error(state, 0, "type double not supported");
12868 eat(state, TOK_SIGNED);
12869 switch(peek(state)) {
12871 eat(state, TOK_LONG);
12872 switch(peek(state)) {
12874 eat(state, TOK_LONG);
12875 error(state, 0, "type long long not supported");
12878 eat(state, TOK_INT);
12879 type = new_type(TYPE_LONG | spec, 0, 0);
12882 type = new_type(TYPE_LONG | spec, 0, 0);
12887 eat(state, TOK_INT);
12888 type = new_type(TYPE_INT | spec, 0, 0);
12891 eat(state, TOK_SHORT);
12892 type = new_type(TYPE_SHORT | spec, 0, 0);
12895 eat(state, TOK_CHAR);
12896 type = new_type(TYPE_CHAR | spec, 0, 0);
12899 type = new_type(TYPE_INT | spec, 0, 0);
12904 eat(state, TOK_UNSIGNED);
12905 switch(peek(state)) {
12907 eat(state, TOK_LONG);
12908 switch(peek(state)) {
12910 eat(state, TOK_LONG);
12911 error(state, 0, "unsigned long long not supported");
12914 eat(state, TOK_INT);
12915 type = new_type(TYPE_ULONG | spec, 0, 0);
12918 type = new_type(TYPE_ULONG | spec, 0, 0);
12923 eat(state, TOK_INT);
12924 type = new_type(TYPE_UINT | spec, 0, 0);
12927 eat(state, TOK_SHORT);
12928 type = new_type(TYPE_USHORT | spec, 0, 0);
12931 eat(state, TOK_CHAR);
12932 type = new_type(TYPE_UCHAR | spec, 0, 0);
12935 type = new_type(TYPE_UINT | spec, 0, 0);
12939 /* struct or union specifier */
12942 type = struct_or_union_specifier(state, spec);
12944 /* enum-spefifier */
12946 type = enum_specifier(state, spec);
12949 case TOK_TYPE_NAME:
12950 type = typedef_name(state, spec);
12953 error(state, 0, "bad type specifier %s",
12960 static int istype(int tok)
12978 case TOK_TYPE_NAME:
12986 static struct type *specifier_qualifier_list(struct compile_state *state)
12989 unsigned int specifiers = 0;
12991 /* type qualifiers */
12992 specifiers |= type_qualifiers(state);
12994 /* type specifier */
12995 type = type_specifier(state, specifiers);
13000 #if DEBUG_ROMCC_WARNING
13001 static int isdecl_specifier(int tok)
13004 /* storage class specifier */
13010 /* type qualifier */
13014 /* type specifiers */
13024 /* struct or union specifier */
13027 /* enum-spefifier */
13030 case TOK_TYPE_NAME:
13031 /* function specifiers */
13040 static struct type *decl_specifiers(struct compile_state *state)
13043 unsigned int specifiers;
13044 /* I am overly restrictive in the arragement of specifiers supported.
13045 * C is overly flexible in this department it makes interpreting
13046 * the parse tree difficult.
13050 /* storage class specifier */
13051 specifiers |= storage_class_specifier_opt(state);
13053 /* function-specifier */
13054 specifiers |= function_specifier_opt(state);
13057 specifiers |= attributes_opt(state, 0);
13059 /* type qualifier */
13060 specifiers |= type_qualifiers(state);
13062 /* type specifier */
13063 type = type_specifier(state, specifiers);
13067 struct field_info {
13072 static struct field_info designator(struct compile_state *state, struct type *type)
13075 struct field_info info;
13079 switch(peek(state)) {
13082 struct triple *value;
13083 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13084 error(state, 0, "Array designator not in array initializer");
13086 eat(state, TOK_LBRACKET);
13087 value = constant_expr(state);
13088 eat(state, TOK_RBRACKET);
13090 info.type = type->left;
13091 info.offset = value->u.cval * size_of(state, info.type);
13096 struct hash_entry *field;
13097 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13098 ((type->type & TYPE_MASK) != TYPE_UNION))
13100 error(state, 0, "Struct designator not in struct initializer");
13102 eat(state, TOK_DOT);
13103 field = eat(state, TOK_IDENT)->ident;
13104 info.offset = field_offset(state, type, field);
13105 info.type = field_type(state, type, field);
13109 error(state, 0, "Invalid designator");
13112 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13113 eat(state, TOK_EQ);
13117 static struct triple *initializer(
13118 struct compile_state *state, struct type *type)
13120 struct triple *result;
13121 #if DEBUG_ROMCC_WARNINGS
13122 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13124 if (peek(state) != TOK_LBRACE) {
13125 result = assignment_expr(state);
13126 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13127 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13128 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13129 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13130 (equiv_types(type->left, result->type->left))) {
13131 type->elements = result->type->elements;
13133 if (is_lvalue(state, result) &&
13134 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13135 (type->type & TYPE_MASK) != TYPE_ARRAY)
13137 result = lvalue_conversion(state, result);
13139 if (!is_init_compatible(state, type, result->type)) {
13140 error(state, 0, "Incompatible types in initializer");
13142 if (!equiv_types(type, result->type)) {
13143 result = mk_cast_expr(state, type, result);
13149 struct field_info info;
13151 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13152 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13153 internal_error(state, 0, "unknown initializer type");
13156 info.type = type->left;
13157 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13158 info.type = next_field(state, type, 0);
13160 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13163 max_offset = size_of(state, type);
13165 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13166 eat(state, TOK_LBRACE);
13168 struct triple *value;
13169 struct type *value_type;
13175 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13176 info = designator(state, type);
13178 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13179 (info.offset >= max_offset)) {
13180 error(state, 0, "element beyond bounds");
13182 value_type = info.type;
13183 value = eval_const_expr(state, initializer(state, value_type));
13184 value_size = size_of(state, value_type);
13185 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13186 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13187 (max_offset <= info.offset)) {
13191 old_size = max_offset;
13192 max_offset = info.offset + value_size;
13193 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13194 memcpy(buf, old_buf, bits_to_bytes(old_size));
13197 dest = ((char *)buf) + bits_to_bytes(info.offset);
13198 #if DEBUG_INITIALIZER
13199 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13201 bits_to_bytes(max_offset),
13202 bits_to_bytes(value_size),
13205 if (value->op == OP_BLOBCONST) {
13206 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13208 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13209 #if DEBUG_INITIALIZER
13210 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13212 *((uint8_t *)dest) = value->u.cval & 0xff;
13214 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13215 *((uint16_t *)dest) = value->u.cval & 0xffff;
13217 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13218 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13221 internal_error(state, 0, "unhandled constant initializer");
13223 free_triple(state, value);
13224 if (peek(state) == TOK_COMMA) {
13225 eat(state, TOK_COMMA);
13228 info.offset += value_size;
13229 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13230 info.type = next_field(state, type, info.type);
13231 info.offset = field_offset(state, type,
13232 info.type->field_ident);
13234 } while(comma && (peek(state) != TOK_RBRACE));
13235 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13236 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13237 type->elements = max_offset / size_of(state, type->left);
13239 eat(state, TOK_RBRACE);
13240 result = triple(state, OP_BLOBCONST, type, 0, 0);
13241 result->u.blob = buf;
13246 static void resolve_branches(struct compile_state *state, struct triple *first)
13248 /* Make a second pass and finish anything outstanding
13249 * with respect to branches. The only outstanding item
13250 * is to see if there are goto to labels that have not
13251 * been defined and to error about them.
13254 struct triple *ins;
13255 /* Also error on branches that do not use their targets */
13258 if (!triple_is_ret(state, ins)) {
13259 struct triple **expr ;
13260 struct triple_set *set;
13261 expr = triple_targ(state, ins, 0);
13262 for(; expr; expr = triple_targ(state, ins, expr)) {
13263 struct triple *targ;
13265 for(set = targ?targ->use:0; set; set = set->next) {
13266 if (set->member == ins) {
13271 internal_error(state, ins, "targ not used");
13276 } while(ins != first);
13277 /* See if there are goto to labels that have not been defined */
13278 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13279 struct hash_entry *entry;
13280 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13281 struct triple *ins;
13282 if (!entry->sym_label) {
13285 ins = entry->sym_label->def;
13286 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13287 error(state, ins, "label `%s' used but not defined",
13294 static struct triple *function_definition(
13295 struct compile_state *state, struct type *type)
13297 struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13298 struct triple *fname;
13299 struct type *fname_type;
13300 struct hash_entry *ident;
13301 struct type *param, *crtype, *ctype;
13303 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13304 error(state, 0, "Invalid function header");
13307 /* Verify the function type */
13308 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13309 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13310 (type->right->field_ident == 0)) {
13311 error(state, 0, "Invalid function parameters");
13313 param = type->right;
13315 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13317 if (!param->left->field_ident) {
13318 error(state, 0, "No identifier for parameter %d\n", i);
13320 param = param->right;
13323 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13324 error(state, 0, "No identifier for paramter %d\n", i);
13327 /* Get a list of statements for this function. */
13328 def = triple(state, OP_LIST, type, 0, 0);
13330 /* Start a new scope for the passed parameters */
13331 start_scope(state);
13333 /* Put a label at the very start of a function */
13334 first = label(state);
13335 RHS(def, 0) = first;
13337 /* Put a label at the very end of a function */
13338 end = label(state);
13339 flatten(state, first, end);
13340 /* Remember where return goes */
13341 ident = state->i_return;
13342 symbol(state, ident, &ident->sym_ident, end, end->type);
13344 /* Get the initial closure type */
13345 ctype = new_type(TYPE_JOIN, &void_type, 0);
13346 ctype->elements = 1;
13348 /* Add a variable for the return value */
13349 crtype = new_type(TYPE_TUPLE,
13350 /* Remove all type qualifiers from the return type */
13351 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13352 crtype->elements = 2;
13353 result = flatten(state, end, variable(state, crtype));
13355 /* Allocate a variable for the return address */
13356 retvar = flatten(state, end, variable(state, &void_ptr_type));
13358 /* Add in the return instruction */
13359 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13360 ret = flatten(state, first, ret);
13362 /* Walk through the parameters and create symbol table entries
13365 param = type->right;
13366 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13367 ident = param->left->field_ident;
13368 tmp = variable(state, param->left);
13369 var_symbol(state, ident, tmp);
13370 flatten(state, end, tmp);
13371 param = param->right;
13373 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13374 /* And don't forget the last parameter */
13375 ident = param->field_ident;
13376 tmp = variable(state, param);
13377 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13378 flatten(state, end, tmp);
13381 /* Add the declaration static const char __func__ [] = "func-name" */
13382 fname_type = new_type(TYPE_ARRAY,
13383 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13384 fname_type->type |= QUAL_CONST | STOR_STATIC;
13385 fname_type->elements = strlen(state->function) + 1;
13387 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13388 fname->u.blob = (void *)state->function;
13389 fname = flatten(state, end, fname);
13391 ident = state->i___func__;
13392 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13394 /* Remember which function I am compiling.
13395 * Also assume the last defined function is the main function.
13397 state->main_function = def;
13399 /* Now get the actual function definition */
13400 compound_statement(state, end);
13402 /* Finish anything unfinished with branches */
13403 resolve_branches(state, first);
13405 /* Remove the parameter scope */
13409 /* Remember I have defined a function */
13410 if (!state->functions) {
13411 state->functions = def;
13413 insert_triple(state, state->functions, def);
13415 if (state->compiler->debug & DEBUG_INLINE) {
13416 FILE *fp = state->dbgout;
13419 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13420 display_func(state, fp, def);
13421 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13427 static struct triple *do_decl(struct compile_state *state,
13428 struct type *type, struct hash_entry *ident)
13430 struct triple *def;
13432 /* Clean up the storage types used */
13433 switch (type->type & STOR_MASK) {
13436 /* These are the good types I am aiming for */
13438 case STOR_REGISTER:
13439 type->type &= ~STOR_MASK;
13440 type->type |= STOR_AUTO;
13444 type->type &= ~STOR_MASK;
13445 type->type |= STOR_STATIC;
13449 error(state, 0, "typedef without name");
13451 symbol(state, ident, &ident->sym_ident, 0, type);
13452 ident->tok = TOK_TYPE_NAME;
13456 internal_error(state, 0, "Undefined storage class");
13458 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13459 error(state, 0, "Function prototypes not supported");
13462 ((type->type & STOR_MASK) == STOR_STATIC) &&
13463 ((type->type & QUAL_CONST) == 0)) {
13464 error(state, 0, "non const static variables not supported");
13467 def = variable(state, type);
13468 var_symbol(state, ident, def);
13473 static void decl(struct compile_state *state, struct triple *first)
13475 struct type *base_type, *type;
13476 struct hash_entry *ident;
13477 struct triple *def;
13479 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13480 base_type = decl_specifiers(state);
13482 type = declarator(state, base_type, &ident, 0);
13483 type->type = attributes_opt(state, type->type);
13484 if (global && ident && (peek(state) == TOK_LBRACE)) {
13486 type->type_ident = ident;
13487 state->function = ident->name;
13488 def = function_definition(state, type);
13489 symbol(state, ident, &ident->sym_ident, def, type);
13490 state->function = 0;
13494 flatten(state, first, do_decl(state, type, ident));
13495 /* type or variable definition */
13498 if (peek(state) == TOK_EQ) {
13500 error(state, 0, "cannot assign to a type");
13502 eat(state, TOK_EQ);
13503 flatten(state, first,
13505 ident->sym_ident->def,
13506 initializer(state, type)));
13508 arrays_complete(state, type);
13509 if (peek(state) == TOK_COMMA) {
13510 eat(state, TOK_COMMA);
13512 type = declarator(state, base_type, &ident, 0);
13513 flatten(state, first, do_decl(state, type, ident));
13517 eat(state, TOK_SEMI);
13521 static void decls(struct compile_state *state)
13523 struct triple *list;
13525 list = label(state);
13528 if (tok == TOK_EOF) {
13531 if (tok == TOK_SPACE) {
13532 eat(state, TOK_SPACE);
13535 if (list->next != list) {
13536 error(state, 0, "global variables not supported");
13542 * Function inlining
13544 struct triple_reg_set {
13545 struct triple_reg_set *next;
13546 struct triple *member;
13547 struct triple *new;
13550 struct block *block;
13551 struct triple_reg_set *in;
13552 struct triple_reg_set *out;
13555 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13556 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13557 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13558 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13559 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13560 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13562 static void print_block(
13563 struct compile_state *state, struct block *block, void *arg);
13564 static int do_triple_set(struct triple_reg_set **head,
13565 struct triple *member, struct triple *new_member);
13566 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13567 static struct reg_block *compute_variable_lifetimes(
13568 struct compile_state *state, struct basic_blocks *bb);
13569 static void free_variable_lifetimes(struct compile_state *state,
13570 struct basic_blocks *bb, struct reg_block *blocks);
13571 #if DEBUG_EXPLICIT_CLOSURES
13572 static void print_live_variables(struct compile_state *state,
13573 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13577 static struct triple *call(struct compile_state *state,
13578 struct triple *retvar, struct triple *ret_addr,
13579 struct triple *targ, struct triple *ret)
13581 struct triple *call;
13583 if (!retvar || !is_lvalue(state, retvar)) {
13584 internal_error(state, 0, "writing to a non lvalue?");
13586 write_compatible(state, retvar->type, &void_ptr_type);
13588 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13589 TARG(call, 0) = targ;
13590 MISC(call, 0) = ret;
13591 if (!targ || (targ->op != OP_LABEL)) {
13592 internal_error(state, 0, "call not to a label");
13594 if (!ret || (ret->op != OP_RET)) {
13595 internal_error(state, 0, "call not matched with return");
13600 static void walk_functions(struct compile_state *state,
13601 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13604 struct triple *func, *first;
13605 func = first = state->functions;
13607 cb(state, func, arg);
13609 } while(func != first);
13612 static void reverse_walk_functions(struct compile_state *state,
13613 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13616 struct triple *func, *first;
13617 func = first = state->functions;
13620 cb(state, func, arg);
13621 } while(func != first);
13625 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13627 struct triple *ptr, *first;
13628 if (func->u.cval == 0) {
13631 ptr = first = RHS(func, 0);
13633 if (ptr->op == OP_FCALL) {
13634 struct triple *called_func;
13635 called_func = MISC(ptr, 0);
13636 /* Mark the called function as used */
13637 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13638 called_func->u.cval++;
13640 /* Remove the called function from the list */
13641 called_func->prev->next = called_func->next;
13642 called_func->next->prev = called_func->prev;
13644 /* Place the called function before me on the list */
13645 called_func->next = func;
13646 called_func->prev = func->prev;
13647 called_func->prev->next = called_func;
13648 called_func->next->prev = called_func;
13651 } while(ptr != first);
13652 func->id |= TRIPLE_FLAG_FLATTENED;
13655 static void mark_live_functions(struct compile_state *state)
13657 /* Ensure state->main_function is the last function in
13658 * the list of functions.
13660 if ((state->main_function->next != state->functions) ||
13661 (state->functions->prev != state->main_function)) {
13662 internal_error(state, 0,
13663 "state->main_function is not at the end of the function list ");
13665 state->main_function->u.cval = 1;
13666 reverse_walk_functions(state, mark_live, 0);
13669 static int local_triple(struct compile_state *state,
13670 struct triple *func, struct triple *ins)
13672 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13675 FILE *fp = state->errout;
13676 fprintf(fp, "global: ");
13677 display_triple(fp, ins);
13683 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13684 struct occurance *base_occurance)
13686 struct triple *nfunc;
13687 struct triple *nfirst, *ofirst;
13688 struct triple *new, *old;
13690 if (state->compiler->debug & DEBUG_INLINE) {
13691 FILE *fp = state->dbgout;
13694 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13695 display_func(state, fp, ofunc);
13696 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13699 /* Make a new copy of the old function */
13700 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13702 ofirst = old = RHS(ofunc, 0);
13704 struct triple *new;
13705 struct occurance *occurance;
13706 int old_lhs, old_rhs;
13707 old_lhs = old->lhs;
13708 old_rhs = old->rhs;
13709 occurance = inline_occurance(state, base_occurance, old->occurance);
13710 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13711 MISC(old, 0)->u.cval += 1;
13713 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13715 if (!triple_stores_block(state, new)) {
13716 memcpy(&new->u, &old->u, sizeof(new->u));
13719 RHS(nfunc, 0) = nfirst = new;
13722 insert_triple(state, nfirst, new);
13724 new->id |= TRIPLE_FLAG_FLATTENED;
13725 new->id |= old->id & TRIPLE_FLAG_COPY;
13727 /* During the copy remember new as user of old */
13728 use_triple(old, new);
13730 /* Remember which instructions are local */
13731 old->id |= TRIPLE_FLAG_LOCAL;
13733 } while(old != ofirst);
13735 /* Make a second pass to fix up any unresolved references */
13739 struct triple **oexpr, **nexpr;
13741 /* Lookup where the copy is, to join pointers */
13742 count = TRIPLE_SIZE(old);
13743 for(i = 0; i < count; i++) {
13744 oexpr = &old->param[i];
13745 nexpr = &new->param[i];
13746 if (*oexpr && !*nexpr) {
13747 if (!local_triple(state, ofunc, *oexpr)) {
13750 else if ((*oexpr)->use) {
13751 *nexpr = (*oexpr)->use->member;
13753 if (*nexpr == old) {
13754 internal_error(state, 0, "new == old?");
13756 use_triple(*nexpr, new);
13758 if (!*nexpr && *oexpr) {
13759 internal_error(state, 0, "Could not copy %d", i);
13764 } while((old != ofirst) && (new != nfirst));
13766 /* Make a third pass to cleanup the extra useses */
13770 unuse_triple(old, new);
13771 /* Forget which instructions are local */
13772 old->id &= ~TRIPLE_FLAG_LOCAL;
13775 } while ((old != ofirst) && (new != nfirst));
13779 static void expand_inline_call(
13780 struct compile_state *state, struct triple *me, struct triple *fcall)
13782 /* Inline the function call */
13783 struct type *ptype;
13784 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13785 struct triple *end, *nend;
13788 /* Find the triples */
13789 ofunc = MISC(fcall, 0);
13790 if (ofunc->op != OP_LIST) {
13791 internal_error(state, 0, "improper function");
13793 nfunc = copy_func(state, ofunc, fcall->occurance);
13794 /* Prepend the parameter reading into the new function list */
13795 ptype = nfunc->type->right;
13796 pvals = fcall->rhs;
13797 for(i = 0; i < pvals; i++) {
13798 struct type *atype;
13799 struct triple *arg, *param;
13801 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13802 atype = ptype->left;
13804 param = farg(state, nfunc, i);
13805 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13806 internal_error(state, fcall, "param %d type mismatch", i);
13808 arg = RHS(fcall, i);
13809 flatten(state, fcall, write_expr(state, param, arg));
13810 ptype = ptype->right;
13813 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13814 result = read_expr(state,
13815 deref_index(state, fresult(state, nfunc), 1));
13817 if (state->compiler->debug & DEBUG_INLINE) {
13818 FILE *fp = state->dbgout;
13821 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13822 display_func(state, fp, nfunc);
13823 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13827 * Get rid of the extra triples
13829 /* Remove the read of the return address */
13830 ins = RHS(nfunc, 0)->prev->prev;
13831 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13832 internal_error(state, ins, "Not return addres read?");
13834 release_triple(state, ins);
13835 /* Remove the return instruction */
13836 ins = RHS(nfunc, 0)->prev;
13837 if (ins->op != OP_RET) {
13838 internal_error(state, ins, "Not return?");
13840 release_triple(state, ins);
13841 /* Remove the retaddres variable */
13842 retvar = fretaddr(state, nfunc);
13843 if ((retvar->lhs != 1) ||
13844 (retvar->op != OP_ADECL) ||
13845 (retvar->next->op != OP_PIECE) ||
13846 (MISC(retvar->next, 0) != retvar)) {
13847 internal_error(state, retvar, "Not the return address?");
13849 release_triple(state, retvar->next);
13850 release_triple(state, retvar);
13852 /* Remove the label at the start of the function */
13853 ins = RHS(nfunc, 0);
13854 if (ins->op != OP_LABEL) {
13855 internal_error(state, ins, "Not label?");
13857 nfirst = ins->next;
13858 free_triple(state, ins);
13859 /* Release the new function header */
13861 free_triple(state, nfunc);
13863 /* Append the new function list onto the return list */
13865 nend = nfirst->prev;
13866 end->next = nfirst;
13867 nfirst->prev = end;
13868 nend->next = fcall;
13869 fcall->prev = nend;
13871 /* Now the result reading code */
13873 result = flatten(state, fcall, result);
13874 propogate_use(state, fcall, result);
13877 /* Release the original fcall instruction */
13878 release_triple(state, fcall);
13885 * Type of the result variable.
13889 * +----------+------------+
13891 * union of closures result_type
13893 * +------------------+---------------+
13895 * closure1 ... closuerN
13897 * +----+--+-+--------+-----+ +----+----+---+-----+
13898 * | | | | | | | | |
13899 * var1 var2 var3 ... varN result var1 var2 ... varN result
13901 * +--------+---------+
13903 * union of closures result_type
13905 * +-----+-------------------+
13907 * closure1 ... closureN
13909 * +-----+---+----+----+ +----+---+----+-----+
13911 * var1 var2 ... varN result var1 var2 ... varN result
13914 static int add_closure_type(struct compile_state *state,
13915 struct triple *func, struct type *closure_type)
13917 struct type *type, *ctype, **next;
13918 struct triple *var, *new_var;
13922 FILE *fp = state->errout;
13923 fprintf(fp, "original_type: ");
13924 name_of(fp, fresult(state, func)->type);
13927 /* find the original type */
13928 var = fresult(state, func);
13930 if (type->elements != 2) {
13931 internal_error(state, var, "bad return type");
13934 /* Find the complete closure type and update it */
13935 ctype = type->left->left;
13936 next = &ctype->left;
13937 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13938 next = &(*next)->right;
13940 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13941 ctype->elements += 1;
13944 fprintf(fp, "new_type: ");
13947 fprintf(fp, "ctype: %p %d bits: %d ",
13948 ctype, ctype->elements, reg_size_of(state, ctype));
13949 name_of(fp, ctype);
13953 /* Regenerate the variable with the new type definition */
13954 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13955 new_var->id |= TRIPLE_FLAG_FLATTENED;
13956 for(i = 0; i < new_var->lhs; i++) {
13957 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13960 /* Point everyone at the new variable */
13961 propogate_use(state, var, new_var);
13963 /* Release the original variable */
13964 for(i = 0; i < var->lhs; i++) {
13965 release_triple(state, LHS(var, i));
13967 release_triple(state, var);
13969 /* Return the index of the added closure type */
13970 return ctype->elements - 1;
13973 static struct triple *closure_expr(struct compile_state *state,
13974 struct triple *func, int closure_idx, int var_idx)
13976 return deref_index(state,
13978 deref_index(state, fresult(state, func), 0),
13984 static void insert_triple_set(
13985 struct triple_reg_set **head, struct triple *member)
13987 struct triple_reg_set *new;
13988 new = xcmalloc(sizeof(*new), "triple_set");
13989 new->member = member;
13995 static int ordered_triple_set(
13996 struct triple_reg_set **head, struct triple *member)
13998 struct triple_reg_set **ptr;
14003 if (member == (*ptr)->member) {
14006 /* keep the list ordered */
14007 if (member->id < (*ptr)->member->id) {
14010 ptr = &(*ptr)->next;
14012 insert_triple_set(ptr, member);
14017 static void free_closure_variables(struct compile_state *state,
14018 struct triple_reg_set **enclose)
14020 struct triple_reg_set *entry, *next;
14021 for(entry = *enclose; entry; entry = next) {
14022 next = entry->next;
14023 do_triple_unset(enclose, entry->member);
14027 static int lookup_closure_index(struct compile_state *state,
14028 struct triple *me, struct triple *val)
14030 struct triple *first, *ins, *next;
14031 first = RHS(me, 0);
14032 ins = next = first;
14034 struct triple *result;
14035 struct triple *index0, *index1, *index2, *read, *write;
14038 if (ins->op != OP_CALL) {
14041 /* I am at a previous call point examine it closely */
14042 if (ins->next->op != OP_LABEL) {
14043 internal_error(state, ins, "call not followed by label");
14045 /* Does this call does not enclose any variables? */
14046 if ((ins->next->next->op != OP_INDEX) ||
14047 (ins->next->next->u.cval != 0) ||
14048 (result = MISC(ins->next->next, 0)) ||
14049 (result->id & TRIPLE_FLAG_LOCAL)) {
14052 index0 = ins->next->next;
14054 * 0 index result < 0 >
14060 for(index0 = ins->next->next;
14061 (index0->op == OP_INDEX) &&
14062 (MISC(index0, 0) == result) &&
14063 (index0->u.cval == 0) ;
14064 index0 = write->next)
14066 index1 = index0->next;
14067 index2 = index1->next;
14068 read = index2->next;
14069 write = read->next;
14070 if ((index0->op != OP_INDEX) ||
14071 (index1->op != OP_INDEX) ||
14072 (index2->op != OP_INDEX) ||
14073 (read->op != OP_READ) ||
14074 (write->op != OP_WRITE) ||
14075 (MISC(index1, 0) != index0) ||
14076 (MISC(index2, 0) != index1) ||
14077 (RHS(read, 0) != index2) ||
14078 (RHS(write, 0) != read)) {
14079 internal_error(state, index0, "bad var read");
14081 if (MISC(write, 0) == val) {
14082 return index2->u.cval;
14085 } while(next != first);
14089 static inline int enclose_triple(struct triple *ins)
14091 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14094 static void compute_closure_variables(struct compile_state *state,
14095 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14097 struct triple_reg_set *set, *vars, **last_var;
14098 struct basic_blocks bb;
14099 struct reg_block *rb;
14100 struct block *block;
14101 struct triple *old_result, *first, *ins;
14103 unsigned long used_indicies;
14105 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14106 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14113 /* Find the basic blocks of this function */
14115 bb.first = RHS(me, 0);
14117 if (!triple_is_ret(state, bb.first->prev)) {
14120 old_result = fresult(state, me);
14122 analyze_basic_blocks(state, &bb);
14124 /* Find which variables are currently alive in a given block */
14125 rb = compute_variable_lifetimes(state, &bb);
14127 /* Find the variables that are currently alive */
14128 block = block_of_triple(state, fcall);
14129 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14130 internal_error(state, fcall, "No reg block? block: %p", block);
14133 #if DEBUG_EXPLICIT_CLOSURES
14134 print_live_variables(state, &bb, rb, state->dbgout);
14135 fflush(state->dbgout);
14138 /* Count the number of triples in the function */
14139 first = RHS(me, 0);
14145 } while(ins != first);
14147 /* Allocate some memory to temorary hold the id info */
14148 info = xcmalloc(sizeof(*info) * (count +1), "info");
14150 /* Mark the local function */
14151 first = RHS(me, 0);
14155 info[idx].id = ins->id;
14156 ins->id = TRIPLE_FLAG_LOCAL | idx;
14159 } while(ins != first);
14162 * Build the list of variables to enclose.
14164 * A target it to put the same variable in the
14165 * same slot for ever call of a given function.
14166 * After coloring this removes all of the variable
14167 * manipulation code.
14169 * The list of variables to enclose is built ordered
14170 * program order because except in corner cases this
14171 * gives me the stability of assignment I need.
14173 * To gurantee that stability I lookup the variables
14174 * to see where they have been used before and
14175 * I build my final list with the assigned indicies.
14178 if (enclose_triple(old_result)) {
14179 ordered_triple_set(&vars, old_result);
14181 for(set = rb[block->vertex].out; set; set = set->next) {
14182 if (!enclose_triple(set->member)) {
14185 if ((set->member == fcall) || (set->member == old_result)) {
14188 if (!local_triple(state, me, set->member)) {
14189 internal_error(state, set->member, "not local?");
14191 ordered_triple_set(&vars, set->member);
14194 /* Lookup the current indicies of the live varialbe */
14197 for(set = vars; set ; set = set->next) {
14198 struct triple *ins;
14201 index = lookup_closure_index(state, me, ins);
14202 info[ID_BITS(ins->id)].index = index;
14206 if (index >= MAX_INDICIES) {
14207 internal_error(state, ins, "index unexpectedly large");
14209 if (used_indicies & (1 << index)) {
14210 internal_error(state, ins, "index previously used?");
14212 /* Remember which indicies have been used */
14213 used_indicies |= (1 << index);
14214 if (index > max_index) {
14219 /* Walk through the live variables and make certain
14220 * everything is assigned an index.
14222 for(set = vars; set; set = set->next) {
14223 struct triple *ins;
14226 index = info[ID_BITS(ins->id)].index;
14230 /* Find the lowest unused index value */
14231 for(index = 0; index < MAX_INDICIES; index++) {
14232 if (!(used_indicies & (1 << index))) {
14236 if (index == MAX_INDICIES) {
14237 internal_error(state, ins, "no free indicies?");
14239 info[ID_BITS(ins->id)].index = index;
14240 /* Remember which indicies have been used */
14241 used_indicies |= (1 << index);
14242 if (index > max_index) {
14247 /* Build the return list of variables with positions matching
14251 last_var = enclose;
14252 for(i = 0; i <= max_index; i++) {
14253 struct triple *var;
14255 if (used_indicies & (1 << i)) {
14256 for(set = vars; set; set = set->next) {
14258 index = info[ID_BITS(set->member->id)].index;
14265 internal_error(state, me, "missing variable");
14268 insert_triple_set(last_var, var);
14269 last_var = &(*last_var)->next;
14272 #if DEBUG_EXPLICIT_CLOSURES
14273 /* Print out the variables to be enclosed */
14274 loc(state->dbgout, state, fcall);
14275 fprintf(state->dbgout, "Alive: \n");
14276 for(set = *enclose; set; set = set->next) {
14277 display_triple(state->dbgout, set->member);
14279 fflush(state->dbgout);
14282 /* Clear the marks */
14285 ins->id = info[ID_BITS(ins->id)].id;
14287 } while(ins != first);
14289 /* Release the ordered list of live variables */
14290 free_closure_variables(state, &vars);
14292 /* Release the storage of the old ids */
14295 /* Release the variable lifetime information */
14296 free_variable_lifetimes(state, &bb, rb);
14298 /* Release the basic blocks of this function */
14299 free_basic_blocks(state, &bb);
14302 static void expand_function_call(
14303 struct compile_state *state, struct triple *me, struct triple *fcall)
14305 /* Generate an ordinary function call */
14306 struct type *closure_type, **closure_next;
14307 struct triple *func, *func_first, *func_last, *retvar;
14308 struct triple *first;
14309 struct type *ptype, *rtype;
14310 struct triple *jmp;
14311 struct triple *ret_addr, *ret_loc, *ret_set;
14312 struct triple_reg_set *enclose, *set;
14313 int closure_idx, pvals, i;
14315 #if DEBUG_EXPLICIT_CLOSURES
14316 FILE *fp = state->dbgout;
14317 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14318 display_func(state, fp, MISC(fcall, 0));
14319 display_func(state, fp, me);
14320 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14323 /* Find the triples */
14324 func = MISC(fcall, 0);
14325 func_first = RHS(func, 0);
14326 retvar = fretaddr(state, func);
14327 func_last = func_first->prev;
14328 first = fcall->next;
14330 /* Find what I need to enclose */
14331 compute_closure_variables(state, me, fcall, &enclose);
14333 /* Compute the closure type */
14334 closure_type = new_type(TYPE_TUPLE, 0, 0);
14335 closure_type->elements = 0;
14336 closure_next = &closure_type->left;
14337 for(set = enclose; set ; set = set->next) {
14341 type = set->member->type;
14343 if (!*closure_next) {
14344 *closure_next = type;
14346 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14348 closure_next = &(*closure_next)->right;
14350 closure_type->elements += 1;
14352 if (closure_type->elements == 0) {
14353 closure_type->type = TYPE_VOID;
14357 #if DEBUG_EXPLICIT_CLOSURES
14358 fprintf(state->dbgout, "closure type: ");
14359 name_of(state->dbgout, closure_type);
14360 fprintf(state->dbgout, "\n");
14363 /* Update the called functions closure variable */
14364 closure_idx = add_closure_type(state, func, closure_type);
14366 /* Generate some needed triples */
14367 ret_loc = label(state);
14368 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14370 /* Pass the parameters to the new function */
14371 ptype = func->type->right;
14372 pvals = fcall->rhs;
14373 for(i = 0; i < pvals; i++) {
14374 struct type *atype;
14375 struct triple *arg, *param;
14377 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14378 atype = ptype->left;
14380 param = farg(state, func, i);
14381 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14382 internal_error(state, fcall, "param type mismatch");
14384 arg = RHS(fcall, i);
14385 flatten(state, first, write_expr(state, param, arg));
14386 ptype = ptype->right;
14388 rtype = func->type->left;
14390 /* Thread the triples together */
14391 ret_loc = flatten(state, first, ret_loc);
14393 /* Save the active variables in the result variable */
14394 for(i = 0, set = enclose; set ; set = set->next, i++) {
14395 if (!set->member) {
14398 flatten(state, ret_loc,
14400 closure_expr(state, func, closure_idx, i),
14401 read_expr(state, set->member)));
14404 /* Initialize the return value */
14405 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14406 flatten(state, ret_loc,
14408 deref_index(state, fresult(state, func), 1),
14409 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14412 ret_addr = flatten(state, ret_loc, ret_addr);
14413 ret_set = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14414 jmp = flatten(state, ret_loc,
14415 call(state, retvar, ret_addr, func_first, func_last));
14417 /* Find the result */
14418 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14419 struct triple * result;
14420 result = flatten(state, first,
14422 deref_index(state, fresult(state, func), 1)));
14424 propogate_use(state, fcall, result);
14427 /* Release the original fcall instruction */
14428 release_triple(state, fcall);
14430 /* Restore the active variables from the result variable */
14431 for(i = 0, set = enclose; set ; set = set->next, i++) {
14432 struct triple_set *use, *next;
14433 struct triple *new;
14434 struct basic_blocks bb;
14435 if (!set->member || (set->member == fcall)) {
14438 /* Generate an expression for the value */
14439 new = flatten(state, first,
14441 closure_expr(state, func, closure_idx, i)));
14444 /* If the original is an lvalue restore the preserved value */
14445 if (is_lvalue(state, set->member)) {
14446 flatten(state, first,
14447 write_expr(state, set->member, new));
14451 * If the original is a value update the dominated uses.
14454 /* Analyze the basic blocks so I can see who dominates whom */
14456 bb.first = RHS(me, 0);
14457 if (!triple_is_ret(state, bb.first->prev)) {
14460 analyze_basic_blocks(state, &bb);
14463 #if DEBUG_EXPLICIT_CLOSURES
14464 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14467 /* If fcall dominates the use update the expression */
14468 for(use = set->member->use; use; use = next) {
14469 /* Replace use modifies the use chain and
14470 * removes use, so I must take a copy of the
14471 * next entry early.
14474 if (!tdominates(state, fcall, use->member)) {
14477 replace_use(state, set->member, new, use->member);
14480 /* Release the basic blocks, the instructions will be
14481 * different next time, and flatten/insert_triple does
14482 * not update the block values so I can't cache the analysis.
14484 free_basic_blocks(state, &bb);
14487 /* Release the closure variable list */
14488 free_closure_variables(state, &enclose);
14490 if (state->compiler->debug & DEBUG_INLINE) {
14491 FILE *fp = state->dbgout;
14494 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14495 display_func(state, fp, func);
14496 display_func(state, fp, me);
14497 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14503 static int do_inline(struct compile_state *state, struct triple *func)
14508 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14510 case COMPILER_INLINE_ALWAYS:
14512 if (func->type->type & ATTRIB_NOINLINE) {
14513 error(state, func, "noinline with always_inline compiler option");
14516 case COMPILER_INLINE_NEVER:
14518 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14519 error(state, func, "always_inline with noinline compiler option");
14522 case COMPILER_INLINE_DEFAULTON:
14523 switch(func->type->type & STOR_MASK) {
14524 case STOR_STATIC | STOR_INLINE:
14525 case STOR_LOCAL | STOR_INLINE:
14526 case STOR_EXTERN | STOR_INLINE:
14534 case COMPILER_INLINE_DEFAULTOFF:
14535 switch(func->type->type & STOR_MASK) {
14536 case STOR_STATIC | STOR_INLINE:
14537 case STOR_LOCAL | STOR_INLINE:
14538 case STOR_EXTERN | STOR_INLINE:
14546 case COMPILER_INLINE_NOPENALTY:
14547 switch(func->type->type & STOR_MASK) {
14548 case STOR_STATIC | STOR_INLINE:
14549 case STOR_LOCAL | STOR_INLINE:
14550 case STOR_EXTERN | STOR_INLINE:
14554 do_inline = (func->u.cval == 1);
14560 internal_error(state, 0, "Unimplemented inline policy");
14563 /* Force inlining */
14564 if (func->type->type & ATTRIB_NOINLINE) {
14567 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14573 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14575 struct triple *first, *ptr, *next;
14576 /* If the function is not used don't bother */
14577 if (me->u.cval <= 0) {
14580 if (state->compiler->debug & DEBUG_CALLS2) {
14581 FILE *fp = state->dbgout;
14582 fprintf(fp, "in: %s\n",
14583 me->type->type_ident->name);
14586 first = RHS(me, 0);
14587 ptr = next = first;
14589 struct triple *func, *prev;
14593 if (ptr->op != OP_FCALL) {
14596 func = MISC(ptr, 0);
14597 /* See if the function should be inlined */
14598 if (!do_inline(state, func)) {
14599 /* Put a label after the fcall */
14600 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14603 if (state->compiler->debug & DEBUG_CALLS) {
14604 FILE *fp = state->dbgout;
14605 if (state->compiler->debug & DEBUG_CALLS2) {
14606 loc(fp, state, ptr);
14608 fprintf(fp, "inlining %s\n",
14609 func->type->type_ident->name);
14613 /* Update the function use counts */
14616 /* Replace the fcall with the called function */
14617 expand_inline_call(state, me, ptr);
14620 } while (next != first);
14622 ptr = next = first;
14624 struct triple *prev, *func;
14628 if (ptr->op != OP_FCALL) {
14631 func = MISC(ptr, 0);
14632 if (state->compiler->debug & DEBUG_CALLS) {
14633 FILE *fp = state->dbgout;
14634 if (state->compiler->debug & DEBUG_CALLS2) {
14635 loc(fp, state, ptr);
14637 fprintf(fp, "calling %s\n",
14638 func->type->type_ident->name);
14641 /* Replace the fcall with the instruction sequence
14642 * needed to make the call.
14644 expand_function_call(state, me, ptr);
14646 } while(next != first);
14649 static void inline_functions(struct compile_state *state, struct triple *func)
14651 inline_function(state, func, 0);
14652 reverse_walk_functions(state, inline_function, 0);
14655 static void insert_function(struct compile_state *state,
14656 struct triple *func, void *arg)
14658 struct triple *first, *end, *ffirst, *fend;
14660 if (state->compiler->debug & DEBUG_INLINE) {
14661 FILE *fp = state->errout;
14662 fprintf(fp, "%s func count: %d\n",
14663 func->type->type_ident->name, func->u.cval);
14665 if (func->u.cval == 0) {
14669 /* Find the end points of the lists */
14672 ffirst = RHS(func, 0);
14673 fend = ffirst->prev;
14675 /* splice the lists together */
14676 end->next = ffirst;
14677 ffirst->prev = end;
14678 fend->next = first;
14679 first->prev = fend;
14682 struct triple *input_asm(struct compile_state *state)
14684 struct asm_info *info;
14685 struct triple *def;
14688 info = xcmalloc(sizeof(*info), "asm_info");
14691 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14692 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14694 def = new_triple(state, OP_ASM, &void_type, out, 0);
14695 def->u.ainfo = info;
14696 def->id |= TRIPLE_FLAG_VOLATILE;
14698 for(i = 0; i < out; i++) {
14699 struct triple *piece;
14700 piece = triple(state, OP_PIECE, &int_type, def, 0);
14702 LHS(def, i) = piece;
14708 struct triple *output_asm(struct compile_state *state)
14710 struct asm_info *info;
14711 struct triple *def;
14714 info = xcmalloc(sizeof(*info), "asm_info");
14717 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14718 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14720 def = new_triple(state, OP_ASM, &void_type, 0, in);
14721 def->u.ainfo = info;
14722 def->id |= TRIPLE_FLAG_VOLATILE;
14727 static void join_functions(struct compile_state *state)
14729 struct triple *jmp, *start, *end, *call, *in, *out, *func;
14730 struct file_state file;
14731 struct type *pnext, *param;
14732 struct type *result_type, *args_type;
14735 /* Be clear the functions have not been joined yet */
14736 state->functions_joined = 0;
14738 /* Dummy file state to get debug handing right */
14739 memset(&file, 0, sizeof(file));
14740 file.basename = "";
14742 file.report_line = 0;
14743 file.report_name = file.basename;
14744 file.prev = state->file;
14745 state->file = &file;
14746 state->function = "";
14748 if (!state->main_function) {
14749 error(state, 0, "No functions to compile\n");
14752 /* The type of arguments */
14753 args_type = state->main_function->type->right;
14754 /* The return type without any specifiers */
14755 result_type = clone_type(0, state->main_function->type->left);
14758 /* Verify the external arguments */
14759 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14760 error(state, state->main_function,
14761 "Too many external input arguments");
14763 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14764 error(state, state->main_function,
14765 "Too many external output arguments");
14768 /* Lay down the basic program structure */
14769 end = label(state);
14770 start = label(state);
14771 start = flatten(state, state->first, start);
14772 end = flatten(state, state->first, end);
14773 in = input_asm(state);
14774 out = output_asm(state);
14775 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14776 MISC(call, 0) = state->main_function;
14777 in = flatten(state, state->first, in);
14778 call = flatten(state, state->first, call);
14779 out = flatten(state, state->first, out);
14782 /* Read the external input arguments */
14785 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14786 struct triple *expr;
14789 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14790 pnext = param->right;
14791 param = param->left;
14793 if (registers_of(state, param) != 1) {
14794 error(state, state->main_function,
14795 "Arg: %d %s requires multiple registers",
14796 idx + 1, param->field_ident->name);
14798 expr = read_expr(state, LHS(in, idx));
14799 RHS(call, idx) = expr;
14800 expr = flatten(state, call, expr);
14801 use_triple(expr, call);
14807 /* Write the external output arguments */
14808 pnext = result_type;
14809 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14810 pnext = result_type->left;
14812 for(idx = 0; idx < out->rhs; idx++) {
14813 struct triple *expr;
14816 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14817 pnext = param->right;
14818 param = param->left;
14820 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14824 if (registers_of(state, param) != 1) {
14825 error(state, state->main_function,
14826 "Result: %d %s requires multiple registers",
14827 idx, param->field_ident->name);
14829 expr = read_expr(state, call);
14830 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14831 expr = deref_field(state, expr, param->field_ident);
14834 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14836 flatten(state, out, expr);
14837 RHS(out, idx) = expr;
14838 use_triple(expr, out);
14841 /* Allocate a dummy containing function */
14842 func = triple(state, OP_LIST,
14843 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14844 func->type->type_ident = lookup(state, "", 0);
14845 RHS(func, 0) = state->first;
14848 /* See which functions are called, and how often */
14849 mark_live_functions(state);
14850 inline_functions(state, func);
14851 walk_functions(state, insert_function, end);
14853 if (start->next != end) {
14854 jmp = flatten(state, start, branch(state, end, 0));
14857 /* OK now the functions have been joined. */
14858 state->functions_joined = 1;
14860 /* Done now cleanup */
14861 state->file = file.prev;
14862 state->function = 0;
14866 * Data structurs for optimation.
14870 static int do_use_block(
14871 struct block *used, struct block_set **head, struct block *user,
14874 struct block_set **ptr, *new;
14881 if ((*ptr)->member == user) {
14884 ptr = &(*ptr)->next;
14886 new = xcmalloc(sizeof(*new), "block_set");
14887 new->member = user;
14898 static int do_unuse_block(
14899 struct block *used, struct block_set **head, struct block *unuser)
14901 struct block_set *use, **ptr;
14907 if (use->member == unuser) {
14909 memset(use, -1, sizeof(*use));
14920 static void use_block(struct block *used, struct block *user)
14923 /* Append new to the head of the list, print_block
14926 count = do_use_block(used, &used->use, user, 1);
14927 used->users += count;
14929 static void unuse_block(struct block *used, struct block *unuser)
14932 count = do_unuse_block(used, &used->use, unuser);
14933 used->users -= count;
14936 static void add_block_edge(struct block *block, struct block *edge, int front)
14939 count = do_use_block(block, &block->edges, edge, front);
14940 block->edge_count += count;
14943 static void remove_block_edge(struct block *block, struct block *edge)
14946 count = do_unuse_block(block, &block->edges, edge);
14947 block->edge_count -= count;
14950 static void idom_block(struct block *idom, struct block *user)
14952 do_use_block(idom, &idom->idominates, user, 0);
14955 static void unidom_block(struct block *idom, struct block *unuser)
14957 do_unuse_block(idom, &idom->idominates, unuser);
14960 static void domf_block(struct block *block, struct block *domf)
14962 do_use_block(block, &block->domfrontier, domf, 0);
14965 static void undomf_block(struct block *block, struct block *undomf)
14967 do_unuse_block(block, &block->domfrontier, undomf);
14970 static void ipdom_block(struct block *ipdom, struct block *user)
14972 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14975 static void unipdom_block(struct block *ipdom, struct block *unuser)
14977 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14980 static void ipdomf_block(struct block *block, struct block *ipdomf)
14982 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14985 static void unipdomf_block(struct block *block, struct block *unipdomf)
14987 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14990 static int walk_triples(
14991 struct compile_state *state,
14992 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
14995 struct triple *ptr;
14997 ptr = state->first;
14999 result = cb(state, ptr, arg);
15000 if (ptr->next->prev != ptr) {
15001 internal_error(state, ptr->next, "bad prev");
15004 } while((result == 0) && (ptr != state->first));
15008 #define PRINT_LIST 1
15009 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15014 if (op == OP_LIST) {
15019 if ((op == OP_LABEL) && (ins->use)) {
15020 fprintf(fp, "\n%p:\n", ins);
15022 display_triple(fp, ins);
15024 if (triple_is_branch(state, ins) && ins->use &&
15025 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15026 internal_error(state, ins, "branch used?");
15028 if (triple_is_branch(state, ins)) {
15034 static void print_triples(struct compile_state *state)
15036 if (state->compiler->debug & DEBUG_TRIPLES) {
15037 FILE *fp = state->dbgout;
15038 fprintf(fp, "--------------- triples ---------------\n");
15039 walk_triples(state, do_print_triple, fp);
15045 struct block *block;
15047 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15049 struct block_set *edge;
15050 if (!block || (cf[block->vertex].block == block)) {
15053 cf[block->vertex].block = block;
15054 for(edge = block->edges; edge; edge = edge->next) {
15055 find_cf_blocks(cf, edge->member);
15059 static void print_control_flow(struct compile_state *state,
15060 FILE *fp, struct basic_blocks *bb)
15062 struct cf_block *cf;
15064 fprintf(fp, "\ncontrol flow\n");
15065 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15066 find_cf_blocks(cf, bb->first_block);
15068 for(i = 1; i <= bb->last_vertex; i++) {
15069 struct block *block;
15070 struct block_set *edge;
15071 block = cf[i].block;
15074 fprintf(fp, "(%p) %d:", block, block->vertex);
15075 for(edge = block->edges; edge; edge = edge->next) {
15076 fprintf(fp, " %d", edge->member->vertex);
15084 static void free_basic_block(struct compile_state *state, struct block *block)
15086 struct block_set *edge, *entry;
15087 struct block *child;
15091 if (block->vertex == -1) {
15094 block->vertex = -1;
15095 for(edge = block->edges; edge; edge = edge->next) {
15096 if (edge->member) {
15097 unuse_block(edge->member, block);
15101 unidom_block(block->idom, block);
15104 if (block->ipdom) {
15105 unipdom_block(block->ipdom, block);
15108 while((entry = block->use)) {
15109 child = entry->member;
15110 unuse_block(block, child);
15111 if (child && (child->vertex != -1)) {
15112 for(edge = child->edges; edge; edge = edge->next) {
15117 while((entry = block->idominates)) {
15118 child = entry->member;
15119 unidom_block(block, child);
15120 if (child && (child->vertex != -1)) {
15124 while((entry = block->domfrontier)) {
15125 child = entry->member;
15126 undomf_block(block, child);
15128 while((entry = block->ipdominates)) {
15129 child = entry->member;
15130 unipdom_block(block, child);
15131 if (child && (child->vertex != -1)) {
15135 while((entry = block->ipdomfrontier)) {
15136 child = entry->member;
15137 unipdomf_block(block, child);
15139 if (block->users != 0) {
15140 internal_error(state, 0, "block still has users");
15142 while((edge = block->edges)) {
15143 child = edge->member;
15144 remove_block_edge(block, child);
15146 if (child && (child->vertex != -1)) {
15147 free_basic_block(state, child);
15150 memset(block, -1, sizeof(*block));
15156 static void free_basic_blocks(struct compile_state *state,
15157 struct basic_blocks *bb)
15159 struct triple *first, *ins;
15160 free_basic_block(state, bb->first_block);
15161 bb->last_vertex = 0;
15162 bb->first_block = bb->last_block = 0;
15166 if (triple_stores_block(state, ins)) {
15170 } while(ins != first);
15174 static struct block *basic_block(struct compile_state *state,
15175 struct basic_blocks *bb, struct triple *first)
15177 struct block *block;
15178 struct triple *ptr;
15179 if (!triple_is_label(state, first)) {
15180 internal_error(state, first, "block does not start with a label");
15182 /* See if this basic block has already been setup */
15183 if (first->u.block != 0) {
15184 return first->u.block;
15186 /* Allocate another basic block structure */
15187 bb->last_vertex += 1;
15188 block = xcmalloc(sizeof(*block), "block");
15189 block->first = block->last = first;
15190 block->vertex = bb->last_vertex;
15193 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15197 /* If ptr->u is not used remember where the baic block is */
15198 if (triple_stores_block(state, ptr)) {
15199 ptr->u.block = block;
15201 if (triple_is_branch(state, ptr)) {
15205 } while (ptr != bb->first);
15206 if ((ptr == bb->first) ||
15207 ((ptr->next == bb->first) && (
15208 triple_is_end(state, ptr) ||
15209 triple_is_ret(state, ptr))))
15211 /* The block has no outflowing edges */
15213 else if (triple_is_label(state, ptr)) {
15214 struct block *next;
15215 next = basic_block(state, bb, ptr);
15216 add_block_edge(block, next, 0);
15217 use_block(next, block);
15219 else if (triple_is_branch(state, ptr)) {
15220 struct triple **expr, *first;
15221 struct block *child;
15222 /* Find the branch targets.
15223 * I special case the first branch as that magically
15224 * avoids some difficult cases for the register allocator.
15226 expr = triple_edge_targ(state, ptr, 0);
15228 internal_error(state, ptr, "branch without targets");
15231 expr = triple_edge_targ(state, ptr, expr);
15232 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15233 if (!*expr) continue;
15234 child = basic_block(state, bb, *expr);
15235 use_block(child, block);
15236 add_block_edge(block, child, 0);
15239 child = basic_block(state, bb, first);
15240 use_block(child, block);
15241 add_block_edge(block, child, 1);
15243 /* Be certain the return block of a call is
15244 * in a basic block. When it is not find
15245 * start of the block, insert a label if
15246 * necessary and build the basic block.
15247 * Then add a fake edge from the start block
15248 * to the return block of the function.
15250 if (state->functions_joined && triple_is_call(state, ptr)
15251 && !block_of_triple(state, MISC(ptr, 0))) {
15252 struct block *tail;
15253 struct triple *start;
15254 start = triple_to_block_start(state, MISC(ptr, 0));
15255 if (!triple_is_label(state, start)) {
15256 start = pre_triple(state,
15257 start, OP_LABEL, &void_type, 0, 0);
15259 tail = basic_block(state, bb, start);
15260 add_block_edge(child, tail, 0);
15261 use_block(tail, child);
15266 internal_error(state, 0, "Bad basic block split");
15270 struct block_set *edge;
15271 FILE *fp = state->errout;
15272 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15273 block, block->vertex,
15274 block->first, block->last);
15275 for(edge = block->edges; edge; edge = edge->next) {
15276 fprintf(fp, " %10p [%2d]",
15277 edge->member ? edge->member->first : 0,
15278 edge->member ? edge->member->vertex : -1);
15287 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15288 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15291 struct triple *ptr, *first;
15292 struct block *last_block;
15297 if (triple_stores_block(state, ptr)) {
15298 struct block *block;
15299 block = ptr->u.block;
15300 if (block && (block != last_block)) {
15301 cb(state, block, arg);
15303 last_block = block;
15306 } while(ptr != first);
15309 static void print_block(
15310 struct compile_state *state, struct block *block, void *arg)
15312 struct block_set *user, *edge;
15313 struct triple *ptr;
15316 fprintf(fp, "\nblock: %p (%d) ",
15320 for(edge = block->edges; edge; edge = edge->next) {
15321 fprintf(fp, " %p<-%p",
15323 (edge->member && edge->member->use)?
15324 edge->member->use->member : 0);
15327 if (block->first->op == OP_LABEL) {
15328 fprintf(fp, "%p:\n", block->first);
15330 for(ptr = block->first; ; ) {
15331 display_triple(fp, ptr);
15332 if (ptr == block->last)
15335 if (ptr == block->first) {
15336 internal_error(state, 0, "missing block last?");
15339 fprintf(fp, "users %d: ", block->users);
15340 for(user = block->use; user; user = user->next) {
15341 fprintf(fp, "%p (%d) ",
15343 user->member->vertex);
15345 fprintf(fp,"\n\n");
15349 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15351 fprintf(fp, "--------------- blocks ---------------\n");
15352 walk_blocks(state, &state->bb, print_block, fp);
15354 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15356 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15357 fprintf(fp, "After %s\n", func);
15358 romcc_print_blocks(state, fp);
15359 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15360 print_dominators(state, fp, &state->bb);
15361 print_dominance_frontiers(state, fp, &state->bb);
15363 print_control_flow(state, fp, &state->bb);
15367 static void prune_nonblock_triples(struct compile_state *state,
15368 struct basic_blocks *bb)
15370 struct block *block;
15371 struct triple *first, *ins, *next;
15372 /* Delete the triples not in a basic block */
15378 if (ins->op == OP_LABEL) {
15379 block = ins->u.block;
15382 struct triple_set *use;
15383 for(use = ins->use; use; use = use->next) {
15384 struct block *block;
15385 block = block_of_triple(state, use->member);
15387 internal_error(state, ins, "pruning used ins?");
15390 release_triple(state, ins);
15392 if (block && block->last == ins) {
15396 } while(ins != first);
15399 static void setup_basic_blocks(struct compile_state *state,
15400 struct basic_blocks *bb)
15402 if (!triple_stores_block(state, bb->first)) {
15403 internal_error(state, 0, "ins will not store block?");
15405 /* Initialize the state */
15406 bb->first_block = bb->last_block = 0;
15407 bb->last_vertex = 0;
15408 free_basic_blocks(state, bb);
15410 /* Find the basic blocks */
15411 bb->first_block = basic_block(state, bb, bb->first);
15413 /* Be certain the last instruction of a function, or the
15414 * entire program is in a basic block. When it is not find
15415 * the start of the block, insert a label if necessary and build
15416 * basic block. Then add a fake edge from the start block
15417 * to the final block.
15419 if (!block_of_triple(state, bb->first->prev)) {
15420 struct triple *start;
15421 struct block *tail;
15422 start = triple_to_block_start(state, bb->first->prev);
15423 if (!triple_is_label(state, start)) {
15424 start = pre_triple(state,
15425 start, OP_LABEL, &void_type, 0, 0);
15427 tail = basic_block(state, bb, start);
15428 add_block_edge(bb->first_block, tail, 0);
15429 use_block(tail, bb->first_block);
15432 /* Find the last basic block.
15434 bb->last_block = block_of_triple(state, bb->first->prev);
15436 /* Delete the triples not in a basic block */
15437 prune_nonblock_triples(state, bb);
15440 /* If we are debugging print what I have just done */
15441 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15442 print_blocks(state, state->dbgout);
15443 print_control_flow(state, bb);
15449 struct sdom_block {
15450 struct block *block;
15451 struct sdom_block *sdominates;
15452 struct sdom_block *sdom_next;
15453 struct sdom_block *sdom;
15454 struct sdom_block *label;
15455 struct sdom_block *parent;
15456 struct sdom_block *ancestor;
15461 static void unsdom_block(struct sdom_block *block)
15463 struct sdom_block **ptr;
15464 if (!block->sdom_next) {
15467 ptr = &block->sdom->sdominates;
15469 if ((*ptr) == block) {
15470 *ptr = block->sdom_next;
15473 ptr = &(*ptr)->sdom_next;
15477 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15479 unsdom_block(block);
15480 block->sdom = sdom;
15481 block->sdom_next = sdom->sdominates;
15482 sdom->sdominates = block;
15487 static int initialize_sdblock(struct sdom_block *sd,
15488 struct block *parent, struct block *block, int vertex)
15490 struct block_set *edge;
15491 if (!block || (sd[block->vertex].block == block)) {
15495 /* Renumber the blocks in a convinient fashion */
15496 block->vertex = vertex;
15497 sd[vertex].block = block;
15498 sd[vertex].sdom = &sd[vertex];
15499 sd[vertex].label = &sd[vertex];
15500 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15501 sd[vertex].ancestor = 0;
15502 sd[vertex].vertex = vertex;
15503 for(edge = block->edges; edge; edge = edge->next) {
15504 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15509 static int initialize_spdblock(
15510 struct compile_state *state, struct sdom_block *sd,
15511 struct block *parent, struct block *block, int vertex)
15513 struct block_set *user;
15514 if (!block || (sd[block->vertex].block == block)) {
15518 /* Renumber the blocks in a convinient fashion */
15519 block->vertex = vertex;
15520 sd[vertex].block = block;
15521 sd[vertex].sdom = &sd[vertex];
15522 sd[vertex].label = &sd[vertex];
15523 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15524 sd[vertex].ancestor = 0;
15525 sd[vertex].vertex = vertex;
15526 for(user = block->use; user; user = user->next) {
15527 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15532 static int setup_spdblocks(struct compile_state *state,
15533 struct basic_blocks *bb, struct sdom_block *sd)
15535 struct block *block;
15537 /* Setup as many sdpblocks as possible without using fake edges */
15538 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15540 /* Walk through the graph and find unconnected blocks. Add a
15541 * fake edge from the unconnected blocks to the end of the
15544 block = bb->first_block->last->next->u.block;
15545 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15546 if (sd[block->vertex].block == block) {
15549 #if DEBUG_SDP_BLOCKS
15551 FILE *fp = state->errout;
15552 fprintf(fp, "Adding %d\n", vertex +1);
15555 add_block_edge(block, bb->last_block, 0);
15556 use_block(bb->last_block, block);
15558 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15563 static void compress_ancestors(struct sdom_block *v)
15565 /* This procedure assumes ancestor(v) != 0 */
15566 /* if (ancestor(ancestor(v)) != 0) {
15567 * compress(ancestor(ancestor(v)));
15568 * if (semi(label(ancestor(v))) < semi(label(v))) {
15569 * label(v) = label(ancestor(v));
15571 * ancestor(v) = ancestor(ancestor(v));
15574 if (!v->ancestor) {
15577 if (v->ancestor->ancestor) {
15578 compress_ancestors(v->ancestor->ancestor);
15579 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15580 v->label = v->ancestor->label;
15582 v->ancestor = v->ancestor->ancestor;
15586 static void compute_sdom(struct compile_state *state,
15587 struct basic_blocks *bb, struct sdom_block *sd)
15591 * for each v <= pred(w) {
15593 * if (semi[u] < semi[w] {
15594 * semi[w] = semi[u];
15597 * add w to bucket(vertex(semi[w]));
15598 * LINK(parent(w), w);
15601 * for each v <= bucket(parent(w)) {
15602 * delete v from bucket(parent(w));
15604 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15607 for(i = bb->last_vertex; i >= 2; i--) {
15608 struct sdom_block *v, *parent, *next;
15609 struct block_set *user;
15610 struct block *block;
15611 block = sd[i].block;
15612 parent = sd[i].parent;
15614 for(user = block->use; user; user = user->next) {
15615 struct sdom_block *v, *u;
15616 v = &sd[user->member->vertex];
15617 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15618 if (u->sdom->vertex < sd[i].sdom->vertex) {
15619 sd[i].sdom = u->sdom;
15622 sdom_block(sd[i].sdom, &sd[i]);
15623 sd[i].ancestor = parent;
15625 for(v = parent->sdominates; v; v = next) {
15626 struct sdom_block *u;
15627 next = v->sdom_next;
15629 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15630 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15631 u->block : parent->block;
15636 static void compute_spdom(struct compile_state *state,
15637 struct basic_blocks *bb, struct sdom_block *sd)
15641 * for each v <= pred(w) {
15643 * if (semi[u] < semi[w] {
15644 * semi[w] = semi[u];
15647 * add w to bucket(vertex(semi[w]));
15648 * LINK(parent(w), w);
15651 * for each v <= bucket(parent(w)) {
15652 * delete v from bucket(parent(w));
15654 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15657 for(i = bb->last_vertex; i >= 2; i--) {
15658 struct sdom_block *u, *v, *parent, *next;
15659 struct block_set *edge;
15660 struct block *block;
15661 block = sd[i].block;
15662 parent = sd[i].parent;
15664 for(edge = block->edges; edge; edge = edge->next) {
15665 v = &sd[edge->member->vertex];
15666 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15667 if (u->sdom->vertex < sd[i].sdom->vertex) {
15668 sd[i].sdom = u->sdom;
15671 sdom_block(sd[i].sdom, &sd[i]);
15672 sd[i].ancestor = parent;
15674 for(v = parent->sdominates; v; v = next) {
15675 struct sdom_block *u;
15676 next = v->sdom_next;
15678 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15679 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15680 u->block : parent->block;
15685 static void compute_idom(struct compile_state *state,
15686 struct basic_blocks *bb, struct sdom_block *sd)
15689 for(i = 2; i <= bb->last_vertex; i++) {
15690 struct block *block;
15691 block = sd[i].block;
15692 if (block->idom->vertex != sd[i].sdom->vertex) {
15693 block->idom = block->idom->idom;
15695 idom_block(block->idom, block);
15697 sd[1].block->idom = 0;
15700 static void compute_ipdom(struct compile_state *state,
15701 struct basic_blocks *bb, struct sdom_block *sd)
15704 for(i = 2; i <= bb->last_vertex; i++) {
15705 struct block *block;
15706 block = sd[i].block;
15707 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15708 block->ipdom = block->ipdom->ipdom;
15710 ipdom_block(block->ipdom, block);
15712 sd[1].block->ipdom = 0;
15716 * Every vertex of a flowgraph G = (V, E, r) except r has
15717 * a unique immediate dominator.
15718 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15719 * rooted at r, called the dominator tree of G, such that
15720 * v dominates w if and only if v is a proper ancestor of w in
15721 * the dominator tree.
15724 * If v and w are vertices of G such that v <= w,
15725 * than any path from v to w must contain a common ancestor
15728 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15729 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15730 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15732 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15733 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15736 * Let w != r and let u be a vertex for which sdom(u) is
15737 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15738 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15740 /* Lemma 5: Let vertices v,w satisfy v -> w.
15741 * Then v -> idom(w) or idom(w) -> idom(v)
15744 static void find_immediate_dominators(struct compile_state *state,
15745 struct basic_blocks *bb)
15747 struct sdom_block *sd;
15748 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15749 * vi > w for (1 <= i <= k - 1}
15752 * For any vertex w != r.
15754 * {v|(v,w) <= E and v < w } U
15755 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15758 * Let w != r and let u be a vertex for which sdom(u) is
15759 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15761 * { sdom(w) if sdom(w) = sdom(u),
15763 * { idom(u) otherwise
15765 /* The algorithm consists of the following 4 steps.
15766 * Step 1. Carry out a depth-first search of the problem graph.
15767 * Number the vertices from 1 to N as they are reached during
15768 * the search. Initialize the variables used in succeeding steps.
15769 * Step 2. Compute the semidominators of all vertices by applying
15770 * theorem 4. Carry out the computation vertex by vertex in
15771 * decreasing order by number.
15772 * Step 3. Implicitly define the immediate dominator of each vertex
15773 * by applying Corollary 1.
15774 * Step 4. Explicitly define the immediate dominator of each vertex,
15775 * carrying out the computation vertex by vertex in increasing order
15778 /* Step 1 initialize the basic block information */
15779 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15780 initialize_sdblock(sd, 0, bb->first_block, 0);
15786 /* Step 2 compute the semidominators */
15787 /* Step 3 implicitly define the immediate dominator of each vertex */
15788 compute_sdom(state, bb, sd);
15789 /* Step 4 explicitly define the immediate dominator of each vertex */
15790 compute_idom(state, bb, sd);
15794 static void find_post_dominators(struct compile_state *state,
15795 struct basic_blocks *bb)
15797 struct sdom_block *sd;
15799 /* Step 1 initialize the basic block information */
15800 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15802 vertex = setup_spdblocks(state, bb, sd);
15803 if (vertex != bb->last_vertex) {
15804 internal_error(state, 0, "missing %d blocks",
15805 bb->last_vertex - vertex);
15808 /* Step 2 compute the semidominators */
15809 /* Step 3 implicitly define the immediate dominator of each vertex */
15810 compute_spdom(state, bb, sd);
15811 /* Step 4 explicitly define the immediate dominator of each vertex */
15812 compute_ipdom(state, bb, sd);
15818 static void find_block_domf(struct compile_state *state, struct block *block)
15820 struct block *child;
15821 struct block_set *user, *edge;
15822 if (block->domfrontier != 0) {
15823 internal_error(state, block->first, "domfrontier present?");
15825 for(user = block->idominates; user; user = user->next) {
15826 child = user->member;
15827 if (child->idom != block) {
15828 internal_error(state, block->first, "bad idom");
15830 find_block_domf(state, child);
15832 for(edge = block->edges; edge; edge = edge->next) {
15833 if (edge->member->idom != block) {
15834 domf_block(block, edge->member);
15837 for(user = block->idominates; user; user = user->next) {
15838 struct block_set *frontier;
15839 child = user->member;
15840 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15841 if (frontier->member->idom != block) {
15842 domf_block(block, frontier->member);
15848 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15850 struct block *child;
15851 struct block_set *user;
15852 if (block->ipdomfrontier != 0) {
15853 internal_error(state, block->first, "ipdomfrontier present?");
15855 for(user = block->ipdominates; user; user = user->next) {
15856 child = user->member;
15857 if (child->ipdom != block) {
15858 internal_error(state, block->first, "bad ipdom");
15860 find_block_ipdomf(state, child);
15862 for(user = block->use; user; user = user->next) {
15863 if (user->member->ipdom != block) {
15864 ipdomf_block(block, user->member);
15867 for(user = block->ipdominates; user; user = user->next) {
15868 struct block_set *frontier;
15869 child = user->member;
15870 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15871 if (frontier->member->ipdom != block) {
15872 ipdomf_block(block, frontier->member);
15878 static void print_dominated(
15879 struct compile_state *state, struct block *block, void *arg)
15881 struct block_set *user;
15884 fprintf(fp, "%d:", block->vertex);
15885 for(user = block->idominates; user; user = user->next) {
15886 fprintf(fp, " %d", user->member->vertex);
15887 if (user->member->idom != block) {
15888 internal_error(state, user->member->first, "bad idom");
15894 static void print_dominated2(
15895 struct compile_state *state, FILE *fp, int depth, struct block *block)
15897 struct block_set *user;
15898 struct triple *ins;
15899 struct occurance *ptr, *ptr2;
15900 const char *filename1, *filename2;
15901 int equal_filenames;
15903 for(i = 0; i < depth; i++) {
15906 fprintf(fp, "%3d: %p (%p - %p) @",
15907 block->vertex, block, block->first, block->last);
15908 ins = block->first;
15909 while(ins != block->last && (ins->occurance->line == 0)) {
15912 ptr = ins->occurance;
15913 ptr2 = block->last->occurance;
15914 filename1 = ptr->filename? ptr->filename : "";
15915 filename2 = ptr2->filename? ptr2->filename : "";
15916 equal_filenames = (strcmp(filename1, filename2) == 0);
15917 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15918 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15919 } else if (equal_filenames) {
15920 fprintf(fp, " %s:(%d - %d)",
15921 ptr->filename, ptr->line, ptr2->line);
15923 fprintf(fp, " (%s:%d - %s:%d)",
15924 ptr->filename, ptr->line,
15925 ptr2->filename, ptr2->line);
15928 for(user = block->idominates; user; user = user->next) {
15929 print_dominated2(state, fp, depth + 1, user->member);
15933 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15935 fprintf(fp, "\ndominates\n");
15936 walk_blocks(state, bb, print_dominated, fp);
15937 fprintf(fp, "dominates\n");
15938 print_dominated2(state, fp, 0, bb->first_block);
15942 static int print_frontiers(
15943 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15945 struct block_set *user, *edge;
15947 if (!block || (block->vertex != vertex + 1)) {
15952 fprintf(fp, "%d:", block->vertex);
15953 for(user = block->domfrontier; user; user = user->next) {
15954 fprintf(fp, " %d", user->member->vertex);
15958 for(edge = block->edges; edge; edge = edge->next) {
15959 vertex = print_frontiers(state, fp, edge->member, vertex);
15963 static void print_dominance_frontiers(struct compile_state *state,
15964 FILE *fp, struct basic_blocks *bb)
15966 fprintf(fp, "\ndominance frontiers\n");
15967 print_frontiers(state, fp, bb->first_block, 0);
15971 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15973 /* Find the immediate dominators */
15974 find_immediate_dominators(state, bb);
15975 /* Find the dominance frontiers */
15976 find_block_domf(state, bb->first_block);
15977 /* If debuging print the print what I have just found */
15978 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15979 print_dominators(state, state->dbgout, bb);
15980 print_dominance_frontiers(state, state->dbgout, bb);
15981 print_control_flow(state, state->dbgout, bb);
15986 static void print_ipdominated(
15987 struct compile_state *state, struct block *block, void *arg)
15989 struct block_set *user;
15992 fprintf(fp, "%d:", block->vertex);
15993 for(user = block->ipdominates; user; user = user->next) {
15994 fprintf(fp, " %d", user->member->vertex);
15995 if (user->member->ipdom != block) {
15996 internal_error(state, user->member->first, "bad ipdom");
16002 static void print_ipdominators(struct compile_state *state, FILE *fp,
16003 struct basic_blocks *bb)
16005 fprintf(fp, "\nipdominates\n");
16006 walk_blocks(state, bb, print_ipdominated, fp);
16009 static int print_pfrontiers(
16010 struct compile_state *state, FILE *fp, struct block *block, int vertex)
16012 struct block_set *user;
16014 if (!block || (block->vertex != vertex + 1)) {
16019 fprintf(fp, "%d:", block->vertex);
16020 for(user = block->ipdomfrontier; user; user = user->next) {
16021 fprintf(fp, " %d", user->member->vertex);
16024 for(user = block->use; user; user = user->next) {
16025 vertex = print_pfrontiers(state, fp, user->member, vertex);
16029 static void print_ipdominance_frontiers(struct compile_state *state,
16030 FILE *fp, struct basic_blocks *bb)
16032 fprintf(fp, "\nipdominance frontiers\n");
16033 print_pfrontiers(state, fp, bb->last_block, 0);
16037 static void analyze_ipdominators(struct compile_state *state,
16038 struct basic_blocks *bb)
16040 /* Find the post dominators */
16041 find_post_dominators(state, bb);
16042 /* Find the control dependencies (post dominance frontiers) */
16043 find_block_ipdomf(state, bb->last_block);
16044 /* If debuging print the print what I have just found */
16045 if (state->compiler->debug & DEBUG_RDOMINATORS) {
16046 print_ipdominators(state, state->dbgout, bb);
16047 print_ipdominance_frontiers(state, state->dbgout, bb);
16048 print_control_flow(state, state->dbgout, bb);
16052 static int bdominates(struct compile_state *state,
16053 struct block *dom, struct block *sub)
16055 while(sub && (sub != dom)) {
16061 static int tdominates(struct compile_state *state,
16062 struct triple *dom, struct triple *sub)
16064 struct block *bdom, *bsub;
16066 bdom = block_of_triple(state, dom);
16067 bsub = block_of_triple(state, sub);
16068 if (bdom != bsub) {
16069 result = bdominates(state, bdom, bsub);
16072 struct triple *ins;
16073 if (!bdom || !bsub) {
16074 internal_error(state, dom, "huh?");
16077 while((ins != bsub->first) && (ins != dom)) {
16080 result = (ins == dom);
16085 static void analyze_basic_blocks(
16086 struct compile_state *state, struct basic_blocks *bb)
16088 setup_basic_blocks(state, bb);
16089 analyze_idominators(state, bb);
16090 analyze_ipdominators(state, bb);
16093 static void insert_phi_operations(struct compile_state *state)
16096 struct triple *first;
16097 int *has_already, *work;
16098 struct block *work_list, **work_list_tail;
16100 struct triple *var, *vnext;
16102 size = sizeof(int) * (state->bb.last_vertex + 1);
16103 has_already = xcmalloc(size, "has_already");
16104 work = xcmalloc(size, "work");
16107 first = state->first;
16108 for(var = first->next; var != first ; var = vnext) {
16109 struct block *block;
16110 struct triple_set *user, *unext;
16113 if (!triple_is_auto_var(state, var) || !var->use) {
16119 work_list_tail = &work_list;
16120 for(user = var->use; user; user = unext) {
16121 unext = user->next;
16122 if (MISC(var, 0) == user->member) {
16125 if (user->member->op == OP_READ) {
16128 if (user->member->op != OP_WRITE) {
16129 internal_error(state, user->member,
16130 "bad variable access");
16132 block = user->member->u.block;
16134 warning(state, user->member, "dead code");
16135 release_triple(state, user->member);
16138 if (work[block->vertex] >= iter) {
16141 work[block->vertex] = iter;
16142 *work_list_tail = block;
16143 block->work_next = 0;
16144 work_list_tail = &block->work_next;
16146 for(block = work_list; block; block = block->work_next) {
16147 struct block_set *df;
16148 for(df = block->domfrontier; df; df = df->next) {
16149 struct triple *phi;
16150 struct block *front;
16152 front = df->member;
16154 if (has_already[front->vertex] >= iter) {
16157 /* Count how many edges flow into this block */
16158 in_edges = front->users;
16159 /* Insert a phi function for this variable */
16160 get_occurance(var->occurance);
16161 phi = alloc_triple(
16162 state, OP_PHI, var->type, -1, in_edges,
16164 phi->u.block = front;
16165 MISC(phi, 0) = var;
16166 use_triple(var, phi);
16168 if (phi->rhs != in_edges) {
16169 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16170 phi->rhs, in_edges);
16173 /* Insert the phi functions immediately after the label */
16174 insert_triple(state, front->first->next, phi);
16175 if (front->first == front->last) {
16176 front->last = front->first->next;
16178 has_already[front->vertex] = iter;
16179 transform_to_arch_instruction(state, phi);
16181 /* If necessary plan to visit the basic block */
16182 if (work[front->vertex] >= iter) {
16185 work[front->vertex] = iter;
16186 *work_list_tail = front;
16187 front->work_next = 0;
16188 work_list_tail = &front->work_next;
16192 xfree(has_already);
16198 struct triple_set *top;
16202 static int count_auto_vars(struct compile_state *state)
16204 struct triple *first, *ins;
16206 first = state->first;
16209 if (triple_is_auto_var(state, ins)) {
16213 } while(ins != first);
16217 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16219 struct triple *first, *ins;
16221 first = state->first;
16224 if (triple_is_auto_var(state, ins)) {
16226 stacks[auto_vars].orig_id = ins->id;
16227 ins->id = auto_vars;
16230 } while(ins != first);
16233 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16235 struct triple *first, *ins;
16236 first = state->first;
16239 if (triple_is_auto_var(state, ins)) {
16240 ins->id = stacks[ins->id].orig_id;
16243 } while(ins != first);
16246 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16248 struct triple_set *head;
16249 struct triple *top_val;
16251 head = stacks[var->id].top;
16253 top_val = head->member;
16258 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16260 struct triple_set *new;
16261 /* Append new to the head of the list,
16262 * it's the only sensible behavoir for a stack.
16264 new = xcmalloc(sizeof(*new), "triple_set");
16266 new->next = stacks[var->id].top;
16267 stacks[var->id].top = new;
16270 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16272 struct triple_set *set, **ptr;
16273 ptr = &stacks[var->id].top;
16276 if (set->member == oldval) {
16279 /* Only free one occurance from the stack */
16292 static void fixup_block_phi_variables(
16293 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16295 struct block_set *set;
16296 struct triple *ptr;
16298 if (!parent || !block)
16300 /* Find the edge I am coming in on */
16302 for(set = block->use; set; set = set->next, edge++) {
16303 if (set->member == parent) {
16308 internal_error(state, 0, "phi input is not on a control predecessor");
16310 for(ptr = block->first; ; ptr = ptr->next) {
16311 if (ptr->op == OP_PHI) {
16312 struct triple *var, *val, **slot;
16313 var = MISC(ptr, 0);
16315 internal_error(state, ptr, "no var???");
16317 /* Find the current value of the variable */
16318 val = peek_triple(stacks, var);
16319 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16320 internal_error(state, val, "bad value in phi");
16322 if (edge >= ptr->rhs) {
16323 internal_error(state, ptr, "edges > phi rhs");
16325 slot = &RHS(ptr, edge);
16326 if ((*slot != 0) && (*slot != val)) {
16327 internal_error(state, ptr, "phi already bound on this edge");
16330 use_triple(val, ptr);
16332 if (ptr == block->last) {
16339 static void rename_block_variables(
16340 struct compile_state *state, struct stack *stacks, struct block *block)
16342 struct block_set *user, *edge;
16343 struct triple *ptr, *next, *last;
16347 last = block->first;
16349 for(ptr = block->first; !done; ptr = next) {
16351 if (ptr == block->last) {
16355 if (ptr->op == OP_READ) {
16356 struct triple *var, *val;
16358 if (!triple_is_auto_var(state, var)) {
16359 internal_error(state, ptr, "read of non auto var!");
16361 unuse_triple(var, ptr);
16362 /* Find the current value of the variable */
16363 val = peek_triple(stacks, var);
16365 /* Let the optimizer at variables that are not initially
16366 * set. But give it a bogus value so things seem to
16367 * work by accident. This is useful for bitfields because
16368 * setting them always involves a read-modify-write.
16370 if (TYPE_ARITHMETIC(ptr->type->type)) {
16371 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16372 val->u.cval = 0xdeadbeaf;
16374 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16378 error(state, ptr, "variable used without being set");
16380 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16381 internal_error(state, val, "bad value in read");
16383 propogate_use(state, ptr, val);
16384 release_triple(state, ptr);
16388 if (ptr->op == OP_WRITE) {
16389 struct triple *var, *val, *tval;
16390 var = MISC(ptr, 0);
16391 if (!triple_is_auto_var(state, var)) {
16392 internal_error(state, ptr, "write to non auto var!");
16394 tval = val = RHS(ptr, 0);
16395 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16396 triple_is_auto_var(state, val)) {
16397 internal_error(state, ptr, "bad value in write");
16399 /* Insert a cast if the types differ */
16400 if (!is_subset_type(ptr->type, val->type)) {
16401 if (val->op == OP_INTCONST) {
16402 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16403 tval->u.cval = val->u.cval;
16406 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16407 use_triple(val, tval);
16409 transform_to_arch_instruction(state, tval);
16410 unuse_triple(val, ptr);
16411 RHS(ptr, 0) = tval;
16412 use_triple(tval, ptr);
16414 propogate_use(state, ptr, tval);
16415 unuse_triple(var, ptr);
16416 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16417 push_triple(stacks, var, tval);
16419 if (ptr->op == OP_PHI) {
16420 struct triple *var;
16421 var = MISC(ptr, 0);
16422 if (!triple_is_auto_var(state, var)) {
16423 internal_error(state, ptr, "phi references non auto var!");
16425 /* Push OP_PHI onto a stack of variable uses */
16426 push_triple(stacks, var, ptr);
16430 block->last = last;
16432 /* Fixup PHI functions in the cf successors */
16433 for(edge = block->edges; edge; edge = edge->next) {
16434 fixup_block_phi_variables(state, stacks, block, edge->member);
16436 /* rename variables in the dominated nodes */
16437 for(user = block->idominates; user; user = user->next) {
16438 rename_block_variables(state, stacks, user->member);
16440 /* pop the renamed variable stack */
16441 last = block->first;
16443 for(ptr = block->first; !done ; ptr = next) {
16445 if (ptr == block->last) {
16448 if (ptr->op == OP_WRITE) {
16449 struct triple *var;
16450 var = MISC(ptr, 0);
16451 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16452 pop_triple(stacks, var, RHS(ptr, 0));
16453 release_triple(state, ptr);
16456 if (ptr->op == OP_PHI) {
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, ptr);
16464 block->last = last;
16467 static void rename_variables(struct compile_state *state)
16469 struct stack *stacks;
16472 /* Allocate stacks for the Variables */
16473 auto_vars = count_auto_vars(state);
16474 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16476 /* Give each auto_var a stack */
16477 number_auto_vars(state, stacks);
16479 /* Rename the variables */
16480 rename_block_variables(state, stacks, state->bb.first_block);
16482 /* Remove the stacks from the auto_vars */
16483 restore_auto_vars(state, stacks);
16487 static void prune_block_variables(struct compile_state *state,
16488 struct block *block)
16490 struct block_set *user;
16491 struct triple *next, *ptr;
16495 for(ptr = block->first; !done; ptr = next) {
16496 /* Be extremely careful I am deleting the list
16497 * as I walk trhough it.
16500 if (ptr == block->last) {
16503 if (triple_is_auto_var(state, ptr)) {
16504 struct triple_set *user, *next;
16505 for(user = ptr->use; user; user = next) {
16506 struct triple *use;
16508 use = user->member;
16509 if (MISC(ptr, 0) == user->member) {
16512 if (use->op != OP_PHI) {
16513 internal_error(state, use, "decl still used");
16515 if (MISC(use, 0) != ptr) {
16516 internal_error(state, use, "bad phi use of decl");
16518 unuse_triple(ptr, use);
16521 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16522 /* Delete the adecl */
16523 release_triple(state, MISC(ptr, 0));
16524 /* And the piece */
16525 release_triple(state, ptr);
16530 for(user = block->idominates; user; user = user->next) {
16531 prune_block_variables(state, user->member);
16535 struct phi_triple {
16536 struct triple *phi;
16541 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16543 struct triple **slot;
16545 if (live[phi->id].alive) {
16548 live[phi->id].alive = 1;
16550 slot = &RHS(phi, 0);
16551 for(i = 0; i < zrhs; i++) {
16552 struct triple *used;
16554 if (used && (used->op == OP_PHI)) {
16555 keep_phi(state, live, used);
16560 static void prune_unused_phis(struct compile_state *state)
16562 struct triple *first, *phi;
16563 struct phi_triple *live;
16566 /* Find the first instruction */
16567 first = state->first;
16569 /* Count how many phi functions I need to process */
16571 for(phi = first->next; phi != first; phi = phi->next) {
16572 if (phi->op == OP_PHI) {
16577 /* Mark them all dead */
16578 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16580 for(phi = first->next; phi != first; phi = phi->next) {
16581 if (phi->op != OP_PHI) {
16584 live[phis].alive = 0;
16585 live[phis].orig_id = phi->id;
16586 live[phis].phi = phi;
16591 /* Mark phis alive that are used by non phis */
16592 for(i = 0; i < phis; i++) {
16593 struct triple_set *set;
16594 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16595 if (set->member->op != OP_PHI) {
16596 keep_phi(state, live, live[i].phi);
16602 /* Delete the extraneous phis */
16603 for(i = 0; i < phis; i++) {
16604 struct triple **slot;
16606 if (!live[i].alive) {
16607 release_triple(state, live[i].phi);
16611 slot = &RHS(phi, 0);
16613 for(j = 0; j < zrhs; j++) {
16615 struct triple *unknown;
16616 get_occurance(phi->occurance);
16617 unknown = flatten(state, state->global_pool,
16618 alloc_triple(state, OP_UNKNOWNVAL,
16619 phi->type, 0, 0, phi->occurance));
16621 use_triple(unknown, phi);
16622 transform_to_arch_instruction(state, unknown);
16624 warning(state, phi, "variable not set at index %d on all paths to use", j);
16632 static void transform_to_ssa_form(struct compile_state *state)
16634 insert_phi_operations(state);
16635 rename_variables(state);
16637 prune_block_variables(state, state->bb.first_block);
16638 prune_unused_phis(state);
16640 print_blocks(state, __func__, state->dbgout);
16644 static void clear_vertex(
16645 struct compile_state *state, struct block *block, void *arg)
16647 /* Clear the current blocks vertex and the vertex of all
16648 * of the current blocks neighbors in case there are malformed
16649 * blocks with now instructions at this point.
16651 struct block_set *user, *edge;
16653 for(edge = block->edges; edge; edge = edge->next) {
16654 edge->member->vertex = 0;
16656 for(user = block->use; user; user = user->next) {
16657 user->member->vertex = 0;
16661 static void mark_live_block(
16662 struct compile_state *state, struct block *block, int *next_vertex)
16664 /* See if this is a block that has not been marked */
16665 if (block->vertex != 0) {
16668 block->vertex = *next_vertex;
16670 if (triple_is_branch(state, block->last)) {
16671 struct triple **targ;
16672 targ = triple_edge_targ(state, block->last, 0);
16673 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16677 if (!triple_stores_block(state, *targ)) {
16678 internal_error(state, 0, "bad targ");
16680 mark_live_block(state, (*targ)->u.block, next_vertex);
16682 /* Ensure the last block of a function remains alive */
16683 if (triple_is_call(state, block->last)) {
16684 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16687 else if (block->last->next != state->first) {
16688 struct triple *ins;
16689 ins = block->last->next;
16690 if (!triple_stores_block(state, ins)) {
16691 internal_error(state, 0, "bad block start");
16693 mark_live_block(state, ins->u.block, next_vertex);
16697 static void transform_from_ssa_form(struct compile_state *state)
16699 /* To get out of ssa form we insert moves on the incoming
16700 * edges to blocks containting phi functions.
16702 struct triple *first;
16703 struct triple *phi, *var, *next;
16706 /* Walk the control flow to see which blocks remain alive */
16707 walk_blocks(state, &state->bb, clear_vertex, 0);
16709 mark_live_block(state, state->bb.first_block, &next_vertex);
16711 /* Walk all of the operations to find the phi functions */
16712 first = state->first;
16713 for(phi = first->next; phi != first ; phi = next) {
16714 struct block_set *set;
16715 struct block *block;
16716 struct triple **slot;
16717 struct triple *var;
16718 struct triple_set *use, *use_next;
16719 int edge, writers, readers;
16721 if (phi->op != OP_PHI) {
16725 block = phi->u.block;
16726 slot = &RHS(phi, 0);
16728 /* If this phi is in a dead block just forget it */
16729 if (block->vertex == 0) {
16730 release_triple(state, phi);
16734 /* Forget uses from code in dead blocks */
16735 for(use = phi->use; use; use = use_next) {
16736 struct block *ublock;
16737 struct triple **expr;
16738 use_next = use->next;
16739 ublock = block_of_triple(state, use->member);
16740 if ((use->member == phi) || (ublock->vertex != 0)) {
16743 expr = triple_rhs(state, use->member, 0);
16744 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16745 if (*expr == phi) {
16749 unuse_triple(phi, use->member);
16751 /* A variable to replace the phi function */
16752 if (registers_of(state, phi->type) != 1) {
16753 internal_error(state, phi, "phi->type does not fit in a single register!");
16755 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16756 var = var->next; /* point at the var */
16758 /* Replaces use of phi with var */
16759 propogate_use(state, phi, var);
16761 /* Count the readers */
16763 for(use = var->use; use; use = use->next) {
16764 if (use->member != MISC(var, 0)) {
16769 /* Walk all of the incoming edges/blocks and insert moves.
16772 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16773 struct block *eblock, *vblock;
16774 struct triple *move;
16775 struct triple *val, *base;
16776 eblock = set->member;
16779 unuse_triple(val, phi);
16780 vblock = block_of_triple(state, val);
16782 /* If we don't have a value that belongs in an OP_WRITE
16785 if (!val || (val == &unknown_triple) || (val == phi)
16786 || (vblock && (vblock->vertex == 0))) {
16789 /* If the value should never occur error */
16791 internal_error(state, val, "no vblock?");
16795 /* If the value occurs in a dead block see if a replacement
16796 * block can be found.
16798 while(eblock && (eblock->vertex == 0)) {
16799 eblock = eblock->idom;
16801 /* If not continue on with the next value. */
16802 if (!eblock || (eblock->vertex == 0)) {
16806 /* If we have an empty incoming block ignore it. */
16807 if (!eblock->first) {
16808 internal_error(state, 0, "empty block?");
16811 /* Make certain the write is placed in the edge block... */
16812 /* Walk through the edge block backwards to find an
16813 * appropriate location for the OP_WRITE.
16815 for(base = eblock->last; base != eblock->first; base = base->prev) {
16816 struct triple **expr;
16817 if (base->op == OP_PIECE) {
16818 base = MISC(base, 0);
16820 if ((base == var) || (base == val)) {
16823 expr = triple_lhs(state, base, 0);
16824 for(; expr; expr = triple_lhs(state, base, expr)) {
16825 if ((*expr) == val) {
16829 expr = triple_rhs(state, base, 0);
16830 for(; expr; expr = triple_rhs(state, base, expr)) {
16831 if ((*expr) == var) {
16837 if (triple_is_branch(state, base)) {
16838 internal_error(state, base,
16839 "Could not insert write to phi");
16841 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16842 use_triple(val, move);
16843 use_triple(var, move);
16846 if (!writers && readers) {
16847 internal_error(state, var, "no value written to in use phi?");
16849 /* If var is not used free it */
16851 release_triple(state, MISC(var, 0));
16852 release_triple(state, var);
16854 /* Release the phi function */
16855 release_triple(state, phi);
16858 /* Walk all of the operations to find the adecls */
16859 for(var = first->next; var != first ; var = var->next) {
16860 struct triple_set *use, *use_next;
16861 if (!triple_is_auto_var(state, var)) {
16865 /* Walk through all of the rhs uses of var and
16866 * replace them with read of var.
16868 for(use = var->use; use; use = use_next) {
16869 struct triple *read, *user;
16870 struct triple **slot;
16872 use_next = use->next;
16873 user = use->member;
16875 /* Generate a read of var */
16876 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16877 use_triple(var, read);
16879 /* Find the rhs uses and see if they need to be replaced */
16882 slot = &RHS(user, 0);
16883 for(i = 0; i < zrhs; i++) {
16884 if (slot[i] == var) {
16889 /* If we did use it cleanup the uses */
16891 unuse_triple(var, user);
16892 use_triple(read, user);
16894 /* If we didn't use it release the extra triple */
16896 release_triple(state, read);
16902 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16903 FILE *fp = state->dbgout; \
16904 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16907 static void rebuild_ssa_form(struct compile_state *state)
16910 transform_from_ssa_form(state);
16912 state->bb.first = state->first;
16913 free_basic_blocks(state, &state->bb);
16914 analyze_basic_blocks(state, &state->bb);
16916 insert_phi_operations(state);
16918 rename_variables(state);
16921 prune_block_variables(state, state->bb.first_block);
16923 prune_unused_phis(state);
16929 * Register conflict resolution
16930 * =========================================================
16933 static struct reg_info find_def_color(
16934 struct compile_state *state, struct triple *def)
16936 struct triple_set *set;
16937 struct reg_info info;
16938 info.reg = REG_UNSET;
16940 if (!triple_is_def(state, def)) {
16943 info = arch_reg_lhs(state, def, 0);
16944 if (info.reg >= MAX_REGISTERS) {
16945 info.reg = REG_UNSET;
16947 for(set = def->use; set; set = set->next) {
16948 struct reg_info tinfo;
16950 i = find_rhs_use(state, set->member, def);
16954 tinfo = arch_reg_rhs(state, set->member, i);
16955 if (tinfo.reg >= MAX_REGISTERS) {
16956 tinfo.reg = REG_UNSET;
16958 if ((tinfo.reg != REG_UNSET) &&
16959 (info.reg != REG_UNSET) &&
16960 (tinfo.reg != info.reg)) {
16961 internal_error(state, def, "register conflict");
16963 if ((info.regcm & tinfo.regcm) == 0) {
16964 internal_error(state, def, "regcm conflict %x & %x == 0",
16965 info.regcm, tinfo.regcm);
16967 if (info.reg == REG_UNSET) {
16968 info.reg = tinfo.reg;
16970 info.regcm &= tinfo.regcm;
16972 if (info.reg >= MAX_REGISTERS) {
16973 internal_error(state, def, "register out of range");
16978 static struct reg_info find_lhs_pre_color(
16979 struct compile_state *state, struct triple *ins, int index)
16981 struct reg_info info;
16985 if (!zlhs && triple_is_def(state, ins)) {
16988 if (index >= zlhs) {
16989 internal_error(state, ins, "Bad lhs %d", index);
16991 info = arch_reg_lhs(state, ins, index);
16992 for(i = 0; i < zrhs; i++) {
16993 struct reg_info rinfo;
16994 rinfo = arch_reg_rhs(state, ins, i);
16995 if ((info.reg == rinfo.reg) &&
16996 (rinfo.reg >= MAX_REGISTERS)) {
16997 struct reg_info tinfo;
16998 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
16999 info.reg = tinfo.reg;
17000 info.regcm &= tinfo.regcm;
17004 if (info.reg >= MAX_REGISTERS) {
17005 info.reg = REG_UNSET;
17010 static struct reg_info find_rhs_post_color(
17011 struct compile_state *state, struct triple *ins, int index);
17013 static struct reg_info find_lhs_post_color(
17014 struct compile_state *state, struct triple *ins, int index)
17016 struct triple_set *set;
17017 struct reg_info info;
17018 struct triple *lhs;
17019 #if DEBUG_TRIPLE_COLOR
17020 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17023 if ((index == 0) && triple_is_def(state, ins)) {
17026 else if (index < ins->lhs) {
17027 lhs = LHS(ins, index);
17030 internal_error(state, ins, "Bad lhs %d", index);
17033 info = arch_reg_lhs(state, ins, index);
17034 if (info.reg >= MAX_REGISTERS) {
17035 info.reg = REG_UNSET;
17037 for(set = lhs->use; set; set = set->next) {
17038 struct reg_info rinfo;
17039 struct triple *user;
17041 user = set->member;
17043 for(i = 0; i < zrhs; i++) {
17044 if (RHS(user, i) != lhs) {
17047 rinfo = find_rhs_post_color(state, user, i);
17048 if ((info.reg != REG_UNSET) &&
17049 (rinfo.reg != REG_UNSET) &&
17050 (info.reg != rinfo.reg)) {
17051 internal_error(state, ins, "register conflict");
17053 if ((info.regcm & rinfo.regcm) == 0) {
17054 internal_error(state, ins, "regcm conflict %x & %x == 0",
17055 info.regcm, rinfo.regcm);
17057 if (info.reg == REG_UNSET) {
17058 info.reg = rinfo.reg;
17060 info.regcm &= rinfo.regcm;
17063 #if DEBUG_TRIPLE_COLOR
17064 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17065 ins, index, info.reg, info.regcm);
17070 static struct reg_info find_rhs_post_color(
17071 struct compile_state *state, struct triple *ins, int index)
17073 struct reg_info info, rinfo;
17075 #if DEBUG_TRIPLE_COLOR
17076 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17079 rinfo = arch_reg_rhs(state, ins, index);
17081 if (!zlhs && triple_is_def(state, ins)) {
17085 if (info.reg >= MAX_REGISTERS) {
17086 info.reg = REG_UNSET;
17088 for(i = 0; i < zlhs; i++) {
17089 struct reg_info linfo;
17090 linfo = arch_reg_lhs(state, ins, i);
17091 if ((linfo.reg == rinfo.reg) &&
17092 (linfo.reg >= MAX_REGISTERS)) {
17093 struct reg_info tinfo;
17094 tinfo = find_lhs_post_color(state, ins, i);
17095 if (tinfo.reg >= MAX_REGISTERS) {
17096 tinfo.reg = REG_UNSET;
17098 info.regcm &= linfo.regcm;
17099 info.regcm &= tinfo.regcm;
17100 if (info.reg != REG_UNSET) {
17101 internal_error(state, ins, "register conflict");
17103 if (info.regcm == 0) {
17104 internal_error(state, ins, "regcm conflict");
17106 info.reg = tinfo.reg;
17109 #if DEBUG_TRIPLE_COLOR
17110 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17111 ins, index, info.reg, info.regcm);
17116 static struct reg_info find_lhs_color(
17117 struct compile_state *state, struct triple *ins, int index)
17119 struct reg_info pre, post, info;
17120 #if DEBUG_TRIPLE_COLOR
17121 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17124 pre = find_lhs_pre_color(state, ins, index);
17125 post = find_lhs_post_color(state, ins, index);
17126 if ((pre.reg != post.reg) &&
17127 (pre.reg != REG_UNSET) &&
17128 (post.reg != REG_UNSET)) {
17129 internal_error(state, ins, "register conflict");
17131 info.regcm = pre.regcm & post.regcm;
17132 info.reg = pre.reg;
17133 if (info.reg == REG_UNSET) {
17134 info.reg = post.reg;
17136 #if DEBUG_TRIPLE_COLOR
17137 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17138 ins, index, info.reg, info.regcm,
17139 pre.reg, pre.regcm, post.reg, post.regcm);
17144 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17146 struct triple_set *entry, *next;
17147 struct triple *out;
17148 struct reg_info info, rinfo;
17150 info = arch_reg_lhs(state, ins, 0);
17151 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17152 use_triple(RHS(out, 0), out);
17153 /* Get the users of ins to use out instead */
17154 for(entry = ins->use; entry; entry = next) {
17156 next = entry->next;
17157 if (entry->member == out) {
17160 i = find_rhs_use(state, entry->member, ins);
17164 rinfo = arch_reg_rhs(state, entry->member, i);
17165 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17168 replace_rhs_use(state, ins, out, entry->member);
17170 transform_to_arch_instruction(state, out);
17174 static struct triple *typed_pre_copy(
17175 struct compile_state *state, struct type *type, struct triple *ins, int index)
17177 /* Carefully insert enough operations so that I can
17178 * enter any operation with a GPR32.
17181 struct triple **expr;
17183 struct reg_info info;
17185 if (ins->op == OP_PHI) {
17186 internal_error(state, ins, "pre_copy on a phi?");
17188 classes = arch_type_to_regcm(state, type);
17189 info = arch_reg_rhs(state, ins, index);
17190 expr = &RHS(ins, index);
17191 if ((info.regcm & classes) == 0) {
17192 FILE *fp = state->errout;
17193 fprintf(fp, "src_type: ");
17194 name_of(fp, ins->type);
17195 fprintf(fp, "\ndst_type: ");
17198 internal_error(state, ins, "pre_copy with no register classes");
17201 if (!equiv_types(type, (*expr)->type)) {
17204 in = pre_triple(state, ins, op, type, *expr, 0);
17205 unuse_triple(*expr, ins);
17207 use_triple(RHS(in, 0), in);
17208 use_triple(in, ins);
17209 transform_to_arch_instruction(state, in);
17213 static struct triple *pre_copy(
17214 struct compile_state *state, struct triple *ins, int index)
17216 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17220 static void insert_copies_to_phi(struct compile_state *state)
17222 /* To get out of ssa form we insert moves on the incoming
17223 * edges to blocks containting phi functions.
17225 struct triple *first;
17226 struct triple *phi;
17228 /* Walk all of the operations to find the phi functions */
17229 first = state->first;
17230 for(phi = first->next; phi != first ; phi = phi->next) {
17231 struct block_set *set;
17232 struct block *block;
17233 struct triple **slot, *copy;
17235 if (phi->op != OP_PHI) {
17238 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17239 block = phi->u.block;
17240 slot = &RHS(phi, 0);
17241 /* Phi's that feed into mandatory live range joins
17242 * cause nasty complications. Insert a copy of
17243 * the phi value so I never have to deal with
17244 * that in the rest of the code.
17246 copy = post_copy(state, phi);
17247 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17248 /* Walk all of the incoming edges/blocks and insert moves.
17250 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17251 struct block *eblock;
17252 struct triple *move;
17253 struct triple *val;
17254 struct triple *ptr;
17255 eblock = set->member;
17262 get_occurance(val->occurance);
17263 move = build_triple(state, OP_COPY, val->type, val, 0,
17265 move->u.block = eblock;
17266 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17267 use_triple(val, move);
17270 unuse_triple(val, phi);
17271 use_triple(move, phi);
17273 /* Walk up the dominator tree until I have found the appropriate block */
17274 while(eblock && !tdominates(state, val, eblock->last)) {
17275 eblock = eblock->idom;
17278 internal_error(state, phi, "Cannot find block dominated by %p",
17282 /* Walk through the block backwards to find
17283 * an appropriate location for the OP_COPY.
17285 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17286 struct triple **expr;
17287 if (ptr->op == OP_PIECE) {
17288 ptr = MISC(ptr, 0);
17290 if ((ptr == phi) || (ptr == val)) {
17293 expr = triple_lhs(state, ptr, 0);
17294 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17295 if ((*expr) == val) {
17299 expr = triple_rhs(state, ptr, 0);
17300 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17301 if ((*expr) == phi) {
17307 if (triple_is_branch(state, ptr)) {
17308 internal_error(state, ptr,
17309 "Could not insert write to phi");
17311 insert_triple(state, after_lhs(state, ptr), move);
17312 if (eblock->last == after_lhs(state, ptr)->prev) {
17313 eblock->last = move;
17315 transform_to_arch_instruction(state, move);
17318 print_blocks(state, __func__, state->dbgout);
17321 struct triple_reg_set;
17325 static int do_triple_set(struct triple_reg_set **head,
17326 struct triple *member, struct triple *new_member)
17328 struct triple_reg_set **ptr, *new;
17333 if ((*ptr)->member == member) {
17336 ptr = &(*ptr)->next;
17338 new = xcmalloc(sizeof(*new), "triple_set");
17339 new->member = member;
17340 new->new = new_member;
17346 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17348 struct triple_reg_set *entry, **ptr;
17352 if (entry->member == member) {
17353 *ptr = entry->next;
17358 ptr = &entry->next;
17363 static int in_triple(struct reg_block *rb, struct triple *in)
17365 return do_triple_set(&rb->in, in, 0);
17368 #if DEBUG_ROMCC_WARNING
17369 static void unin_triple(struct reg_block *rb, struct triple *unin)
17371 do_triple_unset(&rb->in, unin);
17375 static int out_triple(struct reg_block *rb, struct triple *out)
17377 return do_triple_set(&rb->out, out, 0);
17379 #if DEBUG_ROMCC_WARNING
17380 static void unout_triple(struct reg_block *rb, struct triple *unout)
17382 do_triple_unset(&rb->out, unout);
17386 static int initialize_regblock(struct reg_block *blocks,
17387 struct block *block, int vertex)
17389 struct block_set *user;
17390 if (!block || (blocks[block->vertex].block == block)) {
17394 /* Renumber the blocks in a convinient fashion */
17395 block->vertex = vertex;
17396 blocks[vertex].block = block;
17397 blocks[vertex].vertex = vertex;
17398 for(user = block->use; user; user = user->next) {
17399 vertex = initialize_regblock(blocks, user->member, vertex);
17404 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17406 /* Part to piece is a best attempt and it cannot be correct all by
17407 * itself. If various values are read as different sizes in different
17408 * parts of the code this function cannot work. Or rather it cannot
17409 * work in conjunction with compute_variable_liftimes. As the
17410 * analysis will get confused.
17412 struct triple *base;
17414 if (!is_lvalue(state, ins)) {
17419 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17420 base = MISC(ins, 0);
17423 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17426 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17429 internal_error(state, ins, "unhandled part");
17435 if (reg > base->lhs) {
17436 internal_error(state, base, "part out of range?");
17438 ins = LHS(base, reg);
17443 static int this_def(struct compile_state *state,
17444 struct triple *ins, struct triple *other)
17446 if (ins == other) {
17449 if (ins->op == OP_WRITE) {
17450 ins = part_to_piece(state, MISC(ins, 0));
17452 return ins == other;
17455 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17456 struct reg_block *rb, struct block *suc)
17458 /* Read the conditional input set of a successor block
17459 * (i.e. the input to the phi nodes) and place it in the
17460 * current blocks output set.
17462 struct block_set *set;
17463 struct triple *ptr;
17467 /* Find the edge I am coming in on */
17468 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17469 if (set->member == rb->block) {
17474 internal_error(state, 0, "Not coming on a control edge?");
17476 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17477 struct triple **slot, *expr, *ptr2;
17478 int out_change, done2;
17479 done = (ptr == suc->last);
17480 if (ptr->op != OP_PHI) {
17483 slot = &RHS(ptr, 0);
17485 out_change = out_triple(rb, expr);
17489 /* If we don't define the variable also plast it
17490 * in the current blocks input set.
17492 ptr2 = rb->block->first;
17493 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17494 if (this_def(state, ptr2, expr)) {
17497 done2 = (ptr2 == rb->block->last);
17502 change |= in_triple(rb, expr);
17507 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17508 struct reg_block *rb, struct block *suc)
17510 struct triple_reg_set *in_set;
17513 /* Read the input set of a successor block
17514 * and place it in the current blocks output set.
17516 in_set = blocks[suc->vertex].in;
17517 for(; in_set; in_set = in_set->next) {
17518 int out_change, done;
17519 struct triple *first, *last, *ptr;
17520 out_change = out_triple(rb, in_set->member);
17524 /* If we don't define the variable also place it
17525 * in the current blocks input set.
17527 first = rb->block->first;
17528 last = rb->block->last;
17530 for(ptr = first; !done; ptr = ptr->next) {
17531 if (this_def(state, ptr, in_set->member)) {
17534 done = (ptr == last);
17539 change |= in_triple(rb, in_set->member);
17541 change |= phi_in(state, blocks, rb, suc);
17545 static int use_in(struct compile_state *state, struct reg_block *rb)
17547 /* Find the variables we use but don't define and add
17548 * it to the current blocks input set.
17550 #if DEBUG_ROMCC_WARNINGS
17551 #warning "FIXME is this O(N^2) algorithm bad?"
17553 struct block *block;
17554 struct triple *ptr;
17559 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17560 struct triple **expr;
17561 done = (ptr == block->first);
17562 /* The variable a phi function uses depends on the
17563 * control flow, and is handled in phi_in, not
17566 if (ptr->op == OP_PHI) {
17569 expr = triple_rhs(state, ptr, 0);
17570 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17571 struct triple *rhs, *test;
17573 rhs = part_to_piece(state, *expr);
17578 /* See if rhs is defined in this block.
17579 * A write counts as a definition.
17581 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17582 tdone = (test == block->first);
17583 if (this_def(state, test, rhs)) {
17588 /* If I still have a valid rhs add it to in */
17589 change |= in_triple(rb, rhs);
17595 static struct reg_block *compute_variable_lifetimes(
17596 struct compile_state *state, struct basic_blocks *bb)
17598 struct reg_block *blocks;
17601 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17602 initialize_regblock(blocks, bb->last_block, 0);
17606 for(i = 1; i <= bb->last_vertex; i++) {
17607 struct block_set *edge;
17608 struct reg_block *rb;
17610 /* Add the all successor's input set to in */
17611 for(edge = rb->block->edges; edge; edge = edge->next) {
17612 change |= reg_in(state, blocks, rb, edge->member);
17614 /* Add use to in... */
17615 change |= use_in(state, rb);
17621 static void free_variable_lifetimes(struct compile_state *state,
17622 struct basic_blocks *bb, struct reg_block *blocks)
17625 /* free in_set && out_set on each block */
17626 for(i = 1; i <= bb->last_vertex; i++) {
17627 struct triple_reg_set *entry, *next;
17628 struct reg_block *rb;
17630 for(entry = rb->in; entry ; entry = next) {
17631 next = entry->next;
17632 do_triple_unset(&rb->in, entry->member);
17634 for(entry = rb->out; entry; entry = next) {
17635 next = entry->next;
17636 do_triple_unset(&rb->out, entry->member);
17643 typedef void (*wvl_cb_t)(
17644 struct compile_state *state,
17645 struct reg_block *blocks, struct triple_reg_set *live,
17646 struct reg_block *rb, struct triple *ins, void *arg);
17648 static void walk_variable_lifetimes(struct compile_state *state,
17649 struct basic_blocks *bb, struct reg_block *blocks,
17650 wvl_cb_t cb, void *arg)
17654 for(i = 1; i <= state->bb.last_vertex; i++) {
17655 struct triple_reg_set *live;
17656 struct triple_reg_set *entry, *next;
17657 struct triple *ptr, *prev;
17658 struct reg_block *rb;
17659 struct block *block;
17662 /* Get the blocks */
17666 /* Copy out into live */
17668 for(entry = rb->out; entry; entry = next) {
17669 next = entry->next;
17670 do_triple_set(&live, entry->member, entry->new);
17672 /* Walk through the basic block calculating live */
17673 for(done = 0, ptr = block->last; !done; ptr = prev) {
17674 struct triple **expr;
17677 done = (ptr == block->first);
17679 /* Ensure the current definition is in live */
17680 if (triple_is_def(state, ptr)) {
17681 do_triple_set(&live, ptr, 0);
17684 /* Inform the callback function of what is
17687 cb(state, blocks, live, rb, ptr, arg);
17689 /* Remove the current definition from live */
17690 do_triple_unset(&live, ptr);
17692 /* Add the current uses to live.
17694 * It is safe to skip phi functions because they do
17695 * not have any block local uses, and the block
17696 * output sets already properly account for what
17697 * control flow depedent uses phi functions do have.
17699 if (ptr->op == OP_PHI) {
17702 expr = triple_rhs(state, ptr, 0);
17703 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17704 /* If the triple is not a definition skip it. */
17705 if (!*expr || !triple_is_def(state, *expr)) {
17708 do_triple_set(&live, *expr, 0);
17712 for(entry = live; entry; entry = next) {
17713 next = entry->next;
17714 do_triple_unset(&live, entry->member);
17719 struct print_live_variable_info {
17720 struct reg_block *rb;
17723 #if DEBUG_EXPLICIT_CLOSURES
17724 static void print_live_variables_block(
17725 struct compile_state *state, struct block *block, void *arg)
17728 struct print_live_variable_info *info = arg;
17729 struct block_set *edge;
17730 FILE *fp = info->fp;
17731 struct reg_block *rb;
17732 struct triple *ptr;
17735 rb = &info->rb[block->vertex];
17737 fprintf(fp, "\nblock: %p (%d),",
17738 block, block->vertex);
17739 for(edge = block->edges; edge; edge = edge->next) {
17740 fprintf(fp, " %p<-%p",
17742 edge->member && edge->member->use?edge->member->use->member : 0);
17746 struct triple_reg_set *in_set;
17747 fprintf(fp, " in:");
17748 for(in_set = rb->in; in_set; in_set = in_set->next) {
17749 fprintf(fp, " %-10p", in_set->member);
17754 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17755 done = (ptr == block->last);
17756 if (ptr->op == OP_PHI) {
17763 for(edge = 0; edge < block->users; edge++) {
17764 fprintf(fp, " in(%d):", edge);
17765 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17766 struct triple **slot;
17767 done = (ptr == block->last);
17768 if (ptr->op != OP_PHI) {
17771 slot = &RHS(ptr, 0);
17772 fprintf(fp, " %-10p", slot[edge]);
17777 if (block->first->op == OP_LABEL) {
17778 fprintf(fp, "%p:\n", block->first);
17780 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17781 done = (ptr == block->last);
17782 display_triple(fp, ptr);
17785 struct triple_reg_set *out_set;
17786 fprintf(fp, " out:");
17787 for(out_set = rb->out; out_set; out_set = out_set->next) {
17788 fprintf(fp, " %-10p", out_set->member);
17795 static void print_live_variables(struct compile_state *state,
17796 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17798 struct print_live_variable_info info;
17801 fprintf(fp, "\nlive variables by block\n");
17802 walk_blocks(state, bb, print_live_variables_block, &info);
17807 static int count_triples(struct compile_state *state)
17809 struct triple *first, *ins;
17811 first = state->first;
17816 } while (ins != first);
17821 struct dead_triple {
17822 struct triple *triple;
17823 struct dead_triple *work_next;
17824 struct block *block;
17827 #define TRIPLE_FLAG_ALIVE 1
17828 #define TRIPLE_FLAG_FREE 1
17831 static void print_dead_triples(struct compile_state *state,
17832 struct dead_triple *dtriple)
17834 struct triple *first, *ins;
17835 struct dead_triple *dt;
17837 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17840 fp = state->dbgout;
17841 fprintf(fp, "--------------- dtriples ---------------\n");
17842 first = state->first;
17845 dt = &dtriple[ins->id];
17846 if ((ins->op == OP_LABEL) && (ins->use)) {
17847 fprintf(fp, "\n%p:\n", ins);
17850 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17851 display_triple(fp, ins);
17852 if (triple_is_branch(state, ins)) {
17856 } while(ins != first);
17861 static void awaken(
17862 struct compile_state *state,
17863 struct dead_triple *dtriple, struct triple **expr,
17864 struct dead_triple ***work_list_tail)
17866 struct triple *triple;
17867 struct dead_triple *dt;
17875 if (triple->id <= 0) {
17876 internal_error(state, triple, "bad triple id: %d",
17879 if (triple->op == OP_NOOP) {
17880 internal_error(state, triple, "awakening noop?");
17883 dt = &dtriple[triple->id];
17884 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17885 dt->flags |= TRIPLE_FLAG_ALIVE;
17886 if (!dt->work_next) {
17887 **work_list_tail = dt;
17888 *work_list_tail = &dt->work_next;
17893 static void eliminate_inefectual_code(struct compile_state *state)
17895 struct block *block;
17896 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17898 struct triple *first, *final, *ins;
17900 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17904 /* Setup the work list */
17906 work_list_tail = &work_list;
17908 first = state->first;
17909 final = state->first->prev;
17911 /* Count how many triples I have */
17912 triples = count_triples(state);
17914 /* Now put then in an array and mark all of the triples dead */
17915 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17921 dtriple[i].triple = ins;
17922 dtriple[i].block = block_of_triple(state, ins);
17923 dtriple[i].flags = 0;
17924 dtriple[i].old_id = ins->id;
17926 /* See if it is an operation we always keep */
17927 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17928 awaken(state, dtriple, &ins, &work_list_tail);
17932 } while(ins != first);
17934 struct block *block;
17935 struct dead_triple *dt;
17936 struct block_set *user;
17937 struct triple **expr;
17939 work_list = dt->work_next;
17941 work_list_tail = &work_list;
17943 /* Make certain the block the current instruction is in lives */
17944 block = block_of_triple(state, dt->triple);
17945 awaken(state, dtriple, &block->first, &work_list_tail);
17946 if (triple_is_branch(state, block->last)) {
17947 awaken(state, dtriple, &block->last, &work_list_tail);
17949 awaken(state, dtriple, &block->last->next, &work_list_tail);
17952 /* Wake up the data depencencies of this triple */
17955 expr = triple_rhs(state, dt->triple, expr);
17956 awaken(state, dtriple, expr, &work_list_tail);
17959 expr = triple_lhs(state, dt->triple, expr);
17960 awaken(state, dtriple, expr, &work_list_tail);
17963 expr = triple_misc(state, dt->triple, expr);
17964 awaken(state, dtriple, expr, &work_list_tail);
17966 /* Wake up the forward control dependencies */
17968 expr = triple_targ(state, dt->triple, expr);
17969 awaken(state, dtriple, expr, &work_list_tail);
17971 /* Wake up the reverse control dependencies of this triple */
17972 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17973 struct triple *last;
17974 last = user->member->last;
17975 while((last->op == OP_NOOP) && (last != user->member->first)) {
17976 #if DEBUG_ROMCC_WARNINGS
17977 #warning "Should we bring the awakening noops back?"
17979 // internal_warning(state, last, "awakening noop?");
17982 awaken(state, dtriple, &last, &work_list_tail);
17985 print_dead_triples(state, dtriple);
17986 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17987 if ((dt->triple->op == OP_NOOP) &&
17988 (dt->flags & TRIPLE_FLAG_ALIVE)) {
17989 internal_error(state, dt->triple, "noop effective?");
17991 dt->triple->id = dt->old_id; /* Restore the color */
17992 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17993 release_triple(state, dt->triple);
17998 rebuild_ssa_form(state);
18000 print_blocks(state, __func__, state->dbgout);
18004 static void insert_mandatory_copies(struct compile_state *state)
18006 struct triple *ins, *first;
18008 /* The object is with a minimum of inserted copies,
18009 * to resolve in fundamental register conflicts between
18010 * register value producers and consumers.
18011 * Theoretically we may be greater than minimal when we
18012 * are inserting copies before instructions but that
18013 * case should be rare.
18015 first = state->first;
18018 struct triple_set *entry, *next;
18019 struct triple *tmp;
18020 struct reg_info info;
18021 unsigned reg, regcm;
18022 int do_post_copy, do_pre_copy;
18024 if (!triple_is_def(state, ins)) {
18027 /* Find the architecture specific color information */
18028 info = find_lhs_pre_color(state, ins, 0);
18029 if (info.reg >= MAX_REGISTERS) {
18030 info.reg = REG_UNSET;
18034 regcm = arch_type_to_regcm(state, ins->type);
18035 do_post_copy = do_pre_copy = 0;
18037 /* Walk through the uses of ins and check for conflicts */
18038 for(entry = ins->use; entry; entry = next) {
18039 struct reg_info rinfo;
18041 next = entry->next;
18042 i = find_rhs_use(state, entry->member, ins);
18047 /* Find the users color requirements */
18048 rinfo = arch_reg_rhs(state, entry->member, i);
18049 if (rinfo.reg >= MAX_REGISTERS) {
18050 rinfo.reg = REG_UNSET;
18053 /* See if I need a pre_copy */
18054 if (rinfo.reg != REG_UNSET) {
18055 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18060 regcm &= rinfo.regcm;
18061 regcm = arch_regcm_normalize(state, regcm);
18065 /* Always use pre_copies for constants.
18066 * They do not take up any registers until a
18067 * copy places them in one.
18069 if ((info.reg == REG_UNNEEDED) &&
18070 (rinfo.reg != REG_UNNEEDED)) {
18076 (((info.reg != REG_UNSET) &&
18077 (reg != REG_UNSET) &&
18078 (info.reg != reg)) ||
18079 ((info.regcm & regcm) == 0));
18082 regcm = info.regcm;
18083 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18084 for(entry = ins->use; entry; entry = next) {
18085 struct reg_info rinfo;
18087 next = entry->next;
18088 i = find_rhs_use(state, entry->member, ins);
18093 /* Find the users color requirements */
18094 rinfo = arch_reg_rhs(state, entry->member, i);
18095 if (rinfo.reg >= MAX_REGISTERS) {
18096 rinfo.reg = REG_UNSET;
18099 /* Now see if it is time to do the pre_copy */
18100 if (rinfo.reg != REG_UNSET) {
18101 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18102 ((regcm & rinfo.regcm) == 0) ||
18103 /* Don't let a mandatory coalesce sneak
18104 * into a operation that is marked to prevent
18107 ((reg != REG_UNNEEDED) &&
18108 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18109 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18112 struct triple *user;
18113 user = entry->member;
18114 if (RHS(user, i) != ins) {
18115 internal_error(state, user, "bad rhs");
18117 tmp = pre_copy(state, user, i);
18118 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18126 if ((regcm & rinfo.regcm) == 0) {
18128 struct triple *user;
18129 user = entry->member;
18130 if (RHS(user, i) != ins) {
18131 internal_error(state, user, "bad rhs");
18133 tmp = pre_copy(state, user, i);
18134 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18140 regcm &= rinfo.regcm;
18143 if (do_post_copy) {
18144 struct reg_info pre, post;
18145 tmp = post_copy(state, ins);
18146 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18147 pre = arch_reg_lhs(state, ins, 0);
18148 post = arch_reg_lhs(state, tmp, 0);
18149 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18150 internal_error(state, tmp, "useless copy");
18155 } while(ins != first);
18157 print_blocks(state, __func__, state->dbgout);
18161 struct live_range_edge;
18162 struct live_range_def;
18163 struct live_range {
18164 struct live_range_edge *edges;
18165 struct live_range_def *defs;
18166 /* Note. The list pointed to by defs is kept in order.
18167 * That is baring splits in the flow control
18168 * defs dominates defs->next wich dominates defs->next->next
18175 struct live_range *group_next, **group_prev;
18178 struct live_range_edge {
18179 struct live_range_edge *next;
18180 struct live_range *node;
18183 struct live_range_def {
18184 struct live_range_def *next;
18185 struct live_range_def *prev;
18186 struct live_range *lr;
18187 struct triple *def;
18191 #define LRE_HASH_SIZE 2048
18193 struct lre_hash *next;
18194 struct live_range *left;
18195 struct live_range *right;
18200 struct lre_hash *hash[LRE_HASH_SIZE];
18201 struct reg_block *blocks;
18202 struct live_range_def *lrd;
18203 struct live_range *lr;
18204 struct live_range *low, **low_tail;
18205 struct live_range *high, **high_tail;
18208 int passes, max_passes;
18212 struct print_interference_block_info {
18213 struct reg_state *rstate;
18217 static void print_interference_block(
18218 struct compile_state *state, struct block *block, void *arg)
18221 struct print_interference_block_info *info = arg;
18222 struct reg_state *rstate = info->rstate;
18223 struct block_set *edge;
18224 FILE *fp = info->fp;
18225 struct reg_block *rb;
18226 struct triple *ptr;
18229 rb = &rstate->blocks[block->vertex];
18231 fprintf(fp, "\nblock: %p (%d),",
18232 block, block->vertex);
18233 for(edge = block->edges; edge; edge = edge->next) {
18234 fprintf(fp, " %p<-%p",
18236 edge->member && edge->member->use?edge->member->use->member : 0);
18240 struct triple_reg_set *in_set;
18241 fprintf(fp, " in:");
18242 for(in_set = rb->in; in_set; in_set = in_set->next) {
18243 fprintf(fp, " %-10p", in_set->member);
18248 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18249 done = (ptr == block->last);
18250 if (ptr->op == OP_PHI) {
18257 for(edge = 0; edge < block->users; edge++) {
18258 fprintf(fp, " in(%d):", edge);
18259 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18260 struct triple **slot;
18261 done = (ptr == block->last);
18262 if (ptr->op != OP_PHI) {
18265 slot = &RHS(ptr, 0);
18266 fprintf(fp, " %-10p", slot[edge]);
18271 if (block->first->op == OP_LABEL) {
18272 fprintf(fp, "%p:\n", block->first);
18274 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18275 struct live_range *lr;
18279 done = (ptr == block->last);
18280 lr = rstate->lrd[ptr->id].lr;
18283 ptr->id = rstate->lrd[id].orig_id;
18284 SET_REG(ptr->id, lr->color);
18285 display_triple(fp, ptr);
18288 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18289 internal_error(state, ptr, "lr has no defs!");
18291 if (info->need_edges) {
18293 struct live_range_def *lrd;
18294 fprintf(fp, " range:");
18297 fprintf(fp, " %-10p", lrd->def);
18299 } while(lrd != lr->defs);
18302 if (lr->edges > 0) {
18303 struct live_range_edge *edge;
18304 fprintf(fp, " edges:");
18305 for(edge = lr->edges; edge; edge = edge->next) {
18306 struct live_range_def *lrd;
18307 lrd = edge->node->defs;
18309 fprintf(fp, " %-10p", lrd->def);
18311 } while(lrd != edge->node->defs);
18317 /* Do a bunch of sanity checks */
18318 valid_ins(state, ptr);
18319 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18320 internal_error(state, ptr, "Invalid triple id: %d",
18325 struct triple_reg_set *out_set;
18326 fprintf(fp, " out:");
18327 for(out_set = rb->out; out_set; out_set = out_set->next) {
18328 fprintf(fp, " %-10p", out_set->member);
18335 static void print_interference_blocks(
18336 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18338 struct print_interference_block_info info;
18339 info.rstate = rstate;
18341 info.need_edges = need_edges;
18342 fprintf(fp, "\nlive variables by block\n");
18343 walk_blocks(state, &state->bb, print_interference_block, &info);
18347 static unsigned regc_max_size(struct compile_state *state, int classes)
18352 for(i = 0; i < MAX_REGC; i++) {
18353 if (classes & (1 << i)) {
18355 size = arch_regc_size(state, i);
18356 if (size > max_size) {
18364 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18366 unsigned equivs[MAX_REG_EQUIVS];
18368 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18369 internal_error(state, 0, "invalid register");
18371 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18372 internal_error(state, 0, "invalid register");
18374 arch_reg_equivs(state, equivs, reg1);
18375 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18376 if (equivs[i] == reg2) {
18383 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18385 unsigned equivs[MAX_REG_EQUIVS];
18387 if (reg == REG_UNNEEDED) {
18390 arch_reg_equivs(state, equivs, reg);
18391 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18392 used[equivs[i]] = 1;
18397 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18399 unsigned equivs[MAX_REG_EQUIVS];
18401 if (reg == REG_UNNEEDED) {
18404 arch_reg_equivs(state, equivs, reg);
18405 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18406 used[equivs[i]] += 1;
18411 static unsigned int hash_live_edge(
18412 struct live_range *left, struct live_range *right)
18414 unsigned int hash, val;
18415 unsigned long lval, rval;
18416 lval = ((unsigned long)left)/sizeof(struct live_range);
18417 rval = ((unsigned long)right)/sizeof(struct live_range);
18422 hash = (hash *263) + val;
18427 hash = (hash *263) + val;
18429 hash = hash & (LRE_HASH_SIZE - 1);
18433 static struct lre_hash **lre_probe(struct reg_state *rstate,
18434 struct live_range *left, struct live_range *right)
18436 struct lre_hash **ptr;
18437 unsigned int index;
18438 /* Ensure left <= right */
18439 if (left > right) {
18440 struct live_range *tmp;
18445 index = hash_live_edge(left, right);
18447 ptr = &rstate->hash[index];
18449 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18452 ptr = &(*ptr)->next;
18457 static int interfere(struct reg_state *rstate,
18458 struct live_range *left, struct live_range *right)
18460 struct lre_hash **ptr;
18461 ptr = lre_probe(rstate, left, right);
18462 return ptr && *ptr;
18465 static void add_live_edge(struct reg_state *rstate,
18466 struct live_range *left, struct live_range *right)
18468 /* FIXME the memory allocation overhead is noticeable here... */
18469 struct lre_hash **ptr, *new_hash;
18470 struct live_range_edge *edge;
18472 if (left == right) {
18475 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18478 /* Ensure left <= right */
18479 if (left > right) {
18480 struct live_range *tmp;
18485 ptr = lre_probe(rstate, left, right);
18490 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18493 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18494 new_hash->next = *ptr;
18495 new_hash->left = left;
18496 new_hash->right = right;
18499 edge = xmalloc(sizeof(*edge), "live_range_edge");
18500 edge->next = left->edges;
18501 edge->node = right;
18502 left->edges = edge;
18505 edge = xmalloc(sizeof(*edge), "live_range_edge");
18506 edge->next = right->edges;
18508 right->edges = edge;
18509 right->degree += 1;
18512 static void remove_live_edge(struct reg_state *rstate,
18513 struct live_range *left, struct live_range *right)
18515 struct live_range_edge *edge, **ptr;
18516 struct lre_hash **hptr, *entry;
18517 hptr = lre_probe(rstate, left, right);
18518 if (!hptr || !*hptr) {
18522 *hptr = entry->next;
18525 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18527 if (edge->node == right) {
18529 memset(edge, 0, sizeof(*edge));
18535 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18537 if (edge->node == left) {
18539 memset(edge, 0, sizeof(*edge));
18547 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18549 struct live_range_edge *edge, *next;
18550 for(edge = range->edges; edge; edge = next) {
18552 remove_live_edge(rstate, range, edge->node);
18556 static void transfer_live_edges(struct reg_state *rstate,
18557 struct live_range *dest, struct live_range *src)
18559 struct live_range_edge *edge, *next;
18560 for(edge = src->edges; edge; edge = next) {
18561 struct live_range *other;
18563 other = edge->node;
18564 remove_live_edge(rstate, src, other);
18565 add_live_edge(rstate, dest, other);
18570 /* Interference graph...
18572 * new(n) --- Return a graph with n nodes but no edges.
18573 * add(g,x,y) --- Return a graph including g with an between x and y
18574 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18575 * x and y in the graph g
18576 * degree(g, x) --- Return the degree of the node x in the graph g
18577 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18579 * Implement with a hash table && a set of adjcency vectors.
18580 * The hash table supports constant time implementations of add and interfere.
18581 * The adjacency vectors support an efficient implementation of neighbors.
18585 * +---------------------------------------------------+
18586 * | +--------------+ |
18588 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18590 * -- In simplify implment optimistic coloring... (No backtracking)
18591 * -- Implement Rematerialization it is the only form of spilling we can perform
18592 * Essentially this means dropping a constant from a register because
18593 * we can regenerate it later.
18595 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18596 * coalesce at phi points...
18597 * --- Bias coloring if at all possible do the coalesing a compile time.
18602 #if DEBUG_ROMCC_WARNING
18603 static void different_colored(
18604 struct compile_state *state, struct reg_state *rstate,
18605 struct triple *parent, struct triple *ins)
18607 struct live_range *lr;
18608 struct triple **expr;
18609 lr = rstate->lrd[ins->id].lr;
18610 expr = triple_rhs(state, ins, 0);
18611 for(;expr; expr = triple_rhs(state, ins, expr)) {
18612 struct live_range *lr2;
18613 if (!*expr || (*expr == parent) || (*expr == ins)) {
18616 lr2 = rstate->lrd[(*expr)->id].lr;
18617 if (lr->color == lr2->color) {
18618 internal_error(state, ins, "live range too big");
18624 static struct live_range *coalesce_ranges(
18625 struct compile_state *state, struct reg_state *rstate,
18626 struct live_range *lr1, struct live_range *lr2)
18628 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18634 if (!lr1->defs || !lr2->defs) {
18635 internal_error(state, 0,
18636 "cannot coalese dead live ranges");
18638 if ((lr1->color == REG_UNNEEDED) ||
18639 (lr2->color == REG_UNNEEDED)) {
18640 internal_error(state, 0,
18641 "cannot coalesce live ranges without a possible color");
18643 if ((lr1->color != lr2->color) &&
18644 (lr1->color != REG_UNSET) &&
18645 (lr2->color != REG_UNSET)) {
18646 internal_error(state, lr1->defs->def,
18647 "cannot coalesce live ranges of different colors");
18649 color = lr1->color;
18650 if (color == REG_UNSET) {
18651 color = lr2->color;
18653 classes = lr1->classes & lr2->classes;
18655 internal_error(state, lr1->defs->def,
18656 "cannot coalesce live ranges with dissimilar register classes");
18658 if (state->compiler->debug & DEBUG_COALESCING) {
18659 FILE *fp = state->errout;
18660 fprintf(fp, "coalescing:");
18663 fprintf(fp, " %p", lrd->def);
18665 } while(lrd != lr1->defs);
18669 fprintf(fp, " %p", lrd->def);
18671 } while(lrd != lr2->defs);
18674 /* If there is a clear dominate live range put it in lr1,
18675 * For purposes of this test phi functions are
18676 * considered dominated by the definitions that feed into
18679 if ((lr1->defs->prev->def->op == OP_PHI) ||
18680 ((lr2->defs->prev->def->op != OP_PHI) &&
18681 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18682 struct live_range *tmp;
18688 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18689 fprintf(state->errout, "lr1 post\n");
18691 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18692 fprintf(state->errout, "lr1 pre\n");
18694 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18695 fprintf(state->errout, "lr2 post\n");
18697 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18698 fprintf(state->errout, "lr2 pre\n");
18702 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18709 /* Append lr2 onto lr1 */
18710 #if DEBUG_ROMCC_WARNINGS
18711 #warning "FIXME should this be a merge instead of a splice?"
18713 /* This FIXME item applies to the correctness of live_range_end
18714 * and to the necessity of making multiple passes of coalesce_live_ranges.
18715 * A failure to find some coalesce opportunities in coaleace_live_ranges
18716 * does not impact the correct of the compiler just the efficiency with
18717 * which registers are allocated.
18720 mid1 = lr1->defs->prev;
18722 end = lr2->defs->prev;
18730 /* Fixup the live range in the added live range defs */
18735 } while(lrd != head);
18737 /* Mark lr2 as free. */
18739 lr2->color = REG_UNNEEDED;
18743 internal_error(state, 0, "lr1->defs == 0 ?");
18746 lr1->color = color;
18747 lr1->classes = classes;
18749 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18750 transfer_live_edges(rstate, lr1, lr2);
18755 static struct live_range_def *live_range_head(
18756 struct compile_state *state, struct live_range *lr,
18757 struct live_range_def *last)
18759 struct live_range_def *result;
18764 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18765 result = last->next;
18770 static struct live_range_def *live_range_end(
18771 struct compile_state *state, struct live_range *lr,
18772 struct live_range_def *last)
18774 struct live_range_def *result;
18777 result = lr->defs->prev;
18779 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18780 result = last->prev;
18786 static void initialize_live_ranges(
18787 struct compile_state *state, struct reg_state *rstate)
18789 struct triple *ins, *first;
18790 size_t count, size;
18793 first = state->first;
18794 /* First count how many instructions I have.
18796 count = count_triples(state);
18797 /* Potentially I need one live range definitions for each
18800 rstate->defs = count;
18801 /* Potentially I need one live range for each instruction
18802 * plus an extra for the dummy live range.
18804 rstate->ranges = count + 1;
18805 size = sizeof(rstate->lrd[0]) * rstate->defs;
18806 rstate->lrd = xcmalloc(size, "live_range_def");
18807 size = sizeof(rstate->lr[0]) * rstate->ranges;
18808 rstate->lr = xcmalloc(size, "live_range");
18810 /* Setup the dummy live range */
18811 rstate->lr[0].classes = 0;
18812 rstate->lr[0].color = REG_UNSET;
18813 rstate->lr[0].defs = 0;
18817 /* If the triple is a variable give it a live range */
18818 if (triple_is_def(state, ins)) {
18819 struct reg_info info;
18820 /* Find the architecture specific color information */
18821 info = find_def_color(state, ins);
18823 rstate->lr[i].defs = &rstate->lrd[j];
18824 rstate->lr[i].color = info.reg;
18825 rstate->lr[i].classes = info.regcm;
18826 rstate->lr[i].degree = 0;
18827 rstate->lrd[j].lr = &rstate->lr[i];
18829 /* Otherwise give the triple the dummy live range. */
18831 rstate->lrd[j].lr = &rstate->lr[0];
18834 /* Initalize the live_range_def */
18835 rstate->lrd[j].next = &rstate->lrd[j];
18836 rstate->lrd[j].prev = &rstate->lrd[j];
18837 rstate->lrd[j].def = ins;
18838 rstate->lrd[j].orig_id = ins->id;
18843 } while(ins != first);
18844 rstate->ranges = i;
18846 /* Make a second pass to handle achitecture specific register
18851 int zlhs, zrhs, i, j;
18852 if (ins->id > rstate->defs) {
18853 internal_error(state, ins, "bad id");
18856 /* Walk through the template of ins and coalesce live ranges */
18858 if ((zlhs == 0) && triple_is_def(state, ins)) {
18863 if (state->compiler->debug & DEBUG_COALESCING2) {
18864 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18868 for(i = 0; i < zlhs; i++) {
18869 struct reg_info linfo;
18870 struct live_range_def *lhs;
18871 linfo = arch_reg_lhs(state, ins, i);
18872 if (linfo.reg < MAX_REGISTERS) {
18875 if (triple_is_def(state, ins)) {
18876 lhs = &rstate->lrd[ins->id];
18878 lhs = &rstate->lrd[LHS(ins, i)->id];
18881 if (state->compiler->debug & DEBUG_COALESCING2) {
18882 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18883 i, lhs, linfo.reg);
18886 for(j = 0; j < zrhs; j++) {
18887 struct reg_info rinfo;
18888 struct live_range_def *rhs;
18889 rinfo = arch_reg_rhs(state, ins, j);
18890 if (rinfo.reg < MAX_REGISTERS) {
18893 rhs = &rstate->lrd[RHS(ins, j)->id];
18895 if (state->compiler->debug & DEBUG_COALESCING2) {
18896 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18897 j, rhs, rinfo.reg);
18900 if (rinfo.reg == linfo.reg) {
18901 coalesce_ranges(state, rstate,
18907 } while(ins != first);
18910 static void graph_ins(
18911 struct compile_state *state,
18912 struct reg_block *blocks, struct triple_reg_set *live,
18913 struct reg_block *rb, struct triple *ins, void *arg)
18915 struct reg_state *rstate = arg;
18916 struct live_range *def;
18917 struct triple_reg_set *entry;
18919 /* If the triple is not a definition
18920 * we do not have a definition to add to
18921 * the interference graph.
18923 if (!triple_is_def(state, ins)) {
18926 def = rstate->lrd[ins->id].lr;
18928 /* Create an edge between ins and everything that is
18929 * alive, unless the live_range cannot share
18930 * a physical register with ins.
18932 for(entry = live; entry; entry = entry->next) {
18933 struct live_range *lr;
18934 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18935 internal_error(state, 0, "bad entry?");
18937 lr = rstate->lrd[entry->member->id].lr;
18941 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18944 add_live_edge(rstate, def, lr);
18949 #if DEBUG_CONSISTENCY > 1
18950 static struct live_range *get_verify_live_range(
18951 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18953 struct live_range *lr;
18954 struct live_range_def *lrd;
18956 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18957 internal_error(state, ins, "bad ins?");
18959 lr = rstate->lrd[ins->id].lr;
18963 if (lrd->def == ins) {
18967 } while(lrd != lr->defs);
18969 internal_error(state, ins, "ins not in live range");
18974 static void verify_graph_ins(
18975 struct compile_state *state,
18976 struct reg_block *blocks, struct triple_reg_set *live,
18977 struct reg_block *rb, struct triple *ins, void *arg)
18979 struct reg_state *rstate = arg;
18980 struct triple_reg_set *entry1, *entry2;
18983 /* Compare live against edges and make certain the code is working */
18984 for(entry1 = live; entry1; entry1 = entry1->next) {
18985 struct live_range *lr1;
18986 lr1 = get_verify_live_range(state, rstate, entry1->member);
18987 for(entry2 = live; entry2; entry2 = entry2->next) {
18988 struct live_range *lr2;
18989 struct live_range_edge *edge2;
18992 if (entry2 == entry1) {
18995 lr2 = get_verify_live_range(state, rstate, entry2->member);
18997 internal_error(state, entry2->member,
18998 "live range with 2 values simultaneously alive");
19000 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19003 if (!interfere(rstate, lr1, lr2)) {
19004 internal_error(state, entry2->member,
19005 "edges don't interfere?");
19010 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19012 if (edge2->node == lr1) {
19016 if (lr2_degree != lr2->degree) {
19017 internal_error(state, entry2->member,
19018 "computed degree: %d does not match reported degree: %d\n",
19019 lr2_degree, lr2->degree);
19022 internal_error(state, entry2->member, "missing edge");
19030 static void print_interference_ins(
19031 struct compile_state *state,
19032 struct reg_block *blocks, struct triple_reg_set *live,
19033 struct reg_block *rb, struct triple *ins, void *arg)
19035 struct reg_state *rstate = arg;
19036 struct live_range *lr;
19038 FILE *fp = state->dbgout;
19040 lr = rstate->lrd[ins->id].lr;
19042 ins->id = rstate->lrd[id].orig_id;
19043 SET_REG(ins->id, lr->color);
19044 display_triple(state->dbgout, ins);
19048 struct live_range_def *lrd;
19049 fprintf(fp, " range:");
19052 fprintf(fp, " %-10p", lrd->def);
19054 } while(lrd != lr->defs);
19058 struct triple_reg_set *entry;
19059 fprintf(fp, " live:");
19060 for(entry = live; entry; entry = entry->next) {
19061 fprintf(fp, " %-10p", entry->member);
19066 struct live_range_edge *entry;
19067 fprintf(fp, " edges:");
19068 for(entry = lr->edges; entry; entry = entry->next) {
19069 struct live_range_def *lrd;
19070 lrd = entry->node->defs;
19072 fprintf(fp, " %-10p", lrd->def);
19074 } while(lrd != entry->node->defs);
19079 if (triple_is_branch(state, ins)) {
19085 static int coalesce_live_ranges(
19086 struct compile_state *state, struct reg_state *rstate)
19088 /* At the point where a value is moved from one
19089 * register to another that value requires two
19090 * registers, thus increasing register pressure.
19091 * Live range coaleescing reduces the register
19092 * pressure by keeping a value in one register
19095 * In the case of a phi function all paths leading
19096 * into it must be allocated to the same register
19097 * otherwise the phi function may not be removed.
19099 * Forcing a value to stay in a single register
19100 * for an extended period of time does have
19101 * limitations when applied to non homogenous
19104 * The two cases I have identified are:
19105 * 1) Two forced register assignments may
19107 * 2) Registers may go unused because they
19108 * are only good for storing the value
19109 * and not manipulating it.
19111 * Because of this I need to split live ranges,
19112 * even outside of the context of coalesced live
19113 * ranges. The need to split live ranges does
19114 * impose some constraints on live range coalescing.
19116 * - Live ranges may not be coalesced across phi
19117 * functions. This creates a 2 headed live
19118 * range that cannot be sanely split.
19120 * - phi functions (coalesced in initialize_live_ranges)
19121 * are handled as pre split live ranges so we will
19122 * never attempt to split them.
19128 for(i = 0; i <= rstate->ranges; i++) {
19129 struct live_range *lr1;
19130 struct live_range_def *lrd1;
19131 lr1 = &rstate->lr[i];
19135 lrd1 = live_range_end(state, lr1, 0);
19136 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19137 struct triple_set *set;
19138 if (lrd1->def->op != OP_COPY) {
19141 /* Skip copies that are the result of a live range split. */
19142 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19145 for(set = lrd1->def->use; set; set = set->next) {
19146 struct live_range_def *lrd2;
19147 struct live_range *lr2, *res;
19149 lrd2 = &rstate->lrd[set->member->id];
19151 /* Don't coalesce with instructions
19152 * that are the result of a live range
19155 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19158 lr2 = rstate->lrd[set->member->id].lr;
19162 if ((lr1->color != lr2->color) &&
19163 (lr1->color != REG_UNSET) &&
19164 (lr2->color != REG_UNSET)) {
19167 if ((lr1->classes & lr2->classes) == 0) {
19171 if (interfere(rstate, lr1, lr2)) {
19175 res = coalesce_ranges(state, rstate, lr1, lr2);
19189 static void fix_coalesce_conflicts(struct compile_state *state,
19190 struct reg_block *blocks, struct triple_reg_set *live,
19191 struct reg_block *rb, struct triple *ins, void *arg)
19193 int *conflicts = arg;
19194 int zlhs, zrhs, i, j;
19196 /* See if we have a mandatory coalesce operation between
19197 * a lhs and a rhs value. If so and the rhs value is also
19198 * alive then this triple needs to be pre copied. Otherwise
19199 * we would have two definitions in the same live range simultaneously
19203 if ((zlhs == 0) && triple_is_def(state, ins)) {
19207 for(i = 0; i < zlhs; i++) {
19208 struct reg_info linfo;
19209 linfo = arch_reg_lhs(state, ins, i);
19210 if (linfo.reg < MAX_REGISTERS) {
19213 for(j = 0; j < zrhs; j++) {
19214 struct reg_info rinfo;
19215 struct triple *rhs;
19216 struct triple_reg_set *set;
19219 rinfo = arch_reg_rhs(state, ins, j);
19220 if (rinfo.reg != linfo.reg) {
19224 for(set = live; set && !found; set = set->next) {
19225 if (set->member == rhs) {
19230 struct triple *copy;
19231 copy = pre_copy(state, ins, j);
19232 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19240 static int correct_coalesce_conflicts(
19241 struct compile_state *state, struct reg_block *blocks)
19245 walk_variable_lifetimes(state, &state->bb, blocks,
19246 fix_coalesce_conflicts, &conflicts);
19250 static void replace_set_use(struct compile_state *state,
19251 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19253 struct triple_reg_set *set;
19254 for(set = head; set; set = set->next) {
19255 if (set->member == orig) {
19261 static void replace_block_use(struct compile_state *state,
19262 struct reg_block *blocks, struct triple *orig, struct triple *new)
19265 #if DEBUG_ROMCC_WARNINGS
19266 #warning "WISHLIST visit just those blocks that need it *"
19268 for(i = 1; i <= state->bb.last_vertex; i++) {
19269 struct reg_block *rb;
19271 replace_set_use(state, rb->in, orig, new);
19272 replace_set_use(state, rb->out, orig, new);
19276 static void color_instructions(struct compile_state *state)
19278 struct triple *ins, *first;
19279 first = state->first;
19282 if (triple_is_def(state, ins)) {
19283 struct reg_info info;
19284 info = find_lhs_color(state, ins, 0);
19285 if (info.reg >= MAX_REGISTERS) {
19286 info.reg = REG_UNSET;
19288 SET_INFO(ins->id, info);
19291 } while(ins != first);
19294 static struct reg_info read_lhs_color(
19295 struct compile_state *state, struct triple *ins, int index)
19297 struct reg_info info;
19298 if ((index == 0) && triple_is_def(state, ins)) {
19299 info.reg = ID_REG(ins->id);
19300 info.regcm = ID_REGCM(ins->id);
19302 else if (index < ins->lhs) {
19303 info = read_lhs_color(state, LHS(ins, index), 0);
19306 internal_error(state, ins, "Bad lhs %d", index);
19307 info.reg = REG_UNSET;
19313 static struct triple *resolve_tangle(
19314 struct compile_state *state, struct triple *tangle)
19316 struct reg_info info, uinfo;
19317 struct triple_set *set, *next;
19318 struct triple *copy;
19320 #if DEBUG_ROMCC_WARNINGS
19321 #warning "WISHLIST recalculate all affected instructions colors"
19323 info = find_lhs_color(state, tangle, 0);
19324 for(set = tangle->use; set; set = next) {
19325 struct triple *user;
19328 user = set->member;
19330 for(i = 0; i < zrhs; i++) {
19331 if (RHS(user, i) != tangle) {
19334 uinfo = find_rhs_post_color(state, user, i);
19335 if (uinfo.reg == info.reg) {
19336 copy = pre_copy(state, user, i);
19337 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19338 SET_INFO(copy->id, uinfo);
19343 uinfo = find_lhs_pre_color(state, tangle, 0);
19344 if (uinfo.reg == info.reg) {
19345 struct reg_info linfo;
19346 copy = post_copy(state, tangle);
19347 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19348 linfo = find_lhs_color(state, copy, 0);
19349 SET_INFO(copy->id, linfo);
19351 info = find_lhs_color(state, tangle, 0);
19352 SET_INFO(tangle->id, info);
19358 static void fix_tangles(struct compile_state *state,
19359 struct reg_block *blocks, struct triple_reg_set *live,
19360 struct reg_block *rb, struct triple *ins, void *arg)
19362 int *tangles = arg;
19363 struct triple *tangle;
19365 char used[MAX_REGISTERS];
19366 struct triple_reg_set *set;
19369 /* Find out which registers have multiple uses at this point */
19370 memset(used, 0, sizeof(used));
19371 for(set = live; set; set = set->next) {
19372 struct reg_info info;
19373 info = read_lhs_color(state, set->member, 0);
19374 if (info.reg == REG_UNSET) {
19377 reg_inc_used(state, used, info.reg);
19380 /* Now find the least dominated definition of a register in
19381 * conflict I have seen so far.
19383 for(set = live; set; set = set->next) {
19384 struct reg_info info;
19385 info = read_lhs_color(state, set->member, 0);
19386 if (used[info.reg] < 2) {
19389 /* Changing copies that feed into phi functions
19392 if (set->member->use &&
19393 (set->member->use->member->op == OP_PHI)) {
19396 if (!tangle || tdominates(state, set->member, tangle)) {
19397 tangle = set->member;
19400 /* If I have found a tangle resolve it */
19402 struct triple *post_copy;
19404 post_copy = resolve_tangle(state, tangle);
19406 replace_block_use(state, blocks, tangle, post_copy);
19408 if (post_copy && (tangle != ins)) {
19409 replace_set_use(state, live, tangle, post_copy);
19416 static int correct_tangles(
19417 struct compile_state *state, struct reg_block *blocks)
19421 color_instructions(state);
19422 walk_variable_lifetimes(state, &state->bb, blocks,
19423 fix_tangles, &tangles);
19428 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19429 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19431 struct triple *find_constrained_def(
19432 struct compile_state *state, struct live_range *range, struct triple *constrained)
19434 struct live_range_def *lrd, *lrd_next;
19435 lrd_next = range->defs;
19437 struct reg_info info;
19441 lrd_next = lrd->next;
19443 regcm = arch_type_to_regcm(state, lrd->def->type);
19444 info = find_lhs_color(state, lrd->def, 0);
19445 regcm = arch_regcm_reg_normalize(state, regcm);
19446 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19447 /* If the 2 register class masks are equal then
19448 * the current register class is not constrained.
19450 if (regcm == info.regcm) {
19454 /* If there is just one use.
19455 * That use cannot accept a larger register class.
19456 * There are no intervening definitions except
19457 * definitions that feed into that use.
19458 * Then a triple is not constrained.
19459 * FIXME handle this case!
19461 #if DEBUG_ROMCC_WARNINGS
19462 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19466 /* Of the constrained live ranges deal with the
19467 * least dominated one first.
19469 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19470 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19471 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19473 if (!constrained ||
19474 tdominates(state, lrd->def, constrained))
19476 constrained = lrd->def;
19478 } while(lrd_next != range->defs);
19479 return constrained;
19482 static int split_constrained_ranges(
19483 struct compile_state *state, struct reg_state *rstate,
19484 struct live_range *range)
19486 /* Walk through the edges in conflict and our current live
19487 * range, and find definitions that are more severly constrained
19488 * than they type of data they contain require.
19490 * Then pick one of those ranges and relax the constraints.
19492 struct live_range_edge *edge;
19493 struct triple *constrained;
19496 for(edge = range->edges; edge; edge = edge->next) {
19497 constrained = find_constrained_def(state, edge->node, constrained);
19499 #if DEBUG_ROMCC_WARNINGS
19500 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19502 if (!constrained) {
19503 constrained = find_constrained_def(state, range, constrained);
19506 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19507 fprintf(state->errout, "constrained: ");
19508 display_triple(state->errout, constrained);
19511 ids_from_rstate(state, rstate);
19512 cleanup_rstate(state, rstate);
19513 resolve_tangle(state, constrained);
19515 return !!constrained;
19518 static int split_ranges(
19519 struct compile_state *state, struct reg_state *rstate,
19520 char *used, struct live_range *range)
19523 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19524 fprintf(state->errout, "split_ranges %d %s %p\n",
19525 rstate->passes, tops(range->defs->def->op), range->defs->def);
19527 if ((range->color == REG_UNNEEDED) ||
19528 (rstate->passes >= rstate->max_passes)) {
19531 split = split_constrained_ranges(state, rstate, range);
19533 /* Ideally I would split the live range that will not be used
19534 * for the longest period of time in hopes that this will
19535 * (a) allow me to spill a register or
19536 * (b) allow me to place a value in another register.
19538 * So far I don't have a test case for this, the resolving
19539 * of mandatory constraints has solved all of my
19540 * know issues. So I have choosen not to write any
19541 * code until I cat get a better feel for cases where
19542 * it would be useful to have.
19545 #if DEBUG_ROMCC_WARNINGS
19546 #warning "WISHLIST implement live range splitting..."
19549 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19550 FILE *fp = state->errout;
19551 print_interference_blocks(state, rstate, fp, 0);
19552 print_dominators(state, fp, &state->bb);
19557 static FILE *cgdebug_fp(struct compile_state *state)
19561 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19562 fp = state->errout;
19564 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19565 fp = state->dbgout;
19570 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19573 fp = cgdebug_fp(state);
19576 va_start(args, fmt);
19577 vfprintf(fp, fmt, args);
19582 static void cgdebug_flush(struct compile_state *state)
19585 fp = cgdebug_fp(state);
19591 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19594 fp = cgdebug_fp(state);
19596 loc(fp, state, ins);
19600 static int select_free_color(struct compile_state *state,
19601 struct reg_state *rstate, struct live_range *range)
19603 struct triple_set *entry;
19604 struct live_range_def *lrd;
19605 struct live_range_def *phi;
19606 struct live_range_edge *edge;
19607 char used[MAX_REGISTERS];
19608 struct triple **expr;
19610 /* Instead of doing just the trivial color select here I try
19611 * a few extra things because a good color selection will help reduce
19615 /* Find the registers currently in use */
19616 memset(used, 0, sizeof(used));
19617 for(edge = range->edges; edge; edge = edge->next) {
19618 if (edge->node->color == REG_UNSET) {
19621 reg_fill_used(state, used, edge->node->color);
19624 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19627 for(edge = range->edges; edge; edge = edge->next) {
19630 cgdebug_printf(state, "\n%s edges: %d",
19631 tops(range->defs->def->op), i);
19632 cgdebug_loc(state, range->defs->def);
19633 cgdebug_printf(state, "\n");
19634 for(i = 0; i < MAX_REGISTERS; i++) {
19636 cgdebug_printf(state, "used: %s\n",
19642 /* If a color is already assigned see if it will work */
19643 if (range->color != REG_UNSET) {
19644 struct live_range_def *lrd;
19645 if (!used[range->color]) {
19648 for(edge = range->edges; edge; edge = edge->next) {
19649 if (edge->node->color != range->color) {
19652 warning(state, edge->node->defs->def, "edge: ");
19653 lrd = edge->node->defs;
19655 warning(state, lrd->def, " %p %s",
19656 lrd->def, tops(lrd->def->op));
19658 } while(lrd != edge->node->defs);
19661 warning(state, range->defs->def, "def: ");
19663 warning(state, lrd->def, " %p %s",
19664 lrd->def, tops(lrd->def->op));
19666 } while(lrd != range->defs);
19667 internal_error(state, range->defs->def,
19668 "live range with already used color %s",
19669 arch_reg_str(range->color));
19672 /* If I feed into an expression reuse it's color.
19673 * This should help remove copies in the case of 2 register instructions
19674 * and phi functions.
19677 lrd = live_range_end(state, range, 0);
19678 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19679 entry = lrd->def->use;
19680 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19681 struct live_range_def *insd;
19683 insd = &rstate->lrd[entry->member->id];
19684 if (insd->lr->defs == 0) {
19687 if (!phi && (insd->def->op == OP_PHI) &&
19688 !interfere(rstate, range, insd->lr)) {
19691 if (insd->lr->color == REG_UNSET) {
19694 regcm = insd->lr->classes;
19695 if (((regcm & range->classes) == 0) ||
19696 (used[insd->lr->color])) {
19699 if (interfere(rstate, range, insd->lr)) {
19702 range->color = insd->lr->color;
19705 /* If I feed into a phi function reuse it's color or the color
19706 * of something else that feeds into the phi function.
19709 if (phi->lr->color != REG_UNSET) {
19710 if (used[phi->lr->color]) {
19711 range->color = phi->lr->color;
19715 expr = triple_rhs(state, phi->def, 0);
19716 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19717 struct live_range *lr;
19722 lr = rstate->lrd[(*expr)->id].lr;
19723 if (lr->color == REG_UNSET) {
19726 regcm = lr->classes;
19727 if (((regcm & range->classes) == 0) ||
19728 (used[lr->color])) {
19731 if (interfere(rstate, range, lr)) {
19734 range->color = lr->color;
19738 /* If I don't interfere with a rhs node reuse it's color */
19739 lrd = live_range_head(state, range, 0);
19740 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19741 expr = triple_rhs(state, lrd->def, 0);
19742 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19743 struct live_range *lr;
19748 lr = rstate->lrd[(*expr)->id].lr;
19749 if (lr->color == REG_UNSET) {
19752 regcm = lr->classes;
19753 if (((regcm & range->classes) == 0) ||
19754 (used[lr->color])) {
19757 if (interfere(rstate, range, lr)) {
19760 range->color = lr->color;
19764 /* If I have not opportunitically picked a useful color
19765 * pick the first color that is free.
19767 if (range->color == REG_UNSET) {
19769 arch_select_free_register(state, used, range->classes);
19771 if (range->color == REG_UNSET) {
19772 struct live_range_def *lrd;
19774 if (split_ranges(state, rstate, used, range)) {
19777 for(edge = range->edges; edge; edge = edge->next) {
19778 warning(state, edge->node->defs->def, "edge reg %s",
19779 arch_reg_str(edge->node->color));
19780 lrd = edge->node->defs;
19782 warning(state, lrd->def, " %s %p",
19783 tops(lrd->def->op), lrd->def);
19785 } while(lrd != edge->node->defs);
19787 warning(state, range->defs->def, "range: ");
19790 warning(state, lrd->def, " %s %p",
19791 tops(lrd->def->op), lrd->def);
19793 } while(lrd != range->defs);
19795 warning(state, range->defs->def, "classes: %x",
19797 for(i = 0; i < MAX_REGISTERS; i++) {
19799 warning(state, range->defs->def, "used: %s",
19803 error(state, range->defs->def, "too few registers");
19805 range->classes &= arch_reg_regcm(state, range->color);
19806 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19807 internal_error(state, range->defs->def, "select_free_color did not?");
19812 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19815 struct live_range_edge *edge;
19816 struct live_range *range;
19818 cgdebug_printf(state, "Lo: ");
19819 range = rstate->low;
19820 if (*range->group_prev != range) {
19821 internal_error(state, 0, "lo: *prev != range?");
19823 *range->group_prev = range->group_next;
19824 if (range->group_next) {
19825 range->group_next->group_prev = range->group_prev;
19827 if (&range->group_next == rstate->low_tail) {
19828 rstate->low_tail = range->group_prev;
19830 if (rstate->low == range) {
19831 internal_error(state, 0, "low: next != prev?");
19834 else if (rstate->high) {
19835 cgdebug_printf(state, "Hi: ");
19836 range = rstate->high;
19837 if (*range->group_prev != range) {
19838 internal_error(state, 0, "hi: *prev != range?");
19840 *range->group_prev = range->group_next;
19841 if (range->group_next) {
19842 range->group_next->group_prev = range->group_prev;
19844 if (&range->group_next == rstate->high_tail) {
19845 rstate->high_tail = range->group_prev;
19847 if (rstate->high == range) {
19848 internal_error(state, 0, "high: next != prev?");
19854 cgdebug_printf(state, " %d\n", range - rstate->lr);
19855 range->group_prev = 0;
19856 for(edge = range->edges; edge; edge = edge->next) {
19857 struct live_range *node;
19859 /* Move nodes from the high to the low list */
19860 if (node->group_prev && (node->color == REG_UNSET) &&
19861 (node->degree == regc_max_size(state, node->classes))) {
19862 if (*node->group_prev != node) {
19863 internal_error(state, 0, "move: *prev != node?");
19865 *node->group_prev = node->group_next;
19866 if (node->group_next) {
19867 node->group_next->group_prev = node->group_prev;
19869 if (&node->group_next == rstate->high_tail) {
19870 rstate->high_tail = node->group_prev;
19872 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19873 node->group_prev = rstate->low_tail;
19874 node->group_next = 0;
19875 *rstate->low_tail = node;
19876 rstate->low_tail = &node->group_next;
19877 if (*node->group_prev != node) {
19878 internal_error(state, 0, "move2: *prev != node?");
19883 colored = color_graph(state, rstate);
19885 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19886 cgdebug_loc(state, range->defs->def);
19887 cgdebug_flush(state);
19888 colored = select_free_color(state, rstate, range);
19890 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19896 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19898 struct live_range *lr;
19899 struct live_range_edge *edge;
19900 struct triple *ins, *first;
19901 char used[MAX_REGISTERS];
19902 first = state->first;
19905 if (triple_is_def(state, ins)) {
19906 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19907 internal_error(state, ins,
19908 "triple without a live range def");
19910 lr = rstate->lrd[ins->id].lr;
19911 if (lr->color == REG_UNSET) {
19912 internal_error(state, ins,
19913 "triple without a color");
19915 /* Find the registers used by the edges */
19916 memset(used, 0, sizeof(used));
19917 for(edge = lr->edges; edge; edge = edge->next) {
19918 if (edge->node->color == REG_UNSET) {
19919 internal_error(state, 0,
19920 "live range without a color");
19922 reg_fill_used(state, used, edge->node->color);
19924 if (used[lr->color]) {
19925 internal_error(state, ins,
19926 "triple with already used color");
19930 } while(ins != first);
19933 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19935 struct live_range_def *lrd;
19936 struct live_range *lr;
19937 struct triple *first, *ins;
19938 first = state->first;
19941 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19942 internal_error(state, ins,
19943 "triple without a live range");
19945 lrd = &rstate->lrd[ins->id];
19947 ins->id = lrd->orig_id;
19948 SET_REG(ins->id, lr->color);
19950 } while (ins != first);
19953 static struct live_range *merge_sort_lr(
19954 struct live_range *first, struct live_range *last)
19956 struct live_range *mid, *join, **join_tail, *pick;
19958 size = (last - first) + 1;
19960 mid = first + size/2;
19961 first = merge_sort_lr(first, mid -1);
19962 mid = merge_sort_lr(mid, last);
19966 /* merge the two lists */
19967 while(first && mid) {
19968 if ((first->degree < mid->degree) ||
19969 ((first->degree == mid->degree) &&
19970 (first->length < mid->length))) {
19972 first = first->group_next;
19974 first->group_prev = 0;
19979 mid = mid->group_next;
19981 mid->group_prev = 0;
19984 pick->group_next = 0;
19985 pick->group_prev = join_tail;
19987 join_tail = &pick->group_next;
19989 /* Splice the remaining list */
19990 pick = (first)? first : mid;
19993 pick->group_prev = join_tail;
19997 if (!first->defs) {
20005 static void ids_from_rstate(struct compile_state *state,
20006 struct reg_state *rstate)
20008 struct triple *ins, *first;
20009 if (!rstate->defs) {
20012 /* Display the graph if desired */
20013 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20014 FILE *fp = state->dbgout;
20015 print_interference_blocks(state, rstate, fp, 0);
20016 print_control_flow(state, fp, &state->bb);
20019 first = state->first;
20023 struct live_range_def *lrd;
20024 lrd = &rstate->lrd[ins->id];
20025 ins->id = lrd->orig_id;
20028 } while(ins != first);
20031 static void cleanup_live_edges(struct reg_state *rstate)
20034 /* Free the edges on each node */
20035 for(i = 1; i <= rstate->ranges; i++) {
20036 remove_live_edges(rstate, &rstate->lr[i]);
20040 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20042 cleanup_live_edges(rstate);
20043 xfree(rstate->lrd);
20046 /* Free the variable lifetime information */
20047 if (rstate->blocks) {
20048 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20051 rstate->ranges = 0;
20054 rstate->blocks = 0;
20057 static void verify_consistency(struct compile_state *state);
20058 static void allocate_registers(struct compile_state *state)
20060 struct reg_state rstate;
20063 /* Clear out the reg_state */
20064 memset(&rstate, 0, sizeof(rstate));
20065 rstate.max_passes = state->compiler->max_allocation_passes;
20068 struct live_range **point, **next;
20073 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20074 FILE *fp = state->errout;
20075 fprintf(fp, "pass: %d\n", rstate.passes);
20080 ids_from_rstate(state, &rstate);
20082 /* Cleanup the temporary data structures */
20083 cleanup_rstate(state, &rstate);
20085 /* Compute the variable lifetimes */
20086 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20088 /* Fix invalid mandatory live range coalesce conflicts */
20089 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20091 /* Fix two simultaneous uses of the same register.
20092 * In a few pathlogical cases a partial untangle moves
20093 * the tangle to a part of the graph we won't revisit.
20094 * So we keep looping until we have no more tangle fixes
20098 tangles = correct_tangles(state, rstate.blocks);
20102 print_blocks(state, "resolve_tangles", state->dbgout);
20103 verify_consistency(state);
20105 /* Allocate and initialize the live ranges */
20106 initialize_live_ranges(state, &rstate);
20108 /* Note currently doing coalescing in a loop appears to
20109 * buys me nothing. The code is left this way in case
20110 * there is some value in it. Or if a future bugfix
20111 * yields some benefit.
20114 if (state->compiler->debug & DEBUG_COALESCING) {
20115 fprintf(state->errout, "coalescing\n");
20118 /* Remove any previous live edge calculations */
20119 cleanup_live_edges(&rstate);
20121 /* Compute the interference graph */
20122 walk_variable_lifetimes(
20123 state, &state->bb, rstate.blocks,
20124 graph_ins, &rstate);
20126 /* Display the interference graph if desired */
20127 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20128 print_interference_blocks(state, &rstate, state->dbgout, 1);
20129 fprintf(state->dbgout, "\nlive variables by instruction\n");
20130 walk_variable_lifetimes(
20131 state, &state->bb, rstate.blocks,
20132 print_interference_ins, &rstate);
20135 coalesced = coalesce_live_ranges(state, &rstate);
20137 if (state->compiler->debug & DEBUG_COALESCING) {
20138 fprintf(state->errout, "coalesced: %d\n", coalesced);
20140 } while(coalesced);
20142 #if DEBUG_CONSISTENCY > 1
20144 fprintf(state->errout, "verify_graph_ins...\n");
20146 /* Verify the interference graph */
20147 walk_variable_lifetimes(
20148 state, &state->bb, rstate.blocks,
20149 verify_graph_ins, &rstate);
20151 fprintf(state->errout, "verify_graph_ins done\n");
20155 /* Build the groups low and high. But with the nodes
20156 * first sorted by degree order.
20158 rstate.low_tail = &rstate.low;
20159 rstate.high_tail = &rstate.high;
20160 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20162 rstate.high->group_prev = &rstate.high;
20164 for(point = &rstate.high; *point; point = &(*point)->group_next)
20166 rstate.high_tail = point;
20167 /* Walk through the high list and move everything that needs
20170 for(point = &rstate.high; *point; point = next) {
20171 struct live_range *range;
20172 next = &(*point)->group_next;
20175 /* If it has a low degree or it already has a color
20176 * place the node in low.
20178 if ((range->degree < regc_max_size(state, range->classes)) ||
20179 (range->color != REG_UNSET)) {
20180 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20181 range - rstate.lr, range->degree,
20182 (range->color != REG_UNSET) ? " (colored)": "");
20183 *range->group_prev = range->group_next;
20184 if (range->group_next) {
20185 range->group_next->group_prev = range->group_prev;
20187 if (&range->group_next == rstate.high_tail) {
20188 rstate.high_tail = range->group_prev;
20190 range->group_prev = rstate.low_tail;
20191 range->group_next = 0;
20192 *rstate.low_tail = range;
20193 rstate.low_tail = &range->group_next;
20197 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20198 range - rstate.lr, range->degree,
20199 (range->color != REG_UNSET) ? " (colored)": "");
20202 /* Color the live_ranges */
20203 colored = color_graph(state, &rstate);
20205 } while (!colored);
20207 /* Verify the graph was properly colored */
20208 verify_colors(state, &rstate);
20210 /* Move the colors from the graph to the triples */
20211 color_triples(state, &rstate);
20213 /* Cleanup the temporary data structures */
20214 cleanup_rstate(state, &rstate);
20216 /* Display the new graph */
20217 print_blocks(state, __func__, state->dbgout);
20220 /* Sparce Conditional Constant Propogation
20221 * =========================================
20225 struct lattice_node {
20227 struct triple *def;
20228 struct ssa_edge *out;
20229 struct flow_block *fblock;
20230 struct triple *val;
20231 /* lattice high val == def
20232 * lattice const is_const(val)
20233 * lattice low other
20237 struct lattice_node *src;
20238 struct lattice_node *dst;
20239 struct ssa_edge *work_next;
20240 struct ssa_edge *work_prev;
20241 struct ssa_edge *out_next;
20244 struct flow_block *src;
20245 struct flow_block *dst;
20246 struct flow_edge *work_next;
20247 struct flow_edge *work_prev;
20248 struct flow_edge *in_next;
20249 struct flow_edge *out_next;
20252 #define MAX_FLOW_BLOCK_EDGES 3
20253 struct flow_block {
20254 struct block *block;
20255 struct flow_edge *in;
20256 struct flow_edge *out;
20257 struct flow_edge *edges;
20262 struct lattice_node *lattice;
20263 struct ssa_edge *ssa_edges;
20264 struct flow_block *flow_blocks;
20265 struct flow_edge *flow_work_list;
20266 struct ssa_edge *ssa_work_list;
20270 static int is_scc_const(struct compile_state *state, struct triple *ins)
20272 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20275 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20277 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20280 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20282 return is_scc_const(state, lnode->val);
20285 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20287 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20290 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20291 struct flow_edge *fedge)
20293 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20294 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20296 fedge->src->block?fedge->src->block->last->id: 0,
20297 fedge->dst->block?fedge->dst->block->first->id: 0);
20299 if ((fedge == scc->flow_work_list) ||
20300 (fedge->work_next != fedge) ||
20301 (fedge->work_prev != fedge)) {
20303 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20304 fprintf(state->errout, "dupped fedge: %p\n",
20309 if (!scc->flow_work_list) {
20310 scc->flow_work_list = fedge;
20311 fedge->work_next = fedge->work_prev = fedge;
20314 struct flow_edge *ftail;
20315 ftail = scc->flow_work_list->work_prev;
20316 fedge->work_next = ftail->work_next;
20317 fedge->work_prev = ftail;
20318 fedge->work_next->work_prev = fedge;
20319 fedge->work_prev->work_next = fedge;
20323 static struct flow_edge *scc_next_fedge(
20324 struct compile_state *state, struct scc_state *scc)
20326 struct flow_edge *fedge;
20327 fedge = scc->flow_work_list;
20329 fedge->work_next->work_prev = fedge->work_prev;
20330 fedge->work_prev->work_next = fedge->work_next;
20331 if (fedge->work_next != fedge) {
20332 scc->flow_work_list = fedge->work_next;
20334 scc->flow_work_list = 0;
20336 fedge->work_next = fedge->work_prev = fedge;
20341 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20342 struct ssa_edge *sedge)
20344 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20345 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20346 (long)(sedge - scc->ssa_edges),
20347 sedge->src->def->id,
20348 sedge->dst->def->id);
20350 if ((sedge == scc->ssa_work_list) ||
20351 (sedge->work_next != sedge) ||
20352 (sedge->work_prev != sedge)) {
20354 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20355 fprintf(state->errout, "dupped sedge: %5ld\n",
20356 (long)(sedge - scc->ssa_edges));
20360 if (!scc->ssa_work_list) {
20361 scc->ssa_work_list = sedge;
20362 sedge->work_next = sedge->work_prev = sedge;
20365 struct ssa_edge *stail;
20366 stail = scc->ssa_work_list->work_prev;
20367 sedge->work_next = stail->work_next;
20368 sedge->work_prev = stail;
20369 sedge->work_next->work_prev = sedge;
20370 sedge->work_prev->work_next = sedge;
20374 static struct ssa_edge *scc_next_sedge(
20375 struct compile_state *state, struct scc_state *scc)
20377 struct ssa_edge *sedge;
20378 sedge = scc->ssa_work_list;
20380 sedge->work_next->work_prev = sedge->work_prev;
20381 sedge->work_prev->work_next = sedge->work_next;
20382 if (sedge->work_next != sedge) {
20383 scc->ssa_work_list = sedge->work_next;
20385 scc->ssa_work_list = 0;
20387 sedge->work_next = sedge->work_prev = sedge;
20392 static void initialize_scc_state(
20393 struct compile_state *state, struct scc_state *scc)
20395 int ins_count, ssa_edge_count;
20396 int ins_index, ssa_edge_index, fblock_index;
20397 struct triple *first, *ins;
20398 struct block *block;
20399 struct flow_block *fblock;
20401 memset(scc, 0, sizeof(*scc));
20403 /* Inialize pass zero find out how much memory we need */
20404 first = state->first;
20406 ins_count = ssa_edge_count = 0;
20408 struct triple_set *edge;
20410 for(edge = ins->use; edge; edge = edge->next) {
20414 } while(ins != first);
20415 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20416 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20417 ins_count, ssa_edge_count, state->bb.last_vertex);
20419 scc->ins_count = ins_count;
20421 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20423 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20425 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20428 /* Initialize pass one collect up the nodes */
20431 ins_index = ssa_edge_index = fblock_index = 0;
20434 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20435 block = ins->u.block;
20437 internal_error(state, ins, "label without block");
20440 block->vertex = fblock_index;
20441 fblock = &scc->flow_blocks[fblock_index];
20442 fblock->block = block;
20443 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20447 struct lattice_node *lnode;
20449 lnode = &scc->lattice[ins_index];
20452 lnode->fblock = fblock;
20453 lnode->val = ins; /* LATTICE HIGH */
20454 if (lnode->val->op == OP_UNKNOWNVAL) {
20455 lnode->val = 0; /* LATTICE LOW by definition */
20457 lnode->old_id = ins->id;
20458 ins->id = ins_index;
20461 } while(ins != first);
20462 /* Initialize pass two collect up the edges */
20468 struct triple_set *edge;
20469 struct ssa_edge **stail;
20470 struct lattice_node *lnode;
20471 lnode = &scc->lattice[ins->id];
20473 stail = &lnode->out;
20474 for(edge = ins->use; edge; edge = edge->next) {
20475 struct ssa_edge *sedge;
20476 ssa_edge_index += 1;
20477 sedge = &scc->ssa_edges[ssa_edge_index];
20479 stail = &sedge->out_next;
20480 sedge->src = lnode;
20481 sedge->dst = &scc->lattice[edge->member->id];
20482 sedge->work_next = sedge->work_prev = sedge;
20483 sedge->out_next = 0;
20486 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20487 struct flow_edge *fedge, **ftail;
20488 struct block_set *bedge;
20489 block = ins->u.block;
20490 fblock = &scc->flow_blocks[block->vertex];
20493 ftail = &fblock->out;
20495 fedge = fblock->edges;
20496 bedge = block->edges;
20497 for(; bedge; bedge = bedge->next, fedge++) {
20498 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20499 if (fedge->dst->block != bedge->member) {
20500 internal_error(state, 0, "block mismatch");
20503 ftail = &fedge->out_next;
20504 fedge->out_next = 0;
20506 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20507 fedge->src = fblock;
20508 fedge->work_next = fedge->work_prev = fedge;
20509 fedge->executable = 0;
20513 } while (ins != first);
20518 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20519 struct flow_edge **ftail;
20520 struct block_set *bedge;
20521 block = ins->u.block;
20522 fblock = &scc->flow_blocks[block->vertex];
20523 ftail = &fblock->in;
20524 for(bedge = block->use; bedge; bedge = bedge->next) {
20525 struct block *src_block;
20526 struct flow_block *sfblock;
20527 struct flow_edge *sfedge;
20528 src_block = bedge->member;
20529 sfblock = &scc->flow_blocks[src_block->vertex];
20530 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20531 if (sfedge->dst == fblock) {
20536 internal_error(state, 0, "edge mismatch");
20539 ftail = &sfedge->in_next;
20540 sfedge->in_next = 0;
20544 } while(ins != first);
20545 /* Setup a dummy block 0 as a node above the start node */
20547 struct flow_block *fblock, *dst;
20548 struct flow_edge *fedge;
20549 fblock = &scc->flow_blocks[0];
20551 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20553 fblock->out = fblock->edges;
20554 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20555 fedge = fblock->edges;
20556 fedge->src = fblock;
20558 fedge->work_next = fedge;
20559 fedge->work_prev = fedge;
20560 fedge->in_next = fedge->dst->in;
20561 fedge->out_next = 0;
20562 fedge->executable = 0;
20563 fedge->dst->in = fedge;
20565 /* Initialize the work lists */
20566 scc->flow_work_list = 0;
20567 scc->ssa_work_list = 0;
20568 scc_add_fedge(state, scc, fedge);
20570 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20571 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20572 ins_index, ssa_edge_index, fblock_index);
20577 static void free_scc_state(
20578 struct compile_state *state, struct scc_state *scc)
20581 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20582 struct flow_block *fblock;
20583 fblock = &scc->flow_blocks[i];
20584 if (fblock->edges) {
20585 xfree(fblock->edges);
20589 xfree(scc->flow_blocks);
20590 xfree(scc->ssa_edges);
20591 xfree(scc->lattice);
20595 static struct lattice_node *triple_to_lattice(
20596 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20598 if (ins->id <= 0) {
20599 internal_error(state, ins, "bad id");
20601 return &scc->lattice[ins->id];
20604 static struct triple *preserve_lval(
20605 struct compile_state *state, struct lattice_node *lnode)
20607 struct triple *old;
20608 /* Preserve the original value */
20610 old = dup_triple(state, lnode->val);
20611 if (lnode->val != lnode->def) {
20621 static int lval_changed(struct compile_state *state,
20622 struct triple *old, struct lattice_node *lnode)
20625 /* See if the lattice value has changed */
20627 if (!old && !lnode->val) {
20631 lnode->val && old &&
20632 (memcmp(lnode->val->param, old->param,
20633 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20634 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20644 static void scc_debug_lnode(
20645 struct compile_state *state, struct scc_state *scc,
20646 struct lattice_node *lnode, int changed)
20648 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20649 display_triple_changes(state->errout, lnode->val, lnode->def);
20651 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20652 FILE *fp = state->errout;
20653 struct triple *val, **expr;
20654 val = lnode->val? lnode->val : lnode->def;
20655 fprintf(fp, "%p %s %3d %10s (",
20657 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20659 tops(lnode->def->op));
20660 expr = triple_rhs(state, lnode->def, 0);
20661 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20663 fprintf(fp, " %d", (*expr)->id);
20666 if (val->op == OP_INTCONST) {
20667 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20669 fprintf(fp, " ) -> %s %s\n",
20670 (is_lattice_hi(state, lnode)? "hi":
20671 is_lattice_const(state, lnode)? "const" : "lo"),
20672 changed? "changed" : ""
20677 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20678 struct lattice_node *lnode)
20681 struct triple *old, *scratch;
20682 struct triple **dexpr, **vexpr;
20685 /* Store the original value */
20686 old = preserve_lval(state, lnode);
20688 /* Reinitialize the value */
20689 lnode->val = scratch = dup_triple(state, lnode->def);
20690 scratch->id = lnode->old_id;
20691 scratch->next = scratch;
20692 scratch->prev = scratch;
20695 count = TRIPLE_SIZE(scratch);
20696 for(i = 0; i < count; i++) {
20697 dexpr = &lnode->def->param[i];
20698 vexpr = &scratch->param[i];
20700 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20701 (i >= TRIPLE_TARG_OFF(scratch))) &&
20703 struct lattice_node *tmp;
20704 tmp = triple_to_lattice(state, scc, *dexpr);
20705 *vexpr = (tmp->val)? tmp->val : tmp->def;
20708 if (triple_is_branch(state, scratch)) {
20709 scratch->next = lnode->def->next;
20711 /* Recompute the value */
20712 #if DEBUG_ROMCC_WARNINGS
20713 #warning "FIXME see if simplify does anything bad"
20715 /* So far it looks like only the strength reduction
20716 * optimization are things I need to worry about.
20718 simplify(state, scratch);
20719 /* Cleanup my value */
20720 if (scratch->use) {
20721 internal_error(state, lnode->def, "scratch used?");
20723 if ((scratch->prev != scratch) ||
20724 ((scratch->next != scratch) &&
20725 (!triple_is_branch(state, lnode->def) ||
20726 (scratch->next != lnode->def->next)))) {
20727 internal_error(state, lnode->def, "scratch in list?");
20729 /* undo any uses... */
20730 count = TRIPLE_SIZE(scratch);
20731 for(i = 0; i < count; i++) {
20732 vexpr = &scratch->param[i];
20734 unuse_triple(*vexpr, scratch);
20737 if (lnode->val->op == OP_UNKNOWNVAL) {
20738 lnode->val = 0; /* Lattice low by definition */
20740 /* Find the case when I am lattice high */
20742 (lnode->val->op == lnode->def->op) &&
20743 (memcmp(lnode->val->param, lnode->def->param,
20744 count * sizeof(lnode->val->param[0])) == 0) &&
20745 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20746 lnode->val = lnode->def;
20748 /* Only allow lattice high when all of my inputs
20749 * are also lattice high. Occassionally I can
20750 * have constants with a lattice low input, so
20751 * I do not need to check that case.
20753 if (is_lattice_hi(state, lnode)) {
20754 struct lattice_node *tmp;
20756 rhs = lnode->val->rhs;
20757 for(i = 0; i < rhs; i++) {
20758 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20759 if (!is_lattice_hi(state, tmp)) {
20765 /* Find the cases that are always lattice lo */
20767 triple_is_def(state, lnode->val) &&
20768 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20771 /* See if the lattice value has changed */
20772 changed = lval_changed(state, old, lnode);
20773 /* See if this value should not change */
20774 if ((lnode->val != lnode->def) &&
20775 (( !triple_is_def(state, lnode->def) &&
20776 !triple_is_cbranch(state, lnode->def)) ||
20777 (lnode->def->op == OP_PIECE))) {
20778 #if DEBUG_ROMCC_WARNINGS
20779 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20782 internal_warning(state, lnode->def, "non def changes value?");
20787 /* See if we need to free the scratch value */
20788 if (lnode->val != scratch) {
20796 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20797 struct lattice_node *lnode)
20799 struct lattice_node *cond;
20800 struct flow_edge *left, *right;
20803 /* Update the branch value */
20804 changed = compute_lnode_val(state, scc, lnode);
20805 scc_debug_lnode(state, scc, lnode, changed);
20807 /* This only applies to conditional branches */
20808 if (!triple_is_cbranch(state, lnode->def)) {
20809 internal_error(state, lnode->def, "not a conditional branch");
20812 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20813 struct flow_edge *fedge;
20814 FILE *fp = state->errout;
20815 fprintf(fp, "%s: %d (",
20816 tops(lnode->def->op),
20819 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20820 fprintf(fp, " %d", fedge->dst->block->vertex);
20823 if (lnode->def->rhs > 0) {
20824 fprintf(fp, " <- %d",
20825 RHS(lnode->def, 0)->id);
20829 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20830 for(left = cond->fblock->out; left; left = left->out_next) {
20831 if (left->dst->block->first == lnode->def->next) {
20836 internal_error(state, lnode->def, "Cannot find left branch edge");
20838 for(right = cond->fblock->out; right; right = right->out_next) {
20839 if (right->dst->block->first == TARG(lnode->def, 0)) {
20844 internal_error(state, lnode->def, "Cannot find right branch edge");
20846 /* I should only come here if the controlling expressions value
20847 * has changed, which means it must be either a constant or lo.
20849 if (is_lattice_hi(state, cond)) {
20850 internal_error(state, cond->def, "condition high?");
20853 if (is_lattice_lo(state, cond)) {
20854 scc_add_fedge(state, scc, left);
20855 scc_add_fedge(state, scc, right);
20857 else if (cond->val->u.cval) {
20858 scc_add_fedge(state, scc, right);
20860 scc_add_fedge(state, scc, left);
20866 static void scc_add_sedge_dst(struct compile_state *state,
20867 struct scc_state *scc, struct ssa_edge *sedge)
20869 if (triple_is_cbranch(state, sedge->dst->def)) {
20870 scc_visit_cbranch(state, scc, sedge->dst);
20872 else if (triple_is_def(state, sedge->dst->def)) {
20873 scc_add_sedge(state, scc, sedge);
20877 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20878 struct lattice_node *lnode)
20880 struct lattice_node *tmp;
20881 struct triple **slot, *old;
20882 struct flow_edge *fedge;
20885 if (lnode->def->op != OP_PHI) {
20886 internal_error(state, lnode->def, "not phi");
20888 /* Store the original value */
20889 old = preserve_lval(state, lnode);
20891 /* default to lattice high */
20892 lnode->val = lnode->def;
20893 slot = &RHS(lnode->def, 0);
20895 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20896 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20897 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20899 fedge->dst->block->vertex,
20903 if (!fedge->executable) {
20906 if (!slot[index]) {
20907 internal_error(state, lnode->def, "no phi value");
20909 tmp = triple_to_lattice(state, scc, slot[index]);
20910 /* meet(X, lattice low) = lattice low */
20911 if (is_lattice_lo(state, tmp)) {
20914 /* meet(X, lattice high) = X */
20915 else if (is_lattice_hi(state, tmp)) {
20916 lnode->val = lnode->val;
20918 /* meet(lattice high, X) = X */
20919 else if (is_lattice_hi(state, lnode)) {
20920 lnode->val = dup_triple(state, tmp->val);
20921 /* Only change the type if necessary */
20922 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20923 lnode->val->type = lnode->def->type;
20926 /* meet(const, const) = const or lattice low */
20927 else if (!constants_equal(state, lnode->val, tmp->val)) {
20931 /* meet(lattice low, X) = lattice low */
20932 if (is_lattice_lo(state, lnode)) {
20937 changed = lval_changed(state, old, lnode);
20938 scc_debug_lnode(state, scc, lnode, changed);
20940 /* If the lattice value has changed update the work lists. */
20942 struct ssa_edge *sedge;
20943 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20944 scc_add_sedge_dst(state, scc, sedge);
20950 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20951 struct lattice_node *lnode)
20955 if (!triple_is_def(state, lnode->def)) {
20956 internal_warning(state, lnode->def, "not visiting an expression?");
20958 changed = compute_lnode_val(state, scc, lnode);
20959 scc_debug_lnode(state, scc, lnode, changed);
20962 struct ssa_edge *sedge;
20963 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20964 scc_add_sedge_dst(state, scc, sedge);
20969 static void scc_writeback_values(
20970 struct compile_state *state, struct scc_state *scc)
20972 struct triple *first, *ins;
20973 first = state->first;
20976 struct lattice_node *lnode;
20977 lnode = triple_to_lattice(state, scc, ins);
20978 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20979 if (is_lattice_hi(state, lnode) &&
20980 (lnode->val->op != OP_NOOP))
20982 struct flow_edge *fedge;
20985 for(fedge = lnode->fblock->in;
20986 !executable && fedge; fedge = fedge->in_next) {
20987 executable |= fedge->executable;
20990 internal_warning(state, lnode->def,
20991 "lattice node %d %s->%s still high?",
20993 tops(lnode->def->op),
20994 tops(lnode->val->op));
21000 ins->id = lnode->old_id;
21001 if (lnode->val && (lnode->val != ins)) {
21002 /* See if it something I know how to write back */
21003 switch(lnode->val->op) {
21005 mkconst(state, ins, lnode->val->u.cval);
21008 mkaddr_const(state, ins,
21009 MISC(lnode->val, 0), lnode->val->u.cval);
21012 /* By default don't copy the changes,
21013 * recompute them in place instead.
21015 simplify(state, ins);
21018 if (is_const(lnode->val) &&
21019 !constants_equal(state, lnode->val, ins)) {
21020 internal_error(state, 0, "constants not equal");
21022 /* Free the lattice nodes */
21027 } while(ins != first);
21030 static void scc_transform(struct compile_state *state)
21032 struct scc_state scc;
21033 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21037 initialize_scc_state(state, &scc);
21039 while(scc.flow_work_list || scc.ssa_work_list) {
21040 struct flow_edge *fedge;
21041 struct ssa_edge *sedge;
21042 struct flow_edge *fptr;
21043 while((fedge = scc_next_fedge(state, &scc))) {
21044 struct block *block;
21045 struct triple *ptr;
21046 struct flow_block *fblock;
21049 if (fedge->executable) {
21053 internal_error(state, 0, "fedge without dst");
21056 internal_error(state, 0, "fedge without src");
21058 fedge->executable = 1;
21059 fblock = fedge->dst;
21060 block = fblock->block;
21062 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21063 if (fptr->executable) {
21068 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21069 fprintf(state->errout, "vertex: %d reps: %d\n",
21070 block->vertex, reps);
21074 for(ptr = block->first; !done; ptr = ptr->next) {
21075 struct lattice_node *lnode;
21076 done = (ptr == block->last);
21077 lnode = &scc.lattice[ptr->id];
21078 if (ptr->op == OP_PHI) {
21079 scc_visit_phi(state, &scc, lnode);
21081 else if ((reps == 1) && triple_is_def(state, ptr))
21083 scc_visit_expr(state, &scc, lnode);
21086 /* Add unconditional branch edges */
21087 if (!triple_is_cbranch(state, fblock->block->last)) {
21088 struct flow_edge *out;
21089 for(out = fblock->out; out; out = out->out_next) {
21090 scc_add_fedge(state, &scc, out);
21094 while((sedge = scc_next_sedge(state, &scc))) {
21095 struct lattice_node *lnode;
21096 struct flow_block *fblock;
21097 lnode = sedge->dst;
21098 fblock = lnode->fblock;
21100 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21101 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21102 sedge - scc.ssa_edges,
21103 sedge->src->def->id,
21104 sedge->dst->def->id);
21107 if (lnode->def->op == OP_PHI) {
21108 scc_visit_phi(state, &scc, lnode);
21111 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21112 if (fptr->executable) {
21117 scc_visit_expr(state, &scc, lnode);
21123 scc_writeback_values(state, &scc);
21124 free_scc_state(state, &scc);
21125 rebuild_ssa_form(state);
21127 print_blocks(state, __func__, state->dbgout);
21131 static void transform_to_arch_instructions(struct compile_state *state)
21133 struct triple *ins, *first;
21134 first = state->first;
21137 ins = transform_to_arch_instruction(state, ins);
21138 } while(ins != first);
21140 print_blocks(state, __func__, state->dbgout);
21143 #if DEBUG_CONSISTENCY
21144 static void verify_uses(struct compile_state *state)
21146 struct triple *first, *ins;
21147 struct triple_set *set;
21148 first = state->first;
21151 struct triple **expr;
21152 expr = triple_rhs(state, ins, 0);
21153 for(; expr; expr = triple_rhs(state, ins, expr)) {
21154 struct triple *rhs;
21156 for(set = rhs?rhs->use:0; set; set = set->next) {
21157 if (set->member == ins) {
21162 internal_error(state, ins, "rhs not used");
21165 expr = triple_lhs(state, ins, 0);
21166 for(; expr; expr = triple_lhs(state, ins, expr)) {
21167 struct triple *lhs;
21169 for(set = lhs?lhs->use:0; set; set = set->next) {
21170 if (set->member == ins) {
21175 internal_error(state, ins, "lhs not used");
21178 expr = triple_misc(state, ins, 0);
21179 if (ins->op != OP_PHI) {
21180 for(; expr; expr = triple_targ(state, ins, expr)) {
21181 struct triple *misc;
21183 for(set = misc?misc->use:0; set; set = set->next) {
21184 if (set->member == ins) {
21189 internal_error(state, ins, "misc not used");
21193 if (!triple_is_ret(state, ins)) {
21194 expr = triple_targ(state, ins, 0);
21195 for(; expr; expr = triple_targ(state, ins, expr)) {
21196 struct triple *targ;
21198 for(set = targ?targ->use:0; set; set = set->next) {
21199 if (set->member == ins) {
21204 internal_error(state, ins, "targ not used");
21209 } while(ins != first);
21212 static void verify_blocks_present(struct compile_state *state)
21214 struct triple *first, *ins;
21215 if (!state->bb.first_block) {
21218 first = state->first;
21221 valid_ins(state, ins);
21222 if (triple_stores_block(state, ins)) {
21223 if (!ins->u.block) {
21224 internal_error(state, ins,
21225 "%p not in a block?", ins);
21229 } while(ins != first);
21234 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21236 struct block_set *bedge;
21237 struct block *targ;
21238 targ = block_of_triple(state, edge);
21239 for(bedge = block->edges; bedge; bedge = bedge->next) {
21240 if (bedge->member == targ) {
21247 static void verify_blocks(struct compile_state *state)
21249 struct triple *ins;
21250 struct block *block;
21252 block = state->bb.first_block;
21259 struct block_set *user, *edge;
21261 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21262 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21263 internal_error(state, ins, "inconsitent block specified");
21265 valid_ins(state, ins);
21268 for(user = block->use; user; user = user->next) {
21270 if (!user->member->first) {
21271 internal_error(state, block->first, "user is empty");
21273 if ((block == state->bb.last_block) &&
21274 (user->member == state->bb.first_block)) {
21277 for(edge = user->member->edges; edge; edge = edge->next) {
21278 if (edge->member == block) {
21283 internal_error(state, user->member->first,
21284 "user does not use block");
21287 if (triple_is_branch(state, block->last)) {
21288 struct triple **expr;
21289 expr = triple_edge_targ(state, block->last, 0);
21290 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21291 if (*expr && !edge_present(state, block, *expr)) {
21292 internal_error(state, block->last, "no edge to targ");
21296 if (!triple_is_ubranch(state, block->last) &&
21297 (block != state->bb.last_block) &&
21298 !edge_present(state, block, block->last->next)) {
21299 internal_error(state, block->last, "no edge to block->last->next");
21301 for(edge = block->edges; edge; edge = edge->next) {
21302 for(user = edge->member->use; user; user = user->next) {
21303 if (user->member == block) {
21307 if (!user || user->member != block) {
21308 internal_error(state, block->first,
21309 "block does not use edge");
21311 if (!edge->member->first) {
21312 internal_error(state, block->first, "edge block is empty");
21315 if (block->users != users) {
21316 internal_error(state, block->first,
21317 "computed users %d != stored users %d",
21318 users, block->users);
21320 if (!triple_stores_block(state, block->last->next)) {
21321 internal_error(state, block->last->next,
21322 "cannot find next block");
21324 block = block->last->next->u.block;
21326 internal_error(state, block->last->next,
21329 } while(block != state->bb.first_block);
21330 if (blocks != state->bb.last_vertex) {
21331 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21332 blocks, state->bb.last_vertex);
21336 static void verify_domination(struct compile_state *state)
21338 struct triple *first, *ins;
21339 struct triple_set *set;
21340 if (!state->bb.first_block) {
21344 first = state->first;
21347 for(set = ins->use; set; set = set->next) {
21348 struct triple **slot;
21349 struct triple *use_point;
21352 zrhs = set->member->rhs;
21353 slot = &RHS(set->member, 0);
21354 /* See if the use is on the right hand side */
21355 for(i = 0; i < zrhs; i++) {
21356 if (slot[i] == ins) {
21361 use_point = set->member;
21362 if (set->member->op == OP_PHI) {
21363 struct block_set *bset;
21365 bset = set->member->u.block->use;
21366 for(edge = 0; bset && (edge < i); edge++) {
21370 internal_error(state, set->member,
21371 "no edge for phi rhs %d", i);
21373 use_point = bset->member->last;
21377 !tdominates(state, ins, use_point)) {
21378 if (is_const(ins)) {
21379 internal_warning(state, ins,
21380 "non dominated rhs use point %p?", use_point);
21383 internal_error(state, ins,
21384 "non dominated rhs use point %p?", use_point);
21389 } while(ins != first);
21392 static void verify_rhs(struct compile_state *state)
21394 struct triple *first, *ins;
21395 first = state->first;
21398 struct triple **slot;
21401 slot = &RHS(ins, 0);
21402 for(i = 0; i < zrhs; i++) {
21403 if (slot[i] == 0) {
21404 internal_error(state, ins,
21405 "missing rhs %d on %s",
21408 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21409 internal_error(state, ins,
21410 "ins == rhs[%d] on %s",
21415 } while(ins != first);
21418 static void verify_piece(struct compile_state *state)
21420 struct triple *first, *ins;
21421 first = state->first;
21424 struct triple *ptr;
21427 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21428 if (ptr != LHS(ins, i)) {
21429 internal_error(state, ins, "malformed lhs on %s",
21432 if (ptr->op != OP_PIECE) {
21433 internal_error(state, ins, "bad lhs op %s at %d on %s",
21434 tops(ptr->op), i, tops(ins->op));
21436 if (ptr->u.cval != i) {
21437 internal_error(state, ins, "bad u.cval of %d %d expected",
21442 } while(ins != first);
21445 static void verify_ins_colors(struct compile_state *state)
21447 struct triple *first, *ins;
21449 first = state->first;
21453 } while(ins != first);
21456 static void verify_unknown(struct compile_state *state)
21458 struct triple *first, *ins;
21459 if ( (unknown_triple.next != &unknown_triple) ||
21460 (unknown_triple.prev != &unknown_triple) ||
21462 (unknown_triple.use != 0) ||
21464 (unknown_triple.op != OP_UNKNOWNVAL) ||
21465 (unknown_triple.lhs != 0) ||
21466 (unknown_triple.rhs != 0) ||
21467 (unknown_triple.misc != 0) ||
21468 (unknown_triple.targ != 0) ||
21469 (unknown_triple.template_id != 0) ||
21470 (unknown_triple.id != -1) ||
21471 (unknown_triple.type != &unknown_type) ||
21472 (unknown_triple.occurance != &dummy_occurance) ||
21473 (unknown_triple.param[0] != 0) ||
21474 (unknown_triple.param[1] != 0)) {
21475 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21477 if ( (dummy_occurance.count != 2) ||
21478 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21479 (strcmp(dummy_occurance.function, "") != 0) ||
21480 (dummy_occurance.col != 0) ||
21481 (dummy_occurance.parent != 0)) {
21482 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21484 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21485 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21487 first = state->first;
21491 if (ins == &unknown_triple) {
21492 internal_error(state, ins, "unknown triple in list");
21494 params = TRIPLE_SIZE(ins);
21495 for(i = 0; i < params; i++) {
21496 if (ins->param[i] == &unknown_triple) {
21497 internal_error(state, ins, "unknown triple used!");
21501 } while(ins != first);
21504 static void verify_types(struct compile_state *state)
21506 struct triple *first, *ins;
21507 first = state->first;
21510 struct type *invalid;
21511 invalid = invalid_type(state, ins->type);
21513 FILE *fp = state->errout;
21514 fprintf(fp, "type: ");
21515 name_of(fp, ins->type);
21517 fprintf(fp, "invalid type: ");
21518 name_of(fp, invalid);
21520 internal_error(state, ins, "invalid ins type");
21522 } while(ins != first);
21525 static void verify_copy(struct compile_state *state)
21527 struct triple *first, *ins, *next;
21528 first = state->first;
21529 next = ins = first;
21533 if (ins->op != OP_COPY) {
21536 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21537 FILE *fp = state->errout;
21538 fprintf(fp, "src type: ");
21539 name_of(fp, RHS(ins, 0)->type);
21541 fprintf(fp, "dst type: ");
21542 name_of(fp, ins->type);
21544 internal_error(state, ins, "type mismatch in copy");
21546 } while(next != first);
21549 static void verify_consistency(struct compile_state *state)
21551 verify_unknown(state);
21552 verify_uses(state);
21553 verify_blocks_present(state);
21554 verify_blocks(state);
21555 verify_domination(state);
21557 verify_piece(state);
21558 verify_ins_colors(state);
21559 verify_types(state);
21560 verify_copy(state);
21561 if (state->compiler->debug & DEBUG_VERIFICATION) {
21562 fprintf(state->dbgout, "consistency verified\n");
21566 static void verify_consistency(struct compile_state *state) {}
21567 #endif /* DEBUG_CONSISTENCY */
21569 static void optimize(struct compile_state *state)
21571 /* Join all of the functions into one giant function */
21572 join_functions(state);
21574 /* Dump what the instruction graph intially looks like */
21575 print_triples(state);
21577 /* Replace structures with simpler data types */
21578 decompose_compound_types(state);
21579 print_triples(state);
21581 verify_consistency(state);
21582 /* Analyze the intermediate code */
21583 state->bb.first = state->first;
21584 analyze_basic_blocks(state, &state->bb);
21586 /* Transform the code to ssa form. */
21588 * The transformation to ssa form puts a phi function
21589 * on each of edge of a dominance frontier where that
21590 * phi function might be needed. At -O2 if we don't
21591 * eleminate the excess phi functions we can get an
21592 * exponential code size growth. So I kill the extra
21593 * phi functions early and I kill them often.
21595 transform_to_ssa_form(state);
21596 verify_consistency(state);
21598 /* Remove dead code */
21599 eliminate_inefectual_code(state);
21600 verify_consistency(state);
21602 /* Do strength reduction and simple constant optimizations */
21603 simplify_all(state);
21604 verify_consistency(state);
21605 /* Propogate constants throughout the code */
21606 scc_transform(state);
21607 verify_consistency(state);
21608 #if DEBUG_ROMCC_WARNINGS
21609 #warning "WISHLIST implement single use constants (least possible register pressure)"
21610 #warning "WISHLIST implement induction variable elimination"
21612 /* Select architecture instructions and an initial partial
21613 * coloring based on architecture constraints.
21615 transform_to_arch_instructions(state);
21616 verify_consistency(state);
21618 /* Remove dead code */
21619 eliminate_inefectual_code(state);
21620 verify_consistency(state);
21622 /* Color all of the variables to see if they will fit in registers */
21623 insert_copies_to_phi(state);
21624 verify_consistency(state);
21626 insert_mandatory_copies(state);
21627 verify_consistency(state);
21629 allocate_registers(state);
21630 verify_consistency(state);
21632 /* Remove the optimization information.
21633 * This is more to check for memory consistency than to free memory.
21635 free_basic_blocks(state, &state->bb);
21638 static void print_op_asm(struct compile_state *state,
21639 struct triple *ins, FILE *fp)
21641 struct asm_info *info;
21643 unsigned lhs, rhs, i;
21644 info = ins->u.ainfo;
21647 /* Don't count the clobbers in lhs */
21648 for(i = 0; i < lhs; i++) {
21649 if (LHS(ins, i)->type == &void_type) {
21654 fprintf(fp, "#ASM\n");
21656 for(ptr = info->str; *ptr; ptr++) {
21658 unsigned long param;
21659 struct triple *piece;
21669 param = strtoul(ptr, &next, 10);
21671 error(state, ins, "Invalid asm template");
21673 if (param >= (lhs + rhs)) {
21674 error(state, ins, "Invalid param %%%u in asm template",
21677 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21679 arch_reg_str(ID_REG(piece->id)));
21682 fprintf(fp, "\n#NOT ASM\n");
21686 /* Only use the low x86 byte registers. This allows me
21687 * allocate the entire register when a byte register is used.
21689 #define X86_4_8BIT_GPRS 1
21692 #define X86_MMX_REGS (1<<0)
21693 #define X86_XMM_REGS (1<<1)
21694 #define X86_NOOP_COPY (1<<2)
21696 /* The x86 register classes */
21697 #define REGC_FLAGS 0
21698 #define REGC_GPR8 1
21699 #define REGC_GPR16 2
21700 #define REGC_GPR32 3
21701 #define REGC_DIVIDEND64 4
21702 #define REGC_DIVIDEND32 5
21705 #define REGC_GPR32_8 8
21706 #define REGC_GPR16_8 9
21707 #define REGC_GPR8_LO 10
21708 #define REGC_IMM32 11
21709 #define REGC_IMM16 12
21710 #define REGC_IMM8 13
21711 #define LAST_REGC REGC_IMM8
21712 #if LAST_REGC >= MAX_REGC
21713 #error "MAX_REGC is to low"
21716 /* Register class masks */
21717 #define REGCM_FLAGS (1 << REGC_FLAGS)
21718 #define REGCM_GPR8 (1 << REGC_GPR8)
21719 #define REGCM_GPR16 (1 << REGC_GPR16)
21720 #define REGCM_GPR32 (1 << REGC_GPR32)
21721 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21722 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21723 #define REGCM_MMX (1 << REGC_MMX)
21724 #define REGCM_XMM (1 << REGC_XMM)
21725 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21726 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21727 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21728 #define REGCM_IMM32 (1 << REGC_IMM32)
21729 #define REGCM_IMM16 (1 << REGC_IMM16)
21730 #define REGCM_IMM8 (1 << REGC_IMM8)
21731 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21732 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21734 /* The x86 registers */
21735 #define REG_EFLAGS 2
21736 #define REGC_FLAGS_FIRST REG_EFLAGS
21737 #define REGC_FLAGS_LAST REG_EFLAGS
21746 #define REGC_GPR8_LO_FIRST REG_AL
21747 #define REGC_GPR8_LO_LAST REG_DL
21748 #define REGC_GPR8_FIRST REG_AL
21749 #define REGC_GPR8_LAST REG_DH
21758 #define REGC_GPR16_FIRST REG_AX
21759 #define REGC_GPR16_LAST REG_SP
21768 #define REGC_GPR32_FIRST REG_EAX
21769 #define REGC_GPR32_LAST REG_ESP
21770 #define REG_EDXEAX 27
21771 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21772 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21773 #define REG_DXAX 28
21774 #define REGC_DIVIDEND32_FIRST REG_DXAX
21775 #define REGC_DIVIDEND32_LAST REG_DXAX
21776 #define REG_MMX0 29
21777 #define REG_MMX1 30
21778 #define REG_MMX2 31
21779 #define REG_MMX3 32
21780 #define REG_MMX4 33
21781 #define REG_MMX5 34
21782 #define REG_MMX6 35
21783 #define REG_MMX7 36
21784 #define REGC_MMX_FIRST REG_MMX0
21785 #define REGC_MMX_LAST REG_MMX7
21786 #define REG_XMM0 37
21787 #define REG_XMM1 38
21788 #define REG_XMM2 39
21789 #define REG_XMM3 40
21790 #define REG_XMM4 41
21791 #define REG_XMM5 42
21792 #define REG_XMM6 43
21793 #define REG_XMM7 44
21794 #define REGC_XMM_FIRST REG_XMM0
21795 #define REGC_XMM_LAST REG_XMM7
21797 #if DEBUG_ROMCC_WARNINGS
21798 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21801 #define LAST_REG REG_XMM7
21803 #define REGC_GPR32_8_FIRST REG_EAX
21804 #define REGC_GPR32_8_LAST REG_EDX
21805 #define REGC_GPR16_8_FIRST REG_AX
21806 #define REGC_GPR16_8_LAST REG_DX
21808 #define REGC_IMM8_FIRST -1
21809 #define REGC_IMM8_LAST -1
21810 #define REGC_IMM16_FIRST -2
21811 #define REGC_IMM16_LAST -1
21812 #define REGC_IMM32_FIRST -4
21813 #define REGC_IMM32_LAST -1
21815 #if LAST_REG >= MAX_REGISTERS
21816 #error "MAX_REGISTERS to low"
21820 static unsigned regc_size[LAST_REGC +1] = {
21821 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21822 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21823 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21824 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21825 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21826 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21827 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21828 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21829 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21830 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21831 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21837 static const struct {
21839 } regcm_bound[LAST_REGC + 1] = {
21840 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21841 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21842 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21843 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21844 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21845 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21846 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21847 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21848 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21849 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21850 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21851 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21852 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21853 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21856 #if ARCH_INPUT_REGS != 4
21857 #error ARCH_INPUT_REGS size mismatch
21859 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21860 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21861 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21862 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21863 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21866 #if ARCH_OUTPUT_REGS != 4
21867 #error ARCH_INPUT_REGS size mismatch
21869 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21870 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21871 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21872 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21873 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21876 static void init_arch_state(struct arch_state *arch)
21878 memset(arch, 0, sizeof(*arch));
21879 arch->features = 0;
21882 static const struct compiler_flag arch_flags[] = {
21883 { "mmx", X86_MMX_REGS },
21884 { "sse", X86_XMM_REGS },
21885 { "noop-copy", X86_NOOP_COPY },
21888 static const struct compiler_flag arch_cpus[] = {
21890 { "p2", X86_MMX_REGS },
21891 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21892 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21893 { "k7", X86_MMX_REGS },
21894 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21895 { "c3", X86_MMX_REGS },
21896 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21899 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21906 if (strncmp(flag, "no-", 3) == 0) {
21910 if (act && strncmp(flag, "cpu=", 4) == 0) {
21912 result = set_flag(arch_cpus, &arch->features, 1, flag);
21915 result = set_flag(arch_flags, &arch->features, act, flag);
21920 static void arch_usage(FILE *fp)
21922 flag_usage(fp, arch_flags, "-m", "-mno-");
21923 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21926 static unsigned arch_regc_size(struct compile_state *state, int class)
21928 if ((class < 0) || (class > LAST_REGC)) {
21931 return regc_size[class];
21934 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21936 /* See if two register classes may have overlapping registers */
21937 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21938 REGCM_GPR32_8 | REGCM_GPR32 |
21939 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21941 /* Special case for the immediates */
21942 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21943 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21944 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21945 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21948 return (regcm1 & regcm2) ||
21949 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21952 static void arch_reg_equivs(
21953 struct compile_state *state, unsigned *equiv, int reg)
21955 if ((reg < 0) || (reg > LAST_REG)) {
21956 internal_error(state, 0, "invalid register");
21961 #if X86_4_8BIT_GPRS
21965 *equiv++ = REG_EAX;
21966 *equiv++ = REG_DXAX;
21967 *equiv++ = REG_EDXEAX;
21970 #if X86_4_8BIT_GPRS
21974 *equiv++ = REG_EAX;
21975 *equiv++ = REG_DXAX;
21976 *equiv++ = REG_EDXEAX;
21979 #if X86_4_8BIT_GPRS
21983 *equiv++ = REG_EBX;
21987 #if X86_4_8BIT_GPRS
21991 *equiv++ = REG_EBX;
21994 #if X86_4_8BIT_GPRS
21998 *equiv++ = REG_ECX;
22002 #if X86_4_8BIT_GPRS
22006 *equiv++ = REG_ECX;
22009 #if X86_4_8BIT_GPRS
22013 *equiv++ = REG_EDX;
22014 *equiv++ = REG_DXAX;
22015 *equiv++ = REG_EDXEAX;
22018 #if X86_4_8BIT_GPRS
22022 *equiv++ = REG_EDX;
22023 *equiv++ = REG_DXAX;
22024 *equiv++ = REG_EDXEAX;
22029 *equiv++ = REG_EAX;
22030 *equiv++ = REG_DXAX;
22031 *equiv++ = REG_EDXEAX;
22036 *equiv++ = REG_EBX;
22041 *equiv++ = REG_ECX;
22046 *equiv++ = REG_EDX;
22047 *equiv++ = REG_DXAX;
22048 *equiv++ = REG_EDXEAX;
22051 *equiv++ = REG_ESI;
22054 *equiv++ = REG_EDI;
22057 *equiv++ = REG_EBP;
22060 *equiv++ = REG_ESP;
22066 *equiv++ = REG_DXAX;
22067 *equiv++ = REG_EDXEAX;
22083 *equiv++ = REG_DXAX;
22084 *equiv++ = REG_EDXEAX;
22105 *equiv++ = REG_EAX;
22106 *equiv++ = REG_EDX;
22107 *equiv++ = REG_EDXEAX;
22116 *equiv++ = REG_EAX;
22117 *equiv++ = REG_EDX;
22118 *equiv++ = REG_DXAX;
22121 *equiv++ = REG_UNSET;
22124 static unsigned arch_avail_mask(struct compile_state *state)
22126 unsigned avail_mask;
22127 /* REGCM_GPR8 is not available */
22128 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22129 REGCM_GPR32 | REGCM_GPR32_8 |
22130 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22131 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22132 if (state->arch->features & X86_MMX_REGS) {
22133 avail_mask |= REGCM_MMX;
22135 if (state->arch->features & X86_XMM_REGS) {
22136 avail_mask |= REGCM_XMM;
22141 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22143 unsigned mask, result;
22147 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22148 if ((result & mask) == 0) {
22151 if (class > LAST_REGC) {
22154 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22155 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22156 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22157 result |= (1 << class2);
22161 result &= arch_avail_mask(state);
22165 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22167 /* Like arch_regcm_normalize except immediate register classes are excluded */
22168 regcm = arch_regcm_normalize(state, regcm);
22169 /* Remove the immediate register classes */
22170 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22175 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22180 for(class = 0; class <= LAST_REGC; class++) {
22181 if ((reg >= regcm_bound[class].first) &&
22182 (reg <= regcm_bound[class].last)) {
22183 mask |= (1 << class);
22187 internal_error(state, 0, "reg %d not in any class", reg);
22192 static struct reg_info arch_reg_constraint(
22193 struct compile_state *state, struct type *type, const char *constraint)
22195 static const struct {
22199 } constraints[] = {
22200 { 'r', REGCM_GPR32, REG_UNSET },
22201 { 'g', REGCM_GPR32, REG_UNSET },
22202 { 'p', REGCM_GPR32, REG_UNSET },
22203 { 'q', REGCM_GPR8_LO, REG_UNSET },
22204 { 'Q', REGCM_GPR32_8, REG_UNSET },
22205 { 'x', REGCM_XMM, REG_UNSET },
22206 { 'y', REGCM_MMX, REG_UNSET },
22207 { 'a', REGCM_GPR32, REG_EAX },
22208 { 'b', REGCM_GPR32, REG_EBX },
22209 { 'c', REGCM_GPR32, REG_ECX },
22210 { 'd', REGCM_GPR32, REG_EDX },
22211 { 'D', REGCM_GPR32, REG_EDI },
22212 { 'S', REGCM_GPR32, REG_ESI },
22213 { '\0', 0, REG_UNSET },
22215 unsigned int regcm;
22216 unsigned int mask, reg;
22217 struct reg_info result;
22219 regcm = arch_type_to_regcm(state, type);
22222 for(ptr = constraint; *ptr; ptr++) {
22227 for(i = 0; constraints[i].class != '\0'; i++) {
22228 if (constraints[i].class == *ptr) {
22232 if (constraints[i].class == '\0') {
22233 error(state, 0, "invalid register constraint ``%c''", *ptr);
22236 if ((constraints[i].mask & regcm) == 0) {
22237 error(state, 0, "invalid register class %c specified",
22240 mask |= constraints[i].mask;
22241 if (constraints[i].reg != REG_UNSET) {
22242 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22243 error(state, 0, "Only one register may be specified");
22245 reg = constraints[i].reg;
22249 result.regcm = mask;
22253 static struct reg_info arch_reg_clobber(
22254 struct compile_state *state, const char *clobber)
22256 struct reg_info result;
22257 if (strcmp(clobber, "memory") == 0) {
22258 result.reg = REG_UNSET;
22261 else if (strcmp(clobber, "eax") == 0) {
22262 result.reg = REG_EAX;
22263 result.regcm = REGCM_GPR32;
22265 else if (strcmp(clobber, "ebx") == 0) {
22266 result.reg = REG_EBX;
22267 result.regcm = REGCM_GPR32;
22269 else if (strcmp(clobber, "ecx") == 0) {
22270 result.reg = REG_ECX;
22271 result.regcm = REGCM_GPR32;
22273 else if (strcmp(clobber, "edx") == 0) {
22274 result.reg = REG_EDX;
22275 result.regcm = REGCM_GPR32;
22277 else if (strcmp(clobber, "esi") == 0) {
22278 result.reg = REG_ESI;
22279 result.regcm = REGCM_GPR32;
22281 else if (strcmp(clobber, "edi") == 0) {
22282 result.reg = REG_EDI;
22283 result.regcm = REGCM_GPR32;
22285 else if (strcmp(clobber, "ebp") == 0) {
22286 result.reg = REG_EBP;
22287 result.regcm = REGCM_GPR32;
22289 else if (strcmp(clobber, "esp") == 0) {
22290 result.reg = REG_ESP;
22291 result.regcm = REGCM_GPR32;
22293 else if (strcmp(clobber, "cc") == 0) {
22294 result.reg = REG_EFLAGS;
22295 result.regcm = REGCM_FLAGS;
22297 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22298 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22299 result.reg = REG_XMM0 + octdigval(clobber[3]);
22300 result.regcm = REGCM_XMM;
22302 else if ((strncmp(clobber, "mm", 2) == 0) &&
22303 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22304 result.reg = REG_MMX0 + octdigval(clobber[3]);
22305 result.regcm = REGCM_MMX;
22308 error(state, 0, "unknown register name `%s' in asm",
22310 result.reg = REG_UNSET;
22316 static int do_select_reg(struct compile_state *state,
22317 char *used, int reg, unsigned classes)
22323 mask = arch_reg_regcm(state, reg);
22324 return (classes & mask) ? reg : REG_UNSET;
22327 static int arch_select_free_register(
22328 struct compile_state *state, char *used, int classes)
22330 /* Live ranges with the most neighbors are colored first.
22332 * Generally it does not matter which colors are given
22333 * as the register allocator attempts to color live ranges
22334 * in an order where you are guaranteed not to run out of colors.
22336 * Occasionally the register allocator cannot find an order
22337 * of register selection that will find a free color. To
22338 * increase the odds the register allocator will work when
22339 * it guesses first give out registers from register classes
22340 * least likely to run out of registers.
22345 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22346 reg = do_select_reg(state, used, i, classes);
22348 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22349 reg = do_select_reg(state, used, i, classes);
22351 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22352 reg = do_select_reg(state, used, i, classes);
22354 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22355 reg = do_select_reg(state, used, i, classes);
22357 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22358 reg = do_select_reg(state, used, i, classes);
22360 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22361 reg = do_select_reg(state, used, i, classes);
22363 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22364 reg = do_select_reg(state, used, i, classes);
22366 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22367 reg = do_select_reg(state, used, i, classes);
22369 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22370 reg = do_select_reg(state, used, i, classes);
22376 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22379 #if DEBUG_ROMCC_WARNINGS
22380 #warning "FIXME force types smaller (if legal) before I get here"
22384 switch(type->type & TYPE_MASK) {
22391 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22392 REGCM_GPR16 | REGCM_GPR16_8 |
22393 REGCM_GPR32 | REGCM_GPR32_8 |
22394 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22395 REGCM_MMX | REGCM_XMM |
22396 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22400 mask = 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;
22412 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22413 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22414 REGCM_MMX | REGCM_XMM |
22419 mask = arch_type_to_regcm(state, type->left);
22422 mask = arch_type_to_regcm(state, type->left) &
22423 arch_type_to_regcm(state, type->right);
22425 case TYPE_BITFIELD:
22426 mask = arch_type_to_regcm(state, type->left);
22429 fprintf(state->errout, "type: ");
22430 name_of(state->errout, type);
22431 fprintf(state->errout, "\n");
22432 internal_error(state, 0, "no register class for type");
22435 mask = arch_regcm_normalize(state, mask);
22439 static int is_imm32(struct triple *imm)
22441 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22442 (imm->op == OP_ADDRCONST);
22445 static int is_imm16(struct triple *imm)
22447 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22449 static int is_imm8(struct triple *imm)
22451 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22454 static int get_imm32(struct triple *ins, struct triple **expr)
22456 struct triple *imm;
22458 while(imm->op == OP_COPY) {
22461 if (!is_imm32(imm)) {
22464 unuse_triple(*expr, ins);
22465 use_triple(imm, ins);
22470 static int get_imm8(struct triple *ins, struct triple **expr)
22472 struct triple *imm;
22474 while(imm->op == OP_COPY) {
22477 if (!is_imm8(imm)) {
22480 unuse_triple(*expr, ins);
22481 use_triple(imm, ins);
22486 #define TEMPLATE_NOP 0
22487 #define TEMPLATE_INTCONST8 1
22488 #define TEMPLATE_INTCONST32 2
22489 #define TEMPLATE_UNKNOWNVAL 3
22490 #define TEMPLATE_COPY8_REG 5
22491 #define TEMPLATE_COPY16_REG 6
22492 #define TEMPLATE_COPY32_REG 7
22493 #define TEMPLATE_COPY_IMM8 8
22494 #define TEMPLATE_COPY_IMM16 9
22495 #define TEMPLATE_COPY_IMM32 10
22496 #define TEMPLATE_PHI8 11
22497 #define TEMPLATE_PHI16 12
22498 #define TEMPLATE_PHI32 13
22499 #define TEMPLATE_STORE8 14
22500 #define TEMPLATE_STORE16 15
22501 #define TEMPLATE_STORE32 16
22502 #define TEMPLATE_LOAD8 17
22503 #define TEMPLATE_LOAD16 18
22504 #define TEMPLATE_LOAD32 19
22505 #define TEMPLATE_BINARY8_REG 20
22506 #define TEMPLATE_BINARY16_REG 21
22507 #define TEMPLATE_BINARY32_REG 22
22508 #define TEMPLATE_BINARY8_IMM 23
22509 #define TEMPLATE_BINARY16_IMM 24
22510 #define TEMPLATE_BINARY32_IMM 25
22511 #define TEMPLATE_SL8_CL 26
22512 #define TEMPLATE_SL16_CL 27
22513 #define TEMPLATE_SL32_CL 28
22514 #define TEMPLATE_SL8_IMM 29
22515 #define TEMPLATE_SL16_IMM 30
22516 #define TEMPLATE_SL32_IMM 31
22517 #define TEMPLATE_UNARY8 32
22518 #define TEMPLATE_UNARY16 33
22519 #define TEMPLATE_UNARY32 34
22520 #define TEMPLATE_CMP8_REG 35
22521 #define TEMPLATE_CMP16_REG 36
22522 #define TEMPLATE_CMP32_REG 37
22523 #define TEMPLATE_CMP8_IMM 38
22524 #define TEMPLATE_CMP16_IMM 39
22525 #define TEMPLATE_CMP32_IMM 40
22526 #define TEMPLATE_TEST8 41
22527 #define TEMPLATE_TEST16 42
22528 #define TEMPLATE_TEST32 43
22529 #define TEMPLATE_SET 44
22530 #define TEMPLATE_JMP 45
22531 #define TEMPLATE_RET 46
22532 #define TEMPLATE_INB_DX 47
22533 #define TEMPLATE_INB_IMM 48
22534 #define TEMPLATE_INW_DX 49
22535 #define TEMPLATE_INW_IMM 50
22536 #define TEMPLATE_INL_DX 51
22537 #define TEMPLATE_INL_IMM 52
22538 #define TEMPLATE_OUTB_DX 53
22539 #define TEMPLATE_OUTB_IMM 54
22540 #define TEMPLATE_OUTW_DX 55
22541 #define TEMPLATE_OUTW_IMM 56
22542 #define TEMPLATE_OUTL_DX 57
22543 #define TEMPLATE_OUTL_IMM 58
22544 #define TEMPLATE_BSF 59
22545 #define TEMPLATE_RDMSR 60
22546 #define TEMPLATE_WRMSR 61
22547 #define TEMPLATE_UMUL8 62
22548 #define TEMPLATE_UMUL16 63
22549 #define TEMPLATE_UMUL32 64
22550 #define TEMPLATE_DIV8 65
22551 #define TEMPLATE_DIV16 66
22552 #define TEMPLATE_DIV32 67
22553 #define LAST_TEMPLATE TEMPLATE_DIV32
22554 #if LAST_TEMPLATE >= MAX_TEMPLATES
22555 #error "MAX_TEMPLATES to low"
22558 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22559 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22560 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22563 static struct ins_template templates[] = {
22566 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22567 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22568 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22569 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22570 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22571 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22572 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22573 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22574 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22575 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22576 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22577 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22578 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22579 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22580 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22581 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22582 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22583 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22584 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22585 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22586 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22587 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22588 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22589 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22590 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22591 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22592 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22593 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22594 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22595 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22596 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22597 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22598 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22599 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22600 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22601 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22602 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22603 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22604 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22605 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22606 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22607 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22608 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22609 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22610 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22611 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22612 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22613 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22614 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22615 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22616 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22617 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22618 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22619 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22620 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22621 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22622 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22623 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22624 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22625 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22626 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22627 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22628 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22629 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22632 [TEMPLATE_INTCONST8] = {
22633 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22635 [TEMPLATE_INTCONST32] = {
22636 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22638 [TEMPLATE_UNKNOWNVAL] = {
22639 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22641 [TEMPLATE_COPY8_REG] = {
22642 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22643 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22645 [TEMPLATE_COPY16_REG] = {
22646 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22647 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22649 [TEMPLATE_COPY32_REG] = {
22650 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22651 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22653 [TEMPLATE_COPY_IMM8] = {
22654 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22655 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22657 [TEMPLATE_COPY_IMM16] = {
22658 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22659 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22661 [TEMPLATE_COPY_IMM32] = {
22662 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22663 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22665 [TEMPLATE_PHI8] = {
22666 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22667 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22669 [TEMPLATE_PHI16] = {
22670 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22671 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22673 [TEMPLATE_PHI32] = {
22674 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22675 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22677 [TEMPLATE_STORE8] = {
22679 [0] = { REG_UNSET, REGCM_GPR32 },
22680 [1] = { REG_UNSET, REGCM_GPR8_LO },
22683 [TEMPLATE_STORE16] = {
22685 [0] = { REG_UNSET, REGCM_GPR32 },
22686 [1] = { REG_UNSET, REGCM_GPR16 },
22689 [TEMPLATE_STORE32] = {
22691 [0] = { REG_UNSET, REGCM_GPR32 },
22692 [1] = { REG_UNSET, REGCM_GPR32 },
22695 [TEMPLATE_LOAD8] = {
22696 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22697 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22699 [TEMPLATE_LOAD16] = {
22700 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22701 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22703 [TEMPLATE_LOAD32] = {
22704 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22705 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22707 [TEMPLATE_BINARY8_REG] = {
22708 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22710 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22711 [1] = { REG_UNSET, REGCM_GPR8_LO },
22714 [TEMPLATE_BINARY16_REG] = {
22715 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22717 [0] = { REG_VIRT0, REGCM_GPR16 },
22718 [1] = { REG_UNSET, REGCM_GPR16 },
22721 [TEMPLATE_BINARY32_REG] = {
22722 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22724 [0] = { REG_VIRT0, REGCM_GPR32 },
22725 [1] = { REG_UNSET, REGCM_GPR32 },
22728 [TEMPLATE_BINARY8_IMM] = {
22729 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22731 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22732 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22735 [TEMPLATE_BINARY16_IMM] = {
22736 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22738 [0] = { REG_VIRT0, REGCM_GPR16 },
22739 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22742 [TEMPLATE_BINARY32_IMM] = {
22743 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22745 [0] = { REG_VIRT0, REGCM_GPR32 },
22746 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22749 [TEMPLATE_SL8_CL] = {
22750 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22752 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22753 [1] = { REG_CL, REGCM_GPR8_LO },
22756 [TEMPLATE_SL16_CL] = {
22757 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22759 [0] = { REG_VIRT0, REGCM_GPR16 },
22760 [1] = { REG_CL, REGCM_GPR8_LO },
22763 [TEMPLATE_SL32_CL] = {
22764 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22766 [0] = { REG_VIRT0, REGCM_GPR32 },
22767 [1] = { REG_CL, REGCM_GPR8_LO },
22770 [TEMPLATE_SL8_IMM] = {
22771 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22773 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22774 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22777 [TEMPLATE_SL16_IMM] = {
22778 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22780 [0] = { REG_VIRT0, REGCM_GPR16 },
22781 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22784 [TEMPLATE_SL32_IMM] = {
22785 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22787 [0] = { REG_VIRT0, REGCM_GPR32 },
22788 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22791 [TEMPLATE_UNARY8] = {
22792 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22793 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22795 [TEMPLATE_UNARY16] = {
22796 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22797 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22799 [TEMPLATE_UNARY32] = {
22800 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22801 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22803 [TEMPLATE_CMP8_REG] = {
22804 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22806 [0] = { REG_UNSET, REGCM_GPR8_LO },
22807 [1] = { REG_UNSET, REGCM_GPR8_LO },
22810 [TEMPLATE_CMP16_REG] = {
22811 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22813 [0] = { REG_UNSET, REGCM_GPR16 },
22814 [1] = { REG_UNSET, REGCM_GPR16 },
22817 [TEMPLATE_CMP32_REG] = {
22818 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22820 [0] = { REG_UNSET, REGCM_GPR32 },
22821 [1] = { REG_UNSET, REGCM_GPR32 },
22824 [TEMPLATE_CMP8_IMM] = {
22825 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22827 [0] = { REG_UNSET, REGCM_GPR8_LO },
22828 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22831 [TEMPLATE_CMP16_IMM] = {
22832 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22834 [0] = { REG_UNSET, REGCM_GPR16 },
22835 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22838 [TEMPLATE_CMP32_IMM] = {
22839 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22841 [0] = { REG_UNSET, REGCM_GPR32 },
22842 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22845 [TEMPLATE_TEST8] = {
22846 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22847 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22849 [TEMPLATE_TEST16] = {
22850 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22851 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22853 [TEMPLATE_TEST32] = {
22854 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22855 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22858 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22859 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22862 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22865 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22867 [TEMPLATE_INB_DX] = {
22868 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22869 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22871 [TEMPLATE_INB_IMM] = {
22872 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22873 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22875 [TEMPLATE_INW_DX] = {
22876 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22877 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22879 [TEMPLATE_INW_IMM] = {
22880 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22881 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22883 [TEMPLATE_INL_DX] = {
22884 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22885 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22887 [TEMPLATE_INL_IMM] = {
22888 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22889 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22891 [TEMPLATE_OUTB_DX] = {
22893 [0] = { REG_AL, REGCM_GPR8_LO },
22894 [1] = { REG_DX, REGCM_GPR16 },
22897 [TEMPLATE_OUTB_IMM] = {
22899 [0] = { REG_AL, REGCM_GPR8_LO },
22900 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22903 [TEMPLATE_OUTW_DX] = {
22905 [0] = { REG_AX, REGCM_GPR16 },
22906 [1] = { REG_DX, REGCM_GPR16 },
22909 [TEMPLATE_OUTW_IMM] = {
22911 [0] = { REG_AX, REGCM_GPR16 },
22912 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22915 [TEMPLATE_OUTL_DX] = {
22917 [0] = { REG_EAX, REGCM_GPR32 },
22918 [1] = { REG_DX, REGCM_GPR16 },
22921 [TEMPLATE_OUTL_IMM] = {
22923 [0] = { REG_EAX, REGCM_GPR32 },
22924 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22928 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22929 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22931 [TEMPLATE_RDMSR] = {
22933 [0] = { REG_EAX, REGCM_GPR32 },
22934 [1] = { REG_EDX, REGCM_GPR32 },
22936 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22938 [TEMPLATE_WRMSR] = {
22940 [0] = { REG_ECX, REGCM_GPR32 },
22941 [1] = { REG_EAX, REGCM_GPR32 },
22942 [2] = { REG_EDX, REGCM_GPR32 },
22945 [TEMPLATE_UMUL8] = {
22946 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22948 [0] = { REG_AL, REGCM_GPR8_LO },
22949 [1] = { REG_UNSET, REGCM_GPR8_LO },
22952 [TEMPLATE_UMUL16] = {
22953 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22955 [0] = { REG_AX, REGCM_GPR16 },
22956 [1] = { REG_UNSET, REGCM_GPR16 },
22959 [TEMPLATE_UMUL32] = {
22960 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22962 [0] = { REG_EAX, REGCM_GPR32 },
22963 [1] = { REG_UNSET, REGCM_GPR32 },
22966 [TEMPLATE_DIV8] = {
22968 [0] = { REG_AL, REGCM_GPR8_LO },
22969 [1] = { REG_AH, REGCM_GPR8 },
22972 [0] = { REG_AX, REGCM_GPR16 },
22973 [1] = { REG_UNSET, REGCM_GPR8_LO },
22976 [TEMPLATE_DIV16] = {
22978 [0] = { REG_AX, REGCM_GPR16 },
22979 [1] = { REG_DX, REGCM_GPR16 },
22982 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22983 [1] = { REG_UNSET, REGCM_GPR16 },
22986 [TEMPLATE_DIV32] = {
22988 [0] = { REG_EAX, REGCM_GPR32 },
22989 [1] = { REG_EDX, REGCM_GPR32 },
22992 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22993 [1] = { REG_UNSET, REGCM_GPR32 },
22998 static void fixup_branch(struct compile_state *state,
22999 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23000 struct triple *left, struct triple *right)
23002 struct triple *test;
23004 internal_error(state, branch, "no branch test?");
23006 test = pre_triple(state, branch,
23007 cmp_op, cmp_type, left, right);
23008 test->template_id = TEMPLATE_TEST32;
23009 if (cmp_op == OP_CMP) {
23010 test->template_id = TEMPLATE_CMP32_REG;
23011 if (get_imm32(test, &RHS(test, 1))) {
23012 test->template_id = TEMPLATE_CMP32_IMM;
23015 use_triple(RHS(test, 0), test);
23016 use_triple(RHS(test, 1), test);
23017 unuse_triple(RHS(branch, 0), branch);
23018 RHS(branch, 0) = test;
23019 branch->op = jmp_op;
23020 branch->template_id = TEMPLATE_JMP;
23021 use_triple(RHS(branch, 0), branch);
23024 static void fixup_branches(struct compile_state *state,
23025 struct triple *cmp, struct triple *use, int jmp_op)
23027 struct triple_set *entry, *next;
23028 for(entry = use->use; entry; entry = next) {
23029 next = entry->next;
23030 if (entry->member->op == OP_COPY) {
23031 fixup_branches(state, cmp, entry->member, jmp_op);
23033 else if (entry->member->op == OP_CBRANCH) {
23034 struct triple *branch;
23035 struct triple *left, *right;
23037 left = RHS(cmp, 0);
23038 if (cmp->rhs > 1) {
23039 right = RHS(cmp, 1);
23041 branch = entry->member;
23042 fixup_branch(state, branch, jmp_op,
23043 cmp->op, cmp->type, left, right);
23048 static void bool_cmp(struct compile_state *state,
23049 struct triple *ins, int cmp_op, int jmp_op, int set_op)
23051 struct triple_set *entry, *next;
23052 struct triple *set, *convert;
23054 /* Put a barrier up before the cmp which preceeds the
23055 * copy instruction. If a set actually occurs this gives
23056 * us a chance to move variables in registers out of the way.
23059 /* Modify the comparison operator */
23061 ins->template_id = TEMPLATE_TEST32;
23062 if (cmp_op == OP_CMP) {
23063 ins->template_id = TEMPLATE_CMP32_REG;
23064 if (get_imm32(ins, &RHS(ins, 1))) {
23065 ins->template_id = TEMPLATE_CMP32_IMM;
23068 /* Generate the instruction sequence that will transform the
23069 * result of the comparison into a logical value.
23071 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23072 use_triple(ins, set);
23073 set->template_id = TEMPLATE_SET;
23076 if (!equiv_types(ins->type, set->type)) {
23077 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23078 use_triple(set, convert);
23079 convert->template_id = TEMPLATE_COPY32_REG;
23082 for(entry = ins->use; entry; entry = next) {
23083 next = entry->next;
23084 if (entry->member == set) {
23087 replace_rhs_use(state, ins, convert, entry->member);
23089 fixup_branches(state, ins, convert, jmp_op);
23092 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23094 struct ins_template *template;
23095 struct reg_info result;
23097 if (ins->op == OP_PIECE) {
23098 index = ins->u.cval;
23099 ins = MISC(ins, 0);
23102 if (triple_is_def(state, ins)) {
23105 if (index >= zlhs) {
23106 internal_error(state, ins, "index %d out of range for %s",
23107 index, tops(ins->op));
23111 template = &ins->u.ainfo->tmpl;
23114 if (ins->template_id > LAST_TEMPLATE) {
23115 internal_error(state, ins, "bad template number %d",
23118 template = &templates[ins->template_id];
23121 result = template->lhs[index];
23122 result.regcm = arch_regcm_normalize(state, result.regcm);
23123 if (result.reg != REG_UNNEEDED) {
23124 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23126 if (result.regcm == 0) {
23127 internal_error(state, ins, "lhs %d regcm == 0", index);
23132 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23134 struct reg_info result;
23135 struct ins_template *template;
23136 if ((index > ins->rhs) ||
23137 (ins->op == OP_PIECE)) {
23138 internal_error(state, ins, "index %d out of range for %s\n",
23139 index, tops(ins->op));
23143 template = &ins->u.ainfo->tmpl;
23149 if (ins->template_id > LAST_TEMPLATE) {
23150 internal_error(state, ins, "bad template number %d",
23153 template = &templates[ins->template_id];
23156 result = template->rhs[index];
23157 result.regcm = arch_regcm_normalize(state, result.regcm);
23158 if (result.regcm == 0) {
23159 internal_error(state, ins, "rhs %d regcm == 0", index);
23164 static struct triple *mod_div(struct compile_state *state,
23165 struct triple *ins, int div_op, int index)
23167 struct triple *div, *piece0, *piece1;
23169 /* Generate the appropriate division instruction */
23170 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23171 RHS(div, 0) = RHS(ins, 0);
23172 RHS(div, 1) = RHS(ins, 1);
23173 piece0 = LHS(div, 0);
23174 piece1 = LHS(div, 1);
23175 div->template_id = TEMPLATE_DIV32;
23176 use_triple(RHS(div, 0), div);
23177 use_triple(RHS(div, 1), div);
23178 use_triple(LHS(div, 0), div);
23179 use_triple(LHS(div, 1), div);
23181 /* Replate uses of ins with the appropriate piece of the div */
23182 propogate_use(state, ins, LHS(div, index));
23183 release_triple(state, ins);
23185 /* Return the address of the next instruction */
23186 return piece1->next;
23189 static int noop_adecl(struct triple *adecl)
23191 struct triple_set *use;
23192 /* It's a noop if it doesn't specify stoorage */
23193 if (adecl->lhs == 0) {
23196 /* Is the adecl used? If not it's a noop */
23197 for(use = adecl->use; use ; use = use->next) {
23198 if ((use->member->op != OP_PIECE) ||
23199 (MISC(use->member, 0) != adecl)) {
23206 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23208 struct triple *mask, *nmask, *shift;
23209 struct triple *val, *val_mask, *val_shift;
23210 struct triple *targ, *targ_mask;
23211 struct triple *new;
23212 ulong_t the_mask, the_nmask;
23214 targ = RHS(ins, 0);
23217 /* Get constant for the mask value */
23219 the_mask <<= ins->u.bitfield.size;
23221 the_mask <<= ins->u.bitfield.offset;
23222 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23223 mask->u.cval = the_mask;
23225 /* Get the inverted mask value */
23226 the_nmask = ~the_mask;
23227 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23228 nmask->u.cval = the_nmask;
23230 /* Get constant for the shift value */
23231 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23232 shift->u.cval = ins->u.bitfield.offset;
23234 /* Shift and mask the source value */
23236 if (shift->u.cval != 0) {
23237 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23238 use_triple(val, val_shift);
23239 use_triple(shift, val_shift);
23241 val_mask = val_shift;
23242 if (is_signed(val->type)) {
23243 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23244 use_triple(val_shift, val_mask);
23245 use_triple(mask, val_mask);
23248 /* Mask the target value */
23249 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23250 use_triple(targ, targ_mask);
23251 use_triple(nmask, targ_mask);
23253 /* Now combined them together */
23254 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23255 use_triple(targ_mask, new);
23256 use_triple(val_mask, new);
23258 /* Move all of the users over to the new expression */
23259 propogate_use(state, ins, new);
23261 /* Delete the original triple */
23262 release_triple(state, ins);
23264 /* Restart the transformation at mask */
23268 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23270 struct triple *mask, *shift;
23271 struct triple *val, *val_mask, *val_shift;
23276 /* Get constant for the mask value */
23278 the_mask <<= ins->u.bitfield.size;
23280 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23281 mask->u.cval = the_mask;
23283 /* Get constant for the right shift value */
23284 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23285 shift->u.cval = ins->u.bitfield.offset;
23287 /* Shift arithmetic right, to correct the sign */
23289 if (shift->u.cval != 0) {
23291 if (ins->op == OP_SEXTRACT) {
23296 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23297 use_triple(val, val_shift);
23298 use_triple(shift, val_shift);
23301 /* Finally mask the value */
23302 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23303 use_triple(val_shift, val_mask);
23304 use_triple(mask, val_mask);
23306 /* Move all of the users over to the new expression */
23307 propogate_use(state, ins, val_mask);
23309 /* Release the original instruction */
23310 release_triple(state, ins);
23316 static struct triple *transform_to_arch_instruction(
23317 struct compile_state *state, struct triple *ins)
23319 /* Transform from generic 3 address instructions
23320 * to archtecture specific instructions.
23321 * And apply architecture specific constraints to instructions.
23322 * Copies are inserted to preserve the register flexibility
23323 * of 3 address instructions.
23325 struct triple *next, *value;
23330 ins->template_id = TEMPLATE_INTCONST32;
23331 if (ins->u.cval < 256) {
23332 ins->template_id = TEMPLATE_INTCONST8;
23336 ins->template_id = TEMPLATE_INTCONST32;
23338 case OP_UNKNOWNVAL:
23339 ins->template_id = TEMPLATE_UNKNOWNVAL;
23345 ins->template_id = TEMPLATE_NOP;
23349 size = size_of(state, ins->type);
23350 value = RHS(ins, 0);
23351 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23352 ins->template_id = TEMPLATE_COPY_IMM8;
23354 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23355 ins->template_id = TEMPLATE_COPY_IMM16;
23357 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23358 ins->template_id = TEMPLATE_COPY_IMM32;
23360 else if (is_const(value)) {
23361 internal_error(state, ins, "bad constant passed to copy");
23363 else if (size <= SIZEOF_I8) {
23364 ins->template_id = TEMPLATE_COPY8_REG;
23366 else if (size <= SIZEOF_I16) {
23367 ins->template_id = TEMPLATE_COPY16_REG;
23369 else if (size <= SIZEOF_I32) {
23370 ins->template_id = TEMPLATE_COPY32_REG;
23373 internal_error(state, ins, "bad type passed to copy");
23377 size = size_of(state, ins->type);
23378 if (size <= SIZEOF_I8) {
23379 ins->template_id = TEMPLATE_PHI8;
23381 else if (size <= SIZEOF_I16) {
23382 ins->template_id = TEMPLATE_PHI16;
23384 else if (size <= SIZEOF_I32) {
23385 ins->template_id = TEMPLATE_PHI32;
23388 internal_error(state, ins, "bad type passed to phi");
23392 /* Adecls should always be treated as dead code and
23393 * removed. If we are not optimizing they may linger.
23395 if (!noop_adecl(ins)) {
23396 internal_error(state, ins, "adecl remains?");
23398 ins->template_id = TEMPLATE_NOP;
23399 next = after_lhs(state, ins);
23402 switch(ins->type->type & TYPE_MASK) {
23403 case TYPE_CHAR: case TYPE_UCHAR:
23404 ins->template_id = TEMPLATE_STORE8;
23406 case TYPE_SHORT: case TYPE_USHORT:
23407 ins->template_id = TEMPLATE_STORE16;
23409 case TYPE_INT: case TYPE_UINT:
23410 case TYPE_LONG: case TYPE_ULONG:
23412 ins->template_id = TEMPLATE_STORE32;
23415 internal_error(state, ins, "unknown type in store");
23420 switch(ins->type->type & TYPE_MASK) {
23421 case TYPE_CHAR: case TYPE_UCHAR:
23422 case TYPE_SHORT: case TYPE_USHORT:
23423 case TYPE_INT: case TYPE_UINT:
23424 case TYPE_LONG: case TYPE_ULONG:
23428 internal_error(state, ins, "unknown type in load");
23431 ins->template_id = TEMPLATE_LOAD32;
23439 ins->template_id = TEMPLATE_BINARY32_REG;
23440 if (get_imm32(ins, &RHS(ins, 1))) {
23441 ins->template_id = TEMPLATE_BINARY32_IMM;
23446 ins->template_id = TEMPLATE_DIV32;
23447 next = after_lhs(state, ins);
23450 ins->template_id = TEMPLATE_UMUL32;
23453 next = mod_div(state, ins, OP_UDIVT, 0);
23456 next = mod_div(state, ins, OP_SDIVT, 0);
23459 next = mod_div(state, ins, OP_UDIVT, 1);
23462 next = mod_div(state, ins, OP_SDIVT, 1);
23467 ins->template_id = TEMPLATE_SL32_CL;
23468 if (get_imm8(ins, &RHS(ins, 1))) {
23469 ins->template_id = TEMPLATE_SL32_IMM;
23470 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23471 typed_pre_copy(state, &uchar_type, ins, 1);
23476 ins->template_id = TEMPLATE_UNARY32;
23479 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23482 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23485 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23488 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23491 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23494 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23497 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23500 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23503 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23506 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23509 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23512 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23516 ins->template_id = TEMPLATE_NOP;
23519 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23520 RHS(ins, 0)->type, RHS(ins, 0), 0);
23523 ins->template_id = TEMPLATE_NOP;
23526 ins->template_id = TEMPLATE_RET;
23532 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23533 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23534 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23536 if (get_imm8(ins, &RHS(ins, 0))) {
23537 ins->template_id += 1;
23544 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23545 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23546 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23548 if (get_imm8(ins, &RHS(ins, 1))) {
23549 ins->template_id += 1;
23554 ins->template_id = TEMPLATE_BSF;
23557 ins->template_id = TEMPLATE_RDMSR;
23558 next = after_lhs(state, ins);
23561 ins->template_id = TEMPLATE_WRMSR;
23564 ins->template_id = TEMPLATE_NOP;
23567 ins->template_id = TEMPLATE_NOP;
23568 next = after_lhs(state, ins);
23570 /* Already transformed instructions */
23572 ins->template_id = TEMPLATE_TEST32;
23575 ins->template_id = TEMPLATE_CMP32_REG;
23576 if (get_imm32(ins, &RHS(ins, 1))) {
23577 ins->template_id = TEMPLATE_CMP32_IMM;
23581 ins->template_id = TEMPLATE_NOP;
23583 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23584 case OP_JMP_SLESS: case OP_JMP_ULESS:
23585 case OP_JMP_SMORE: case OP_JMP_UMORE:
23586 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23587 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23588 ins->template_id = TEMPLATE_JMP;
23590 case OP_SET_EQ: case OP_SET_NOTEQ:
23591 case OP_SET_SLESS: case OP_SET_ULESS:
23592 case OP_SET_SMORE: case OP_SET_UMORE:
23593 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23594 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23595 ins->template_id = TEMPLATE_SET;
23598 next = x86_deposit(state, ins);
23602 next = x86_extract(state, ins);
23604 /* Unhandled instructions */
23607 internal_error(state, ins, "unhandled ins: %d %s",
23608 ins->op, tops(ins->op));
23614 static long next_label(struct compile_state *state)
23616 static long label_counter = 1000;
23617 return ++label_counter;
23619 static void generate_local_labels(struct compile_state *state)
23621 struct triple *first, *label;
23622 first = state->first;
23625 if ((label->op == OP_LABEL) ||
23626 (label->op == OP_SDECL)) {
23628 label->u.cval = next_label(state);
23634 label = label->next;
23635 } while(label != first);
23638 static int check_reg(struct compile_state *state,
23639 struct triple *triple, int classes)
23643 reg = ID_REG(triple->id);
23644 if (reg == REG_UNSET) {
23645 internal_error(state, triple, "register not set");
23647 mask = arch_reg_regcm(state, reg);
23648 if (!(classes & mask)) {
23649 internal_error(state, triple, "reg %d in wrong class",
23657 #error "Registers have renumberd fix arch_reg_str"
23659 static const char *arch_regs[] = {
23663 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23664 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23665 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23668 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23669 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23670 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23672 static const char *arch_reg_str(int reg)
23674 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23677 return arch_regs[reg];
23680 static const char *reg(struct compile_state *state, struct triple *triple,
23684 reg = check_reg(state, triple, classes);
23685 return arch_reg_str(reg);
23688 static int arch_reg_size(int reg)
23692 if (reg == REG_EFLAGS) {
23695 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23698 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23701 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23704 else if (reg == REG_EDXEAX) {
23707 else if (reg == REG_DXAX) {
23710 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23713 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23719 static int reg_size(struct compile_state *state, struct triple *ins)
23722 reg = ID_REG(ins->id);
23723 if (reg == REG_UNSET) {
23724 internal_error(state, ins, "register not set");
23726 return arch_reg_size(reg);
23731 const char *type_suffix(struct compile_state *state, struct type *type)
23733 const char *suffix;
23734 switch(size_of(state, type)) {
23735 case SIZEOF_I8: suffix = "b"; break;
23736 case SIZEOF_I16: suffix = "w"; break;
23737 case SIZEOF_I32: suffix = "l"; break;
23739 internal_error(state, 0, "unknown suffix");
23746 static void print_const_val(
23747 struct compile_state *state, struct triple *ins, FILE *fp)
23751 fprintf(fp, " $%ld ",
23752 (long)(ins->u.cval));
23755 if ((MISC(ins, 0)->op != OP_SDECL) &&
23756 (MISC(ins, 0)->op != OP_LABEL))
23758 internal_error(state, ins, "bad base for addrconst");
23760 if (MISC(ins, 0)->u.cval <= 0) {
23761 internal_error(state, ins, "unlabeled constant");
23763 fprintf(fp, " $L%s%lu+%lu ",
23764 state->compiler->label_prefix,
23765 (unsigned long)(MISC(ins, 0)->u.cval),
23766 (unsigned long)(ins->u.cval));
23769 internal_error(state, ins, "unknown constant type");
23774 static void print_const(struct compile_state *state,
23775 struct triple *ins, FILE *fp)
23779 switch(ins->type->type & TYPE_MASK) {
23782 fprintf(fp, ".byte 0x%02lx\n",
23783 (unsigned long)(ins->u.cval));
23787 fprintf(fp, ".short 0x%04lx\n",
23788 (unsigned long)(ins->u.cval));
23795 fprintf(fp, ".int %lu\n",
23796 (unsigned long)(ins->u.cval));
23799 fprintf(state->errout, "type: ");
23800 name_of(state->errout, ins->type);
23801 fprintf(state->errout, "\n");
23802 internal_error(state, ins, "Unknown constant type. Val: %lu",
23803 (unsigned long)(ins->u.cval));
23808 if ((MISC(ins, 0)->op != OP_SDECL) &&
23809 (MISC(ins, 0)->op != OP_LABEL)) {
23810 internal_error(state, ins, "bad base for addrconst");
23812 if (MISC(ins, 0)->u.cval <= 0) {
23813 internal_error(state, ins, "unlabeled constant");
23815 fprintf(fp, ".int L%s%lu+%lu\n",
23816 state->compiler->label_prefix,
23817 (unsigned long)(MISC(ins, 0)->u.cval),
23818 (unsigned long)(ins->u.cval));
23822 unsigned char *blob;
23824 size = size_of_in_bytes(state, ins->type);
23825 blob = ins->u.blob;
23826 for(i = 0; i < size; i++) {
23827 fprintf(fp, ".byte 0x%02x\n",
23833 internal_error(state, ins, "Unknown constant type");
23838 #define TEXT_SECTION ".rom.text"
23839 #define DATA_SECTION ".rom.data"
23841 static long get_const_pool_ref(
23842 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23846 ref = next_label(state);
23847 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23848 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23849 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23850 print_const(state, ins, fp);
23851 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23853 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23855 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23859 static long get_mask_pool_ref(
23860 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23863 if (mask == 0xff) {
23866 else if (mask == 0xffff) {
23871 internal_error(state, ins, "unhandled mask value");
23876 static void print_binary_op(struct compile_state *state,
23877 const char *op, struct triple *ins, FILE *fp)
23880 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23881 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23882 internal_error(state, ins, "invalid register assignment");
23884 if (is_const(RHS(ins, 1))) {
23885 fprintf(fp, "\t%s ", op);
23886 print_const_val(state, RHS(ins, 1), fp);
23887 fprintf(fp, ", %s\n",
23888 reg(state, RHS(ins, 0), mask));
23891 unsigned lmask, rmask;
23893 lreg = check_reg(state, RHS(ins, 0), mask);
23894 rreg = check_reg(state, RHS(ins, 1), mask);
23895 lmask = arch_reg_regcm(state, lreg);
23896 rmask = arch_reg_regcm(state, rreg);
23897 mask = lmask & rmask;
23898 fprintf(fp, "\t%s %s, %s\n",
23900 reg(state, RHS(ins, 1), mask),
23901 reg(state, RHS(ins, 0), mask));
23904 static void print_unary_op(struct compile_state *state,
23905 const char *op, struct triple *ins, FILE *fp)
23908 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23909 fprintf(fp, "\t%s %s\n",
23911 reg(state, RHS(ins, 0), mask));
23914 static void print_op_shift(struct compile_state *state,
23915 const char *op, struct triple *ins, FILE *fp)
23918 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23919 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23920 internal_error(state, ins, "invalid register assignment");
23922 if (is_const(RHS(ins, 1))) {
23923 fprintf(fp, "\t%s ", op);
23924 print_const_val(state, RHS(ins, 1), fp);
23925 fprintf(fp, ", %s\n",
23926 reg(state, RHS(ins, 0), mask));
23929 fprintf(fp, "\t%s %s, %s\n",
23931 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23932 reg(state, RHS(ins, 0), mask));
23936 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23943 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23944 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23945 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23947 internal_error(state, ins, "not an in operation");
23951 dreg = check_reg(state, ins, mask);
23952 if (!reg_is_reg(state, dreg, REG_EAX)) {
23953 internal_error(state, ins, "dst != %%eax");
23955 if (is_const(RHS(ins, 0))) {
23956 fprintf(fp, "\t%s ", op);
23957 print_const_val(state, RHS(ins, 0), fp);
23958 fprintf(fp, ", %s\n",
23959 reg(state, ins, mask));
23963 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23964 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23965 internal_error(state, ins, "src != %%dx");
23967 fprintf(fp, "\t%s %s, %s\n",
23969 reg(state, RHS(ins, 0), REGCM_GPR16),
23970 reg(state, ins, mask));
23974 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23981 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23982 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23983 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23985 internal_error(state, ins, "not an out operation");
23989 lreg = check_reg(state, RHS(ins, 0), mask);
23990 if (!reg_is_reg(state, lreg, REG_EAX)) {
23991 internal_error(state, ins, "src != %%eax");
23993 if (is_const(RHS(ins, 1))) {
23994 fprintf(fp, "\t%s %s,",
23995 op, reg(state, RHS(ins, 0), mask));
23996 print_const_val(state, RHS(ins, 1), fp);
24001 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24002 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24003 internal_error(state, ins, "dst != %%dx");
24005 fprintf(fp, "\t%s %s, %s\n",
24007 reg(state, RHS(ins, 0), mask),
24008 reg(state, RHS(ins, 1), REGCM_GPR16));
24012 static void print_op_move(struct compile_state *state,
24013 struct triple *ins, FILE *fp)
24015 /* op_move is complex because there are many types
24016 * of registers we can move between.
24017 * Because OP_COPY will be introduced in arbitrary locations
24018 * OP_COPY must not affect flags.
24019 * OP_CONVERT can change the flags and it is the only operation
24020 * where it is expected the types in the registers can change.
24022 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24023 struct triple *dst, *src;
24024 if (state->arch->features & X86_NOOP_COPY) {
24027 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24032 internal_error(state, ins, "unknown move operation");
24035 if (reg_size(state, dst) < size_of(state, dst->type)) {
24036 internal_error(state, ins, "Invalid destination register");
24038 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24039 fprintf(state->errout, "src type: ");
24040 name_of(state->errout, src->type);
24041 fprintf(state->errout, "\n");
24042 fprintf(state->errout, "dst type: ");
24043 name_of(state->errout, dst->type);
24044 fprintf(state->errout, "\n");
24045 internal_error(state, ins, "Type mismatch for OP_COPY");
24048 if (!is_const(src)) {
24049 int src_reg, dst_reg;
24050 int src_regcm, dst_regcm;
24051 src_reg = ID_REG(src->id);
24052 dst_reg = ID_REG(dst->id);
24053 src_regcm = arch_reg_regcm(state, src_reg);
24054 dst_regcm = arch_reg_regcm(state, dst_reg);
24055 /* If the class is the same just move the register */
24056 if (src_regcm & dst_regcm &
24057 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24058 if ((src_reg != dst_reg) || !omit_copy) {
24059 fprintf(fp, "\tmov %s, %s\n",
24060 reg(state, src, src_regcm),
24061 reg(state, dst, dst_regcm));
24064 /* Move 32bit to 16bit */
24065 else if ((src_regcm & REGCM_GPR32) &&
24066 (dst_regcm & REGCM_GPR16)) {
24067 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24068 if ((src_reg != dst_reg) || !omit_copy) {
24069 fprintf(fp, "\tmovw %s, %s\n",
24070 arch_reg_str(src_reg),
24071 arch_reg_str(dst_reg));
24074 /* Move from 32bit gprs to 16bit gprs */
24075 else if ((src_regcm & REGCM_GPR32) &&
24076 (dst_regcm & REGCM_GPR16)) {
24077 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24078 if ((src_reg != dst_reg) || !omit_copy) {
24079 fprintf(fp, "\tmov %s, %s\n",
24080 arch_reg_str(src_reg),
24081 arch_reg_str(dst_reg));
24084 /* Move 32bit to 8bit */
24085 else if ((src_regcm & REGCM_GPR32_8) &&
24086 (dst_regcm & REGCM_GPR8_LO))
24088 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24089 if ((src_reg != dst_reg) || !omit_copy) {
24090 fprintf(fp, "\tmovb %s, %s\n",
24091 arch_reg_str(src_reg),
24092 arch_reg_str(dst_reg));
24095 /* Move 16bit to 8bit */
24096 else if ((src_regcm & REGCM_GPR16_8) &&
24097 (dst_regcm & REGCM_GPR8_LO))
24099 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24100 if ((src_reg != dst_reg) || !omit_copy) {
24101 fprintf(fp, "\tmovb %s, %s\n",
24102 arch_reg_str(src_reg),
24103 arch_reg_str(dst_reg));
24106 /* Move 8/16bit to 16/32bit */
24107 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24108 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24110 op = is_signed(src->type)? "movsx": "movzx";
24111 fprintf(fp, "\t%s %s, %s\n",
24113 reg(state, src, src_regcm),
24114 reg(state, dst, dst_regcm));
24116 /* Move between sse registers */
24117 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24118 if ((src_reg != dst_reg) || !omit_copy) {
24119 fprintf(fp, "\tmovdqa %s, %s\n",
24120 reg(state, src, src_regcm),
24121 reg(state, dst, dst_regcm));
24124 /* Move between mmx registers */
24125 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24126 if ((src_reg != dst_reg) || !omit_copy) {
24127 fprintf(fp, "\tmovq %s, %s\n",
24128 reg(state, src, src_regcm),
24129 reg(state, dst, dst_regcm));
24132 /* Move from sse to mmx registers */
24133 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24134 fprintf(fp, "\tmovdq2q %s, %s\n",
24135 reg(state, src, src_regcm),
24136 reg(state, dst, dst_regcm));
24138 /* Move from mmx to sse registers */
24139 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24140 fprintf(fp, "\tmovq2dq %s, %s\n",
24141 reg(state, src, src_regcm),
24142 reg(state, dst, dst_regcm));
24144 /* Move between 32bit gprs & mmx/sse registers */
24145 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24146 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24147 fprintf(fp, "\tmovd %s, %s\n",
24148 reg(state, src, src_regcm),
24149 reg(state, dst, dst_regcm));
24151 /* Move from 16bit gprs & mmx/sse registers */
24152 else if ((src_regcm & REGCM_GPR16) &&
24153 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24156 op = is_signed(src->type)? "movsx":"movzx";
24157 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24158 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24160 arch_reg_str(src_reg),
24161 arch_reg_str(mid_reg),
24162 arch_reg_str(mid_reg),
24163 arch_reg_str(dst_reg));
24165 /* Move from mmx/sse registers to 16bit gprs */
24166 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24167 (dst_regcm & REGCM_GPR16)) {
24168 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24169 fprintf(fp, "\tmovd %s, %s\n",
24170 arch_reg_str(src_reg),
24171 arch_reg_str(dst_reg));
24173 /* Move from gpr to 64bit dividend */
24174 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24175 (dst_regcm & REGCM_DIVIDEND64)) {
24176 const char *extend;
24177 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24178 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24179 arch_reg_str(src_reg),
24182 /* Move from 64bit gpr to gpr */
24183 else if ((src_regcm & REGCM_DIVIDEND64) &&
24184 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24185 if (dst_regcm & REGCM_GPR32) {
24188 else if (dst_regcm & REGCM_GPR16) {
24191 else if (dst_regcm & REGCM_GPR8_LO) {
24194 fprintf(fp, "\tmov %s, %s\n",
24195 arch_reg_str(src_reg),
24196 arch_reg_str(dst_reg));
24198 /* Move from mmx/sse registers to 64bit gpr */
24199 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24200 (dst_regcm & REGCM_DIVIDEND64)) {
24201 const char *extend;
24202 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24203 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24204 arch_reg_str(src_reg),
24207 /* Move from 64bit gpr to mmx/sse register */
24208 else if ((src_regcm & REGCM_DIVIDEND64) &&
24209 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24210 fprintf(fp, "\tmovd %%eax, %s\n",
24211 arch_reg_str(dst_reg));
24213 #if X86_4_8BIT_GPRS
24214 /* Move from 8bit gprs to mmx/sse registers */
24215 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24216 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24219 op = is_signed(src->type)? "movsx":"movzx";
24220 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24221 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24223 reg(state, src, src_regcm),
24224 arch_reg_str(mid_reg),
24225 arch_reg_str(mid_reg),
24226 reg(state, dst, dst_regcm));
24228 /* Move from mmx/sse registers and 8bit gprs */
24229 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24230 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24232 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24233 fprintf(fp, "\tmovd %s, %s\n",
24234 reg(state, src, src_regcm),
24235 arch_reg_str(mid_reg));
24237 /* Move from 32bit gprs to 8bit gprs */
24238 else if ((src_regcm & REGCM_GPR32) &&
24239 (dst_regcm & REGCM_GPR8_LO)) {
24240 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24241 if ((src_reg != dst_reg) || !omit_copy) {
24242 fprintf(fp, "\tmov %s, %s\n",
24243 arch_reg_str(src_reg),
24244 arch_reg_str(dst_reg));
24247 /* Move from 16bit gprs to 8bit gprs */
24248 else if ((src_regcm & REGCM_GPR16) &&
24249 (dst_regcm & REGCM_GPR8_LO)) {
24250 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24251 if ((src_reg != dst_reg) || !omit_copy) {
24252 fprintf(fp, "\tmov %s, %s\n",
24253 arch_reg_str(src_reg),
24254 arch_reg_str(dst_reg));
24257 #endif /* X86_4_8BIT_GPRS */
24258 /* Move from %eax:%edx to %eax:%edx */
24259 else if ((src_regcm & REGCM_DIVIDEND64) &&
24260 (dst_regcm & REGCM_DIVIDEND64) &&
24261 (src_reg == dst_reg)) {
24263 fprintf(fp, "\t/*mov %s, %s*/\n",
24264 arch_reg_str(src_reg),
24265 arch_reg_str(dst_reg));
24269 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24270 internal_error(state, ins, "attempt to copy from %%eflags!");
24272 internal_error(state, ins, "unknown copy type");
24279 dst_size = size_of(state, dst->type);
24280 dst_reg = ID_REG(dst->id);
24281 dst_regcm = arch_reg_regcm(state, dst_reg);
24282 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24283 fprintf(fp, "\tmov ");
24284 print_const_val(state, src, fp);
24285 fprintf(fp, ", %s\n",
24286 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24288 else if (dst_regcm & REGCM_DIVIDEND64) {
24289 if (dst_size > SIZEOF_I32) {
24290 internal_error(state, ins, "%dbit constant...", dst_size);
24292 fprintf(fp, "\tmov $0, %%edx\n");
24293 fprintf(fp, "\tmov ");
24294 print_const_val(state, src, fp);
24295 fprintf(fp, ", %%eax\n");
24297 else if (dst_regcm & REGCM_DIVIDEND32) {
24298 if (dst_size > SIZEOF_I16) {
24299 internal_error(state, ins, "%dbit constant...", dst_size);
24301 fprintf(fp, "\tmov $0, %%dx\n");
24302 fprintf(fp, "\tmov ");
24303 print_const_val(state, src, fp);
24304 fprintf(fp, ", %%ax");
24306 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24308 if (dst_size > SIZEOF_I32) {
24309 internal_error(state, ins, "%d bit constant...", dst_size);
24311 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24312 fprintf(fp, "\tmovd L%s%lu, %s\n",
24313 state->compiler->label_prefix, ref,
24314 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24317 internal_error(state, ins, "unknown copy immediate type");
24320 /* Leave now if this is not a type conversion */
24321 if (ins->op != OP_CONVERT) {
24324 /* Now make certain I have not logically overflowed the destination */
24325 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24326 (size_of(state, dst->type) < reg_size(state, dst)))
24328 unsigned long mask;
24331 if (size_of(state, dst->type) >= 32) {
24332 fprintf(state->errout, "dst type: ");
24333 name_of(state->errout, dst->type);
24334 fprintf(state->errout, "\n");
24335 internal_error(state, dst, "unhandled dst type size");
24338 mask <<= size_of(state, dst->type);
24341 dst_reg = ID_REG(dst->id);
24342 dst_regcm = arch_reg_regcm(state, dst_reg);
24344 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24345 fprintf(fp, "\tand $0x%lx, %s\n",
24346 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24348 else if (dst_regcm & REGCM_MMX) {
24350 ref = get_mask_pool_ref(state, dst, mask, fp);
24351 fprintf(fp, "\tpand L%s%lu, %s\n",
24352 state->compiler->label_prefix, ref,
24353 reg(state, dst, REGCM_MMX));
24355 else if (dst_regcm & REGCM_XMM) {
24357 ref = get_mask_pool_ref(state, dst, mask, fp);
24358 fprintf(fp, "\tpand L%s%lu, %s\n",
24359 state->compiler->label_prefix, ref,
24360 reg(state, dst, REGCM_XMM));
24363 fprintf(state->errout, "dst type: ");
24364 name_of(state->errout, dst->type);
24365 fprintf(state->errout, "\n");
24366 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24367 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24370 /* Make certain I am properly sign extended */
24371 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24372 (is_signed(src->type)))
24374 int bits, reg_bits, shift_bits;
24378 bits = size_of(state, src->type);
24379 reg_bits = reg_size(state, dst);
24380 if (reg_bits > 32) {
24383 shift_bits = reg_bits - size_of(state, src->type);
24384 dst_reg = ID_REG(dst->id);
24385 dst_regcm = arch_reg_regcm(state, dst_reg);
24387 if (shift_bits < 0) {
24388 internal_error(state, dst, "negative shift?");
24391 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24392 fprintf(fp, "\tshl $%d, %s\n",
24394 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24395 fprintf(fp, "\tsar $%d, %s\n",
24397 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24399 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24400 fprintf(fp, "\tpslld $%d, %s\n",
24402 reg(state, dst, REGCM_MMX | REGCM_XMM));
24403 fprintf(fp, "\tpsrad $%d, %s\n",
24405 reg(state, dst, REGCM_MMX | REGCM_XMM));
24408 fprintf(state->errout, "dst type: ");
24409 name_of(state->errout, dst->type);
24410 fprintf(state->errout, "\n");
24411 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24412 internal_error(state, dst, "failed to signed extend value");
24417 static void print_op_load(struct compile_state *state,
24418 struct triple *ins, FILE *fp)
24420 struct triple *dst, *src;
24424 if (is_const(src) || is_const(dst)) {
24425 internal_error(state, ins, "unknown load operation");
24427 switch(ins->type->type & TYPE_MASK) {
24428 case TYPE_CHAR: op = "movsbl"; break;
24429 case TYPE_UCHAR: op = "movzbl"; break;
24430 case TYPE_SHORT: op = "movswl"; break;
24431 case TYPE_USHORT: op = "movzwl"; break;
24432 case TYPE_INT: case TYPE_UINT:
24433 case TYPE_LONG: case TYPE_ULONG:
24438 internal_error(state, ins, "unknown type in load");
24439 op = "<invalid opcode>";
24442 fprintf(fp, "\t%s (%s), %s\n",
24444 reg(state, src, REGCM_GPR32),
24445 reg(state, dst, REGCM_GPR32));
24449 static void print_op_store(struct compile_state *state,
24450 struct triple *ins, FILE *fp)
24452 struct triple *dst, *src;
24455 if (is_const(src) && (src->op == OP_INTCONST)) {
24457 value = (long_t)(src->u.cval);
24458 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24459 type_suffix(state, src->type),
24461 reg(state, dst, REGCM_GPR32));
24463 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24464 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24465 type_suffix(state, src->type),
24466 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24467 (unsigned long)(dst->u.cval));
24470 if (is_const(src) || is_const(dst)) {
24471 internal_error(state, ins, "unknown store operation");
24473 fprintf(fp, "\tmov%s %s, (%s)\n",
24474 type_suffix(state, src->type),
24475 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24476 reg(state, dst, REGCM_GPR32));
24482 static void print_op_smul(struct compile_state *state,
24483 struct triple *ins, FILE *fp)
24485 if (!is_const(RHS(ins, 1))) {
24486 fprintf(fp, "\timul %s, %s\n",
24487 reg(state, RHS(ins, 1), REGCM_GPR32),
24488 reg(state, RHS(ins, 0), REGCM_GPR32));
24491 fprintf(fp, "\timul ");
24492 print_const_val(state, RHS(ins, 1), fp);
24493 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24497 static void print_op_cmp(struct compile_state *state,
24498 struct triple *ins, FILE *fp)
24502 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24503 dreg = check_reg(state, ins, REGCM_FLAGS);
24504 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24505 internal_error(state, ins, "bad dest register for cmp");
24507 if (is_const(RHS(ins, 1))) {
24508 fprintf(fp, "\tcmp ");
24509 print_const_val(state, RHS(ins, 1), fp);
24510 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24513 unsigned lmask, rmask;
24515 lreg = check_reg(state, RHS(ins, 0), mask);
24516 rreg = check_reg(state, RHS(ins, 1), mask);
24517 lmask = arch_reg_regcm(state, lreg);
24518 rmask = arch_reg_regcm(state, rreg);
24519 mask = lmask & rmask;
24520 fprintf(fp, "\tcmp %s, %s\n",
24521 reg(state, RHS(ins, 1), mask),
24522 reg(state, RHS(ins, 0), mask));
24526 static void print_op_test(struct compile_state *state,
24527 struct triple *ins, FILE *fp)
24530 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24531 fprintf(fp, "\ttest %s, %s\n",
24532 reg(state, RHS(ins, 0), mask),
24533 reg(state, RHS(ins, 0), mask));
24536 static void print_op_branch(struct compile_state *state,
24537 struct triple *branch, FILE *fp)
24539 const char *bop = "j";
24540 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24541 if (branch->rhs != 0) {
24542 internal_error(state, branch, "jmp with condition?");
24547 struct triple *ptr;
24548 if (branch->rhs != 1) {
24549 internal_error(state, branch, "jmpcc without condition?");
24551 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24552 if ((RHS(branch, 0)->op != OP_CMP) &&
24553 (RHS(branch, 0)->op != OP_TEST)) {
24554 internal_error(state, branch, "bad branch test");
24556 #if DEBUG_ROMCC_WARNINGS
24557 #warning "FIXME I have observed instructions between the test and branch instructions"
24559 ptr = RHS(branch, 0);
24560 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24561 if (ptr->op != OP_COPY) {
24562 internal_error(state, branch, "branch does not follow test");
24565 switch(branch->op) {
24566 case OP_JMP_EQ: bop = "jz"; break;
24567 case OP_JMP_NOTEQ: bop = "jnz"; break;
24568 case OP_JMP_SLESS: bop = "jl"; break;
24569 case OP_JMP_ULESS: bop = "jb"; break;
24570 case OP_JMP_SMORE: bop = "jg"; break;
24571 case OP_JMP_UMORE: bop = "ja"; break;
24572 case OP_JMP_SLESSEQ: bop = "jle"; break;
24573 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24574 case OP_JMP_SMOREEQ: bop = "jge"; break;
24575 case OP_JMP_UMOREEQ: bop = "jae"; break;
24577 internal_error(state, branch, "Invalid branch op");
24583 if (branch->op == OP_CALL) {
24584 fprintf(fp, "\t/* call */\n");
24587 fprintf(fp, "\t%s L%s%lu\n",
24589 state->compiler->label_prefix,
24590 (unsigned long)(TARG(branch, 0)->u.cval));
24593 static void print_op_ret(struct compile_state *state,
24594 struct triple *branch, FILE *fp)
24596 fprintf(fp, "\tjmp *%s\n",
24597 reg(state, RHS(branch, 0), REGCM_GPR32));
24600 static void print_op_set(struct compile_state *state,
24601 struct triple *set, FILE *fp)
24603 const char *sop = "set";
24604 if (set->rhs != 1) {
24605 internal_error(state, set, "setcc without condition?");
24607 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24608 if ((RHS(set, 0)->op != OP_CMP) &&
24609 (RHS(set, 0)->op != OP_TEST)) {
24610 internal_error(state, set, "bad set test");
24612 if (RHS(set, 0)->next != set) {
24613 internal_error(state, set, "set does not follow test");
24616 case OP_SET_EQ: sop = "setz"; break;
24617 case OP_SET_NOTEQ: sop = "setnz"; break;
24618 case OP_SET_SLESS: sop = "setl"; break;
24619 case OP_SET_ULESS: sop = "setb"; break;
24620 case OP_SET_SMORE: sop = "setg"; break;
24621 case OP_SET_UMORE: sop = "seta"; break;
24622 case OP_SET_SLESSEQ: sop = "setle"; break;
24623 case OP_SET_ULESSEQ: sop = "setbe"; break;
24624 case OP_SET_SMOREEQ: sop = "setge"; break;
24625 case OP_SET_UMOREEQ: sop = "setae"; break;
24627 internal_error(state, set, "Invalid set op");
24630 fprintf(fp, "\t%s %s\n",
24631 sop, reg(state, set, REGCM_GPR8_LO));
24634 static void print_op_bit_scan(struct compile_state *state,
24635 struct triple *ins, FILE *fp)
24639 case OP_BSF: op = "bsf"; break;
24640 case OP_BSR: op = "bsr"; break;
24642 internal_error(state, ins, "unknown bit scan");
24652 reg(state, RHS(ins, 0), REGCM_GPR32),
24653 reg(state, ins, REGCM_GPR32),
24654 reg(state, ins, REGCM_GPR32));
24658 static void print_sdecl(struct compile_state *state,
24659 struct triple *ins, FILE *fp)
24661 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24662 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24663 fprintf(fp, "L%s%lu:\n",
24664 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24665 print_const(state, MISC(ins, 0), fp);
24666 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24670 static void print_instruction(struct compile_state *state,
24671 struct triple *ins, FILE *fp)
24673 /* Assumption: after I have exted the register allocator
24674 * everything is in a valid register.
24678 print_op_asm(state, ins, fp);
24680 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24681 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24682 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24683 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24684 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24685 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24686 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24687 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24688 case OP_POS: break;
24689 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24690 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24695 /* Don't generate anything here for constants */
24697 /* Don't generate anything for variable declarations. */
24699 case OP_UNKNOWNVAL:
24700 fprintf(fp, " /* unknown %s */\n",
24701 reg(state, ins, REGCM_ALL));
24704 print_sdecl(state, ins, fp);
24708 print_op_move(state, ins, fp);
24711 print_op_load(state, ins, fp);
24714 print_op_store(state, ins, fp);
24717 print_op_smul(state, ins, fp);
24719 case OP_CMP: print_op_cmp(state, ins, fp); break;
24720 case OP_TEST: print_op_test(state, ins, fp); break;
24722 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24723 case OP_JMP_SLESS: case OP_JMP_ULESS:
24724 case OP_JMP_SMORE: case OP_JMP_UMORE:
24725 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24726 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24728 print_op_branch(state, ins, fp);
24731 print_op_ret(state, ins, fp);
24733 case OP_SET_EQ: case OP_SET_NOTEQ:
24734 case OP_SET_SLESS: case OP_SET_ULESS:
24735 case OP_SET_SMORE: case OP_SET_UMORE:
24736 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24737 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24738 print_op_set(state, ins, fp);
24740 case OP_INB: case OP_INW: case OP_INL:
24741 print_op_in(state, ins, fp);
24743 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24744 print_op_out(state, ins, fp);
24748 print_op_bit_scan(state, ins, fp);
24751 after_lhs(state, ins);
24752 fprintf(fp, "\trdmsr\n");
24755 fprintf(fp, "\twrmsr\n");
24758 fprintf(fp, "\thlt\n");
24761 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24764 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24767 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24773 fprintf(fp, "L%s%lu:\n",
24774 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24777 /* Ignore adecls with no registers error otherwise */
24778 if (!noop_adecl(ins)) {
24779 internal_error(state, ins, "adecl remains?");
24782 /* Ignore OP_PIECE */
24785 /* Operations that should never get here */
24786 case OP_SDIV: case OP_UDIV:
24787 case OP_SMOD: case OP_UMOD:
24788 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24789 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24790 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24792 internal_error(state, ins, "unknown op: %d %s",
24793 ins->op, tops(ins->op));
24798 static void print_instructions(struct compile_state *state)
24800 struct triple *first, *ins;
24801 int print_location;
24802 struct occurance *last_occurance;
24804 int max_inline_depth;
24805 max_inline_depth = 0;
24806 print_location = 1;
24807 last_occurance = 0;
24808 fp = state->output;
24809 /* Masks for common sizes */
24810 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24811 fprintf(fp, ".balign 16\n");
24812 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24813 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24814 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24815 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24816 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24817 first = state->first;
24820 if (print_location &&
24821 last_occurance != ins->occurance) {
24822 if (!ins->occurance->parent) {
24823 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24824 ins->occurance->function?ins->occurance->function:"(null)",
24825 ins->occurance->filename?ins->occurance->filename:"(null)",
24826 ins->occurance->line,
24827 ins->occurance->col);
24830 struct occurance *ptr;
24832 fprintf(fp, "\t/*\n");
24834 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24836 fprintf(fp, "\t * %s,%s:%d.%d\n",
24842 fprintf(fp, "\t */\n");
24843 if (inline_depth > max_inline_depth) {
24844 max_inline_depth = inline_depth;
24847 if (last_occurance) {
24848 put_occurance(last_occurance);
24850 get_occurance(ins->occurance);
24851 last_occurance = ins->occurance;
24854 print_instruction(state, ins, fp);
24856 } while(ins != first);
24857 if (print_location) {
24858 fprintf(fp, "/* max inline depth %d */\n",
24863 static void generate_code(struct compile_state *state)
24865 generate_local_labels(state);
24866 print_instructions(state);
24870 static void print_preprocessed_tokens(struct compile_state *state)
24875 const char *filename;
24876 fp = state->output;
24880 struct file_state *file;
24882 const char *token_str;
24884 if (tok == TOK_EOF) {
24887 tk = eat(state, tok);
24889 tk->ident ? tk->ident->name :
24890 tk->str_len ? tk->val.str :
24893 file = state->file;
24894 while(file->macro && file->prev) {
24897 if (!file->macro &&
24898 ((file->line != line) || (file->basename != filename)))
24901 if ((file->basename == filename) &&
24902 (line < file->line)) {
24903 while(line < file->line) {
24909 fprintf(fp, "\n#line %d \"%s\"\n",
24910 file->line, file->basename);
24913 filename = file->basename;
24914 col = get_col(file) - strlen(token_str);
24915 for(i = 0; i < col; i++) {
24920 fprintf(fp, "%s ", token_str);
24922 if (state->compiler->debug & DEBUG_TOKENS) {
24923 loc(state->dbgout, state, 0);
24924 fprintf(state->dbgout, "%s <- `%s'\n",
24925 tokens[tok], token_str);
24930 static void compile(const char *filename, const char *includefile,
24931 struct compiler_state *compiler, struct arch_state *arch)
24934 struct compile_state state;
24935 struct triple *ptr;
24936 memset(&state, 0, sizeof(state));
24937 state.compiler = compiler;
24940 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24941 memset(&state.token[i], 0, sizeof(state.token[i]));
24942 state.token[i].tok = -1;
24944 /* Remember the output descriptors */
24945 state.errout = stderr;
24946 state.dbgout = stdout;
24947 /* Remember the output filename */
24948 state.output = fopen(state.compiler->ofilename, "w");
24949 if (!state.output) {
24950 error(&state, 0, "Cannot open output file %s\n",
24951 state.compiler->ofilename);
24953 /* Make certain a good cleanup happens */
24954 exit_state = &state;
24955 atexit(exit_cleanup);
24957 /* Prep the preprocessor */
24958 state.if_depth = 0;
24959 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24960 /* register the C keywords */
24961 register_keywords(&state);
24962 /* register the keywords the macro preprocessor knows */
24963 register_macro_keywords(&state);
24964 /* generate some builtin macros */
24965 register_builtin_macros(&state);
24966 /* Memorize where some special keywords are. */
24967 state.i_switch = lookup(&state, "switch", 6);
24968 state.i_case = lookup(&state, "case", 4);
24969 state.i_continue = lookup(&state, "continue", 8);
24970 state.i_break = lookup(&state, "break", 5);
24971 state.i_default = lookup(&state, "default", 7);
24972 state.i_return = lookup(&state, "return", 6);
24973 /* Memorize where predefined macros are. */
24974 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24975 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24976 state.i___LINE__ = lookup(&state, "__LINE__", 8);
24977 /* Memorize where predefined identifiers are. */
24978 state.i___func__ = lookup(&state, "__func__", 8);
24979 /* Memorize where some attribute keywords are. */
24980 state.i_noinline = lookup(&state, "noinline", 8);
24981 state.i_always_inline = lookup(&state, "always_inline", 13);
24983 /* Process the command line macros */
24984 process_cmdline_macros(&state);
24986 /* Allocate beginning bounding labels for the function list */
24987 state.first = label(&state);
24988 state.first->id |= TRIPLE_FLAG_VOLATILE;
24989 use_triple(state.first, state.first);
24990 ptr = label(&state);
24991 ptr->id |= TRIPLE_FLAG_VOLATILE;
24992 use_triple(ptr, ptr);
24993 flatten(&state, state.first, ptr);
24995 /* Allocate a label for the pool of global variables */
24996 state.global_pool = label(&state);
24997 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
24998 flatten(&state, state.first, state.global_pool);
25000 /* Enter the globl definition scope */
25001 start_scope(&state);
25002 register_builtins(&state);
25004 compile_file(&state, filename, 1);
25006 compile_file(&state, includefile, 1);
25008 /* Stop if all we want is preprocessor output */
25009 if (state.compiler->flags & COMPILER_PP_ONLY) {
25010 print_preprocessed_tokens(&state);
25016 /* Exit the global definition scope */
25019 /* Now that basic compilation has happened
25020 * optimize the intermediate code
25024 generate_code(&state);
25025 if (state.compiler->debug) {
25026 fprintf(state.errout, "done\n");
25031 static void version(FILE *fp)
25033 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25036 static void usage(void)
25041 "\nUsage: romcc [options] <source>.c\n"
25042 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25044 "-o <output file name>\n"
25045 "-f<option> Specify a generic compiler option\n"
25046 "-m<option> Specify a arch dependent option\n"
25047 "-- Specify this is the last option\n"
25048 "\nGeneric compiler options:\n"
25050 compiler_usage(fp);
25052 "\nArchitecture compiler options:\n"
25060 static void arg_error(char *fmt, ...)
25063 va_start(args, fmt);
25064 vfprintf(stderr, fmt, args);
25070 int main(int argc, char **argv)
25072 const char *filename;
25073 const char *includefile = NULL;
25074 struct compiler_state compiler;
25075 struct arch_state arch;
25079 /* I don't want any surprises */
25080 setlocale(LC_ALL, "C");
25082 init_compiler_state(&compiler);
25083 init_arch_state(&arch);
25087 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25088 compiler.ofilename = argv[2];
25092 else if (!all_opts && argv[1][0] == '-') {
25095 if (strcmp(argv[1], "--") == 0) {
25099 else if (strncmp(argv[1], "-E", 2) == 0) {
25100 result = compiler_encode_flag(&compiler, argv[1]);
25102 else if (strncmp(argv[1], "-O", 2) == 0) {
25103 result = compiler_encode_flag(&compiler, argv[1]);
25105 else if (strncmp(argv[1], "-I", 2) == 0) {
25106 result = compiler_encode_flag(&compiler, argv[1]);
25108 else if (strncmp(argv[1], "-D", 2) == 0) {
25109 result = compiler_encode_flag(&compiler, argv[1]);
25111 else if (strncmp(argv[1], "-U", 2) == 0) {
25112 result = compiler_encode_flag(&compiler, argv[1]);
25114 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25115 result = compiler_encode_flag(&compiler, argv[1]+2);
25117 else if (strncmp(argv[1], "-f", 2) == 0) {
25118 result = compiler_encode_flag(&compiler, argv[1]+2);
25120 else if (strncmp(argv[1], "-m", 2) == 0) {
25121 result = arch_encode_flag(&arch, argv[1]+2);
25123 else if (strncmp(argv[1], "-include", 10) == 0) {
25125 arg_error("Only one -include option may be specified.\n");
25129 includefile = argv[1];
25134 arg_error("Invalid option specified: %s\n",
25142 arg_error("Only one filename may be specified\n");
25144 filename = argv[1];
25150 arg_error("No filename specified\n");
25152 compile(filename, includefile, &compiler, &arch);