14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_CONSISTENCY 2
18 #define DEBUG_RANGE_CONFLICTS 0
19 #define DEBUG_COALESCING 0
21 #warning "FIXME boundary cases with small types in larger registers"
22 #warning "FIXME give clear error messages about unused variables"
24 /* Control flow graph of a loop without goto.
35 * |\ GGG HHH | continue;
63 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
67 * [] == DFlocal(X) U DF(X)
70 * Dominator graph of the same nodes.
74 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
76 * CCC CCC: [ ] ( BBB, JJJ )
78 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
80 * FFF FFF: [ ] ( BBB )
82 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
87 * BBB and JJJ are definitely the dominance frontier.
88 * Where do I place phi functions and how do I make that decision.
91 static void die(char *fmt, ...)
96 vfprintf(stderr, fmt, args);
103 #define MALLOC_STRONG_DEBUG
104 static void *xmalloc(size_t size, const char *name)
109 die("Cannot malloc %ld bytes to hold %s: %s\n",
110 size + 0UL, name, strerror(errno));
115 static void *xcmalloc(size_t size, const char *name)
118 buf = xmalloc(size, name);
119 memset(buf, 0, size);
123 static void xfree(const void *ptr)
128 static char *xstrdup(const char *str)
133 new = xmalloc(len + 1, "xstrdup string");
134 memcpy(new, str, len);
139 static void xchdir(const char *path)
141 if (chdir(path) != 0) {
142 die("chdir to %s failed: %s\n",
143 path, strerror(errno));
147 static int exists(const char *dirname, const char *filename)
151 if (access(filename, O_RDONLY) < 0) {
152 if ((errno != EACCES) && (errno != EROFS)) {
160 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
164 off_t size, progress;
173 fd = open(filename, O_RDONLY);
175 die("Cannot open '%s' : %s\n",
176 filename, strerror(errno));
178 result = fstat(fd, &stats);
180 die("Cannot stat: %s: %s\n",
181 filename, strerror(errno));
183 size = stats.st_size;
185 buf = xmalloc(size +2, filename);
186 buf[size] = '\n'; /* Make certain the file is newline terminated */
187 buf[size+1] = '\0'; /* Null terminate the file for good measure */
189 while(progress < size) {
190 result = read(fd, buf + progress, size - progress);
192 if ((errno == EINTR) || (errno == EAGAIN))
194 die("read on %s of %ld bytes failed: %s\n",
195 filename, (size - progress)+ 0UL, strerror(errno));
201 die("Close of %s failed: %s\n",
202 filename, strerror(errno));
207 /* Long on the destination platform */
208 typedef unsigned long ulong_t;
212 struct file_state *prev;
213 const char *basename;
221 const char *report_name;
222 const char *report_dir;
227 struct hash_entry *ident;
235 /* I have two classes of types:
237 * Logical types. (The type the C standard says the operation is of)
239 * The operational types are:
254 * No memory is useable by the compiler.
255 * There is no floating point support.
256 * All operations take place in general purpose registers.
257 * There is one type of general purpose register.
258 * Unsigned longs are stored in that general purpose register.
261 /* Operations on general purpose registers.
278 #define OP_POS 14 /* Dummy positive operator don't use it */
288 #define OP_SLESSEQ 26
289 #define OP_ULESSEQ 27
290 #define OP_SMOREEQ 28
291 #define OP_UMOREEQ 29
293 #define OP_LFALSE 30 /* Test if the expression is logically false */
294 #define OP_LTRUE 31 /* Test if the expression is logcially true */
301 #define OP_MIN_CONST 50
302 #define OP_MAX_CONST 59
303 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
304 #define OP_INTCONST 50
305 /* For OP_INTCONST ->type holds the type.
306 * ->u.cval holds the constant value.
308 #define OP_BLOBCONST 51
309 /* For OP_BLOBCONST ->type holds the layout and size
310 * information. u.blob holds a pointer to the raw binary
311 * data for the constant initializer.
313 #define OP_ADDRCONST 52
314 /* For OP_ADDRCONST ->type holds the type.
315 * MISC(0) holds the reference to the static variable.
316 * ->u.cval holds an offset from that value.
320 /* OP_WRITE moves one pseudo register to another.
321 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
322 * RHS(0) holds the psuedo to move.
326 /* OP_READ reads the value of a variable and makes
327 * it available for the pseudo operation.
328 * Useful for things like def-use chains.
329 * RHS(0) holds points to the triple to read from.
332 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
335 /* OP_PIECE returns one piece of a instruction that returns a structure.
336 * MISC(0) is the instruction
337 * u.cval is the LHS piece of the instruction to return.
340 /* OP_ASM holds a sequence of assembly instructions, the result
341 * of a C asm directive.
342 * RHS(x) holds input value x to the assembly sequence.
343 * LHS(x) holds the output value x from the assembly sequence.
344 * u.blob holds the string of assembly instructions.
348 /* OP_DEREF generates an lvalue from a pointer.
349 * RHS(0) holds the pointer value.
350 * OP_DEREF serves as a place holder to indicate all necessary
351 * checks have been done to indicate a value is an lvalue.
354 /* OP_DOT references a submember of a structure lvalue.
355 * RHS(0) holds the lvalue.
356 * ->u.field holds the name of the field we want.
358 * Not seen outside of expressions.
361 /* OP_VAL returns the value of a subexpression of the current expression.
362 * Useful for operators that have side effects.
363 * RHS(0) holds the expression.
364 * MISC(0) holds the subexpression of RHS(0) that is the
365 * value of the expression.
367 * Not seen outside of expressions.
370 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
371 * Not seen outside of expressions.
374 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
375 * Not seen outside of expressions.
378 /* OP_CODE performas a C ? : operation.
379 * RHS(0) holds the test.
380 * RHS(1) holds the expression to evaluate if the test returns true.
381 * RHS(2) holds the expression to evaluate if the test returns false.
382 * Not seen outside of expressions.
385 /* OP_COMMA performacs a C comma operation.
386 * That is RHS(0) is evaluated, then RHS(1)
387 * and the value of RHS(1) is returned.
388 * Not seen outside of expressions.
392 /* OP_CALL performs a procedure call.
393 * MISC(0) holds a pointer to the OP_LIST of a function
394 * RHS(x) holds argument x of a function
396 * Currently not seen outside of expressions.
398 #define OP_VAL_VEC 74
399 /* OP_VAL_VEC is an array of triples that are either variable
400 * or values for a structure or an array.
401 * RHS(x) holds element x of the vector.
402 * triple->type->elements holds the size of the vector.
407 /* OP_LIST Holds a list of statements, and a result value.
408 * RHS(0) holds the list of statements.
409 * MISC(0) holds the value of the statements.
412 #define OP_BRANCH 81 /* branch */
413 /* For branch instructions
414 * TARG(0) holds the branch target.
415 * RHS(0) if present holds the branch condition.
416 * ->next holds where to branch to if the branch is not taken.
417 * The branch target can only be a decl...
421 /* OP_LABEL is a triple that establishes an target for branches.
422 * ->use is the list of all branches that use this label.
426 /* OP_DECL is a triple that establishes an lvalue for assignments.
427 * ->use is a list of statements that use the variable.
431 /* OP_SDECL is a triple that establishes a variable of static
433 * ->use is a list of statements that use the variable.
434 * MISC(0) holds the initializer expression.
439 /* OP_PHI is a triple used in SSA form code.
440 * It is used when multiple code paths merge and a variable needs
441 * a single assignment from any of those code paths.
442 * The operation is a cross between OP_DECL and OP_WRITE, which
443 * is what OP_PHI is geneared from.
445 * RHS(x) points to the value from code path x
446 * The number of RHS entries is the number of control paths into the block
447 * in which OP_PHI resides. The elements of the array point to point
448 * to the variables OP_PHI is derived from.
450 * MISC(0) holds a pointer to the orginal OP_DECL node.
453 /* Architecture specific instructions */
456 #define OP_SET_EQ 102
457 #define OP_SET_NOTEQ 103
458 #define OP_SET_SLESS 104
459 #define OP_SET_ULESS 105
460 #define OP_SET_SMORE 106
461 #define OP_SET_UMORE 107
462 #define OP_SET_SLESSEQ 108
463 #define OP_SET_ULESSEQ 109
464 #define OP_SET_SMOREEQ 110
465 #define OP_SET_UMOREEQ 111
468 #define OP_JMP_EQ 113
469 #define OP_JMP_NOTEQ 114
470 #define OP_JMP_SLESS 115
471 #define OP_JMP_ULESS 116
472 #define OP_JMP_SMORE 117
473 #define OP_JMP_UMORE 118
474 #define OP_JMP_SLESSEQ 119
475 #define OP_JMP_ULESSEQ 120
476 #define OP_JMP_SMOREEQ 121
477 #define OP_JMP_UMOREEQ 122
479 /* Builtin operators that it is just simpler to use the compiler for */
497 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
499 #define BLOCK 8 /* Triple stores the current block */
500 unsigned char lhs, rhs, misc, targ;
503 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
511 static const struct op_info table_ops[] = {
512 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
513 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
514 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
515 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
516 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
517 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
518 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
519 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
520 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
521 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
522 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
523 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
524 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
525 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
526 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
527 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
528 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
530 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
531 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
532 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
533 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
534 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
535 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
536 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
537 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
538 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
539 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
540 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
541 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
543 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
544 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE | BLOCK , "store"),
546 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
548 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
549 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
550 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
552 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE | BLOCK, "write"),
553 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
554 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
555 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
556 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
557 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
558 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
560 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
561 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
562 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
563 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
564 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
565 /* Call is special most it can stand in for anything so it depends on context */
566 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
567 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
568 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
570 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
571 /* The number of targets for OP_BRANCH depends on context */
572 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
573 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
574 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
575 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
576 /* The number of RHS elements of OP_PHI depend upon context */
577 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
579 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
580 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
581 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
582 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
583 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
584 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
585 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
586 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
587 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
588 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
589 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
590 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
591 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
592 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
593 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
594 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
595 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
596 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
597 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
598 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
599 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
600 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
601 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
603 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
604 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
605 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
606 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
607 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
608 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
609 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
610 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
611 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
612 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
613 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
616 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
618 static const char *tops(int index)
620 static const char unknown[] = "unknown op";
624 if (index > OP_MAX) {
627 return table_ops[index].name;
634 struct triple_set *next;
635 struct triple *member;
645 const char *filename;
646 const char *function;
649 struct occurance *parent;
652 struct triple *next, *prev;
653 struct triple_set *use;
656 unsigned char template_id;
657 unsigned short sizes;
658 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
659 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
660 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
661 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
662 #define TRIPLE_SIZE(SIZES) \
663 ((((SIZES) >> 0) & 0x0f) + \
664 (((SIZES) >> 4) & 0x0f) + \
665 (((SIZES) >> 8) & 0x0f) + \
666 (((SIZES) >> 12) & 0x0f))
667 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
668 ((((LHS) & 0x0f) << 0) | \
669 (((RHS) & 0x0f) << 4) | \
670 (((MISC) & 0x0f) << 8) | \
671 (((TARG) & 0x0f) << 12))
672 #define TRIPLE_LHS_OFF(SIZES) (0)
673 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
674 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
675 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
676 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
677 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
678 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
679 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
680 unsigned id; /* A scratch value and finally the register */
681 #define TRIPLE_FLAG_FLATTENED (1 << 31)
682 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
683 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
684 struct occurance *occurance;
689 struct hash_entry *field;
690 struct asm_info *ainfo;
692 struct triple *param[2];
699 struct ins_template {
700 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
704 struct ins_template tmpl;
709 struct block_set *next;
710 struct block *member;
713 struct block *work_next;
714 struct block *left, *right;
715 struct triple *first, *last;
717 struct block_set *use;
718 struct block_set *idominates;
719 struct block_set *domfrontier;
721 struct block_set *ipdominates;
722 struct block_set *ipdomfrontier;
730 struct hash_entry *ident;
737 struct hash_entry *ident;
743 struct hash_entry *next;
747 struct macro *sym_define;
748 struct symbol *sym_label;
749 struct symbol *sym_struct;
750 struct symbol *sym_ident;
753 #define HASH_TABLE_SIZE 2048
755 struct compile_state {
756 const char *label_prefix;
757 const char *ofilename;
759 struct file_state *file;
760 struct occurance *last_occurance;
761 const char *function;
762 struct token token[4];
763 struct hash_entry *hash_table[HASH_TABLE_SIZE];
764 struct hash_entry *i_continue;
765 struct hash_entry *i_break;
767 int if_depth, if_value;
769 struct file_state *macro_file;
770 struct triple *main_function;
771 struct block *first_block, *last_block;
778 /* visibility global/local */
779 /* static/auto duration */
780 /* typedef, register, inline */
782 #define STOR_MASK 0x000f
784 #define STOR_GLOBAL 0x0001
786 #define STOR_PERM 0x0002
787 /* Storage specifiers */
788 #define STOR_AUTO 0x0000
789 #define STOR_STATIC 0x0002
790 #define STOR_EXTERN 0x0003
791 #define STOR_REGISTER 0x0004
792 #define STOR_TYPEDEF 0x0008
793 #define STOR_INLINE 0x000c
796 #define QUAL_MASK 0x0070
797 #define QUAL_NONE 0x0000
798 #define QUAL_CONST 0x0010
799 #define QUAL_VOLATILE 0x0020
800 #define QUAL_RESTRICT 0x0040
803 #define TYPE_MASK 0x1f00
804 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
805 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
806 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
807 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
808 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
809 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
810 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
811 #define TYPE_DEFAULT 0x0000
812 #define TYPE_VOID 0x0100
813 #define TYPE_CHAR 0x0200
814 #define TYPE_UCHAR 0x0300
815 #define TYPE_SHORT 0x0400
816 #define TYPE_USHORT 0x0500
817 #define TYPE_INT 0x0600
818 #define TYPE_UINT 0x0700
819 #define TYPE_LONG 0x0800
820 #define TYPE_ULONG 0x0900
821 #define TYPE_LLONG 0x0a00 /* long long */
822 #define TYPE_ULLONG 0x0b00
823 #define TYPE_FLOAT 0x0c00
824 #define TYPE_DOUBLE 0x0d00
825 #define TYPE_LDOUBLE 0x0e00 /* long double */
826 #define TYPE_STRUCT 0x1000
827 #define TYPE_ENUM 0x1100
828 #define TYPE_POINTER 0x1200
830 * type->left holds the type pointed to.
832 #define TYPE_FUNCTION 0x1300
833 /* For TYPE_FUNCTION:
834 * type->left holds the return type.
835 * type->right holds the...
837 #define TYPE_PRODUCT 0x1400
838 /* TYPE_PRODUCT is a basic building block when defining structures
839 * type->left holds the type that appears first in memory.
840 * type->right holds the type that appears next in memory.
842 #define TYPE_OVERLAP 0x1500
843 /* TYPE_OVERLAP is a basic building block when defining unions
844 * type->left and type->right holds to types that overlap
845 * each other in memory.
847 #define TYPE_ARRAY 0x1600
848 /* TYPE_ARRAY is a basic building block when definitng arrays.
849 * type->left holds the type we are an array of.
850 * type-> holds the number of elements.
853 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
857 struct type *left, *right;
859 struct hash_entry *field_ident;
860 struct hash_entry *type_ident;
863 #define MAX_REGISTERS 75
864 #define MAX_REG_EQUIVS 16
865 #define REGISTER_BITS 16
866 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
867 #define TEMPLATE_BITS 6
868 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
871 #define REG_UNNEEDED 1
872 #define REG_VIRT0 (MAX_REGISTERS + 0)
873 #define REG_VIRT1 (MAX_REGISTERS + 1)
874 #define REG_VIRT2 (MAX_REGISTERS + 2)
875 #define REG_VIRT3 (MAX_REGISTERS + 3)
876 #define REG_VIRT4 (MAX_REGISTERS + 4)
877 #define REG_VIRT5 (MAX_REGISTERS + 5)
878 #define REG_VIRT6 (MAX_REGISTERS + 5)
879 #define REG_VIRT7 (MAX_REGISTERS + 5)
880 #define REG_VIRT8 (MAX_REGISTERS + 5)
881 #define REG_VIRT9 (MAX_REGISTERS + 5)
883 /* Provision for 8 register classes */
885 #define REGC_SHIFT REGISTER_BITS
886 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
887 #define REG_MASK (MAX_VIRT_REGISTERS -1)
888 #define ID_REG(ID) ((ID) & REG_MASK)
889 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
890 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
891 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
892 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
893 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
895 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
896 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
897 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
898 static void arch_reg_equivs(
899 struct compile_state *state, unsigned *equiv, int reg);
900 static int arch_select_free_register(
901 struct compile_state *state, char *used, int classes);
902 static unsigned arch_regc_size(struct compile_state *state, int class);
903 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
904 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
905 static const char *arch_reg_str(int reg);
906 static struct reg_info arch_reg_constraint(
907 struct compile_state *state, struct type *type, const char *constraint);
908 static struct reg_info arch_reg_clobber(
909 struct compile_state *state, const char *clobber);
910 static struct reg_info arch_reg_lhs(struct compile_state *state,
911 struct triple *ins, int index);
912 static struct reg_info arch_reg_rhs(struct compile_state *state,
913 struct triple *ins, int index);
914 static struct triple *transform_to_arch_instruction(
915 struct compile_state *state, struct triple *ins);
919 #define DEBUG_ABORT_ON_ERROR 0x0001
920 #define DEBUG_INTERMEDIATE_CODE 0x0002
921 #define DEBUG_CONTROL_FLOW 0x0004
922 #define DEBUG_BASIC_BLOCKS 0x0008
923 #define DEBUG_FDOMINATORS 0x0010
924 #define DEBUG_RDOMINATORS 0x0020
925 #define DEBUG_TRIPLES 0x0040
926 #define DEBUG_INTERFERENCE 0x0080
927 #define DEBUG_ARCH_CODE 0x0100
928 #define DEBUG_CODE_ELIMINATION 0x0200
929 #define DEBUG_INSERTED_COPIES 0x0400
931 #define GLOBAL_SCOPE_DEPTH 1
932 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
934 static void compile_file(struct compile_state *old_state, const char *filename, int local);
936 static void do_cleanup(struct compile_state *state)
939 fclose(state->output);
940 unlink(state->ofilename);
944 static int get_col(struct file_state *file)
948 ptr = file->line_start;
950 for(col = 0; ptr < end; ptr++) {
955 col = (col & ~7) + 8;
961 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
965 struct occurance *spot;
966 spot = triple->occurance;
967 while(spot->parent) {
970 fprintf(fp, "%s:%d.%d: ",
971 spot->filename, spot->line, spot->col);
977 col = get_col(state->file);
978 fprintf(fp, "%s:%d.%d: ",
979 state->file->report_name, state->file->report_line, col);
982 static void __internal_error(struct compile_state *state, struct triple *ptr,
987 loc(stderr, state, ptr);
989 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
991 fprintf(stderr, "Internal compiler error: ");
992 vfprintf(stderr, fmt, args);
993 fprintf(stderr, "\n");
1000 static void __internal_warning(struct compile_state *state, struct triple *ptr,
1004 va_start(args, fmt);
1005 loc(stderr, state, ptr);
1006 fprintf(stderr, "Internal compiler warning: ");
1007 vfprintf(stderr, fmt, args);
1008 fprintf(stderr, "\n");
1014 static void __error(struct compile_state *state, struct triple *ptr,
1018 va_start(args, fmt);
1019 loc(stderr, state, ptr);
1020 vfprintf(stderr, fmt, args);
1022 fprintf(stderr, "\n");
1024 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1030 static void __warning(struct compile_state *state, struct triple *ptr,
1034 va_start(args, fmt);
1035 loc(stderr, state, ptr);
1036 fprintf(stderr, "warning: ");
1037 vfprintf(stderr, fmt, args);
1038 fprintf(stderr, "\n");
1042 #if DEBUG_ERROR_MESSAGES
1043 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1044 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1045 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1046 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1048 # define internal_error __internal_error
1049 # define internal_warning __internal_warning
1050 # define error __error
1051 # define warning __warning
1053 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1055 static void valid_op(struct compile_state *state, int op)
1057 char *fmt = "invalid op: %d";
1059 internal_error(state, 0, fmt, op);
1062 internal_error(state, 0, fmt, op);
1066 static void valid_ins(struct compile_state *state, struct triple *ptr)
1068 valid_op(state, ptr->op);
1071 static void process_trigraphs(struct compile_state *state)
1073 char *src, *dest, *end;
1074 struct file_state *file;
1076 src = dest = file->buf;
1077 end = file->buf + file->size;
1078 while((end - src) >= 3) {
1079 if ((src[0] == '?') && (src[1] == '?')) {
1082 case '=': c = '#'; break;
1083 case '/': c = '\\'; break;
1084 case '\'': c = '^'; break;
1085 case '(': c = '['; break;
1086 case ')': c = ']'; break;
1087 case '!': c = '!'; break;
1088 case '<': c = '{'; break;
1089 case '>': c = '}'; break;
1090 case '-': c = '~'; break;
1107 file->size = dest - file->buf;
1110 static void splice_lines(struct compile_state *state)
1112 char *src, *dest, *end;
1113 struct file_state *file;
1115 src = dest = file->buf;
1116 end = file->buf + file->size;
1117 while((end - src) >= 2) {
1118 if ((src[0] == '\\') && (src[1] == '\n')) {
1128 file->size = dest - file->buf;
1131 static struct type void_type;
1132 static void use_triple(struct triple *used, struct triple *user)
1134 struct triple_set **ptr, *new;
1141 if ((*ptr)->member == user) {
1144 ptr = &(*ptr)->next;
1146 /* Append new to the head of the list,
1147 * copy_func and rename_block_variables
1150 new = xcmalloc(sizeof(*new), "triple_set");
1152 new->next = used->use;
1156 static void unuse_triple(struct triple *used, struct triple *unuser)
1158 struct triple_set *use, **ptr;
1165 if (use->member == unuser) {
1175 static void push_triple(struct triple *used, struct triple *user)
1177 struct triple_set *new;
1182 /* Append new to the head of the list,
1183 * it's the only sensible behavoir for a stack.
1185 new = xcmalloc(sizeof(*new), "triple_set");
1187 new->next = used->use;
1191 static void pop_triple(struct triple *used, struct triple *unuser)
1193 struct triple_set *use, **ptr;
1197 if (use->member == unuser) {
1200 /* Only free one occurance from the stack */
1209 static void put_occurance(struct occurance *occurance)
1211 occurance->count -= 1;
1212 if (occurance->count <= 0) {
1213 if (occurance->parent) {
1214 put_occurance(occurance->parent);
1220 static void get_occurance(struct occurance *occurance)
1222 occurance->count += 1;
1226 static struct occurance *new_occurance(struct compile_state *state)
1228 struct occurance *result, *last;
1229 const char *filename;
1230 const char *function;
1238 filename = state->file->report_name;
1239 line = state->file->report_line;
1240 col = get_col(state->file);
1242 if (state->function) {
1243 function = state->function;
1245 last = state->last_occurance;
1247 (last->col == col) &&
1248 (last->line == line) &&
1249 (last->function == function) &&
1250 (strcmp(last->filename, filename) == 0)) {
1251 get_occurance(last);
1255 state->last_occurance = 0;
1256 put_occurance(last);
1258 result = xmalloc(sizeof(*result), "occurance");
1260 result->filename = filename;
1261 result->function = function;
1262 result->line = line;
1265 state->last_occurance = result;
1269 static struct occurance *inline_occurance(struct compile_state *state,
1270 struct occurance *new, struct occurance *orig)
1272 struct occurance *result, *last;
1273 last = state->last_occurance;
1275 (last->parent == orig) &&
1276 (last->col == new->col) &&
1277 (last->line == new->line) &&
1278 (last->function == new->function) &&
1279 (last->filename == new->filename)) {
1280 get_occurance(last);
1284 state->last_occurance = 0;
1285 put_occurance(last);
1287 get_occurance(orig);
1288 result = xmalloc(sizeof(*result), "occurance");
1290 result->filename = new->filename;
1291 result->function = new->function;
1292 result->line = new->line;
1293 result->col = new->col;
1294 result->parent = orig;
1295 state->last_occurance = result;
1300 static struct occurance dummy_occurance = {
1302 .filename = __FILE__,
1309 /* The zero triple is used as a place holder when we are removing pointers
1310 * from a triple. Having allows certain sanity checks to pass even
1311 * when the original triple that was pointed to is gone.
1313 static struct triple zero_triple = {
1314 .next = &zero_triple,
1315 .prev = &zero_triple,
1318 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1319 .id = -1, /* An invalid id */
1320 .u = { .cval = 0, },
1321 .occurance = &dummy_occurance,
1322 .param { [0] = 0, [1] = 0, },
1326 static unsigned short triple_sizes(struct compile_state *state,
1327 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1329 int lhs, rhs, misc, targ;
1330 valid_op(state, op);
1331 lhs = table_ops[op].lhs;
1332 rhs = table_ops[op].rhs;
1333 misc = table_ops[op].misc;
1334 targ = table_ops[op].targ;
1337 if (op == OP_CALL) {
1340 param = type->right;
1341 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1343 param = param->right;
1345 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1349 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1350 lhs = type->left->elements;
1353 else if (op == OP_VAL_VEC) {
1354 rhs = type->elements;
1356 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1359 else if (op == OP_ASM) {
1363 if ((rhs < 0) || (rhs > MAX_RHS)) {
1364 internal_error(state, 0, "bad rhs");
1366 if ((lhs < 0) || (lhs > MAX_LHS)) {
1367 internal_error(state, 0, "bad lhs");
1369 if ((misc < 0) || (misc > MAX_MISC)) {
1370 internal_error(state, 0, "bad misc");
1372 if ((targ < 0) || (targ > MAX_TARG)) {
1373 internal_error(state, 0, "bad targs");
1375 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1378 static struct triple *alloc_triple(struct compile_state *state,
1379 int op, struct type *type, int lhs, int rhs,
1380 struct occurance *occurance)
1382 size_t size, sizes, extra_count, min_count;
1384 sizes = triple_sizes(state, op, type, lhs, rhs);
1386 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1387 extra_count = TRIPLE_SIZE(sizes);
1388 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1390 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1391 ret = xcmalloc(size, "tripple");
1397 ret->occurance = occurance;
1401 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1404 int src_lhs, src_rhs, src_size;
1405 src_lhs = TRIPLE_LHS(src->sizes);
1406 src_rhs = TRIPLE_RHS(src->sizes);
1407 src_size = TRIPLE_SIZE(src->sizes);
1408 get_occurance(src->occurance);
1409 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1411 memcpy(dup, src, sizeof(*src));
1412 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1416 static struct triple *new_triple(struct compile_state *state,
1417 int op, struct type *type, int lhs, int rhs)
1420 struct occurance *occurance;
1421 occurance = new_occurance(state);
1422 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1426 static struct triple *build_triple(struct compile_state *state,
1427 int op, struct type *type, struct triple *left, struct triple *right,
1428 struct occurance *occurance)
1432 ret = alloc_triple(state, op, type, -1, -1, occurance);
1433 count = TRIPLE_SIZE(ret->sizes);
1435 ret->param[0] = left;
1438 ret->param[1] = right;
1443 static struct triple *triple(struct compile_state *state,
1444 int op, struct type *type, struct triple *left, struct triple *right)
1448 ret = new_triple(state, op, type, -1, -1);
1449 count = TRIPLE_SIZE(ret->sizes);
1451 ret->param[0] = left;
1454 ret->param[1] = right;
1459 static struct triple *branch(struct compile_state *state,
1460 struct triple *targ, struct triple *test)
1463 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1467 TARG(ret, 0) = targ;
1468 /* record the branch target was used */
1469 if (!targ || (targ->op != OP_LABEL)) {
1470 internal_error(state, 0, "branch not to label");
1471 use_triple(targ, ret);
1477 static void insert_triple(struct compile_state *state,
1478 struct triple *first, struct triple *ptr)
1481 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1482 internal_error(state, ptr, "expression already used");
1485 ptr->prev = first->prev;
1486 ptr->prev->next = ptr;
1487 ptr->next->prev = ptr;
1488 if ((ptr->prev->op == OP_BRANCH) &&
1489 TRIPLE_RHS(ptr->prev->sizes)) {
1490 unuse_triple(first, ptr->prev);
1491 use_triple(ptr, ptr->prev);
1496 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1498 /* This function is used to determine if u.block
1499 * is utilized to store the current block number.
1502 valid_ins(state, ins);
1503 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1504 return stores_block;
1507 static struct block *block_of_triple(struct compile_state *state,
1510 struct triple *first;
1511 first = RHS(state->main_function, 0);
1512 while(ins != first && !triple_stores_block(state, ins)) {
1513 if (ins == ins->prev) {
1514 internal_error(state, 0, "ins == ins->prev?");
1518 if (!triple_stores_block(state, ins)) {
1519 internal_error(state, ins, "Cannot find block");
1521 return ins->u.block;
1524 static struct triple *pre_triple(struct compile_state *state,
1525 struct triple *base,
1526 int op, struct type *type, struct triple *left, struct triple *right)
1528 struct block *block;
1530 /* If I am an OP_PIECE jump to the real instruction */
1531 if (base->op == OP_PIECE) {
1532 base = MISC(base, 0);
1534 block = block_of_triple(state, base);
1535 get_occurance(base->occurance);
1536 ret = build_triple(state, op, type, left, right, base->occurance);
1537 if (triple_stores_block(state, ret)) {
1538 ret->u.block = block;
1540 insert_triple(state, base, ret);
1541 if (block->first == base) {
1547 static struct triple *post_triple(struct compile_state *state,
1548 struct triple *base,
1549 int op, struct type *type, struct triple *left, struct triple *right)
1551 struct block *block;
1554 /* If I am an OP_PIECE jump to the real instruction */
1555 if (base->op == OP_PIECE) {
1556 base = MISC(base, 0);
1558 /* If I have a left hand side skip over it */
1559 zlhs = TRIPLE_LHS(base->sizes);
1560 if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1561 base = LHS(base, zlhs - 1);
1564 block = block_of_triple(state, base);
1565 get_occurance(base->occurance);
1566 ret = build_triple(state, op, type, left, right, base->occurance);
1567 if (triple_stores_block(state, ret)) {
1568 ret->u.block = block;
1570 insert_triple(state, base->next, ret);
1571 if (block->last == base) {
1577 static struct triple *label(struct compile_state *state)
1579 /* Labels don't get a type */
1580 struct triple *result;
1581 result = triple(state, OP_LABEL, &void_type, 0, 0);
1585 static void display_triple(FILE *fp, struct triple *ins)
1587 struct occurance *ptr;
1591 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1594 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1597 reg = arch_reg_str(ID_REG(ins->id));
1598 if (ins->op == OP_INTCONST) {
1599 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1600 ins, pre, post, reg, ins->template_id, tops(ins->op),
1603 else if (ins->op == OP_ADDRCONST) {
1604 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1605 ins, pre, post, reg, ins->template_id, tops(ins->op),
1606 MISC(ins, 0), ins->u.cval);
1610 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1611 ins, pre, post, reg, ins->template_id, tops(ins->op));
1612 count = TRIPLE_SIZE(ins->sizes);
1613 for(i = 0; i < count; i++) {
1614 fprintf(fp, " %-10p", ins->param[i]);
1621 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1622 fprintf(fp, " %s,%s:%d.%d",
1632 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1634 /* Does the triple have no side effects.
1635 * I.e. Rexecuting the triple with the same arguments
1636 * gives the same value.
1639 valid_ins(state, ins);
1640 pure = PURE_BITS(table_ops[ins->op].flags);
1641 if ((pure != PURE) && (pure != IMPURE)) {
1642 internal_error(state, 0, "Purity of %s not known\n",
1645 return pure == PURE;
1648 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1650 /* This function is used to determine which triples need
1654 valid_ins(state, ins);
1655 is_branch = (table_ops[ins->op].targ != 0);
1659 static int triple_is_def(struct compile_state *state, struct triple *ins)
1661 /* This function is used to determine which triples need
1665 valid_ins(state, ins);
1666 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1670 static struct triple **triple_iter(struct compile_state *state,
1671 size_t count, struct triple **vector,
1672 struct triple *ins, struct triple **last)
1674 struct triple **ret;
1680 else if ((last >= vector) && (last < (vector + count - 1))) {
1688 static struct triple **triple_lhs(struct compile_state *state,
1689 struct triple *ins, struct triple **last)
1691 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1695 static struct triple **triple_rhs(struct compile_state *state,
1696 struct triple *ins, struct triple **last)
1698 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1702 static struct triple **triple_misc(struct compile_state *state,
1703 struct triple *ins, struct triple **last)
1705 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1709 static struct triple **triple_targ(struct compile_state *state,
1710 struct triple *ins, struct triple **last)
1713 struct triple **ret, **vector;
1715 count = TRIPLE_TARG(ins->sizes);
1716 vector = &TARG(ins, 0);
1721 else if ((last >= vector) && (last < (vector + count - 1))) {
1724 else if ((last == (vector + count - 1)) &&
1725 TRIPLE_RHS(ins->sizes)) {
1733 static void verify_use(struct compile_state *state,
1734 struct triple *user, struct triple *used)
1737 size = TRIPLE_SIZE(user->sizes);
1738 for(i = 0; i < size; i++) {
1739 if (user->param[i] == used) {
1743 if (triple_is_branch(state, user)) {
1744 if (user->next == used) {
1749 internal_error(state, user, "%s(%p) does not use %s(%p)",
1750 tops(user->op), user, tops(used->op), used);
1754 static int find_rhs_use(struct compile_state *state,
1755 struct triple *user, struct triple *used)
1757 struct triple **param;
1759 verify_use(state, user, used);
1760 size = TRIPLE_RHS(user->sizes);
1761 param = &RHS(user, 0);
1762 for(i = 0; i < size; i++) {
1763 if (param[i] == used) {
1770 static void free_triple(struct compile_state *state, struct triple *ptr)
1773 size = sizeof(*ptr) - sizeof(ptr->param) +
1774 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1775 ptr->prev->next = ptr->next;
1776 ptr->next->prev = ptr->prev;
1778 internal_error(state, ptr, "ptr->use != 0");
1780 put_occurance(ptr->occurance);
1781 memset(ptr, -1, size);
1785 static void release_triple(struct compile_state *state, struct triple *ptr)
1787 struct triple_set *set, *next;
1788 struct triple **expr;
1789 /* Remove ptr from use chains where it is the user */
1790 expr = triple_rhs(state, ptr, 0);
1791 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1793 unuse_triple(*expr, ptr);
1796 expr = triple_lhs(state, ptr, 0);
1797 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1799 unuse_triple(*expr, ptr);
1802 expr = triple_misc(state, ptr, 0);
1803 for(; expr; expr = triple_misc(state, ptr, expr)) {
1805 unuse_triple(*expr, ptr);
1808 expr = triple_targ(state, ptr, 0);
1809 for(; expr; expr = triple_targ(state, ptr, expr)) {
1811 unuse_triple(*expr, ptr);
1814 /* Reomve ptr from use chains where it is used */
1815 for(set = ptr->use; set; set = next) {
1817 expr = triple_rhs(state, set->member, 0);
1818 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1820 *expr = &zero_triple;
1823 expr = triple_lhs(state, set->member, 0);
1824 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1826 *expr = &zero_triple;
1829 expr = triple_misc(state, set->member, 0);
1830 for(; expr; expr = triple_misc(state, set->member, expr)) {
1832 *expr = &zero_triple;
1835 expr = triple_targ(state, set->member, 0);
1836 for(; expr; expr = triple_targ(state, set->member, expr)) {
1838 *expr = &zero_triple;
1841 unuse_triple(ptr, set->member);
1843 free_triple(state, ptr);
1846 static void print_triple(struct compile_state *state, struct triple *ptr);
1848 #define TOK_UNKNOWN 0
1851 #define TOK_LBRACE 3
1852 #define TOK_RBRACE 4
1856 #define TOK_LBRACKET 8
1857 #define TOK_RBRACKET 9
1858 #define TOK_LPAREN 10
1859 #define TOK_RPAREN 11
1864 #define TOK_TIMESEQ 16
1865 #define TOK_DIVEQ 17
1866 #define TOK_MODEQ 18
1867 #define TOK_PLUSEQ 19
1868 #define TOK_MINUSEQ 20
1871 #define TOK_ANDEQ 23
1872 #define TOK_XOREQ 24
1875 #define TOK_NOTEQ 27
1876 #define TOK_QUEST 28
1877 #define TOK_LOGOR 29
1878 #define TOK_LOGAND 30
1882 #define TOK_LESSEQ 34
1883 #define TOK_MOREEQ 35
1887 #define TOK_MINUS 39
1890 #define TOK_PLUSPLUS 42
1891 #define TOK_MINUSMINUS 43
1893 #define TOK_ARROW 45
1895 #define TOK_TILDE 47
1896 #define TOK_LIT_STRING 48
1897 #define TOK_LIT_CHAR 49
1898 #define TOK_LIT_INT 50
1899 #define TOK_LIT_FLOAT 51
1900 #define TOK_MACRO 52
1901 #define TOK_CONCATENATE 53
1903 #define TOK_IDENT 54
1904 #define TOK_STRUCT_NAME 55
1905 #define TOK_ENUM_CONST 56
1906 #define TOK_TYPE_NAME 57
1909 #define TOK_BREAK 59
1912 #define TOK_CONST 62
1913 #define TOK_CONTINUE 63
1914 #define TOK_DEFAULT 64
1916 #define TOK_DOUBLE 66
1919 #define TOK_EXTERN 69
1920 #define TOK_FLOAT 70
1924 #define TOK_INLINE 74
1927 #define TOK_REGISTER 77
1928 #define TOK_RESTRICT 78
1929 #define TOK_RETURN 79
1930 #define TOK_SHORT 80
1931 #define TOK_SIGNED 81
1932 #define TOK_SIZEOF 82
1933 #define TOK_STATIC 83
1934 #define TOK_STRUCT 84
1935 #define TOK_SWITCH 85
1936 #define TOK_TYPEDEF 86
1937 #define TOK_UNION 87
1938 #define TOK_UNSIGNED 88
1940 #define TOK_VOLATILE 90
1941 #define TOK_WHILE 91
1943 #define TOK_ATTRIBUTE 93
1944 #define TOK_ALIGNOF 94
1945 #define TOK_FIRST_KEYWORD TOK_AUTO
1946 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1948 #define TOK_DEFINE 100
1949 #define TOK_UNDEF 101
1950 #define TOK_INCLUDE 102
1951 #define TOK_LINE 103
1952 #define TOK_ERROR 104
1953 #define TOK_WARNING 105
1954 #define TOK_PRAGMA 106
1955 #define TOK_IFDEF 107
1956 #define TOK_IFNDEF 108
1957 #define TOK_ELIF 109
1958 #define TOK_ENDIF 110
1960 #define TOK_FIRST_MACRO TOK_DEFINE
1961 #define TOK_LAST_MACRO TOK_ENDIF
1965 static const char *tokens[] = {
1966 [TOK_UNKNOWN ] = "unknown",
1967 [TOK_SPACE ] = ":space:",
1969 [TOK_LBRACE ] = "{",
1970 [TOK_RBRACE ] = "}",
1974 [TOK_LBRACKET ] = "[",
1975 [TOK_RBRACKET ] = "]",
1976 [TOK_LPAREN ] = "(",
1977 [TOK_RPAREN ] = ")",
1979 [TOK_DOTS ] = "...",
1982 [TOK_TIMESEQ ] = "*=",
1983 [TOK_DIVEQ ] = "/=",
1984 [TOK_MODEQ ] = "%=",
1985 [TOK_PLUSEQ ] = "+=",
1986 [TOK_MINUSEQ ] = "-=",
1987 [TOK_SLEQ ] = "<<=",
1988 [TOK_SREQ ] = ">>=",
1989 [TOK_ANDEQ ] = "&=",
1990 [TOK_XOREQ ] = "^=",
1993 [TOK_NOTEQ ] = "!=",
1995 [TOK_LOGOR ] = "||",
1996 [TOK_LOGAND ] = "&&",
2000 [TOK_LESSEQ ] = "<=",
2001 [TOK_MOREEQ ] = ">=",
2008 [TOK_PLUSPLUS ] = "++",
2009 [TOK_MINUSMINUS ] = "--",
2011 [TOK_ARROW ] = "->",
2014 [TOK_LIT_STRING ] = ":string:",
2015 [TOK_IDENT ] = ":ident:",
2016 [TOK_TYPE_NAME ] = ":typename:",
2017 [TOK_LIT_CHAR ] = ":char:",
2018 [TOK_LIT_INT ] = ":integer:",
2019 [TOK_LIT_FLOAT ] = ":float:",
2021 [TOK_CONCATENATE ] = "##",
2023 [TOK_AUTO ] = "auto",
2024 [TOK_BREAK ] = "break",
2025 [TOK_CASE ] = "case",
2026 [TOK_CHAR ] = "char",
2027 [TOK_CONST ] = "const",
2028 [TOK_CONTINUE ] = "continue",
2029 [TOK_DEFAULT ] = "default",
2031 [TOK_DOUBLE ] = "double",
2032 [TOK_ELSE ] = "else",
2033 [TOK_ENUM ] = "enum",
2034 [TOK_EXTERN ] = "extern",
2035 [TOK_FLOAT ] = "float",
2037 [TOK_GOTO ] = "goto",
2039 [TOK_INLINE ] = "inline",
2041 [TOK_LONG ] = "long",
2042 [TOK_REGISTER ] = "register",
2043 [TOK_RESTRICT ] = "restrict",
2044 [TOK_RETURN ] = "return",
2045 [TOK_SHORT ] = "short",
2046 [TOK_SIGNED ] = "signed",
2047 [TOK_SIZEOF ] = "sizeof",
2048 [TOK_STATIC ] = "static",
2049 [TOK_STRUCT ] = "struct",
2050 [TOK_SWITCH ] = "switch",
2051 [TOK_TYPEDEF ] = "typedef",
2052 [TOK_UNION ] = "union",
2053 [TOK_UNSIGNED ] = "unsigned",
2054 [TOK_VOID ] = "void",
2055 [TOK_VOLATILE ] = "volatile",
2056 [TOK_WHILE ] = "while",
2058 [TOK_ATTRIBUTE ] = "__attribute__",
2059 [TOK_ALIGNOF ] = "__alignof__",
2061 [TOK_DEFINE ] = "define",
2062 [TOK_UNDEF ] = "undef",
2063 [TOK_INCLUDE ] = "include",
2064 [TOK_LINE ] = "line",
2065 [TOK_ERROR ] = "error",
2066 [TOK_WARNING ] = "warning",
2067 [TOK_PRAGMA ] = "pragma",
2068 [TOK_IFDEF ] = "ifdef",
2069 [TOK_IFNDEF ] = "ifndef",
2070 [TOK_ELIF ] = "elif",
2071 [TOK_ENDIF ] = "endif",
2076 static unsigned int hash(const char *str, int str_len)
2080 end = str + str_len;
2082 for(; str < end; str++) {
2083 hash = (hash *263) + *str;
2085 hash = hash & (HASH_TABLE_SIZE -1);
2089 static struct hash_entry *lookup(
2090 struct compile_state *state, const char *name, int name_len)
2092 struct hash_entry *entry;
2094 index = hash(name, name_len);
2095 entry = state->hash_table[index];
2097 ((entry->name_len != name_len) ||
2098 (memcmp(entry->name, name, name_len) != 0))) {
2099 entry = entry->next;
2103 /* Get a private copy of the name */
2104 new_name = xmalloc(name_len + 1, "hash_name");
2105 memcpy(new_name, name, name_len);
2106 new_name[name_len] = '\0';
2108 /* Create a new hash entry */
2109 entry = xcmalloc(sizeof(*entry), "hash_entry");
2110 entry->next = state->hash_table[index];
2111 entry->name = new_name;
2112 entry->name_len = name_len;
2114 /* Place the new entry in the hash table */
2115 state->hash_table[index] = entry;
2120 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2122 struct hash_entry *entry;
2124 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2125 (entry->tok == TOK_ENUM_CONST) ||
2126 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2127 (entry->tok <= TOK_LAST_KEYWORD)))) {
2128 tk->tok = entry->tok;
2132 static void ident_to_macro(struct compile_state *state, struct token *tk)
2134 struct hash_entry *entry;
2137 (entry->tok >= TOK_FIRST_MACRO) &&
2138 (entry->tok <= TOK_LAST_MACRO)) {
2139 tk->tok = entry->tok;
2143 static void hash_keyword(
2144 struct compile_state *state, const char *keyword, int tok)
2146 struct hash_entry *entry;
2147 entry = lookup(state, keyword, strlen(keyword));
2148 if (entry && entry->tok != TOK_UNKNOWN) {
2149 die("keyword %s already hashed", keyword);
2155 struct compile_state *state, struct hash_entry *ident,
2156 struct symbol **chain, struct triple *def, struct type *type)
2159 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2160 error(state, 0, "%s already defined", ident->name);
2162 sym = xcmalloc(sizeof(*sym), "symbol");
2166 sym->scope_depth = state->scope_depth;
2171 static void label_symbol(struct compile_state *state,
2172 struct hash_entry *ident, struct triple *label)
2175 if (ident->sym_label) {
2176 error(state, 0, "label %s already defined", ident->name);
2178 sym = xcmalloc(sizeof(*sym), "label");
2181 sym->type = &void_type;
2182 sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2184 ident->sym_label = sym;
2187 static void start_scope(struct compile_state *state)
2189 state->scope_depth++;
2192 static void end_scope_syms(struct symbol **chain, int depth)
2194 struct symbol *sym, *next;
2196 while(sym && (sym->scope_depth == depth)) {
2204 static void end_scope(struct compile_state *state)
2208 /* Walk through the hash table and remove all symbols
2209 * in the current scope.
2211 depth = state->scope_depth;
2212 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2213 struct hash_entry *entry;
2214 entry = state->hash_table[i];
2216 end_scope_syms(&entry->sym_label, depth);
2217 end_scope_syms(&entry->sym_struct, depth);
2218 end_scope_syms(&entry->sym_ident, depth);
2219 entry = entry->next;
2222 state->scope_depth = depth - 1;
2225 static void register_keywords(struct compile_state *state)
2227 hash_keyword(state, "auto", TOK_AUTO);
2228 hash_keyword(state, "break", TOK_BREAK);
2229 hash_keyword(state, "case", TOK_CASE);
2230 hash_keyword(state, "char", TOK_CHAR);
2231 hash_keyword(state, "const", TOK_CONST);
2232 hash_keyword(state, "continue", TOK_CONTINUE);
2233 hash_keyword(state, "default", TOK_DEFAULT);
2234 hash_keyword(state, "do", TOK_DO);
2235 hash_keyword(state, "double", TOK_DOUBLE);
2236 hash_keyword(state, "else", TOK_ELSE);
2237 hash_keyword(state, "enum", TOK_ENUM);
2238 hash_keyword(state, "extern", TOK_EXTERN);
2239 hash_keyword(state, "float", TOK_FLOAT);
2240 hash_keyword(state, "for", TOK_FOR);
2241 hash_keyword(state, "goto", TOK_GOTO);
2242 hash_keyword(state, "if", TOK_IF);
2243 hash_keyword(state, "inline", TOK_INLINE);
2244 hash_keyword(state, "int", TOK_INT);
2245 hash_keyword(state, "long", TOK_LONG);
2246 hash_keyword(state, "register", TOK_REGISTER);
2247 hash_keyword(state, "restrict", TOK_RESTRICT);
2248 hash_keyword(state, "return", TOK_RETURN);
2249 hash_keyword(state, "short", TOK_SHORT);
2250 hash_keyword(state, "signed", TOK_SIGNED);
2251 hash_keyword(state, "sizeof", TOK_SIZEOF);
2252 hash_keyword(state, "static", TOK_STATIC);
2253 hash_keyword(state, "struct", TOK_STRUCT);
2254 hash_keyword(state, "switch", TOK_SWITCH);
2255 hash_keyword(state, "typedef", TOK_TYPEDEF);
2256 hash_keyword(state, "union", TOK_UNION);
2257 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2258 hash_keyword(state, "void", TOK_VOID);
2259 hash_keyword(state, "volatile", TOK_VOLATILE);
2260 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2261 hash_keyword(state, "while", TOK_WHILE);
2262 hash_keyword(state, "asm", TOK_ASM);
2263 hash_keyword(state, "__asm__", TOK_ASM);
2264 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2265 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2268 static void register_macro_keywords(struct compile_state *state)
2270 hash_keyword(state, "define", TOK_DEFINE);
2271 hash_keyword(state, "undef", TOK_UNDEF);
2272 hash_keyword(state, "include", TOK_INCLUDE);
2273 hash_keyword(state, "line", TOK_LINE);
2274 hash_keyword(state, "error", TOK_ERROR);
2275 hash_keyword(state, "warning", TOK_WARNING);
2276 hash_keyword(state, "pragma", TOK_PRAGMA);
2277 hash_keyword(state, "ifdef", TOK_IFDEF);
2278 hash_keyword(state, "ifndef", TOK_IFNDEF);
2279 hash_keyword(state, "elif", TOK_ELIF);
2280 hash_keyword(state, "endif", TOK_ENDIF);
2283 static int spacep(int c)
2299 static int digitp(int c)
2303 case '0': case '1': case '2': case '3': case '4':
2304 case '5': case '6': case '7': case '8': case '9':
2310 static int digval(int c)
2313 if ((c >= '0') && (c <= '9')) {
2319 static int hexdigitp(int c)
2323 case '0': case '1': case '2': case '3': case '4':
2324 case '5': case '6': case '7': case '8': case '9':
2325 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2326 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2332 static int hexdigval(int c)
2335 if ((c >= '0') && (c <= '9')) {
2338 else if ((c >= 'A') && (c <= 'F')) {
2339 val = 10 + (c - 'A');
2341 else if ((c >= 'a') && (c <= 'f')) {
2342 val = 10 + (c - 'a');
2347 static int octdigitp(int c)
2351 case '0': case '1': case '2': case '3':
2352 case '4': case '5': case '6': case '7':
2358 static int octdigval(int c)
2361 if ((c >= '0') && (c <= '7')) {
2367 static int letterp(int c)
2371 case 'a': case 'b': case 'c': case 'd': case 'e':
2372 case 'f': case 'g': case 'h': case 'i': case 'j':
2373 case 'k': case 'l': case 'm': case 'n': case 'o':
2374 case 'p': case 'q': case 'r': case 's': case 't':
2375 case 'u': case 'v': case 'w': case 'x': case 'y':
2377 case 'A': case 'B': case 'C': case 'D': case 'E':
2378 case 'F': case 'G': case 'H': case 'I': case 'J':
2379 case 'K': case 'L': case 'M': case 'N': case 'O':
2380 case 'P': case 'Q': case 'R': case 'S': case 'T':
2381 case 'U': case 'V': case 'W': case 'X': case 'Y':
2390 static int char_value(struct compile_state *state,
2391 const signed char **strp, const signed char *end)
2393 const signed char *str;
2397 if ((c == '\\') && (str < end)) {
2399 case 'n': c = '\n'; str++; break;
2400 case 't': c = '\t'; str++; break;
2401 case 'v': c = '\v'; str++; break;
2402 case 'b': c = '\b'; str++; break;
2403 case 'r': c = '\r'; str++; break;
2404 case 'f': c = '\f'; str++; break;
2405 case 'a': c = '\a'; str++; break;
2406 case '\\': c = '\\'; str++; break;
2407 case '?': c = '?'; str++; break;
2408 case '\'': c = '\''; str++; break;
2409 case '"': c = '"'; break;
2413 while((str < end) && hexdigitp(*str)) {
2415 c += hexdigval(*str);
2419 case '0': case '1': case '2': case '3':
2420 case '4': case '5': case '6': case '7':
2422 while((str < end) && octdigitp(*str)) {
2424 c += octdigval(*str);
2429 error(state, 0, "Invalid character constant");
2437 static char *after_digits(char *ptr, char *end)
2439 while((ptr < end) && digitp(*ptr)) {
2445 static char *after_octdigits(char *ptr, char *end)
2447 while((ptr < end) && octdigitp(*ptr)) {
2453 static char *after_hexdigits(char *ptr, char *end)
2455 while((ptr < end) && hexdigitp(*ptr)) {
2461 static void save_string(struct compile_state *state,
2462 struct token *tk, char *start, char *end, const char *id)
2466 /* Create a private copy of the string */
2467 str_len = end - start + 1;
2468 str = xmalloc(str_len + 1, id);
2469 memcpy(str, start, str_len);
2470 str[str_len] = '\0';
2472 /* Store the copy in the token */
2474 tk->str_len = str_len;
2476 static void next_token(struct compile_state *state, int index)
2478 struct file_state *file;
2486 tk = &state->token[index];
2489 token = tokp = file->pos;
2490 end = file->buf + file->size;
2497 if ((tokp + 1) < end) {
2501 if ((tokp + 2) < end) {
2505 if ((tokp + 3) < end) {
2513 else if (spacep(c)) {
2515 while ((tokp < end) && spacep(c)) {
2518 file->report_line++;
2519 file->line_start = tokp + 1;
2528 else if ((c == '/') && (c1 == '/')) {
2530 for(tokp += 2; tokp < end; tokp++) {
2534 file->report_line++;
2535 file->line_start = tokp +1;
2541 else if ((c == '/') && (c1 == '*')) {
2545 line_start = file->line_start;
2546 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2550 line_start = tokp +1;
2552 else if ((c == '*') && (tokp[1] == '/')) {
2558 if (tok == TOK_UNKNOWN) {
2559 error(state, 0, "unterminated comment");
2561 file->report_line += line - file->line;
2563 file->line_start = line_start;
2565 /* string constants */
2566 else if ((c == '"') ||
2567 ((c == 'L') && (c1 == '"'))) {
2572 line_start = file->line_start;
2578 for(tokp += 1; tokp < end; tokp++) {
2582 line_start = tokp + 1;
2584 else if ((c == '\\') && (tokp +1 < end)) {
2587 else if (c == '"') {
2588 tok = TOK_LIT_STRING;
2592 if (tok == TOK_UNKNOWN) {
2593 error(state, 0, "unterminated string constant");
2595 if (line != file->line) {
2596 warning(state, 0, "multiline string constant");
2598 file->report_line += line - file->line;
2600 file->line_start = line_start;
2602 /* Save the string value */
2603 save_string(state, tk, token, tokp, "literal string");
2605 /* character constants */
2606 else if ((c == '\'') ||
2607 ((c == 'L') && (c1 == '\''))) {
2612 line_start = file->line_start;
2618 for(tokp += 1; tokp < end; tokp++) {
2622 line_start = tokp + 1;
2624 else if ((c == '\\') && (tokp +1 < end)) {
2627 else if (c == '\'') {
2632 if (tok == TOK_UNKNOWN) {
2633 error(state, 0, "unterminated character constant");
2635 if (line != file->line) {
2636 warning(state, 0, "multiline character constant");
2638 file->report_line += line - file->line;
2640 file->line_start = line_start;
2642 /* Save the character value */
2643 save_string(state, tk, token, tokp, "literal character");
2645 /* integer and floating constants
2651 * Floating constants
2652 * {digits}.{digits}[Ee][+-]?{digits}
2654 * {digits}[Ee][+-]?{digits}
2655 * .{digits}[Ee][+-]?{digits}
2659 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2664 next = after_digits(tokp, end);
2669 if (next[0] == '.') {
2670 new = after_digits(next, end);
2671 is_float = (new != next);
2674 if ((next[0] == 'e') || (next[0] == 'E')) {
2675 if (((next + 1) < end) &&
2676 ((next[1] == '+') || (next[1] == '-'))) {
2679 new = after_digits(next, end);
2680 is_float = (new != next);
2684 tok = TOK_LIT_FLOAT;
2685 if ((next < end) && (
2694 if (!is_float && digitp(c)) {
2696 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2697 next = after_hexdigits(tokp + 2, end);
2699 else if (c == '0') {
2700 next = after_octdigits(tokp, end);
2703 next = after_digits(tokp, end);
2705 /* crazy integer suffixes */
2707 ((next[0] == 'u') || (next[0] == 'U'))) {
2710 ((next[0] == 'l') || (next[0] == 'L'))) {
2714 else if ((next < end) &&
2715 ((next[0] == 'l') || (next[0] == 'L'))) {
2718 ((next[0] == 'u') || (next[0] == 'U'))) {
2725 /* Save the integer/floating point value */
2726 save_string(state, tk, token, tokp, "literal number");
2729 else if (letterp(c)) {
2731 for(tokp += 1; tokp < end; tokp++) {
2733 if (!letterp(c) && !digitp(c)) {
2738 tk->ident = lookup(state, token, tokp +1 - token);
2740 /* C99 alternate macro characters */
2741 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2743 tok = TOK_CONCATENATE;
2745 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2746 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2747 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2748 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2749 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2750 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2751 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2752 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2753 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2754 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2755 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2756 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2757 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2758 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2759 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2760 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2761 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2762 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2763 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2764 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2765 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2766 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2767 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2768 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2769 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2770 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2771 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2772 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2773 else if (c == ';') { tok = TOK_SEMI; }
2774 else if (c == '{') { tok = TOK_LBRACE; }
2775 else if (c == '}') { tok = TOK_RBRACE; }
2776 else if (c == ',') { tok = TOK_COMMA; }
2777 else if (c == '=') { tok = TOK_EQ; }
2778 else if (c == ':') { tok = TOK_COLON; }
2779 else if (c == '[') { tok = TOK_LBRACKET; }
2780 else if (c == ']') { tok = TOK_RBRACKET; }
2781 else if (c == '(') { tok = TOK_LPAREN; }
2782 else if (c == ')') { tok = TOK_RPAREN; }
2783 else if (c == '*') { tok = TOK_STAR; }
2784 else if (c == '>') { tok = TOK_MORE; }
2785 else if (c == '<') { tok = TOK_LESS; }
2786 else if (c == '?') { tok = TOK_QUEST; }
2787 else if (c == '|') { tok = TOK_OR; }
2788 else if (c == '&') { tok = TOK_AND; }
2789 else if (c == '^') { tok = TOK_XOR; }
2790 else if (c == '+') { tok = TOK_PLUS; }
2791 else if (c == '-') { tok = TOK_MINUS; }
2792 else if (c == '/') { tok = TOK_DIV; }
2793 else if (c == '%') { tok = TOK_MOD; }
2794 else if (c == '!') { tok = TOK_BANG; }
2795 else if (c == '.') { tok = TOK_DOT; }
2796 else if (c == '~') { tok = TOK_TILDE; }
2797 else if (c == '#') { tok = TOK_MACRO; }
2798 if (tok == TOK_MACRO) {
2799 /* Only match preprocessor directives at the start of a line */
2801 for(ptr = file->line_start; spacep(*ptr); ptr++)
2807 if (tok == TOK_UNKNOWN) {
2808 error(state, 0, "unknown token");
2811 file->pos = tokp + 1;
2813 if (tok == TOK_IDENT) {
2814 ident_to_keyword(state, tk);
2816 /* Don't return space tokens. */
2817 if (tok == TOK_SPACE) {
2822 static void compile_macro(struct compile_state *state, struct token *tk)
2824 struct file_state *file;
2825 struct hash_entry *ident;
2827 file = xmalloc(sizeof(*file), "file_state");
2828 file->basename = xstrdup(tk->ident->name);
2829 file->dirname = xstrdup("");
2830 file->size = ident->sym_define->buf_len;
2831 file->buf = xmalloc(file->size +2, file->basename);
2832 memcpy(file->buf, ident->sym_define->buf, file->size);
2833 file->buf[file->size] = '\n';
2834 file->buf[file->size + 1] = '\0';
2835 file->pos = file->buf;
2836 file->line_start = file->pos;
2838 file->report_line = 1;
2839 file->report_name = file->basename;
2840 file->report_dir = file->dirname;
2841 file->prev = state->file;
2846 static int mpeek(struct compile_state *state, int index)
2850 tk = &state->token[index + 1];
2851 if (tk->tok == -1) {
2852 next_token(state, index + 1);
2856 if ((tk->tok == TOK_EOF) &&
2857 (state->file != state->macro_file) &&
2858 (state->file->prev)) {
2859 struct file_state *file = state->file;
2860 state->file = file->prev;
2861 /* file->basename is used keep it */
2862 if (file->report_dir != file->dirname) {
2863 xfree(file->report_dir);
2865 xfree(file->dirname);
2868 next_token(state, index + 1);
2871 else if (tk->ident && tk->ident->sym_define) {
2872 compile_macro(state, tk);
2873 next_token(state, index + 1);
2877 /* Don't show the token on the next line */
2878 if (state->macro_line < state->macro_file->line) {
2881 return state->token[index +1].tok;
2884 static void meat(struct compile_state *state, int index, int tok)
2888 next_tok = mpeek(state, index);
2889 if (next_tok != tok) {
2890 const char *name1, *name2;
2891 name1 = tokens[next_tok];
2893 if (next_tok == TOK_IDENT) {
2894 name2 = state->token[index + 1].ident->name;
2896 error(state, 0, "found %s %s expected %s",
2897 name1, name2, tokens[tok]);
2899 /* Free the old token value */
2900 if (state->token[index].str_len) {
2901 memset((void *)(state->token[index].val.str), -1,
2902 state->token[index].str_len);
2903 xfree(state->token[index].val.str);
2905 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2906 state->token[i] = state->token[i + 1];
2908 memset(&state->token[i], 0, sizeof(state->token[i]));
2909 state->token[i].tok = -1;
2912 static long_t mcexpr(struct compile_state *state, int index);
2914 static long_t mprimary_expr(struct compile_state *state, int index)
2918 tok = mpeek(state, index);
2919 while(state->token[index + 1].ident &&
2920 state->token[index + 1].ident->sym_define) {
2921 meat(state, index, tok);
2922 compile_macro(state, &state->token[index]);
2923 tok = mpeek(state, index);
2927 meat(state, index, TOK_LPAREN);
2928 val = mcexpr(state, index);
2929 meat(state, index, TOK_RPAREN);
2934 meat(state, index, TOK_LIT_INT);
2936 val = strtol(state->token[index].val.str, &end, 0);
2937 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2938 (errno == ERANGE)) {
2939 error(state, 0, "Integer constant to large");
2944 meat(state, index, TOK_LIT_INT);
2949 static long_t munary_expr(struct compile_state *state, int index)
2952 switch(mpeek(state, index)) {
2954 meat(state, index, TOK_PLUS);
2955 val = munary_expr(state, index);
2959 meat(state, index, TOK_MINUS);
2960 val = munary_expr(state, index);
2964 meat(state, index, TOK_BANG);
2965 val = munary_expr(state, index);
2969 meat(state, index, TOK_BANG);
2970 val = munary_expr(state, index);
2974 val = mprimary_expr(state, index);
2980 static long_t mmul_expr(struct compile_state *state, int index)
2984 val = munary_expr(state, index);
2988 switch(mpeek(state, index)) {
2990 meat(state, index, TOK_STAR);
2991 right = munary_expr(state, index);
2995 meat(state, index, TOK_DIV);
2996 right = munary_expr(state, index);
3000 meat(state, index, TOK_MOD);
3001 right = munary_expr(state, index);
3013 static long_t madd_expr(struct compile_state *state, int index)
3017 val = mmul_expr(state, index);
3021 switch(mpeek(state, index)) {
3023 meat(state, index, TOK_PLUS);
3024 right = mmul_expr(state, index);
3028 meat(state, index, TOK_MINUS);
3029 right = mmul_expr(state, index);
3041 static long_t mshift_expr(struct compile_state *state, int index)
3045 val = madd_expr(state, index);
3049 switch(mpeek(state, index)) {
3051 meat(state, index, TOK_SL);
3052 right = madd_expr(state, index);
3056 meat(state, index, TOK_SR);
3057 right = madd_expr(state, index);
3069 static long_t mrel_expr(struct compile_state *state, int index)
3073 val = mshift_expr(state, index);
3077 switch(mpeek(state, index)) {
3079 meat(state, index, TOK_LESS);
3080 right = mshift_expr(state, index);
3084 meat(state, index, TOK_MORE);
3085 right = mshift_expr(state, index);
3089 meat(state, index, TOK_LESSEQ);
3090 right = mshift_expr(state, index);
3094 meat(state, index, TOK_MOREEQ);
3095 right = mshift_expr(state, index);
3106 static long_t meq_expr(struct compile_state *state, int index)
3110 val = mrel_expr(state, index);
3114 switch(mpeek(state, index)) {
3116 meat(state, index, TOK_EQEQ);
3117 right = mrel_expr(state, index);
3121 meat(state, index, TOK_NOTEQ);
3122 right = mrel_expr(state, index);
3133 static long_t mand_expr(struct compile_state *state, int index)
3136 val = meq_expr(state, index);
3137 if (mpeek(state, index) == TOK_AND) {
3139 meat(state, index, TOK_AND);
3140 right = meq_expr(state, index);
3146 static long_t mxor_expr(struct compile_state *state, int index)
3149 val = mand_expr(state, index);
3150 if (mpeek(state, index) == TOK_XOR) {
3152 meat(state, index, TOK_XOR);
3153 right = mand_expr(state, index);
3159 static long_t mor_expr(struct compile_state *state, int index)
3162 val = mxor_expr(state, index);
3163 if (mpeek(state, index) == TOK_OR) {
3165 meat(state, index, TOK_OR);
3166 right = mxor_expr(state, index);
3172 static long_t mland_expr(struct compile_state *state, int index)
3175 val = mor_expr(state, index);
3176 if (mpeek(state, index) == TOK_LOGAND) {
3178 meat(state, index, TOK_LOGAND);
3179 right = mor_expr(state, index);
3184 static long_t mlor_expr(struct compile_state *state, int index)
3187 val = mland_expr(state, index);
3188 if (mpeek(state, index) == TOK_LOGOR) {
3190 meat(state, index, TOK_LOGOR);
3191 right = mland_expr(state, index);
3197 static long_t mcexpr(struct compile_state *state, int index)
3199 return mlor_expr(state, index);
3201 static void preprocess(struct compile_state *state, int index)
3203 /* Doing much more with the preprocessor would require
3204 * a parser and a major restructuring.
3205 * Postpone that for later.
3207 struct file_state *file;
3213 tk = &state->token[index];
3214 state->macro_line = line = file->line;
3215 state->macro_file = file;
3217 next_token(state, index);
3218 ident_to_macro(state, tk);
3219 if (tk->tok == TOK_IDENT) {
3220 error(state, 0, "undefined preprocessing directive `%s'",
3227 override_line = strtoul(tk->val.str, 0, 10);
3228 next_token(state, index);
3229 /* I have a cpp line marker parse it */
3230 if (tk->tok == TOK_LIT_STRING) {
3231 const char *token, *base;
3233 int name_len, dir_len;
3234 name = xmalloc(tk->str_len, "report_name");
3235 token = tk->val.str + 1;
3236 base = strrchr(token, '/');
3237 name_len = tk->str_len -2;
3239 dir_len = base - token;
3241 name_len -= base - token;
3246 memcpy(name, base, name_len);
3247 name[name_len] = '\0';
3248 dir = xmalloc(dir_len + 1, "report_dir");
3249 memcpy(dir, token, dir_len);
3250 dir[dir_len] = '\0';
3251 file->report_line = override_line - 1;
3252 file->report_name = name;
3253 file->report_dir = dir;
3258 meat(state, index, TOK_LINE);
3259 meat(state, index, TOK_LIT_INT);
3260 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3261 if (mpeek(state, index) == TOK_LIT_STRING) {
3262 const char *token, *base;
3264 int name_len, dir_len;
3265 meat(state, index, TOK_LIT_STRING);
3266 name = xmalloc(tk->str_len, "report_name");
3267 token = tk->val.str + 1;
3268 name_len = tk->str_len - 2;
3270 dir_len = base - token;
3272 name_len -= base - token;
3277 memcpy(name, base, name_len);
3278 name[name_len] = '\0';
3279 dir = xmalloc(dir_len + 1, "report_dir");
3280 memcpy(dir, token, dir_len);
3281 dir[dir_len] = '\0';
3282 file->report_name = name;
3283 file->report_dir = dir;
3288 if (state->if_value < 0) {
3291 warning(state, 0, "Ignoring preprocessor directive: %s",
3295 error(state, 0, "#elif not supported");
3296 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3297 if (state->if_depth == 0) {
3298 error(state, 0, "#elif without #if");
3300 /* If the #if was taken the #elif just disables the following code */
3301 if (state->if_value >= 0) {
3302 state->if_value = - state->if_value;
3304 /* If the previous #if was not taken see if the #elif enables the
3307 else if ((state->if_value < 0) &&
3308 (state->if_depth == - state->if_value))
3310 if (mcexpr(state, index) != 0) {
3311 state->if_value = state->if_depth;
3314 state->if_value = - state->if_depth;
3320 if (state->if_value < 0) {
3323 if (mcexpr(state, index) != 0) {
3324 state->if_value = state->if_depth;
3327 state->if_value = - state->if_depth;
3332 if (state->if_value < 0) {
3335 next_token(state, index);
3336 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3337 error(state, 0, "Invalid macro name");
3339 if (tk->ident->sym_define == 0) {
3340 state->if_value = state->if_depth;
3343 state->if_value = - state->if_depth;
3348 if (state->if_value < 0) {
3351 next_token(state, index);
3352 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3353 error(state, 0, "Invalid macro name");
3355 if (tk->ident->sym_define != 0) {
3356 state->if_value = state->if_depth;
3359 state->if_value = - state->if_depth;
3363 if (state->if_depth == 0) {
3364 error(state, 0, "#else without #if");
3366 if ((state->if_value >= 0) ||
3367 ((state->if_value < 0) &&
3368 (state->if_depth == -state->if_value)))
3370 state->if_value = - state->if_value;
3374 if (state->if_depth == 0) {
3375 error(state, 0, "#endif without #if");
3377 if ((state->if_value >= 0) ||
3378 ((state->if_value < 0) &&
3379 (state->if_depth == -state->if_value)))
3381 state->if_value = state->if_depth - 1;
3387 struct hash_entry *ident;
3388 struct macro *macro;
3391 if (state->if_value < 0) /* quit early when #if'd out */
3394 meat(state, index, TOK_IDENT);
3398 if (*file->pos == '(') {
3399 #warning "FIXME macros with arguments not supported"
3400 error(state, 0, "Macros with arguments not supported");
3403 /* Find the end of the line to get an estimate of
3404 * the macro's length.
3406 for(ptr = file->pos; *ptr != '\n'; ptr++)
3409 if (ident->sym_define != 0) {
3410 error(state, 0, "macro %s already defined\n", ident->name);
3412 macro = xmalloc(sizeof(*macro), "macro");
3413 macro->ident = ident;
3414 macro->buf_len = ptr - file->pos +1;
3415 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3417 memcpy(macro->buf, file->pos, macro->buf_len);
3418 macro->buf[macro->buf_len] = '\n';
3419 macro->buf[macro->buf_len +1] = '\0';
3421 ident->sym_define = macro;
3428 /* Find the end of the line */
3429 for(end = file->pos; *end != '\n'; end++)
3431 len = (end - file->pos);
3432 if (state->if_value >= 0) {
3433 error(state, 0, "%*.*s", len, len, file->pos);
3442 /* Find the end of the line */
3443 for(end = file->pos; *end != '\n'; end++)
3445 len = (end - file->pos);
3446 if (state->if_value >= 0) {
3447 warning(state, 0, "%*.*s", len, len, file->pos);
3459 next_token(state, index);
3460 if (tk->tok == TOK_LIT_STRING) {
3463 name = xmalloc(tk->str_len, "include");
3464 token = tk->val.str +1;
3465 name_len = tk->str_len -2;
3466 if (*token == '"') {
3470 memcpy(name, token, name_len);
3471 name[name_len] = '\0';
3474 else if (tk->tok == TOK_LESS) {
3477 for(end = start; *end != '\n'; end++) {
3483 error(state, 0, "Unterminated included directive");
3485 name = xmalloc(end - start + 1, "include");
3486 memcpy(name, start, end - start);
3487 name[end - start] = '\0';
3492 error(state, 0, "Invalid include directive");
3494 /* Error if there are any characters after the include */
3495 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3502 error(state, 0, "garbage after include directive");
3505 if (state->if_value >= 0) {
3506 compile_file(state, name, local);
3509 next_token(state, index);
3513 /* Ignore # without a following ident */
3514 if (tk->tok == TOK_IDENT) {
3515 error(state, 0, "Invalid preprocessor directive: %s",
3520 /* Consume the rest of the macro line */
3522 tok = mpeek(state, index);
3523 meat(state, index, tok);
3524 } while(tok != TOK_EOF);
3528 static void token(struct compile_state *state, int index)
3530 struct file_state *file;
3534 tk = &state->token[index];
3535 next_token(state, index);
3539 if (tk->tok == TOK_EOF && file->prev) {
3540 state->file = file->prev;
3541 /* file->basename is used keep it */
3542 xfree(file->dirname);
3545 next_token(state, index);
3548 else if (tk->tok == TOK_MACRO) {
3549 preprocess(state, index);
3552 else if (tk->ident && tk->ident->sym_define) {
3553 compile_macro(state, tk);
3554 next_token(state, index);
3557 else if (state->if_value < 0) {
3558 next_token(state, index);
3564 static int peek(struct compile_state *state)
3566 if (state->token[1].tok == -1) {
3569 return state->token[1].tok;
3572 static int peek2(struct compile_state *state)
3574 if (state->token[1].tok == -1) {
3577 if (state->token[2].tok == -1) {
3580 return state->token[2].tok;
3583 static void eat(struct compile_state *state, int tok)
3587 next_tok = peek(state);
3588 if (next_tok != tok) {
3589 const char *name1, *name2;
3590 name1 = tokens[next_tok];
3592 if (next_tok == TOK_IDENT) {
3593 name2 = state->token[1].ident->name;
3595 error(state, 0, "\tfound %s %s expected %s",
3596 name1, name2 ,tokens[tok]);
3598 /* Free the old token value */
3599 if (state->token[0].str_len) {
3600 xfree((void *)(state->token[0].val.str));
3602 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3603 state->token[i] = state->token[i + 1];
3605 memset(&state->token[i], 0, sizeof(state->token[i]));
3606 state->token[i].tok = -1;
3609 #warning "FIXME do not hardcode the include paths"
3610 static char *include_paths[] = {
3611 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3612 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3613 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3617 static void compile_file(struct compile_state *state, const char *filename, int local)
3620 const char *subdir, *base;
3622 struct file_state *file;
3624 file = xmalloc(sizeof(*file), "file_state");
3626 base = strrchr(filename, '/');
3629 subdir_len = base - filename;
3636 basename = xmalloc(strlen(base) +1, "basename");
3637 strcpy(basename, base);
3638 file->basename = basename;
3640 if (getcwd(cwd, sizeof(cwd)) == 0) {
3641 die("cwd buffer to small");
3644 if (subdir[0] == '/') {
3645 file->dirname = xmalloc(subdir_len + 1, "dirname");
3646 memcpy(file->dirname, subdir, subdir_len);
3647 file->dirname[subdir_len] = '\0';
3653 /* Find the appropriate directory... */
3655 if (!state->file && exists(cwd, filename)) {
3658 if (local && state->file && exists(state->file->dirname, filename)) {
3659 dir = state->file->dirname;
3661 for(path = include_paths; !dir && *path; path++) {
3662 if (exists(*path, filename)) {
3667 error(state, 0, "Cannot find `%s'\n", filename);
3669 dirlen = strlen(dir);
3670 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3671 memcpy(file->dirname, dir, dirlen);
3672 file->dirname[dirlen] = '/';
3673 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3674 file->dirname[dirlen + 1 + subdir_len] = '\0';
3676 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3679 file->pos = file->buf;
3680 file->line_start = file->pos;
3683 file->report_line = 1;
3684 file->report_name = file->basename;
3685 file->report_dir = file->dirname;
3687 file->prev = state->file;
3690 process_trigraphs(state);
3691 splice_lines(state);
3694 /* Type helper functions */
3696 static struct type *new_type(
3697 unsigned int type, struct type *left, struct type *right)
3699 struct type *result;
3700 result = xmalloc(sizeof(*result), "type");
3701 result->type = type;
3702 result->left = left;
3703 result->right = right;
3704 result->field_ident = 0;
3705 result->type_ident = 0;
3709 static struct type *clone_type(unsigned int specifiers, struct type *old)
3711 struct type *result;
3712 result = xmalloc(sizeof(*result), "type");
3713 memcpy(result, old, sizeof(*result));
3714 result->type &= TYPE_MASK;
3715 result->type |= specifiers;
3719 #define SIZEOF_SHORT 2
3720 #define SIZEOF_INT 4
3721 #define SIZEOF_LONG (sizeof(long_t))
3723 #define ALIGNOF_SHORT 2
3724 #define ALIGNOF_INT 4
3725 #define ALIGNOF_LONG (sizeof(long_t))
3727 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3728 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3729 static inline ulong_t mask_uint(ulong_t x)
3731 if (SIZEOF_INT < SIZEOF_LONG) {
3732 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3737 #define MASK_UINT(X) (mask_uint(X))
3738 #define MASK_ULONG(X) (X)
3740 static struct type void_type = { .type = TYPE_VOID };
3741 static struct type char_type = { .type = TYPE_CHAR };
3742 static struct type uchar_type = { .type = TYPE_UCHAR };
3743 static struct type short_type = { .type = TYPE_SHORT };
3744 static struct type ushort_type = { .type = TYPE_USHORT };
3745 static struct type int_type = { .type = TYPE_INT };
3746 static struct type uint_type = { .type = TYPE_UINT };
3747 static struct type long_type = { .type = TYPE_LONG };
3748 static struct type ulong_type = { .type = TYPE_ULONG };
3750 static struct triple *variable(struct compile_state *state, struct type *type)
3752 struct triple *result;
3753 if ((type->type & STOR_MASK) != STOR_PERM) {
3754 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3755 result = triple(state, OP_ADECL, type, 0, 0);
3758 struct triple **vector;
3760 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3761 vector = &result->param[0];
3765 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3766 vector[index] = variable(state, field->left);
3767 field = field->right;
3770 vector[index] = variable(state, field);
3774 result = triple(state, OP_SDECL, type, 0, 0);
3779 static void stor_of(FILE *fp, struct type *type)
3781 switch(type->type & STOR_MASK) {
3783 fprintf(fp, "auto ");
3786 fprintf(fp, "static ");
3789 fprintf(fp, "extern ");
3792 fprintf(fp, "register ");
3795 fprintf(fp, "typedef ");
3798 fprintf(fp, "inline ");
3802 static void qual_of(FILE *fp, struct type *type)
3804 if (type->type & QUAL_CONST) {
3805 fprintf(fp, " const");
3807 if (type->type & QUAL_VOLATILE) {
3808 fprintf(fp, " volatile");
3810 if (type->type & QUAL_RESTRICT) {
3811 fprintf(fp, " restrict");
3815 static void name_of(FILE *fp, struct type *type)
3818 switch(type->type & TYPE_MASK) {
3820 fprintf(fp, "void");
3824 fprintf(fp, "signed char");
3828 fprintf(fp, "unsigned char");
3832 fprintf(fp, "signed short");
3836 fprintf(fp, "unsigned short");
3840 fprintf(fp, "signed int");
3844 fprintf(fp, "unsigned int");
3848 fprintf(fp, "signed long");
3852 fprintf(fp, "unsigned long");
3856 name_of(fp, type->left);
3862 name_of(fp, type->left);
3864 name_of(fp, type->right);
3867 fprintf(fp, "enum %s", type->type_ident->name);
3871 fprintf(fp, "struct %s", type->type_ident->name);
3876 name_of(fp, type->left);
3877 fprintf(fp, " (*)(");
3878 name_of(fp, type->right);
3883 name_of(fp, type->left);
3884 fprintf(fp, " [%ld]", type->elements);
3887 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3892 static size_t align_of(struct compile_state *state, struct type *type)
3896 switch(type->type & TYPE_MASK) {
3906 align = ALIGNOF_SHORT;
3911 align = ALIGNOF_INT;
3916 align = ALIGNOF_LONG;
3921 size_t left_align, right_align;
3922 left_align = align_of(state, type->left);
3923 right_align = align_of(state, type->right);
3924 align = (left_align >= right_align) ? left_align : right_align;
3928 align = align_of(state, type->left);
3931 align = align_of(state, type->left);
3934 error(state, 0, "alignof not yet defined for type\n");
3940 static size_t needed_padding(size_t offset, size_t align)
3944 if (offset % align) {
3945 padding = align - (offset % align);
3949 static size_t size_of(struct compile_state *state, struct type *type)
3953 switch(type->type & TYPE_MASK) {
3963 size = SIZEOF_SHORT;
3979 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3980 align = align_of(state, type->left);
3981 pad = needed_padding(size, align);
3982 size = size + pad + size_of(state, type->left);
3985 align = align_of(state, type);
3986 pad = needed_padding(size, align);
3987 size = size + pad + sizeof(type);
3992 size_t size_left, size_right;
3993 size_left = size_of(state, type->left);
3994 size_right = size_of(state, type->right);
3995 size = (size_left >= size_right)? size_left : size_right;
3999 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4000 internal_error(state, 0, "Invalid array type");
4002 size = size_of(state, type->left) * type->elements;
4006 size = size_of(state, type->left);
4009 internal_error(state, 0, "sizeof not yet defined for type\n");
4015 static size_t field_offset(struct compile_state *state,
4016 struct type *type, struct hash_entry *field)
4018 struct type *member;
4020 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4021 internal_error(state, 0, "field_offset only works on structures");
4024 member = type->left;
4025 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4026 align = align_of(state, member->left);
4027 size += needed_padding(size, align);
4028 if (member->left->field_ident == field) {
4029 member = member->left;
4032 size += size_of(state, member->left);
4033 member = member->right;
4035 align = align_of(state, member);
4036 size += needed_padding(size, align);
4037 if (member->field_ident != field) {
4038 error(state, 0, "member %s not present", field->name);
4043 static struct type *field_type(struct compile_state *state,
4044 struct type *type, struct hash_entry *field)
4046 struct type *member;
4047 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4048 internal_error(state, 0, "field_type only works on structures");
4050 member = type->left;
4051 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4052 if (member->left->field_ident == field) {
4053 member = member->left;
4056 member = member->right;
4058 if (member->field_ident != field) {
4059 error(state, 0, "member %s not present", field->name);
4064 static struct type *next_field(struct compile_state *state,
4065 struct type *type, struct type *prev_member)
4067 struct type *member;
4068 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4069 internal_error(state, 0, "next_field only works on structures");
4071 member = type->left;
4072 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4074 member = member->left;
4077 if (member->left == prev_member) {
4080 member = member->right;
4082 if (member == prev_member) {
4086 internal_error(state, 0, "prev_member %s not present",
4087 prev_member->field_ident->name);
4092 static struct triple *struct_field(struct compile_state *state,
4093 struct triple *decl, struct hash_entry *field)
4095 struct triple **vector;
4099 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4102 if (decl->op != OP_VAL_VEC) {
4103 internal_error(state, 0, "Invalid struct variable");
4106 internal_error(state, 0, "Missing structure field");
4109 vector = &RHS(decl, 0);
4111 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4112 if (type->left->field_ident == field) {
4119 if (type->field_ident != field) {
4120 internal_error(state, 0, "field %s not found?", field->name);
4122 return vector[index];
4125 static void arrays_complete(struct compile_state *state, struct type *type)
4127 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4128 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4129 error(state, 0, "array size not specified");
4131 arrays_complete(state, type->left);
4135 static unsigned int do_integral_promotion(unsigned int type)
4138 if (TYPE_INTEGER(type) &&
4139 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4145 static unsigned int do_arithmetic_conversion(
4146 unsigned int left, unsigned int right)
4150 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4151 return TYPE_LDOUBLE;
4153 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4156 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4159 left = do_integral_promotion(left);
4160 right = do_integral_promotion(right);
4161 /* If both operands have the same size done */
4162 if (left == right) {
4165 /* If both operands have the same signedness pick the larger */
4166 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4167 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4169 /* If the signed type can hold everything use it */
4170 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4173 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4176 /* Convert to the unsigned type with the same rank as the signed type */
4177 else if (TYPE_SIGNED(left)) {
4178 return TYPE_MKUNSIGNED(left);
4181 return TYPE_MKUNSIGNED(right);
4185 /* see if two types are the same except for qualifiers */
4186 static int equiv_types(struct type *left, struct type *right)
4189 /* Error if the basic types do not match */
4190 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4193 type = left->type & TYPE_MASK;
4194 /* if the basic types match and it is an arithmetic type we are done */
4195 if (TYPE_ARITHMETIC(type)) {
4198 /* If it is a pointer type recurse and keep testing */
4199 if (type == TYPE_POINTER) {
4200 return equiv_types(left->left, right->left);
4202 else if (type == TYPE_ARRAY) {
4203 return (left->elements == right->elements) &&
4204 equiv_types(left->left, right->left);
4206 /* test for struct/union equality */
4207 else if (type == TYPE_STRUCT) {
4208 return left->type_ident == right->type_ident;
4210 /* Test for equivalent functions */
4211 else if (type == TYPE_FUNCTION) {
4212 return equiv_types(left->left, right->left) &&
4213 equiv_types(left->right, right->right);
4215 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4216 else if (type == TYPE_PRODUCT) {
4217 return equiv_types(left->left, right->left) &&
4218 equiv_types(left->right, right->right);
4220 /* We should see TYPE_OVERLAP */
4226 static int equiv_ptrs(struct type *left, struct type *right)
4228 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4229 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4232 return equiv_types(left->left, right->left);
4235 static struct type *compatible_types(struct type *left, struct type *right)
4237 struct type *result;
4238 unsigned int type, qual_type;
4239 /* Error if the basic types do not match */
4240 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4243 type = left->type & TYPE_MASK;
4244 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4246 /* if the basic types match and it is an arithmetic type we are done */
4247 if (TYPE_ARITHMETIC(type)) {
4248 result = new_type(qual_type, 0, 0);
4250 /* If it is a pointer type recurse and keep testing */
4251 else if (type == TYPE_POINTER) {
4252 result = compatible_types(left->left, right->left);
4254 result = new_type(qual_type, result, 0);
4257 /* test for struct/union equality */
4258 else if (type == TYPE_STRUCT) {
4259 if (left->type_ident == right->type_ident) {
4263 /* Test for equivalent functions */
4264 else if (type == TYPE_FUNCTION) {
4265 struct type *lf, *rf;
4266 lf = compatible_types(left->left, right->left);
4267 rf = compatible_types(left->right, right->right);
4269 result = new_type(qual_type, lf, rf);
4272 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4273 else if (type == TYPE_PRODUCT) {
4274 struct type *lf, *rf;
4275 lf = compatible_types(left->left, right->left);
4276 rf = compatible_types(left->right, right->right);
4278 result = new_type(qual_type, lf, rf);
4282 /* Nothing else is compatible */
4287 static struct type *compatible_ptrs(struct type *left, struct type *right)
4289 struct type *result;
4290 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4291 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4294 result = compatible_types(left->left, right->left);
4296 unsigned int qual_type;
4297 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4298 result = new_type(qual_type, result, 0);
4303 static struct triple *integral_promotion(
4304 struct compile_state *state, struct triple *def)
4308 /* As all operations are carried out in registers
4309 * the values are converted on load I just convert
4310 * logical type of the operand.
4312 if (TYPE_INTEGER(type->type)) {
4313 unsigned int int_type;
4314 int_type = type->type & ~TYPE_MASK;
4315 int_type |= do_integral_promotion(type->type);
4316 if (int_type != type->type) {
4317 def->type = new_type(int_type, 0, 0);
4324 static void arithmetic(struct compile_state *state, struct triple *def)
4326 if (!TYPE_ARITHMETIC(def->type->type)) {
4327 error(state, 0, "arithmetic type expexted");
4331 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4333 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4334 error(state, def, "pointer or arithmetic type expected");
4338 static int is_integral(struct triple *ins)
4340 return TYPE_INTEGER(ins->type->type);
4343 static void integral(struct compile_state *state, struct triple *def)
4345 if (!is_integral(def)) {
4346 error(state, 0, "integral type expected");
4351 static void bool(struct compile_state *state, struct triple *def)
4353 if (!TYPE_ARITHMETIC(def->type->type) &&
4354 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4355 error(state, 0, "arithmetic or pointer type expected");
4359 static int is_signed(struct type *type)
4361 return !!TYPE_SIGNED(type->type);
4364 /* Is this value located in a register otherwise it must be in memory */
4365 static int is_in_reg(struct compile_state *state, struct triple *def)
4368 if (def->op == OP_ADECL) {
4371 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4374 else if (def->op == OP_VAL_VEC) {
4375 in_reg = is_in_reg(state, RHS(def, 0));
4377 else if (def->op == OP_DOT) {
4378 in_reg = is_in_reg(state, RHS(def, 0));
4381 internal_error(state, 0, "unknown expr storage location");
4387 /* Is this a stable variable location otherwise it must be a temporary */
4388 static int is_stable(struct compile_state *state, struct triple *def)
4395 if ((def->op == OP_ADECL) ||
4396 (def->op == OP_SDECL) ||
4397 (def->op == OP_DEREF) ||
4398 (def->op == OP_BLOBCONST)) {
4401 else if (def->op == OP_DOT) {
4402 ret = is_stable(state, RHS(def, 0));
4404 else if (def->op == OP_VAL_VEC) {
4405 struct triple **vector;
4408 vector = &RHS(def, 0);
4409 for(i = 0; i < def->type->elements; i++) {
4410 if (!is_stable(state, vector[i])) {
4419 static int is_lvalue(struct compile_state *state, struct triple *def)
4426 if (!is_stable(state, def)) {
4429 if (def->op == OP_DOT) {
4430 ret = is_lvalue(state, RHS(def, 0));
4435 static void clvalue(struct compile_state *state, struct triple *def)
4438 internal_error(state, def, "nothing where lvalue expected?");
4440 if (!is_lvalue(state, def)) {
4441 error(state, def, "lvalue expected");
4444 static void lvalue(struct compile_state *state, struct triple *def)
4446 clvalue(state, def);
4447 if (def->type->type & QUAL_CONST) {
4448 error(state, def, "modifable lvalue expected");
4452 static int is_pointer(struct triple *def)
4454 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4457 static void pointer(struct compile_state *state, struct triple *def)
4459 if (!is_pointer(def)) {
4460 error(state, def, "pointer expected");
4464 static struct triple *int_const(
4465 struct compile_state *state, struct type *type, ulong_t value)
4467 struct triple *result;
4468 switch(type->type & TYPE_MASK) {
4470 case TYPE_INT: case TYPE_UINT:
4471 case TYPE_LONG: case TYPE_ULONG:
4474 internal_error(state, 0, "constant for unkown type");
4476 result = triple(state, OP_INTCONST, type, 0, 0);
4477 result->u.cval = value;
4482 static struct triple *do_mk_addr_expr(struct compile_state *state,
4483 struct triple *expr, struct type *type, ulong_t offset)
4485 struct triple *result;
4486 clvalue(state, expr);
4488 type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4491 if (expr->op == OP_ADECL) {
4492 error(state, expr, "address of auto variables not supported");
4494 else if (expr->op == OP_SDECL) {
4495 result = triple(state, OP_ADDRCONST, type, 0, 0);
4496 MISC(result, 0) = expr;
4497 result->u.cval = offset;
4499 else if (expr->op == OP_DEREF) {
4500 result = triple(state, OP_ADD, type,
4502 int_const(state, &ulong_type, offset));
4507 static struct triple *mk_addr_expr(
4508 struct compile_state *state, struct triple *expr, ulong_t offset)
4510 return do_mk_addr_expr(state, expr, expr->type, offset);
4513 static struct triple *mk_deref_expr(
4514 struct compile_state *state, struct triple *expr)
4516 struct type *base_type;
4517 pointer(state, expr);
4518 base_type = expr->type->left;
4519 return triple(state, OP_DEREF, base_type, expr, 0);
4522 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4524 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4526 struct triple *addrconst;
4528 TYPE_POINTER | (def->type->type & QUAL_MASK),
4529 def->type->left, 0);
4530 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4531 MISC(addrconst, 0) = def;
4537 static struct triple *deref_field(
4538 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4540 struct triple *result;
4541 struct type *type, *member;
4543 internal_error(state, 0, "No field passed to deref_field");
4547 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4548 error(state, 0, "request for member %s in something not a struct or union",
4551 member = field_type(state, type, field);
4552 if ((type->type & STOR_MASK) == STOR_PERM) {
4553 /* Do the pointer arithmetic to get a deref the field */
4555 offset = field_offset(state, type, field);
4556 result = do_mk_addr_expr(state, expr, member, offset);
4557 result = mk_deref_expr(state, result);
4560 /* Find the variable for the field I want. */
4561 result = triple(state, OP_DOT, member, expr, 0);
4562 result->u.field = field;
4567 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4573 if (!is_stable(state, def)) {
4576 /* Tranform an array to a pointer to the first element */
4578 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4579 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4580 return array_to_pointer(state, def);
4582 if (is_in_reg(state, def)) {
4587 return triple(state, op, def->type, def, 0);
4590 static void write_compatible(struct compile_state *state,
4591 struct type *dest, struct type *rval)
4594 /* Both operands have arithmetic type */
4595 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4598 /* One operand is a pointer and the other is a pointer to void */
4599 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4600 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4601 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4602 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4605 /* If both types are the same without qualifiers we are good */
4606 else if (equiv_ptrs(dest, rval)) {
4609 /* test for struct/union equality */
4610 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4611 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4612 (dest->type_ident == rval->type_ident)) {
4616 error(state, 0, "Incompatible types in assignment");
4620 static struct triple *write_expr(
4621 struct compile_state *state, struct triple *dest, struct triple *rval)
4628 internal_error(state, 0, "missing rval");
4631 if (rval->op == OP_LIST) {
4632 internal_error(state, 0, "expression of type OP_LIST?");
4634 if (!is_lvalue(state, dest)) {
4635 internal_error(state, 0, "writing to a non lvalue?");
4637 if (dest->type->type & QUAL_CONST) {
4638 internal_error(state, 0, "modifable lvalue expexted");
4641 write_compatible(state, dest->type, rval->type);
4643 /* Now figure out which assignment operator to use */
4645 if (is_in_reg(state, dest)) {
4650 def = triple(state, op, dest->type, dest, rval);
4654 static struct triple *init_expr(
4655 struct compile_state *state, struct triple *dest, struct triple *rval)
4661 internal_error(state, 0, "missing rval");
4663 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4664 rval = read_expr(state, rval);
4665 def = write_expr(state, dest, rval);
4668 /* Fill in the array size if necessary */
4669 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4670 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4671 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4672 dest->type->elements = rval->type->elements;
4675 if (!equiv_types(dest->type, rval->type)) {
4676 error(state, 0, "Incompatible types in inializer");
4678 MISC(dest, 0) = rval;
4679 insert_triple(state, dest, rval);
4680 rval->id |= TRIPLE_FLAG_FLATTENED;
4681 use_triple(MISC(dest, 0), dest);
4686 struct type *arithmetic_result(
4687 struct compile_state *state, struct triple *left, struct triple *right)
4690 /* Sanity checks to ensure I am working with arithmetic types */
4691 arithmetic(state, left);
4692 arithmetic(state, right);
4694 do_arithmetic_conversion(
4696 right->type->type), 0, 0);
4700 struct type *ptr_arithmetic_result(
4701 struct compile_state *state, struct triple *left, struct triple *right)
4704 /* Sanity checks to ensure I am working with the proper types */
4705 ptr_arithmetic(state, left);
4706 arithmetic(state, right);
4707 if (TYPE_ARITHMETIC(left->type->type) &&
4708 TYPE_ARITHMETIC(right->type->type)) {
4709 type = arithmetic_result(state, left, right);
4711 else if (TYPE_PTR(left->type->type)) {
4715 internal_error(state, 0, "huh?");
4722 /* boolean helper function */
4724 static struct triple *ltrue_expr(struct compile_state *state,
4725 struct triple *expr)
4728 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4729 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4730 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4731 /* If the expression is already boolean do nothing */
4734 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4740 static struct triple *lfalse_expr(struct compile_state *state,
4741 struct triple *expr)
4743 return triple(state, OP_LFALSE, &int_type, expr, 0);
4746 static struct triple *cond_expr(
4747 struct compile_state *state,
4748 struct triple *test, struct triple *left, struct triple *right)
4751 struct type *result_type;
4752 unsigned int left_type, right_type;
4754 left_type = left->type->type;
4755 right_type = right->type->type;
4757 /* Both operands have arithmetic type */
4758 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4759 result_type = arithmetic_result(state, left, right);
4761 /* Both operands have void type */
4762 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4763 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4764 result_type = &void_type;
4766 /* pointers to the same type... */
4767 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4770 /* Both operands are pointers and left is a pointer to void */
4771 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4772 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4773 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4774 result_type = right->type;
4776 /* Both operands are pointers and right is a pointer to void */
4777 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4778 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4779 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4780 result_type = left->type;
4783 error(state, 0, "Incompatible types in conditional expression");
4785 /* Cleanup and invert the test */
4786 test = lfalse_expr(state, read_expr(state, test));
4787 def = new_triple(state, OP_COND, result_type, 0, 3);
4788 def->param[0] = test;
4789 def->param[1] = left;
4790 def->param[2] = right;
4795 static int expr_depth(struct compile_state *state, struct triple *ins)
4799 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4802 else if (ins->op == OP_DEREF) {
4803 count = expr_depth(state, RHS(ins, 0)) - 1;
4805 else if (ins->op == OP_VAL) {
4806 count = expr_depth(state, RHS(ins, 0)) - 1;
4808 else if (ins->op == OP_COMMA) {
4810 ldepth = expr_depth(state, RHS(ins, 0));
4811 rdepth = expr_depth(state, RHS(ins, 1));
4812 count = (ldepth >= rdepth)? ldepth : rdepth;
4814 else if (ins->op == OP_CALL) {
4815 /* Don't figure the depth of a call just guess it is huge */
4819 struct triple **expr;
4820 expr = triple_rhs(state, ins, 0);
4821 for(;expr; expr = triple_rhs(state, ins, expr)) {
4824 depth = expr_depth(state, *expr);
4825 if (depth > count) {
4834 static struct triple *flatten(
4835 struct compile_state *state, struct triple *first, struct triple *ptr);
4837 static struct triple *flatten_generic(
4838 struct compile_state *state, struct triple *first, struct triple *ptr)
4842 struct triple **ins;
4845 /* Only operations with just a rhs should come here */
4846 rhs = TRIPLE_RHS(ptr->sizes);
4847 lhs = TRIPLE_LHS(ptr->sizes);
4848 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4849 internal_error(state, ptr, "unexpected args for: %d %s",
4850 ptr->op, tops(ptr->op));
4852 /* Find the depth of the rhs elements */
4853 for(i = 0; i < rhs; i++) {
4854 vector[i].ins = &RHS(ptr, i);
4855 vector[i].depth = expr_depth(state, *vector[i].ins);
4857 /* Selection sort the rhs */
4858 for(i = 0; i < rhs; i++) {
4860 for(j = i + 1; j < rhs; j++ ) {
4861 if (vector[j].depth > vector[max].depth) {
4866 struct rhs_vector tmp;
4868 vector[i] = vector[max];
4872 /* Now flatten the rhs elements */
4873 for(i = 0; i < rhs; i++) {
4874 *vector[i].ins = flatten(state, first, *vector[i].ins);
4875 use_triple(*vector[i].ins, ptr);
4878 /* Now flatten the lhs elements */
4879 for(i = 0; i < lhs; i++) {
4880 struct triple **ins = &LHS(ptr, i);
4881 *ins = flatten(state, first, *ins);
4882 use_triple(*ins, ptr);
4887 static struct triple *flatten_land(
4888 struct compile_state *state, struct triple *first, struct triple *ptr)
4890 struct triple *left, *right;
4891 struct triple *val, *test, *jmp, *label1, *end;
4893 /* Find the triples */
4895 right = RHS(ptr, 1);
4897 /* Generate the needed triples */
4900 /* Thread the triples together */
4901 val = flatten(state, first, variable(state, ptr->type));
4902 left = flatten(state, first, write_expr(state, val, left));
4903 test = flatten(state, first,
4904 lfalse_expr(state, read_expr(state, val)));
4905 jmp = flatten(state, first, branch(state, end, test));
4906 label1 = flatten(state, first, label(state));
4907 right = flatten(state, first, write_expr(state, val, right));
4908 TARG(jmp, 0) = flatten(state, first, end);
4910 /* Now give the caller something to chew on */
4911 return read_expr(state, val);
4914 static struct triple *flatten_lor(
4915 struct compile_state *state, struct triple *first, struct triple *ptr)
4917 struct triple *left, *right;
4918 struct triple *val, *jmp, *label1, *end;
4920 /* Find the triples */
4922 right = RHS(ptr, 1);
4924 /* Generate the needed triples */
4927 /* Thread the triples together */
4928 val = flatten(state, first, variable(state, ptr->type));
4929 left = flatten(state, first, write_expr(state, val, left));
4930 jmp = flatten(state, first, branch(state, end, left));
4931 label1 = flatten(state, first, label(state));
4932 right = flatten(state, first, write_expr(state, val, right));
4933 TARG(jmp, 0) = flatten(state, first, end);
4936 /* Now give the caller something to chew on */
4937 return read_expr(state, val);
4940 static struct triple *flatten_cond(
4941 struct compile_state *state, struct triple *first, struct triple *ptr)
4943 struct triple *test, *left, *right;
4944 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4946 /* Find the triples */
4949 right = RHS(ptr, 2);
4951 /* Generate the needed triples */
4953 middle = label(state);
4955 /* Thread the triples together */
4956 val = flatten(state, first, variable(state, ptr->type));
4957 test = flatten(state, first, test);
4958 jmp1 = flatten(state, first, branch(state, middle, test));
4959 label1 = flatten(state, first, label(state));
4960 left = flatten(state, first, left);
4961 mv1 = flatten(state, first, write_expr(state, val, left));
4962 jmp2 = flatten(state, first, branch(state, end, 0));
4963 TARG(jmp1, 0) = flatten(state, first, middle);
4964 right = flatten(state, first, right);
4965 mv2 = flatten(state, first, write_expr(state, val, right));
4966 TARG(jmp2, 0) = flatten(state, first, end);
4968 /* Now give the caller something to chew on */
4969 return read_expr(state, val);
4972 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
4973 struct occurance *base_occurance)
4975 struct triple *nfunc;
4976 struct triple *nfirst, *ofirst;
4977 struct triple *new, *old;
4980 fprintf(stdout, "\n");
4981 loc(stdout, state, 0);
4982 fprintf(stdout, "\n__________ copy_func _________\n");
4983 print_triple(state, ofunc);
4984 fprintf(stdout, "__________ copy_func _________ done\n\n");
4987 /* Make a new copy of the old function */
4988 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4990 ofirst = old = RHS(ofunc, 0);
4993 struct occurance *occurance;
4994 int old_lhs, old_rhs;
4995 old_lhs = TRIPLE_LHS(old->sizes);
4996 old_rhs = TRIPLE_RHS(old->sizes);
4997 occurance = inline_occurance(state, base_occurance, old->occurance);
4998 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
5000 if (!triple_stores_block(state, new)) {
5001 memcpy(&new->u, &old->u, sizeof(new->u));
5004 RHS(nfunc, 0) = nfirst = new;
5007 insert_triple(state, nfirst, new);
5009 new->id |= TRIPLE_FLAG_FLATTENED;
5011 /* During the copy remember new as user of old */
5012 use_triple(old, new);
5014 /* Populate the return type if present */
5015 if (old == MISC(ofunc, 0)) {
5016 MISC(nfunc, 0) = new;
5019 } while(old != ofirst);
5021 /* Make a second pass to fix up any unresolved references */
5025 struct triple **oexpr, **nexpr;
5027 /* Lookup where the copy is, to join pointers */
5028 count = TRIPLE_SIZE(old->sizes);
5029 for(i = 0; i < count; i++) {
5030 oexpr = &old->param[i];
5031 nexpr = &new->param[i];
5032 if (!*nexpr && *oexpr && (*oexpr)->use) {
5033 *nexpr = (*oexpr)->use->member;
5034 if (*nexpr == old) {
5035 internal_error(state, 0, "new == old?");
5037 use_triple(*nexpr, new);
5039 if (!*nexpr && *oexpr) {
5040 internal_error(state, 0, "Could not copy %d\n", i);
5045 } while((old != ofirst) && (new != nfirst));
5047 /* Make a third pass to cleanup the extra useses */
5051 unuse_triple(old, new);
5054 } while ((old != ofirst) && (new != nfirst));
5058 static struct triple *flatten_call(
5059 struct compile_state *state, struct triple *first, struct triple *ptr)
5061 /* Inline the function call */
5063 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5064 struct triple *end, *nend;
5067 /* Find the triples */
5068 ofunc = MISC(ptr, 0);
5069 if (ofunc->op != OP_LIST) {
5070 internal_error(state, 0, "improper function");
5072 nfunc = copy_func(state, ofunc, ptr->occurance);
5073 nfirst = RHS(nfunc, 0)->next;
5074 /* Prepend the parameter reading into the new function list */
5075 ptype = nfunc->type->right;
5076 param = RHS(nfunc, 0)->next;
5077 pvals = TRIPLE_RHS(ptr->sizes);
5078 for(i = 0; i < pvals; i++) {
5082 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5083 atype = ptype->left;
5085 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5086 param = param->next;
5089 flatten(state, nfirst, write_expr(state, param, arg));
5090 ptype = ptype->right;
5091 param = param->next;
5094 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5095 result = read_expr(state, MISC(nfunc,0));
5098 fprintf(stdout, "\n");
5099 loc(stdout, state, 0);
5100 fprintf(stdout, "\n__________ flatten_call _________\n");
5101 print_triple(state, nfunc);
5102 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5105 /* Get rid of the extra triples */
5106 nfirst = RHS(nfunc, 0)->next;
5107 free_triple(state, RHS(nfunc, 0));
5109 free_triple(state, nfunc);
5111 /* Append the new function list onto the return list */
5113 nend = nfirst->prev;
5122 static struct triple *flatten(
5123 struct compile_state *state, struct triple *first, struct triple *ptr)
5125 struct triple *orig_ptr;
5130 /* Only flatten triples once */
5131 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5137 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5138 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5139 use_triple(LHS(ptr, 0), ptr);
5140 use_triple(RHS(ptr, 0), ptr);
5143 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5147 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5148 return MISC(ptr, 0);
5151 ptr = flatten_land(state, first, ptr);
5154 ptr = flatten_lor(state, first, ptr);
5157 ptr = flatten_cond(state, first, ptr);
5160 ptr = flatten_call(state, first, ptr);
5164 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5165 use_triple(RHS(ptr, 0), ptr);
5168 use_triple(TARG(ptr, 0), ptr);
5169 if (TRIPLE_RHS(ptr->sizes)) {
5170 use_triple(RHS(ptr, 0), ptr);
5171 if (ptr->next != ptr) {
5172 use_triple(ptr->next, ptr);
5177 insert_triple(state, first, ptr);
5178 ptr->id |= TRIPLE_FLAG_FLATTENED;
5179 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5180 use_triple(MISC(ptr, 0), ptr);
5183 /* Since OP_DEREF is just a marker delete it when I flatten it */
5185 RHS(orig_ptr, 0) = 0;
5186 free_triple(state, orig_ptr);
5190 struct triple *base;
5192 if (base->op == OP_DEREF) {
5193 struct triple *left;
5195 offset = field_offset(state, base->type, ptr->u.field);
5196 left = RHS(base, 0);
5197 ptr = triple(state, OP_ADD, left->type,
5198 read_expr(state, left),
5199 int_const(state, &ulong_type, offset));
5200 free_triple(state, base);
5202 else if (base->op == OP_VAL_VEC) {
5203 base = flatten(state, first, base);
5204 ptr = struct_field(state, base, ptr->u.field);
5209 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5210 use_triple(MISC(ptr, 0), ptr);
5211 use_triple(ptr, MISC(ptr, 0));
5215 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5216 use_triple(MISC(ptr, 0), ptr);
5221 /* Flatten the easy cases we don't override */
5222 ptr = flatten_generic(state, first, ptr);
5225 } while(ptr && (ptr != orig_ptr));
5227 insert_triple(state, first, ptr);
5228 ptr->id |= TRIPLE_FLAG_FLATTENED;
5233 static void release_expr(struct compile_state *state, struct triple *expr)
5235 struct triple *head;
5236 head = label(state);
5237 flatten(state, head, expr);
5238 while(head->next != head) {
5239 release_triple(state, head->next);
5241 free_triple(state, head);
5244 static int replace_rhs_use(struct compile_state *state,
5245 struct triple *orig, struct triple *new, struct triple *use)
5247 struct triple **expr;
5250 expr = triple_rhs(state, use, 0);
5251 for(;expr; expr = triple_rhs(state, use, expr)) {
5252 if (*expr == orig) {
5258 unuse_triple(orig, use);
5259 use_triple(new, use);
5264 static int replace_lhs_use(struct compile_state *state,
5265 struct triple *orig, struct triple *new, struct triple *use)
5267 struct triple **expr;
5270 expr = triple_lhs(state, use, 0);
5271 for(;expr; expr = triple_lhs(state, use, expr)) {
5272 if (*expr == orig) {
5278 unuse_triple(orig, use);
5279 use_triple(new, use);
5284 static void propogate_use(struct compile_state *state,
5285 struct triple *orig, struct triple *new)
5287 struct triple_set *user, *next;
5288 for(user = orig->use; user; user = next) {
5294 found |= replace_rhs_use(state, orig, new, use);
5295 found |= replace_lhs_use(state, orig, new, use);
5297 internal_error(state, use, "use without use");
5301 internal_error(state, orig, "used after propogate_use");
5307 * ===========================
5310 static struct triple *mk_add_expr(
5311 struct compile_state *state, struct triple *left, struct triple *right)
5313 struct type *result_type;
5314 /* Put pointer operands on the left */
5315 if (is_pointer(right)) {
5321 left = read_expr(state, left);
5322 right = read_expr(state, right);
5323 result_type = ptr_arithmetic_result(state, left, right);
5324 if (is_pointer(left)) {
5325 right = triple(state,
5326 is_signed(right->type)? OP_SMUL : OP_UMUL,
5329 int_const(state, &ulong_type,
5330 size_of(state, left->type->left)));
5332 return triple(state, OP_ADD, result_type, left, right);
5335 static struct triple *mk_sub_expr(
5336 struct compile_state *state, struct triple *left, struct triple *right)
5338 struct type *result_type;
5339 result_type = ptr_arithmetic_result(state, left, right);
5340 left = read_expr(state, left);
5341 right = read_expr(state, right);
5342 if (is_pointer(left)) {
5343 right = triple(state,
5344 is_signed(right->type)? OP_SMUL : OP_UMUL,
5347 int_const(state, &ulong_type,
5348 size_of(state, left->type->left)));
5350 return triple(state, OP_SUB, result_type, left, right);
5353 static struct triple *mk_pre_inc_expr(
5354 struct compile_state *state, struct triple *def)
5358 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5359 return triple(state, OP_VAL, def->type,
5360 write_expr(state, def, val),
5364 static struct triple *mk_pre_dec_expr(
5365 struct compile_state *state, struct triple *def)
5369 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5370 return triple(state, OP_VAL, def->type,
5371 write_expr(state, def, val),
5375 static struct triple *mk_post_inc_expr(
5376 struct compile_state *state, struct triple *def)
5380 val = read_expr(state, def);
5381 return triple(state, OP_VAL, def->type,
5382 write_expr(state, def,
5383 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5387 static struct triple *mk_post_dec_expr(
5388 struct compile_state *state, struct triple *def)
5392 val = read_expr(state, def);
5393 return triple(state, OP_VAL, def->type,
5394 write_expr(state, def,
5395 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5399 static struct triple *mk_subscript_expr(
5400 struct compile_state *state, struct triple *left, struct triple *right)
5402 left = read_expr(state, left);
5403 right = read_expr(state, right);
5404 if (!is_pointer(left) && !is_pointer(right)) {
5405 error(state, left, "subscripted value is not a pointer");
5407 return mk_deref_expr(state, mk_add_expr(state, left, right));
5411 * Compile time evaluation
5412 * ===========================
5414 static int is_const(struct triple *ins)
5416 return IS_CONST_OP(ins->op);
5419 static int constants_equal(struct compile_state *state,
5420 struct triple *left, struct triple *right)
5423 if (!is_const(left) || !is_const(right)) {
5426 else if (left->op != right->op) {
5429 else if (!equiv_types(left->type, right->type)) {
5436 if (left->u.cval == right->u.cval) {
5442 size_t lsize, rsize;
5443 lsize = size_of(state, left->type);
5444 rsize = size_of(state, right->type);
5445 if (lsize != rsize) {
5448 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5454 if ((MISC(left, 0) == MISC(right, 0)) &&
5455 (left->u.cval == right->u.cval)) {
5460 internal_error(state, left, "uknown constant type");
5467 static int is_zero(struct triple *ins)
5469 return is_const(ins) && (ins->u.cval == 0);
5472 static int is_one(struct triple *ins)
5474 return is_const(ins) && (ins->u.cval == 1);
5477 static long_t bsr(ulong_t value)
5480 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5491 static long_t bsf(ulong_t value)
5494 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5505 static long_t log2(ulong_t value)
5510 static long_t tlog2(struct triple *ins)
5512 return log2(ins->u.cval);
5515 static int is_pow2(struct triple *ins)
5517 ulong_t value, mask;
5519 if (!is_const(ins)) {
5522 value = ins->u.cval;
5529 return ((value & mask) == value);
5532 static ulong_t read_const(struct compile_state *state,
5533 struct triple *ins, struct triple **expr)
5537 switch(rhs->type->type &TYPE_MASK) {
5549 internal_error(state, rhs, "bad type to read_const\n");
5555 static long_t read_sconst(struct triple *ins, struct triple **expr)
5559 return (long_t)(rhs->u.cval);
5562 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5564 struct triple **expr;
5565 expr = triple_rhs(state, ins, 0);
5566 for(;expr;expr = triple_rhs(state, ins, expr)) {
5568 unuse_triple(*expr, ins);
5574 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5576 struct triple **expr;
5577 expr = triple_lhs(state, ins, 0);
5578 for(;expr;expr = triple_lhs(state, ins, expr)) {
5579 unuse_triple(*expr, ins);
5584 static void check_lhs(struct compile_state *state, struct triple *ins)
5586 struct triple **expr;
5587 expr = triple_lhs(state, ins, 0);
5588 for(;expr;expr = triple_lhs(state, ins, expr)) {
5589 internal_error(state, ins, "unexpected lhs");
5593 static void check_targ(struct compile_state *state, struct triple *ins)
5595 struct triple **expr;
5596 expr = triple_targ(state, ins, 0);
5597 for(;expr;expr = triple_targ(state, ins, expr)) {
5598 internal_error(state, ins, "unexpected targ");
5602 static void wipe_ins(struct compile_state *state, struct triple *ins)
5604 /* Becareful which instructions you replace the wiped
5605 * instruction with, as there are not enough slots
5606 * in all instructions to hold all others.
5608 check_targ(state, ins);
5609 unuse_rhs(state, ins);
5610 unuse_lhs(state, ins);
5613 static void mkcopy(struct compile_state *state,
5614 struct triple *ins, struct triple *rhs)
5616 wipe_ins(state, ins);
5618 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5620 use_triple(RHS(ins, 0), ins);
5623 static void mkconst(struct compile_state *state,
5624 struct triple *ins, ulong_t value)
5626 if (!is_integral(ins) && !is_pointer(ins)) {
5627 internal_error(state, ins, "unknown type to make constant\n");
5629 wipe_ins(state, ins);
5630 ins->op = OP_INTCONST;
5631 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5632 ins->u.cval = value;
5635 static void mkaddr_const(struct compile_state *state,
5636 struct triple *ins, struct triple *sdecl, ulong_t value)
5638 wipe_ins(state, ins);
5639 ins->op = OP_ADDRCONST;
5640 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5641 MISC(ins, 0) = sdecl;
5642 ins->u.cval = value;
5643 use_triple(sdecl, ins);
5646 /* Transform multicomponent variables into simple register variables */
5647 static void flatten_structures(struct compile_state *state)
5649 struct triple *ins, *first;
5650 first = RHS(state->main_function, 0);
5652 /* Pass one expand structure values into valvecs.
5656 struct triple *next;
5658 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5659 if (ins->op == OP_VAL_VEC) {
5662 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5663 struct triple *def, **vector;
5670 get_occurance(ins->occurance);
5671 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5674 vector = &RHS(next, 0);
5675 tptr = next->type->left;
5676 for(i = 0; i < next->type->elements; i++) {
5677 struct triple *sfield;
5680 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5681 mtype = mtype->left;
5683 sfield = deref_field(state, def, mtype->field_ident);
5686 state, op, mtype, sfield, 0);
5687 put_occurance(vector[i]->occurance);
5688 get_occurance(next->occurance);
5689 vector[i]->occurance = next->occurance;
5692 propogate_use(state, ins, next);
5693 flatten(state, ins, next);
5694 free_triple(state, ins);
5696 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5697 struct triple *src, *dst, **vector;
5705 get_occurance(ins->occurance);
5706 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5709 vector = &RHS(next, 0);
5710 tptr = next->type->left;
5711 for(i = 0; i < ins->type->elements; i++) {
5712 struct triple *dfield, *sfield;
5715 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5716 mtype = mtype->left;
5718 sfield = deref_field(state, src, mtype->field_ident);
5719 dfield = deref_field(state, dst, mtype->field_ident);
5721 state, op, mtype, dfield, sfield);
5722 put_occurance(vector[i]->occurance);
5723 get_occurance(next->occurance);
5724 vector[i]->occurance = next->occurance;
5727 propogate_use(state, ins, next);
5728 flatten(state, ins, next);
5729 free_triple(state, ins);
5733 } while(ins != first);
5734 /* Pass two flatten the valvecs.
5738 struct triple *next;
5740 if (ins->op == OP_VAL_VEC) {
5741 release_triple(state, ins);
5744 } while(ins != first);
5745 /* Pass three verify the state and set ->id to 0.
5749 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5750 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5751 internal_error(state, ins, "STRUCT_TYPE remains?");
5753 if (ins->op == OP_DOT) {
5754 internal_error(state, ins, "OP_DOT remains?");
5756 if (ins->op == OP_VAL_VEC) {
5757 internal_error(state, ins, "OP_VAL_VEC remains?");
5760 } while(ins != first);
5763 /* For those operations that cannot be simplified */
5764 static void simplify_noop(struct compile_state *state, struct triple *ins)
5769 static void simplify_smul(struct compile_state *state, struct triple *ins)
5771 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5774 RHS(ins, 0) = RHS(ins, 1);
5777 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5779 left = read_sconst(ins, &RHS(ins, 0));
5780 right = read_sconst(ins, &RHS(ins, 1));
5781 mkconst(state, ins, left * right);
5783 else if (is_zero(RHS(ins, 1))) {
5784 mkconst(state, ins, 0);
5786 else if (is_one(RHS(ins, 1))) {
5787 mkcopy(state, ins, RHS(ins, 0));
5789 else if (is_pow2(RHS(ins, 1))) {
5791 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5793 insert_triple(state, ins, val);
5794 unuse_triple(RHS(ins, 1), ins);
5795 use_triple(val, ins);
5800 static void simplify_umul(struct compile_state *state, struct triple *ins)
5802 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5805 RHS(ins, 0) = RHS(ins, 1);
5808 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5809 ulong_t left, right;
5810 left = read_const(state, ins, &RHS(ins, 0));
5811 right = read_const(state, ins, &RHS(ins, 1));
5812 mkconst(state, ins, left * right);
5814 else if (is_zero(RHS(ins, 1))) {
5815 mkconst(state, ins, 0);
5817 else if (is_one(RHS(ins, 1))) {
5818 mkcopy(state, ins, RHS(ins, 0));
5820 else if (is_pow2(RHS(ins, 1))) {
5822 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5824 insert_triple(state, ins, val);
5825 unuse_triple(RHS(ins, 1), ins);
5826 use_triple(val, ins);
5831 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5833 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5835 left = read_sconst(ins, &RHS(ins, 0));
5836 right = read_sconst(ins, &RHS(ins, 1));
5837 mkconst(state, ins, left / right);
5839 else if (is_zero(RHS(ins, 0))) {
5840 mkconst(state, ins, 0);
5842 else if (is_zero(RHS(ins, 1))) {
5843 error(state, ins, "division by zero");
5845 else if (is_one(RHS(ins, 1))) {
5846 mkcopy(state, ins, RHS(ins, 0));
5848 else if (is_pow2(RHS(ins, 1))) {
5850 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5852 insert_triple(state, ins, val);
5853 unuse_triple(RHS(ins, 1), ins);
5854 use_triple(val, ins);
5859 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5861 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5862 ulong_t left, right;
5863 left = read_const(state, ins, &RHS(ins, 0));
5864 right = read_const(state, ins, &RHS(ins, 1));
5865 mkconst(state, ins, left / right);
5867 else if (is_zero(RHS(ins, 0))) {
5868 mkconst(state, ins, 0);
5870 else if (is_zero(RHS(ins, 1))) {
5871 error(state, ins, "division by zero");
5873 else if (is_one(RHS(ins, 1))) {
5874 mkcopy(state, ins, RHS(ins, 0));
5876 else if (is_pow2(RHS(ins, 1))) {
5878 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5880 insert_triple(state, ins, val);
5881 unuse_triple(RHS(ins, 1), ins);
5882 use_triple(val, ins);
5887 static void simplify_smod(struct compile_state *state, struct triple *ins)
5889 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5891 left = read_const(state, ins, &RHS(ins, 0));
5892 right = read_const(state, ins, &RHS(ins, 1));
5893 mkconst(state, ins, left % right);
5895 else if (is_zero(RHS(ins, 0))) {
5896 mkconst(state, ins, 0);
5898 else if (is_zero(RHS(ins, 1))) {
5899 error(state, ins, "division by zero");
5901 else if (is_one(RHS(ins, 1))) {
5902 mkconst(state, ins, 0);
5904 else if (is_pow2(RHS(ins, 1))) {
5906 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5908 insert_triple(state, ins, val);
5909 unuse_triple(RHS(ins, 1), ins);
5910 use_triple(val, ins);
5914 static void simplify_umod(struct compile_state *state, struct triple *ins)
5916 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5917 ulong_t left, right;
5918 left = read_const(state, ins, &RHS(ins, 0));
5919 right = read_const(state, ins, &RHS(ins, 1));
5920 mkconst(state, ins, left % right);
5922 else if (is_zero(RHS(ins, 0))) {
5923 mkconst(state, ins, 0);
5925 else if (is_zero(RHS(ins, 1))) {
5926 error(state, ins, "division by zero");
5928 else if (is_one(RHS(ins, 1))) {
5929 mkconst(state, ins, 0);
5931 else if (is_pow2(RHS(ins, 1))) {
5933 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5935 insert_triple(state, ins, val);
5936 unuse_triple(RHS(ins, 1), ins);
5937 use_triple(val, ins);
5942 static void simplify_add(struct compile_state *state, struct triple *ins)
5944 /* start with the pointer on the left */
5945 if (is_pointer(RHS(ins, 1))) {
5948 RHS(ins, 0) = RHS(ins, 1);
5951 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5952 if (!is_pointer(RHS(ins, 0))) {
5953 ulong_t left, right;
5954 left = read_const(state, ins, &RHS(ins, 0));
5955 right = read_const(state, ins, &RHS(ins, 1));
5956 mkconst(state, ins, left + right);
5958 else /* op == OP_ADDRCONST */ {
5959 struct triple *sdecl;
5960 ulong_t left, right;
5961 sdecl = MISC(RHS(ins, 0), 0);
5962 left = RHS(ins, 0)->u.cval;
5963 right = RHS(ins, 1)->u.cval;
5964 mkaddr_const(state, ins, sdecl, left + right);
5967 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5970 RHS(ins, 1) = RHS(ins, 0);
5975 static void simplify_sub(struct compile_state *state, struct triple *ins)
5977 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5978 if (!is_pointer(RHS(ins, 0))) {
5979 ulong_t left, right;
5980 left = read_const(state, ins, &RHS(ins, 0));
5981 right = read_const(state, ins, &RHS(ins, 1));
5982 mkconst(state, ins, left - right);
5984 else /* op == OP_ADDRCONST */ {
5985 struct triple *sdecl;
5986 ulong_t left, right;
5987 sdecl = MISC(RHS(ins, 0), 0);
5988 left = RHS(ins, 0)->u.cval;
5989 right = RHS(ins, 1)->u.cval;
5990 mkaddr_const(state, ins, sdecl, left - right);
5995 static void simplify_sl(struct compile_state *state, struct triple *ins)
5997 if (is_const(RHS(ins, 1))) {
5999 right = read_const(state, ins, &RHS(ins, 1));
6000 if (right >= (size_of(state, ins->type)*8)) {
6001 warning(state, ins, "left shift count >= width of type");
6004 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6005 ulong_t left, right;
6006 left = read_const(state, ins, &RHS(ins, 0));
6007 right = read_const(state, ins, &RHS(ins, 1));
6008 mkconst(state, ins, left << right);
6012 static void simplify_usr(struct compile_state *state, struct triple *ins)
6014 if (is_const(RHS(ins, 1))) {
6016 right = read_const(state, ins, &RHS(ins, 1));
6017 if (right >= (size_of(state, ins->type)*8)) {
6018 warning(state, ins, "right shift count >= width of type");
6021 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6022 ulong_t left, right;
6023 left = read_const(state, ins, &RHS(ins, 0));
6024 right = read_const(state, ins, &RHS(ins, 1));
6025 mkconst(state, ins, left >> right);
6029 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6031 if (is_const(RHS(ins, 1))) {
6033 right = read_const(state, ins, &RHS(ins, 1));
6034 if (right >= (size_of(state, ins->type)*8)) {
6035 warning(state, ins, "right shift count >= width of type");
6038 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6040 left = read_sconst(ins, &RHS(ins, 0));
6041 right = read_sconst(ins, &RHS(ins, 1));
6042 mkconst(state, ins, left >> right);
6046 static void simplify_and(struct compile_state *state, struct triple *ins)
6048 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6049 ulong_t left, right;
6050 left = read_const(state, ins, &RHS(ins, 0));
6051 right = read_const(state, ins, &RHS(ins, 1));
6052 mkconst(state, ins, left & right);
6056 static void simplify_or(struct compile_state *state, struct triple *ins)
6058 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6059 ulong_t left, right;
6060 left = read_const(state, ins, &RHS(ins, 0));
6061 right = read_const(state, ins, &RHS(ins, 1));
6062 mkconst(state, ins, left | right);
6066 static void simplify_xor(struct compile_state *state, struct triple *ins)
6068 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6069 ulong_t left, right;
6070 left = read_const(state, ins, &RHS(ins, 0));
6071 right = read_const(state, ins, &RHS(ins, 1));
6072 mkconst(state, ins, left ^ right);
6076 static void simplify_pos(struct compile_state *state, struct triple *ins)
6078 if (is_const(RHS(ins, 0))) {
6079 mkconst(state, ins, RHS(ins, 0)->u.cval);
6082 mkcopy(state, ins, RHS(ins, 0));
6086 static void simplify_neg(struct compile_state *state, struct triple *ins)
6088 if (is_const(RHS(ins, 0))) {
6090 left = read_const(state, ins, &RHS(ins, 0));
6091 mkconst(state, ins, -left);
6093 else if (RHS(ins, 0)->op == OP_NEG) {
6094 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6098 static void simplify_invert(struct compile_state *state, struct triple *ins)
6100 if (is_const(RHS(ins, 0))) {
6102 left = read_const(state, ins, &RHS(ins, 0));
6103 mkconst(state, ins, ~left);
6107 static void simplify_eq(struct compile_state *state, struct triple *ins)
6109 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6110 ulong_t left, right;
6111 left = read_const(state, ins, &RHS(ins, 0));
6112 right = read_const(state, ins, &RHS(ins, 1));
6113 mkconst(state, ins, left == right);
6115 else if (RHS(ins, 0) == RHS(ins, 1)) {
6116 mkconst(state, ins, 1);
6120 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6122 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6123 ulong_t left, right;
6124 left = read_const(state, ins, &RHS(ins, 0));
6125 right = read_const(state, ins, &RHS(ins, 1));
6126 mkconst(state, ins, left != right);
6128 else if (RHS(ins, 0) == RHS(ins, 1)) {
6129 mkconst(state, ins, 0);
6133 static void simplify_sless(struct compile_state *state, struct triple *ins)
6135 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6137 left = read_sconst(ins, &RHS(ins, 0));
6138 right = read_sconst(ins, &RHS(ins, 1));
6139 mkconst(state, ins, left < right);
6141 else if (RHS(ins, 0) == RHS(ins, 1)) {
6142 mkconst(state, ins, 0);
6146 static void simplify_uless(struct compile_state *state, struct triple *ins)
6148 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6149 ulong_t left, right;
6150 left = read_const(state, ins, &RHS(ins, 0));
6151 right = read_const(state, ins, &RHS(ins, 1));
6152 mkconst(state, ins, left < right);
6154 else if (is_zero(RHS(ins, 0))) {
6155 mkconst(state, ins, 1);
6157 else if (RHS(ins, 0) == RHS(ins, 1)) {
6158 mkconst(state, ins, 0);
6162 static void simplify_smore(struct compile_state *state, struct triple *ins)
6164 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6166 left = read_sconst(ins, &RHS(ins, 0));
6167 right = read_sconst(ins, &RHS(ins, 1));
6168 mkconst(state, ins, left > right);
6170 else if (RHS(ins, 0) == RHS(ins, 1)) {
6171 mkconst(state, ins, 0);
6175 static void simplify_umore(struct compile_state *state, struct triple *ins)
6177 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6178 ulong_t left, right;
6179 left = read_const(state, ins, &RHS(ins, 0));
6180 right = read_const(state, ins, &RHS(ins, 1));
6181 mkconst(state, ins, left > right);
6183 else if (is_zero(RHS(ins, 1))) {
6184 mkconst(state, ins, 1);
6186 else if (RHS(ins, 0) == RHS(ins, 1)) {
6187 mkconst(state, ins, 0);
6192 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6194 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6196 left = read_sconst(ins, &RHS(ins, 0));
6197 right = read_sconst(ins, &RHS(ins, 1));
6198 mkconst(state, ins, left <= right);
6200 else if (RHS(ins, 0) == RHS(ins, 1)) {
6201 mkconst(state, ins, 1);
6205 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6207 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6208 ulong_t left, right;
6209 left = read_const(state, ins, &RHS(ins, 0));
6210 right = read_const(state, ins, &RHS(ins, 1));
6211 mkconst(state, ins, left <= right);
6213 else if (is_zero(RHS(ins, 0))) {
6214 mkconst(state, ins, 1);
6216 else if (RHS(ins, 0) == RHS(ins, 1)) {
6217 mkconst(state, ins, 1);
6221 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6223 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6225 left = read_sconst(ins, &RHS(ins, 0));
6226 right = read_sconst(ins, &RHS(ins, 1));
6227 mkconst(state, ins, left >= right);
6229 else if (RHS(ins, 0) == RHS(ins, 1)) {
6230 mkconst(state, ins, 1);
6234 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6236 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6237 ulong_t left, right;
6238 left = read_const(state, ins, &RHS(ins, 0));
6239 right = read_const(state, ins, &RHS(ins, 1));
6240 mkconst(state, ins, left >= right);
6242 else if (is_zero(RHS(ins, 1))) {
6243 mkconst(state, ins, 1);
6245 else if (RHS(ins, 0) == RHS(ins, 1)) {
6246 mkconst(state, ins, 1);
6250 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6252 if (is_const(RHS(ins, 0))) {
6254 left = read_const(state, ins, &RHS(ins, 0));
6255 mkconst(state, ins, left == 0);
6257 /* Otherwise if I am the only user... */
6258 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6260 /* Invert a boolean operation */
6261 switch(RHS(ins, 0)->op) {
6262 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6263 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6264 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6265 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6266 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6267 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6268 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6269 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6270 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6271 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6272 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6273 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6279 mkcopy(state, ins, RHS(ins, 0));
6284 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6286 if (is_const(RHS(ins, 0))) {
6288 left = read_const(state, ins, &RHS(ins, 0));
6289 mkconst(state, ins, left != 0);
6291 else switch(RHS(ins, 0)->op) {
6292 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6293 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6294 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6295 mkcopy(state, ins, RHS(ins, 0));
6300 static void simplify_copy(struct compile_state *state, struct triple *ins)
6302 if (is_const(RHS(ins, 0))) {
6303 switch(RHS(ins, 0)->op) {
6307 left = read_const(state, ins, &RHS(ins, 0));
6308 mkconst(state, ins, left);
6313 struct triple *sdecl;
6315 sdecl = MISC(RHS(ins, 0), 0);
6316 offset = RHS(ins, 0)->u.cval;
6317 mkaddr_const(state, ins, sdecl, offset);
6321 internal_error(state, ins, "uknown constant");
6327 static void simplify_branch(struct compile_state *state, struct triple *ins)
6329 struct block *block;
6330 if (ins->op != OP_BRANCH) {
6331 internal_error(state, ins, "not branch");
6333 if (ins->use != 0) {
6334 internal_error(state, ins, "branch use");
6336 #warning "FIXME implement simplify branch."
6337 /* The challenge here with simplify branch is that I need to
6338 * make modifications to the control flow graph as well
6339 * as to the branch instruction itself.
6341 block = ins->u.block;
6343 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6344 struct triple *targ;
6346 value = read_const(state, ins, &RHS(ins, 0));
6347 unuse_triple(RHS(ins, 0), ins);
6348 targ = TARG(ins, 0);
6349 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6351 unuse_triple(ins->next, ins);
6352 TARG(ins, 0) = targ;
6355 unuse_triple(targ, ins);
6356 TARG(ins, 0) = ins->next;
6358 #warning "FIXME handle the case of making a branch unconditional"
6360 if (TARG(ins, 0) == ins->next) {
6361 unuse_triple(ins->next, ins);
6362 if (TRIPLE_RHS(ins->sizes)) {
6363 unuse_triple(RHS(ins, 0), ins);
6364 unuse_triple(ins->next, ins);
6366 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6369 internal_error(state, ins, "noop use != 0");
6371 #warning "FIXME handle the case of killing a branch"
6375 static void simplify_phi(struct compile_state *state, struct triple *ins)
6377 struct triple **expr;
6379 expr = triple_rhs(state, ins, 0);
6380 if (!*expr || !is_const(*expr)) {
6383 value = read_const(state, ins, expr);
6384 for(;expr;expr = triple_rhs(state, ins, expr)) {
6385 if (!*expr || !is_const(*expr)) {
6388 if (value != read_const(state, ins, expr)) {
6392 mkconst(state, ins, value);
6396 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6398 if (is_const(RHS(ins, 0))) {
6400 left = read_const(state, ins, &RHS(ins, 0));
6401 mkconst(state, ins, bsf(left));
6405 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6407 if (is_const(RHS(ins, 0))) {
6409 left = read_const(state, ins, &RHS(ins, 0));
6410 mkconst(state, ins, bsr(left));
6415 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6416 static const simplify_t table_simplify[] = {
6418 #define simplify_smul simplify_noop
6419 #define simplify_umul simplify_noop
6420 #define simplify_sdiv simplify_noop
6421 #define simplify_udiv simplify_noop
6422 #define simplify_smod simplify_noop
6423 #define simplify_umod simplify_noop
6426 #define simplify_add simplify_noop
6427 #define simplify_sub simplify_noop
6430 #define simplify_sl simplify_noop
6431 #define simplify_usr simplify_noop
6432 #define simplify_ssr simplify_noop
6435 #define simplify_and simplify_noop
6436 #define simplify_xor simplify_noop
6437 #define simplify_or simplify_noop
6440 #define simplify_pos simplify_noop
6441 #define simplify_neg simplify_noop
6442 #define simplify_invert simplify_noop
6446 #define simplify_eq simplify_noop
6447 #define simplify_noteq simplify_noop
6450 #define simplify_sless simplify_noop
6451 #define simplify_uless simplify_noop
6452 #define simplify_smore simplify_noop
6453 #define simplify_umore simplify_noop
6456 #define simplify_slesseq simplify_noop
6457 #define simplify_ulesseq simplify_noop
6458 #define simplify_smoreeq simplify_noop
6459 #define simplify_umoreeq simplify_noop
6462 #define simplify_lfalse simplify_noop
6465 #define simplify_ltrue simplify_noop
6469 #define simplify_copy simplify_noop
6473 #define simplify_branch simplify_noop
6477 #define simplify_phi simplify_noop
6481 #define simplify_bsf simplify_noop
6482 #define simplify_bsr simplify_noop
6485 [OP_SMUL ] = simplify_smul,
6486 [OP_UMUL ] = simplify_umul,
6487 [OP_SDIV ] = simplify_sdiv,
6488 [OP_UDIV ] = simplify_udiv,
6489 [OP_SMOD ] = simplify_smod,
6490 [OP_UMOD ] = simplify_umod,
6491 [OP_ADD ] = simplify_add,
6492 [OP_SUB ] = simplify_sub,
6493 [OP_SL ] = simplify_sl,
6494 [OP_USR ] = simplify_usr,
6495 [OP_SSR ] = simplify_ssr,
6496 [OP_AND ] = simplify_and,
6497 [OP_XOR ] = simplify_xor,
6498 [OP_OR ] = simplify_or,
6499 [OP_POS ] = simplify_pos,
6500 [OP_NEG ] = simplify_neg,
6501 [OP_INVERT ] = simplify_invert,
6503 [OP_EQ ] = simplify_eq,
6504 [OP_NOTEQ ] = simplify_noteq,
6505 [OP_SLESS ] = simplify_sless,
6506 [OP_ULESS ] = simplify_uless,
6507 [OP_SMORE ] = simplify_smore,
6508 [OP_UMORE ] = simplify_umore,
6509 [OP_SLESSEQ ] = simplify_slesseq,
6510 [OP_ULESSEQ ] = simplify_ulesseq,
6511 [OP_SMOREEQ ] = simplify_smoreeq,
6512 [OP_UMOREEQ ] = simplify_umoreeq,
6513 [OP_LFALSE ] = simplify_lfalse,
6514 [OP_LTRUE ] = simplify_ltrue,
6516 [OP_LOAD ] = simplify_noop,
6517 [OP_STORE ] = simplify_noop,
6519 [OP_NOOP ] = simplify_noop,
6521 [OP_INTCONST ] = simplify_noop,
6522 [OP_BLOBCONST ] = simplify_noop,
6523 [OP_ADDRCONST ] = simplify_noop,
6525 [OP_WRITE ] = simplify_noop,
6526 [OP_READ ] = simplify_noop,
6527 [OP_COPY ] = simplify_copy,
6528 [OP_PIECE ] = simplify_noop,
6529 [OP_ASM ] = simplify_noop,
6531 [OP_DOT ] = simplify_noop,
6532 [OP_VAL_VEC ] = simplify_noop,
6534 [OP_LIST ] = simplify_noop,
6535 [OP_BRANCH ] = simplify_branch,
6536 [OP_LABEL ] = simplify_noop,
6537 [OP_ADECL ] = simplify_noop,
6538 [OP_SDECL ] = simplify_noop,
6539 [OP_PHI ] = simplify_phi,
6541 [OP_INB ] = simplify_noop,
6542 [OP_INW ] = simplify_noop,
6543 [OP_INL ] = simplify_noop,
6544 [OP_OUTB ] = simplify_noop,
6545 [OP_OUTW ] = simplify_noop,
6546 [OP_OUTL ] = simplify_noop,
6547 [OP_BSF ] = simplify_bsf,
6548 [OP_BSR ] = simplify_bsr,
6549 [OP_RDMSR ] = simplify_noop,
6550 [OP_WRMSR ] = simplify_noop,
6551 [OP_HLT ] = simplify_noop,
6554 static void simplify(struct compile_state *state, struct triple *ins)
6557 simplify_t do_simplify;
6561 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6565 do_simplify = table_simplify[op];
6568 internal_error(state, ins, "cannot simplify op: %d %s\n",
6572 do_simplify(state, ins);
6573 } while(ins->op != op);
6576 static void simplify_all(struct compile_state *state)
6578 struct triple *ins, *first;
6579 first = RHS(state->main_function, 0);
6582 simplify(state, ins);
6584 } while(ins != first);
6589 * ============================
6592 static void register_builtin_function(struct compile_state *state,
6593 const char *name, int op, struct type *rtype, ...)
6595 struct type *ftype, *atype, *param, **next;
6596 struct triple *def, *arg, *result, *work, *last, *first;
6597 struct hash_entry *ident;
6598 struct file_state file;
6604 /* Dummy file state to get debug handling right */
6605 memset(&file, 0, sizeof(file));
6606 file.basename = "<built-in>";
6608 file.report_line = 1;
6609 file.report_name = file.basename;
6610 file.prev = state->file;
6611 state->file = &file;
6612 state->function = name;
6614 /* Find the Parameter count */
6615 valid_op(state, op);
6616 parameters = table_ops[op].rhs;
6617 if (parameters < 0 ) {
6618 internal_error(state, 0, "Invalid builtin parameter count");
6621 /* Find the function type */
6622 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6623 next = &ftype->right;
6624 va_start(args, rtype);
6625 for(i = 0; i < parameters; i++) {
6626 atype = va_arg(args, struct type *);
6630 *next = new_type(TYPE_PRODUCT, *next, atype);
6631 next = &((*next)->right);
6639 /* Generate the needed triples */
6640 def = triple(state, OP_LIST, ftype, 0, 0);
6641 first = label(state);
6642 RHS(def, 0) = first;
6644 /* Now string them together */
6645 param = ftype->right;
6646 for(i = 0; i < parameters; i++) {
6647 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6648 atype = param->left;
6652 arg = flatten(state, first, variable(state, atype));
6653 param = param->right;
6656 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6657 result = flatten(state, first, variable(state, rtype));
6659 MISC(def, 0) = result;
6660 work = new_triple(state, op, rtype, -1, parameters);
6661 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6662 RHS(work, i) = read_expr(state, arg);
6664 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6666 /* Populate the LHS with the target registers */
6667 work = flatten(state, first, work);
6668 work->type = &void_type;
6669 param = rtype->left;
6670 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6671 internal_error(state, 0, "Invalid result type");
6673 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6674 for(i = 0; i < rtype->elements; i++) {
6675 struct triple *piece;
6677 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6678 atype = param->left;
6680 if (!TYPE_ARITHMETIC(atype->type) &&
6681 !TYPE_PTR(atype->type)) {
6682 internal_error(state, 0, "Invalid lhs type");
6684 piece = triple(state, OP_PIECE, atype, work, 0);
6686 LHS(work, i) = piece;
6687 RHS(val, i) = piece;
6692 work = write_expr(state, result, work);
6694 work = flatten(state, first, work);
6695 last = flatten(state, first, label(state));
6696 name_len = strlen(name);
6697 ident = lookup(state, name, name_len);
6698 symbol(state, ident, &ident->sym_ident, def, ftype);
6700 state->file = file.prev;
6701 state->function = 0;
6703 fprintf(stdout, "\n");
6704 loc(stdout, state, 0);
6705 fprintf(stdout, "\n__________ builtin_function _________\n");
6706 print_triple(state, def);
6707 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6711 static struct type *partial_struct(struct compile_state *state,
6712 const char *field_name, struct type *type, struct type *rest)
6714 struct hash_entry *field_ident;
6715 struct type *result;
6718 field_name_len = strlen(field_name);
6719 field_ident = lookup(state, field_name, field_name_len);
6721 result = clone_type(0, type);
6722 result->field_ident = field_ident;
6725 result = new_type(TYPE_PRODUCT, result, rest);
6730 static struct type *register_builtin_type(struct compile_state *state,
6731 const char *name, struct type *type)
6733 struct hash_entry *ident;
6736 name_len = strlen(name);
6737 ident = lookup(state, name, name_len);
6739 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6740 ulong_t elements = 0;
6742 type = new_type(TYPE_STRUCT, type, 0);
6744 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6746 field = field->right;
6749 symbol(state, ident, &ident->sym_struct, 0, type);
6750 type->type_ident = ident;
6751 type->elements = elements;
6753 symbol(state, ident, &ident->sym_ident, 0, type);
6754 ident->tok = TOK_TYPE_NAME;
6759 static void register_builtins(struct compile_state *state)
6761 struct type *msr_type;
6763 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6765 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6767 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6770 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6771 &uchar_type, &ushort_type);
6772 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6773 &ushort_type, &ushort_type);
6774 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6775 &uint_type, &ushort_type);
6777 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6779 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6782 msr_type = register_builtin_type(state, "__builtin_msr_t",
6783 partial_struct(state, "lo", &ulong_type,
6784 partial_struct(state, "hi", &ulong_type, 0)));
6786 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6788 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6789 &ulong_type, &ulong_type, &ulong_type);
6791 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6795 static struct type *declarator(
6796 struct compile_state *state, struct type *type,
6797 struct hash_entry **ident, int need_ident);
6798 static void decl(struct compile_state *state, struct triple *first);
6799 static struct type *specifier_qualifier_list(struct compile_state *state);
6800 static int isdecl_specifier(int tok);
6801 static struct type *decl_specifiers(struct compile_state *state);
6802 static int istype(int tok);
6803 static struct triple *expr(struct compile_state *state);
6804 static struct triple *assignment_expr(struct compile_state *state);
6805 static struct type *type_name(struct compile_state *state);
6806 static void statement(struct compile_state *state, struct triple *fist);
6808 static struct triple *call_expr(
6809 struct compile_state *state, struct triple *func)
6812 struct type *param, *type;
6813 ulong_t pvals, index;
6815 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6816 error(state, 0, "Called object is not a function");
6818 if (func->op != OP_LIST) {
6819 internal_error(state, 0, "improper function");
6821 eat(state, TOK_LPAREN);
6822 /* Find the return type without any specifiers */
6823 type = clone_type(0, func->type->left);
6824 def = new_triple(state, OP_CALL, func->type, -1, -1);
6827 pvals = TRIPLE_RHS(def->sizes);
6828 MISC(def, 0) = func;
6830 param = func->type->right;
6831 for(index = 0; index < pvals; index++) {
6833 struct type *arg_type;
6834 val = read_expr(state, assignment_expr(state));
6836 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6837 arg_type = param->left;
6839 write_compatible(state, arg_type, val->type);
6840 RHS(def, index) = val;
6841 if (index != (pvals - 1)) {
6842 eat(state, TOK_COMMA);
6843 param = param->right;
6846 eat(state, TOK_RPAREN);
6851 static struct triple *character_constant(struct compile_state *state)
6855 const signed char *str, *end;
6858 eat(state, TOK_LIT_CHAR);
6859 tk = &state->token[0];
6860 str = tk->val.str + 1;
6861 str_len = tk->str_len - 2;
6863 error(state, 0, "empty character constant");
6865 end = str + str_len;
6866 c = char_value(state, &str, end);
6868 error(state, 0, "multibyte character constant not supported");
6870 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6874 static struct triple *string_constant(struct compile_state *state)
6879 const signed char *str, *end;
6880 signed char *buf, *ptr;
6884 type = new_type(TYPE_ARRAY, &char_type, 0);
6886 /* The while loop handles string concatenation */
6888 eat(state, TOK_LIT_STRING);
6889 tk = &state->token[0];
6890 str = tk->val.str + 1;
6891 str_len = tk->str_len - 2;
6893 error(state, 0, "negative string constant length");
6895 end = str + str_len;
6897 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6898 memcpy(buf, ptr, type->elements);
6899 ptr = buf + type->elements;
6901 *ptr++ = char_value(state, &str, end);
6903 type->elements = ptr - buf;
6904 } while(peek(state) == TOK_LIT_STRING);
6906 type->elements += 1;
6907 def = triple(state, OP_BLOBCONST, type, 0, 0);
6913 static struct triple *integer_constant(struct compile_state *state)
6922 eat(state, TOK_LIT_INT);
6923 tk = &state->token[0];
6925 decimal = (tk->val.str[0] != '0');
6926 val = strtoul(tk->val.str, &end, 0);
6927 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6928 error(state, 0, "Integer constant to large");
6931 if ((*end == 'u') || (*end == 'U')) {
6935 if ((*end == 'l') || (*end == 'L')) {
6939 if ((*end == 'u') || (*end == 'U')) {
6944 error(state, 0, "Junk at end of integer constant");
6951 if (!decimal && (val > LONG_MAX)) {
6957 if (val > UINT_MAX) {
6963 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6966 else if (!decimal && (val > LONG_MAX)) {
6969 else if (val > INT_MAX) {
6973 def = int_const(state, type, val);
6977 static struct triple *primary_expr(struct compile_state *state)
6985 struct hash_entry *ident;
6986 /* Here ident is either:
6989 * an enumeration constant.
6991 eat(state, TOK_IDENT);
6992 ident = state->token[0].ident;
6993 if (!ident->sym_ident) {
6994 error(state, 0, "%s undeclared", ident->name);
6996 def = ident->sym_ident->def;
6999 case TOK_ENUM_CONST:
7000 /* Here ident is an enumeration constant */
7001 eat(state, TOK_ENUM_CONST);
7006 eat(state, TOK_LPAREN);
7008 eat(state, TOK_RPAREN);
7011 def = integer_constant(state);
7014 eat(state, TOK_LIT_FLOAT);
7015 error(state, 0, "Floating point constants not supported");
7020 def = character_constant(state);
7022 case TOK_LIT_STRING:
7023 def = string_constant(state);
7027 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7032 static struct triple *postfix_expr(struct compile_state *state)
7036 def = primary_expr(state);
7038 struct triple *left;
7042 switch((tok = peek(state))) {
7044 eat(state, TOK_LBRACKET);
7045 def = mk_subscript_expr(state, left, expr(state));
7046 eat(state, TOK_RBRACKET);
7049 def = call_expr(state, def);
7053 struct hash_entry *field;
7054 eat(state, TOK_DOT);
7055 eat(state, TOK_IDENT);
7056 field = state->token[0].ident;
7057 def = deref_field(state, def, field);
7062 struct hash_entry *field;
7063 eat(state, TOK_ARROW);
7064 eat(state, TOK_IDENT);
7065 field = state->token[0].ident;
7066 def = mk_deref_expr(state, read_expr(state, def));
7067 def = deref_field(state, def, field);
7071 eat(state, TOK_PLUSPLUS);
7072 def = mk_post_inc_expr(state, left);
7074 case TOK_MINUSMINUS:
7075 eat(state, TOK_MINUSMINUS);
7076 def = mk_post_dec_expr(state, left);
7086 static struct triple *cast_expr(struct compile_state *state);
7088 static struct triple *unary_expr(struct compile_state *state)
7090 struct triple *def, *right;
7092 switch((tok = peek(state))) {
7094 eat(state, TOK_PLUSPLUS);
7095 def = mk_pre_inc_expr(state, unary_expr(state));
7097 case TOK_MINUSMINUS:
7098 eat(state, TOK_MINUSMINUS);
7099 def = mk_pre_dec_expr(state, unary_expr(state));
7102 eat(state, TOK_AND);
7103 def = mk_addr_expr(state, cast_expr(state), 0);
7106 eat(state, TOK_STAR);
7107 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7110 eat(state, TOK_PLUS);
7111 right = read_expr(state, cast_expr(state));
7112 arithmetic(state, right);
7113 def = integral_promotion(state, right);
7116 eat(state, TOK_MINUS);
7117 right = read_expr(state, cast_expr(state));
7118 arithmetic(state, right);
7119 def = integral_promotion(state, right);
7120 def = triple(state, OP_NEG, def->type, def, 0);
7123 eat(state, TOK_TILDE);
7124 right = read_expr(state, cast_expr(state));
7125 integral(state, right);
7126 def = integral_promotion(state, right);
7127 def = triple(state, OP_INVERT, def->type, def, 0);
7130 eat(state, TOK_BANG);
7131 right = read_expr(state, cast_expr(state));
7133 def = lfalse_expr(state, right);
7139 eat(state, TOK_SIZEOF);
7141 tok2 = peek2(state);
7142 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7143 eat(state, TOK_LPAREN);
7144 type = type_name(state);
7145 eat(state, TOK_RPAREN);
7148 struct triple *expr;
7149 expr = unary_expr(state);
7151 release_expr(state, expr);
7153 def = int_const(state, &ulong_type, size_of(state, type));
7160 eat(state, TOK_ALIGNOF);
7162 tok2 = peek2(state);
7163 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7164 eat(state, TOK_LPAREN);
7165 type = type_name(state);
7166 eat(state, TOK_RPAREN);
7169 struct triple *expr;
7170 expr = unary_expr(state);
7172 release_expr(state, expr);
7174 def = int_const(state, &ulong_type, align_of(state, type));
7178 def = postfix_expr(state);
7184 static struct triple *cast_expr(struct compile_state *state)
7189 tok2 = peek2(state);
7190 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7192 eat(state, TOK_LPAREN);
7193 type = type_name(state);
7194 eat(state, TOK_RPAREN);
7195 def = read_expr(state, cast_expr(state));
7196 def = triple(state, OP_COPY, type, def, 0);
7199 def = unary_expr(state);
7204 static struct triple *mult_expr(struct compile_state *state)
7208 def = cast_expr(state);
7210 struct triple *left, *right;
7211 struct type *result_type;
7214 switch(tok = (peek(state))) {
7218 left = read_expr(state, def);
7219 arithmetic(state, left);
7223 right = read_expr(state, cast_expr(state));
7224 arithmetic(state, right);
7226 result_type = arithmetic_result(state, left, right);
7227 sign = is_signed(result_type);
7230 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7231 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7232 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7234 def = triple(state, op, result_type, left, right);
7244 static struct triple *add_expr(struct compile_state *state)
7248 def = mult_expr(state);
7251 switch( peek(state)) {
7253 eat(state, TOK_PLUS);
7254 def = mk_add_expr(state, def, mult_expr(state));
7257 eat(state, TOK_MINUS);
7258 def = mk_sub_expr(state, def, mult_expr(state));
7268 static struct triple *shift_expr(struct compile_state *state)
7272 def = add_expr(state);
7274 struct triple *left, *right;
7277 switch((tok = peek(state))) {
7280 left = read_expr(state, def);
7281 integral(state, left);
7282 left = integral_promotion(state, left);
7286 right = read_expr(state, add_expr(state));
7287 integral(state, right);
7288 right = integral_promotion(state, right);
7290 op = (tok == TOK_SL)? OP_SL :
7291 is_signed(left->type)? OP_SSR: OP_USR;
7293 def = triple(state, op, left->type, left, right);
7303 static struct triple *relational_expr(struct compile_state *state)
7305 #warning "Extend relational exprs to work on more than arithmetic types"
7308 def = shift_expr(state);
7310 struct triple *left, *right;
7311 struct type *arg_type;
7314 switch((tok = peek(state))) {
7319 left = read_expr(state, def);
7320 arithmetic(state, left);
7324 right = read_expr(state, shift_expr(state));
7325 arithmetic(state, right);
7327 arg_type = arithmetic_result(state, left, right);
7328 sign = is_signed(arg_type);
7331 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7332 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7333 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7334 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7336 def = triple(state, op, &int_type, left, right);
7346 static struct triple *equality_expr(struct compile_state *state)
7348 #warning "Extend equality exprs to work on more than arithmetic types"
7351 def = relational_expr(state);
7353 struct triple *left, *right;
7356 switch((tok = peek(state))) {
7359 left = read_expr(state, def);
7360 arithmetic(state, left);
7362 right = read_expr(state, relational_expr(state));
7363 arithmetic(state, right);
7364 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7365 def = triple(state, op, &int_type, left, right);
7375 static struct triple *and_expr(struct compile_state *state)
7378 def = equality_expr(state);
7379 while(peek(state) == TOK_AND) {
7380 struct triple *left, *right;
7381 struct type *result_type;
7382 left = read_expr(state, def);
7383 integral(state, left);
7384 eat(state, TOK_AND);
7385 right = read_expr(state, equality_expr(state));
7386 integral(state, right);
7387 result_type = arithmetic_result(state, left, right);
7388 def = triple(state, OP_AND, result_type, left, right);
7393 static struct triple *xor_expr(struct compile_state *state)
7396 def = and_expr(state);
7397 while(peek(state) == TOK_XOR) {
7398 struct triple *left, *right;
7399 struct type *result_type;
7400 left = read_expr(state, def);
7401 integral(state, left);
7402 eat(state, TOK_XOR);
7403 right = read_expr(state, and_expr(state));
7404 integral(state, right);
7405 result_type = arithmetic_result(state, left, right);
7406 def = triple(state, OP_XOR, result_type, left, right);
7411 static struct triple *or_expr(struct compile_state *state)
7414 def = xor_expr(state);
7415 while(peek(state) == TOK_OR) {
7416 struct triple *left, *right;
7417 struct type *result_type;
7418 left = read_expr(state, def);
7419 integral(state, left);
7421 right = read_expr(state, xor_expr(state));
7422 integral(state, right);
7423 result_type = arithmetic_result(state, left, right);
7424 def = triple(state, OP_OR, result_type, left, right);
7429 static struct triple *land_expr(struct compile_state *state)
7432 def = or_expr(state);
7433 while(peek(state) == TOK_LOGAND) {
7434 struct triple *left, *right;
7435 left = read_expr(state, def);
7437 eat(state, TOK_LOGAND);
7438 right = read_expr(state, or_expr(state));
7441 def = triple(state, OP_LAND, &int_type,
7442 ltrue_expr(state, left),
7443 ltrue_expr(state, right));
7448 static struct triple *lor_expr(struct compile_state *state)
7451 def = land_expr(state);
7452 while(peek(state) == TOK_LOGOR) {
7453 struct triple *left, *right;
7454 left = read_expr(state, def);
7456 eat(state, TOK_LOGOR);
7457 right = read_expr(state, land_expr(state));
7460 def = triple(state, OP_LOR, &int_type,
7461 ltrue_expr(state, left),
7462 ltrue_expr(state, right));
7467 static struct triple *conditional_expr(struct compile_state *state)
7470 def = lor_expr(state);
7471 if (peek(state) == TOK_QUEST) {
7472 struct triple *test, *left, *right;
7474 test = ltrue_expr(state, read_expr(state, def));
7475 eat(state, TOK_QUEST);
7476 left = read_expr(state, expr(state));
7477 eat(state, TOK_COLON);
7478 right = read_expr(state, conditional_expr(state));
7480 def = cond_expr(state, test, left, right);
7485 static struct triple *eval_const_expr(
7486 struct compile_state *state, struct triple *expr)
7489 if (is_const(expr)) {
7493 /* If we don't start out as a constant simplify into one */
7494 struct triple *head, *ptr;
7495 head = label(state); /* dummy initial triple */
7496 flatten(state, head, expr);
7497 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7498 simplify(state, ptr);
7500 /* Remove the constant value the tail of the list */
7502 def->prev->next = def->next;
7503 def->next->prev = def->prev;
7504 def->next = def->prev = def;
7505 if (!is_const(def)) {
7506 error(state, 0, "Not a constant expression");
7508 /* Free the intermediate expressions */
7509 while(head->next != head) {
7510 release_triple(state, head->next);
7512 free_triple(state, head);
7517 static struct triple *constant_expr(struct compile_state *state)
7519 return eval_const_expr(state, conditional_expr(state));
7522 static struct triple *assignment_expr(struct compile_state *state)
7524 struct triple *def, *left, *right;
7526 /* The C grammer in K&R shows assignment expressions
7527 * only taking unary expressions as input on their
7528 * left hand side. But specifies the precedence of
7529 * assignemnt as the lowest operator except for comma.
7531 * Allowing conditional expressions on the left hand side
7532 * of an assignement results in a grammar that accepts
7533 * a larger set of statements than standard C. As long
7534 * as the subset of the grammar that is standard C behaves
7535 * correctly this should cause no problems.
7537 * For the extra token strings accepted by the grammar
7538 * none of them should produce a valid lvalue, so they
7539 * should not produce functioning programs.
7541 * GCC has this bug as well, so surprises should be minimal.
7543 def = conditional_expr(state);
7545 switch((tok = peek(state))) {
7547 lvalue(state, left);
7549 def = write_expr(state, left,
7550 read_expr(state, assignment_expr(state)));
7555 lvalue(state, left);
7556 arithmetic(state, left);
7558 right = read_expr(state, assignment_expr(state));
7559 arithmetic(state, right);
7561 sign = is_signed(left->type);
7564 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7565 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7566 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7568 def = write_expr(state, left,
7569 triple(state, op, left->type,
7570 read_expr(state, left), right));
7573 lvalue(state, left);
7574 eat(state, TOK_PLUSEQ);
7575 def = write_expr(state, left,
7576 mk_add_expr(state, left, assignment_expr(state)));
7579 lvalue(state, left);
7580 eat(state, TOK_MINUSEQ);
7581 def = write_expr(state, left,
7582 mk_sub_expr(state, left, assignment_expr(state)));
7589 lvalue(state, left);
7590 integral(state, left);
7592 right = read_expr(state, assignment_expr(state));
7593 integral(state, right);
7594 right = integral_promotion(state, right);
7595 sign = is_signed(left->type);
7598 case TOK_SLEQ: op = OP_SL; break;
7599 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7600 case TOK_ANDEQ: op = OP_AND; break;
7601 case TOK_XOREQ: op = OP_XOR; break;
7602 case TOK_OREQ: op = OP_OR; break;
7604 def = write_expr(state, left,
7605 triple(state, op, left->type,
7606 read_expr(state, left), right));
7612 static struct triple *expr(struct compile_state *state)
7615 def = assignment_expr(state);
7616 while(peek(state) == TOK_COMMA) {
7617 struct triple *left, *right;
7619 eat(state, TOK_COMMA);
7620 right = assignment_expr(state);
7621 def = triple(state, OP_COMMA, right->type, left, right);
7626 static void expr_statement(struct compile_state *state, struct triple *first)
7628 if (peek(state) != TOK_SEMI) {
7629 flatten(state, first, expr(state));
7631 eat(state, TOK_SEMI);
7634 static void if_statement(struct compile_state *state, struct triple *first)
7636 struct triple *test, *jmp1, *jmp2, *middle, *end;
7638 jmp1 = jmp2 = middle = 0;
7640 eat(state, TOK_LPAREN);
7643 /* Cleanup and invert the test */
7644 test = lfalse_expr(state, read_expr(state, test));
7645 eat(state, TOK_RPAREN);
7646 /* Generate the needed pieces */
7647 middle = label(state);
7648 jmp1 = branch(state, middle, test);
7649 /* Thread the pieces together */
7650 flatten(state, first, test);
7651 flatten(state, first, jmp1);
7652 flatten(state, first, label(state));
7653 statement(state, first);
7654 if (peek(state) == TOK_ELSE) {
7655 eat(state, TOK_ELSE);
7656 /* Generate the rest of the pieces */
7658 jmp2 = branch(state, end, 0);
7659 /* Thread them together */
7660 flatten(state, first, jmp2);
7661 flatten(state, first, middle);
7662 statement(state, first);
7663 flatten(state, first, end);
7666 flatten(state, first, middle);
7670 static void for_statement(struct compile_state *state, struct triple *first)
7672 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7673 struct triple *label1, *label2, *label3;
7674 struct hash_entry *ident;
7676 eat(state, TOK_FOR);
7677 eat(state, TOK_LPAREN);
7678 head = test = tail = jmp1 = jmp2 = 0;
7679 if (peek(state) != TOK_SEMI) {
7682 eat(state, TOK_SEMI);
7683 if (peek(state) != TOK_SEMI) {
7686 test = ltrue_expr(state, read_expr(state, test));
7688 eat(state, TOK_SEMI);
7689 if (peek(state) != TOK_RPAREN) {
7692 eat(state, TOK_RPAREN);
7693 /* Generate the needed pieces */
7694 label1 = label(state);
7695 label2 = label(state);
7696 label3 = label(state);
7698 jmp1 = branch(state, label3, 0);
7699 jmp2 = branch(state, label1, test);
7702 jmp2 = branch(state, label1, 0);
7705 /* Remember where break and continue go */
7707 ident = state->i_break;
7708 symbol(state, ident, &ident->sym_ident, end, end->type);
7709 ident = state->i_continue;
7710 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7711 /* Now include the body */
7712 flatten(state, first, head);
7713 flatten(state, first, jmp1);
7714 flatten(state, first, label1);
7715 statement(state, first);
7716 flatten(state, first, label2);
7717 flatten(state, first, tail);
7718 flatten(state, first, label3);
7719 flatten(state, first, test);
7720 flatten(state, first, jmp2);
7721 flatten(state, first, end);
7722 /* Cleanup the break/continue scope */
7726 static void while_statement(struct compile_state *state, struct triple *first)
7728 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7729 struct hash_entry *ident;
7730 eat(state, TOK_WHILE);
7731 eat(state, TOK_LPAREN);
7734 test = ltrue_expr(state, read_expr(state, test));
7735 eat(state, TOK_RPAREN);
7736 /* Generate the needed pieces */
7737 label1 = label(state);
7738 label2 = label(state);
7739 jmp1 = branch(state, label2, 0);
7740 jmp2 = branch(state, label1, test);
7742 /* Remember where break and continue go */
7744 ident = state->i_break;
7745 symbol(state, ident, &ident->sym_ident, end, end->type);
7746 ident = state->i_continue;
7747 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7748 /* Thread them together */
7749 flatten(state, first, jmp1);
7750 flatten(state, first, label1);
7751 statement(state, first);
7752 flatten(state, first, label2);
7753 flatten(state, first, test);
7754 flatten(state, first, jmp2);
7755 flatten(state, first, end);
7756 /* Cleanup the break/continue scope */
7760 static void do_statement(struct compile_state *state, struct triple *first)
7762 struct triple *label1, *label2, *test, *end;
7763 struct hash_entry *ident;
7765 /* Generate the needed pieces */
7766 label1 = label(state);
7767 label2 = label(state);
7769 /* Remember where break and continue go */
7771 ident = state->i_break;
7772 symbol(state, ident, &ident->sym_ident, end, end->type);
7773 ident = state->i_continue;
7774 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7775 /* Now include the body */
7776 flatten(state, first, label1);
7777 statement(state, first);
7778 /* Cleanup the break/continue scope */
7780 /* Eat the rest of the loop */
7781 eat(state, TOK_WHILE);
7782 eat(state, TOK_LPAREN);
7783 test = read_expr(state, expr(state));
7785 eat(state, TOK_RPAREN);
7786 eat(state, TOK_SEMI);
7787 /* Thread the pieces together */
7788 test = ltrue_expr(state, test);
7789 flatten(state, first, label2);
7790 flatten(state, first, test);
7791 flatten(state, first, branch(state, label1, test));
7792 flatten(state, first, end);
7796 static void return_statement(struct compile_state *state, struct triple *first)
7798 struct triple *jmp, *mv, *dest, *var, *val;
7800 eat(state, TOK_RETURN);
7802 #warning "FIXME implement a more general excess branch elimination"
7804 /* If we have a return value do some more work */
7805 if (peek(state) != TOK_SEMI) {
7806 val = read_expr(state, expr(state));
7808 eat(state, TOK_SEMI);
7810 /* See if this last statement in a function */
7811 last = ((peek(state) == TOK_RBRACE) &&
7812 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7814 /* Find the return variable */
7815 var = MISC(state->main_function, 0);
7816 /* Find the return destination */
7817 dest = RHS(state->main_function, 0)->prev;
7819 /* If needed generate a jump instruction */
7821 jmp = branch(state, dest, 0);
7823 /* If needed generate an assignment instruction */
7825 mv = write_expr(state, var, val);
7827 /* Now put the code together */
7829 flatten(state, first, mv);
7830 flatten(state, first, jmp);
7833 flatten(state, first, jmp);
7837 static void break_statement(struct compile_state *state, struct triple *first)
7839 struct triple *dest;
7840 eat(state, TOK_BREAK);
7841 eat(state, TOK_SEMI);
7842 if (!state->i_break->sym_ident) {
7843 error(state, 0, "break statement not within loop or switch");
7845 dest = state->i_break->sym_ident->def;
7846 flatten(state, first, branch(state, dest, 0));
7849 static void continue_statement(struct compile_state *state, struct triple *first)
7851 struct triple *dest;
7852 eat(state, TOK_CONTINUE);
7853 eat(state, TOK_SEMI);
7854 if (!state->i_continue->sym_ident) {
7855 error(state, 0, "continue statement outside of a loop");
7857 dest = state->i_continue->sym_ident->def;
7858 flatten(state, first, branch(state, dest, 0));
7861 static void goto_statement(struct compile_state *state, struct triple *first)
7863 struct hash_entry *ident;
7864 eat(state, TOK_GOTO);
7865 eat(state, TOK_IDENT);
7866 ident = state->token[0].ident;
7867 if (!ident->sym_label) {
7868 /* If this is a forward branch allocate the label now,
7869 * it will be flattend in the appropriate location later.
7873 label_symbol(state, ident, ins);
7875 eat(state, TOK_SEMI);
7877 flatten(state, first, branch(state, ident->sym_label->def, 0));
7880 static void labeled_statement(struct compile_state *state, struct triple *first)
7883 struct hash_entry *ident;
7884 eat(state, TOK_IDENT);
7886 ident = state->token[0].ident;
7887 if (ident->sym_label && ident->sym_label->def) {
7888 ins = ident->sym_label->def;
7889 put_occurance(ins->occurance);
7890 ins->occurance = new_occurance(state);
7894 label_symbol(state, ident, ins);
7896 if (ins->id & TRIPLE_FLAG_FLATTENED) {
7897 error(state, 0, "label %s already defined", ident->name);
7899 flatten(state, first, ins);
7901 eat(state, TOK_COLON);
7902 statement(state, first);
7905 static void switch_statement(struct compile_state *state, struct triple *first)
7908 eat(state, TOK_SWITCH);
7909 eat(state, TOK_LPAREN);
7911 eat(state, TOK_RPAREN);
7912 statement(state, first);
7913 error(state, 0, "switch statements are not implemented");
7917 static void case_statement(struct compile_state *state, struct triple *first)
7920 eat(state, TOK_CASE);
7921 constant_expr(state);
7922 eat(state, TOK_COLON);
7923 statement(state, first);
7924 error(state, 0, "case statements are not implemented");
7928 static void default_statement(struct compile_state *state, struct triple *first)
7931 eat(state, TOK_DEFAULT);
7932 eat(state, TOK_COLON);
7933 statement(state, first);
7934 error(state, 0, "default statements are not implemented");
7938 static void asm_statement(struct compile_state *state, struct triple *first)
7940 struct asm_info *info;
7942 struct triple *constraint;
7943 struct triple *expr;
7944 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7945 struct triple *def, *asm_str;
7946 int out, in, clobbers, more, colons, i;
7948 eat(state, TOK_ASM);
7949 /* For now ignore the qualifiers */
7950 switch(peek(state)) {
7952 eat(state, TOK_CONST);
7955 eat(state, TOK_VOLATILE);
7958 eat(state, TOK_LPAREN);
7959 asm_str = string_constant(state);
7962 out = in = clobbers = 0;
7964 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7965 eat(state, TOK_COLON);
7967 more = (peek(state) == TOK_LIT_STRING);
7970 struct triple *constraint;
7973 if (out > MAX_LHS) {
7974 error(state, 0, "Maximum output count exceeded.");
7976 constraint = string_constant(state);
7977 str = constraint->u.blob;
7978 if (str[0] != '=') {
7979 error(state, 0, "Output constraint does not start with =");
7981 constraint->u.blob = str + 1;
7982 eat(state, TOK_LPAREN);
7983 var = conditional_expr(state);
7984 eat(state, TOK_RPAREN);
7987 out_param[out].constraint = constraint;
7988 out_param[out].expr = var;
7989 if (peek(state) == TOK_COMMA) {
7990 eat(state, TOK_COMMA);
7997 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7998 eat(state, TOK_COLON);
8000 more = (peek(state) == TOK_LIT_STRING);
8003 struct triple *constraint;
8007 error(state, 0, "Maximum input count exceeded.");
8009 constraint = string_constant(state);
8010 str = constraint->u.blob;
8011 if (digitp(str[0] && str[1] == '\0')) {
8013 val = digval(str[0]);
8014 if ((val < 0) || (val >= out)) {
8015 error(state, 0, "Invalid input constraint %d", val);
8018 eat(state, TOK_LPAREN);
8019 val = conditional_expr(state);
8020 eat(state, TOK_RPAREN);
8022 in_param[in].constraint = constraint;
8023 in_param[in].expr = val;
8024 if (peek(state) == TOK_COMMA) {
8025 eat(state, TOK_COMMA);
8033 if ((colons == 2) && (peek(state) == TOK_COLON)) {
8034 eat(state, TOK_COLON);
8036 more = (peek(state) == TOK_LIT_STRING);
8038 struct triple *clobber;
8040 if ((clobbers + out) > MAX_LHS) {
8041 error(state, 0, "Maximum clobber limit exceeded.");
8043 clobber = string_constant(state);
8044 eat(state, TOK_RPAREN);
8046 clob_param[clobbers].constraint = clobber;
8047 if (peek(state) == TOK_COMMA) {
8048 eat(state, TOK_COMMA);
8054 eat(state, TOK_RPAREN);
8055 eat(state, TOK_SEMI);
8058 info = xcmalloc(sizeof(*info), "asm_info");
8059 info->str = asm_str->u.blob;
8060 free_triple(state, asm_str);
8062 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8063 def->u.ainfo = info;
8065 /* Find the register constraints */
8066 for(i = 0; i < out; i++) {
8067 struct triple *constraint;
8068 constraint = out_param[i].constraint;
8069 info->tmpl.lhs[i] = arch_reg_constraint(state,
8070 out_param[i].expr->type, constraint->u.blob);
8071 free_triple(state, constraint);
8073 for(; i - out < clobbers; i++) {
8074 struct triple *constraint;
8075 constraint = clob_param[i - out].constraint;
8076 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8077 free_triple(state, constraint);
8079 for(i = 0; i < in; i++) {
8080 struct triple *constraint;
8082 constraint = in_param[i].constraint;
8083 str = constraint->u.blob;
8084 if (digitp(str[0]) && str[1] == '\0') {
8085 struct reg_info cinfo;
8087 val = digval(str[0]);
8088 cinfo.reg = info->tmpl.lhs[val].reg;
8089 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8090 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8091 if (cinfo.reg == REG_UNSET) {
8092 cinfo.reg = REG_VIRT0 + val;
8094 if (cinfo.regcm == 0) {
8095 error(state, 0, "No registers for %d", val);
8097 info->tmpl.lhs[val] = cinfo;
8098 info->tmpl.rhs[i] = cinfo;
8101 info->tmpl.rhs[i] = arch_reg_constraint(state,
8102 in_param[i].expr->type, str);
8104 free_triple(state, constraint);
8107 /* Now build the helper expressions */
8108 for(i = 0; i < in; i++) {
8109 RHS(def, i) = read_expr(state,in_param[i].expr);
8111 flatten(state, first, def);
8112 for(i = 0; i < out; i++) {
8113 struct triple *piece;
8114 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8116 LHS(def, i) = piece;
8117 flatten(state, first,
8118 write_expr(state, out_param[i].expr, piece));
8120 for(; i - out < clobbers; i++) {
8121 struct triple *piece;
8122 piece = triple(state, OP_PIECE, &void_type, def, 0);
8124 LHS(def, i) = piece;
8125 flatten(state, first, piece);
8130 static int isdecl(int tok)
8153 case TOK_TYPE_NAME: /* typedef name */
8160 static void compound_statement(struct compile_state *state, struct triple *first)
8162 eat(state, TOK_LBRACE);
8165 /* statement-list opt */
8166 while (peek(state) != TOK_RBRACE) {
8167 statement(state, first);
8170 eat(state, TOK_RBRACE);
8173 static void statement(struct compile_state *state, struct triple *first)
8177 if (tok == TOK_LBRACE) {
8178 compound_statement(state, first);
8180 else if (tok == TOK_IF) {
8181 if_statement(state, first);
8183 else if (tok == TOK_FOR) {
8184 for_statement(state, first);
8186 else if (tok == TOK_WHILE) {
8187 while_statement(state, first);
8189 else if (tok == TOK_DO) {
8190 do_statement(state, first);
8192 else if (tok == TOK_RETURN) {
8193 return_statement(state, first);
8195 else if (tok == TOK_BREAK) {
8196 break_statement(state, first);
8198 else if (tok == TOK_CONTINUE) {
8199 continue_statement(state, first);
8201 else if (tok == TOK_GOTO) {
8202 goto_statement(state, first);
8204 else if (tok == TOK_SWITCH) {
8205 switch_statement(state, first);
8207 else if (tok == TOK_ASM) {
8208 asm_statement(state, first);
8210 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8211 labeled_statement(state, first);
8213 else if (tok == TOK_CASE) {
8214 case_statement(state, first);
8216 else if (tok == TOK_DEFAULT) {
8217 default_statement(state, first);
8219 else if (isdecl(tok)) {
8220 /* This handles C99 intermixing of statements and decls */
8224 expr_statement(state, first);
8228 static struct type *param_decl(struct compile_state *state)
8231 struct hash_entry *ident;
8232 /* Cheat so the declarator will know we are not global */
8235 type = decl_specifiers(state);
8236 type = declarator(state, type, &ident, 0);
8237 type->field_ident = ident;
8242 static struct type *param_type_list(struct compile_state *state, struct type *type)
8244 struct type *ftype, **next;
8245 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8246 next = &ftype->right;
8247 while(peek(state) == TOK_COMMA) {
8248 eat(state, TOK_COMMA);
8249 if (peek(state) == TOK_DOTS) {
8250 eat(state, TOK_DOTS);
8251 error(state, 0, "variadic functions not supported");
8254 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8255 next = &((*next)->right);
8262 static struct type *type_name(struct compile_state *state)
8265 type = specifier_qualifier_list(state);
8266 /* abstract-declarator (may consume no tokens) */
8267 type = declarator(state, type, 0, 0);
8271 static struct type *direct_declarator(
8272 struct compile_state *state, struct type *type,
8273 struct hash_entry **ident, int need_ident)
8278 arrays_complete(state, type);
8279 switch(peek(state)) {
8281 eat(state, TOK_IDENT);
8283 error(state, 0, "Unexpected identifier found");
8285 /* The name of what we are declaring */
8286 *ident = state->token[0].ident;
8289 eat(state, TOK_LPAREN);
8290 outer = declarator(state, type, ident, need_ident);
8291 eat(state, TOK_RPAREN);
8295 error(state, 0, "Identifier expected");
8301 arrays_complete(state, type);
8302 switch(peek(state)) {
8304 eat(state, TOK_LPAREN);
8305 type = param_type_list(state, type);
8306 eat(state, TOK_RPAREN);
8310 unsigned int qualifiers;
8311 struct triple *value;
8313 eat(state, TOK_LBRACKET);
8314 if (peek(state) != TOK_RBRACKET) {
8315 value = constant_expr(state);
8316 integral(state, value);
8318 eat(state, TOK_RBRACKET);
8320 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8321 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8323 type->elements = value->u.cval;
8324 free_triple(state, value);
8326 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8338 arrays_complete(state, type);
8340 for(inner = outer; inner->left; inner = inner->left)
8348 static struct type *declarator(
8349 struct compile_state *state, struct type *type,
8350 struct hash_entry **ident, int need_ident)
8352 while(peek(state) == TOK_STAR) {
8353 eat(state, TOK_STAR);
8354 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8356 type = direct_declarator(state, type, ident, need_ident);
8361 static struct type *typedef_name(
8362 struct compile_state *state, unsigned int specifiers)
8364 struct hash_entry *ident;
8366 eat(state, TOK_TYPE_NAME);
8367 ident = state->token[0].ident;
8368 type = ident->sym_ident->type;
8369 specifiers |= type->type & QUAL_MASK;
8370 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8371 (type->type & (STOR_MASK | QUAL_MASK))) {
8372 type = clone_type(specifiers, type);
8377 static struct type *enum_specifier(
8378 struct compile_state *state, unsigned int specifiers)
8384 eat(state, TOK_ENUM);
8386 if (tok == TOK_IDENT) {
8387 eat(state, TOK_IDENT);
8389 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8390 eat(state, TOK_LBRACE);
8392 eat(state, TOK_IDENT);
8393 if (peek(state) == TOK_EQ) {
8395 constant_expr(state);
8397 if (peek(state) == TOK_COMMA) {
8398 eat(state, TOK_COMMA);
8400 } while(peek(state) != TOK_RBRACE);
8401 eat(state, TOK_RBRACE);
8408 static struct type *struct_declarator(
8409 struct compile_state *state, struct type *type, struct hash_entry **ident)
8412 #warning "struct_declarator is complicated because of bitfields, kill them?"
8414 if (tok != TOK_COLON) {
8415 type = declarator(state, type, ident, 1);
8417 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8418 eat(state, TOK_COLON);
8419 constant_expr(state);
8426 static struct type *struct_or_union_specifier(
8427 struct compile_state *state, unsigned int spec)
8429 struct type *struct_type;
8430 struct hash_entry *ident;
8431 unsigned int type_join;
8435 switch(peek(state)) {
8437 eat(state, TOK_STRUCT);
8438 type_join = TYPE_PRODUCT;
8441 eat(state, TOK_UNION);
8442 type_join = TYPE_OVERLAP;
8443 error(state, 0, "unions not yet supported\n");
8446 eat(state, TOK_STRUCT);
8447 type_join = TYPE_PRODUCT;
8451 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8453 ident = state->token[0].ident;
8455 if (!ident || (peek(state) == TOK_LBRACE)) {
8459 eat(state, TOK_LBRACE);
8460 next = &struct_type;
8462 struct type *base_type;
8464 base_type = specifier_qualifier_list(state);
8467 struct hash_entry *fident;
8469 type = declarator(state, base_type, &fident, 1);
8471 if (peek(state) == TOK_COMMA) {
8473 eat(state, TOK_COMMA);
8475 type = clone_type(0, type);
8476 type->field_ident = fident;
8478 *next = new_type(type_join, *next, type);
8479 next = &((*next)->right);
8484 eat(state, TOK_SEMI);
8485 } while(peek(state) != TOK_RBRACE);
8486 eat(state, TOK_RBRACE);
8487 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8488 struct_type->type_ident = ident;
8489 struct_type->elements = elements;
8490 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8492 if (ident && ident->sym_struct) {
8493 struct_type = clone_type(spec, ident->sym_struct->type);
8495 else if (ident && !ident->sym_struct) {
8496 error(state, 0, "struct %s undeclared", ident->name);
8501 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8503 unsigned int specifiers;
8504 switch(peek(state)) {
8506 eat(state, TOK_AUTO);
8507 specifiers = STOR_AUTO;
8510 eat(state, TOK_REGISTER);
8511 specifiers = STOR_REGISTER;
8514 eat(state, TOK_STATIC);
8515 specifiers = STOR_STATIC;
8518 eat(state, TOK_EXTERN);
8519 specifiers = STOR_EXTERN;
8522 eat(state, TOK_TYPEDEF);
8523 specifiers = STOR_TYPEDEF;
8526 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8527 specifiers = STOR_STATIC;
8530 specifiers = STOR_AUTO;
8536 static unsigned int function_specifier_opt(struct compile_state *state)
8538 /* Ignore the inline keyword */
8539 unsigned int specifiers;
8541 switch(peek(state)) {
8543 eat(state, TOK_INLINE);
8544 specifiers = STOR_INLINE;
8549 static unsigned int type_qualifiers(struct compile_state *state)
8551 unsigned int specifiers;
8554 specifiers = QUAL_NONE;
8556 switch(peek(state)) {
8558 eat(state, TOK_CONST);
8559 specifiers = QUAL_CONST;
8562 eat(state, TOK_VOLATILE);
8563 specifiers = QUAL_VOLATILE;
8566 eat(state, TOK_RESTRICT);
8567 specifiers = QUAL_RESTRICT;
8577 static struct type *type_specifier(
8578 struct compile_state *state, unsigned int spec)
8582 switch(peek(state)) {
8584 eat(state, TOK_VOID);
8585 type = new_type(TYPE_VOID | spec, 0, 0);
8588 eat(state, TOK_CHAR);
8589 type = new_type(TYPE_CHAR | spec, 0, 0);
8592 eat(state, TOK_SHORT);
8593 if (peek(state) == TOK_INT) {
8594 eat(state, TOK_INT);
8596 type = new_type(TYPE_SHORT | spec, 0, 0);
8599 eat(state, TOK_INT);
8600 type = new_type(TYPE_INT | spec, 0, 0);
8603 eat(state, TOK_LONG);
8604 switch(peek(state)) {
8606 eat(state, TOK_LONG);
8607 error(state, 0, "long long not supported");
8610 eat(state, TOK_DOUBLE);
8611 error(state, 0, "long double not supported");
8614 eat(state, TOK_INT);
8615 type = new_type(TYPE_LONG | spec, 0, 0);
8618 type = new_type(TYPE_LONG | spec, 0, 0);
8623 eat(state, TOK_FLOAT);
8624 error(state, 0, "type float not supported");
8627 eat(state, TOK_DOUBLE);
8628 error(state, 0, "type double not supported");
8631 eat(state, TOK_SIGNED);
8632 switch(peek(state)) {
8634 eat(state, TOK_LONG);
8635 switch(peek(state)) {
8637 eat(state, TOK_LONG);
8638 error(state, 0, "type long long not supported");
8641 eat(state, TOK_INT);
8642 type = new_type(TYPE_LONG | spec, 0, 0);
8645 type = new_type(TYPE_LONG | spec, 0, 0);
8650 eat(state, TOK_INT);
8651 type = new_type(TYPE_INT | spec, 0, 0);
8654 eat(state, TOK_SHORT);
8655 type = new_type(TYPE_SHORT | spec, 0, 0);
8658 eat(state, TOK_CHAR);
8659 type = new_type(TYPE_CHAR | spec, 0, 0);
8662 type = new_type(TYPE_INT | spec, 0, 0);
8667 eat(state, TOK_UNSIGNED);
8668 switch(peek(state)) {
8670 eat(state, TOK_LONG);
8671 switch(peek(state)) {
8673 eat(state, TOK_LONG);
8674 error(state, 0, "unsigned long long not supported");
8677 eat(state, TOK_INT);
8678 type = new_type(TYPE_ULONG | spec, 0, 0);
8681 type = new_type(TYPE_ULONG | spec, 0, 0);
8686 eat(state, TOK_INT);
8687 type = new_type(TYPE_UINT | spec, 0, 0);
8690 eat(state, TOK_SHORT);
8691 type = new_type(TYPE_USHORT | spec, 0, 0);
8694 eat(state, TOK_CHAR);
8695 type = new_type(TYPE_UCHAR | spec, 0, 0);
8698 type = new_type(TYPE_UINT | spec, 0, 0);
8702 /* struct or union specifier */
8705 type = struct_or_union_specifier(state, spec);
8707 /* enum-spefifier */
8709 type = enum_specifier(state, spec);
8713 type = typedef_name(state, spec);
8716 error(state, 0, "bad type specifier %s",
8717 tokens[peek(state)]);
8723 static int istype(int tok)
8749 static struct type *specifier_qualifier_list(struct compile_state *state)
8752 unsigned int specifiers = 0;
8754 /* type qualifiers */
8755 specifiers |= type_qualifiers(state);
8757 /* type specifier */
8758 type = type_specifier(state, specifiers);
8763 static int isdecl_specifier(int tok)
8766 /* storage class specifier */
8772 /* type qualifier */
8776 /* type specifiers */
8786 /* struct or union specifier */
8789 /* enum-spefifier */
8793 /* function specifiers */
8801 static struct type *decl_specifiers(struct compile_state *state)
8804 unsigned int specifiers;
8805 /* I am overly restrictive in the arragement of specifiers supported.
8806 * C is overly flexible in this department it makes interpreting
8807 * the parse tree difficult.
8811 /* storage class specifier */
8812 specifiers |= storage_class_specifier_opt(state);
8814 /* function-specifier */
8815 specifiers |= function_specifier_opt(state);
8817 /* type qualifier */
8818 specifiers |= type_qualifiers(state);
8820 /* type specifier */
8821 type = type_specifier(state, specifiers);
8830 static struct field_info designator(struct compile_state *state, struct type *type)
8833 struct field_info info;
8837 switch(peek(state)) {
8840 struct triple *value;
8841 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8842 error(state, 0, "Array designator not in array initializer");
8844 eat(state, TOK_LBRACKET);
8845 value = constant_expr(state);
8846 eat(state, TOK_RBRACKET);
8848 info.type = type->left;
8849 info.offset = value->u.cval * size_of(state, info.type);
8854 struct hash_entry *field;
8855 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8856 error(state, 0, "Struct designator not in struct initializer");
8858 eat(state, TOK_DOT);
8859 eat(state, TOK_IDENT);
8860 field = state->token[0].ident;
8861 info.offset = field_offset(state, type, field);
8862 info.type = field_type(state, type, field);
8866 error(state, 0, "Invalid designator");
8869 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8874 static struct triple *initializer(
8875 struct compile_state *state, struct type *type)
8877 struct triple *result;
8878 if (peek(state) != TOK_LBRACE) {
8879 result = assignment_expr(state);
8884 struct field_info info;
8886 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8887 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8888 internal_error(state, 0, "unknown initializer type");
8891 info.type = type->left;
8892 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8893 info.type = next_field(state, type, 0);
8895 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8898 max_offset = size_of(state, type);
8900 buf = xcmalloc(max_offset, "initializer");
8901 eat(state, TOK_LBRACE);
8903 struct triple *value;
8904 struct type *value_type;
8910 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8911 info = designator(state, type);
8913 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8914 (info.offset >= max_offset)) {
8915 error(state, 0, "element beyond bounds");
8917 value_type = info.type;
8918 value = eval_const_expr(state, initializer(state, value_type));
8919 value_size = size_of(state, value_type);
8920 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8921 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8922 (max_offset <= info.offset)) {
8926 old_size = max_offset;
8927 max_offset = info.offset + value_size;
8928 buf = xmalloc(max_offset, "initializer");
8929 memcpy(buf, old_buf, old_size);
8932 dest = ((char *)buf) + info.offset;
8933 if (value->op == OP_BLOBCONST) {
8934 memcpy(dest, value->u.blob, value_size);
8936 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8937 *((uint8_t *)dest) = value->u.cval & 0xff;
8939 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8940 *((uint16_t *)dest) = value->u.cval & 0xffff;
8942 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8943 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8946 internal_error(state, 0, "unhandled constant initializer");
8948 free_triple(state, value);
8949 if (peek(state) == TOK_COMMA) {
8950 eat(state, TOK_COMMA);
8953 info.offset += value_size;
8954 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8955 info.type = next_field(state, type, info.type);
8956 info.offset = field_offset(state, type,
8957 info.type->field_ident);
8959 } while(comma && (peek(state) != TOK_RBRACE));
8960 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8961 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8962 type->elements = max_offset / size_of(state, type->left);
8964 eat(state, TOK_RBRACE);
8965 result = triple(state, OP_BLOBCONST, type, 0, 0);
8966 result->u.blob = buf;
8971 static void resolve_branches(struct compile_state *state)
8973 /* Make a second pass and finish anything outstanding
8974 * with respect to branches. The only outstanding item
8975 * is to see if there are goto to labels that have not
8976 * been defined and to error about them.
8979 for(i = 0; i < HASH_TABLE_SIZE; i++) {
8980 struct hash_entry *entry;
8981 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8983 if (!entry->sym_label) {
8986 ins = entry->sym_label->def;
8987 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8988 error(state, ins, "label `%s' used but not defined",
8995 static struct triple *function_definition(
8996 struct compile_state *state, struct type *type)
8998 struct triple *def, *tmp, *first, *end;
8999 struct hash_entry *ident;
9002 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9003 error(state, 0, "Invalid function header");
9006 /* Verify the function type */
9007 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
9008 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9009 (type->right->field_ident == 0)) {
9010 error(state, 0, "Invalid function parameters");
9012 param = type->right;
9014 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9016 if (!param->left->field_ident) {
9017 error(state, 0, "No identifier for parameter %d\n", i);
9019 param = param->right;
9022 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9023 error(state, 0, "No identifier for paramter %d\n", i);
9026 /* Get a list of statements for this function. */
9027 def = triple(state, OP_LIST, type, 0, 0);
9029 /* Start a new scope for the passed parameters */
9032 /* Put a label at the very start of a function */
9033 first = label(state);
9034 RHS(def, 0) = first;
9036 /* Put a label at the very end of a function */
9038 flatten(state, first, end);
9040 /* Walk through the parameters and create symbol table entries
9043 param = type->right;
9044 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9045 ident = param->left->field_ident;
9046 tmp = variable(state, param->left);
9047 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9048 flatten(state, end, tmp);
9049 param = param->right;
9051 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9052 /* And don't forget the last parameter */
9053 ident = param->field_ident;
9054 tmp = variable(state, param);
9055 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9056 flatten(state, end, tmp);
9058 /* Add a variable for the return value */
9060 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9061 /* Remove all type qualifiers from the return type */
9062 tmp = variable(state, clone_type(0, type->left));
9063 flatten(state, end, tmp);
9064 /* Remember where the return value is */
9068 /* Remember which function I am compiling.
9069 * Also assume the last defined function is the main function.
9071 state->main_function = def;
9073 /* Now get the actual function definition */
9074 compound_statement(state, end);
9076 /* Finish anything unfinished with branches */
9077 resolve_branches(state);
9079 /* Remove the parameter scope */
9083 fprintf(stdout, "\n");
9084 loc(stdout, state, 0);
9085 fprintf(stdout, "\n__________ function_definition _________\n");
9086 print_triple(state, def);
9087 fprintf(stdout, "__________ function_definition _________ done\n\n");
9093 static struct triple *do_decl(struct compile_state *state,
9094 struct type *type, struct hash_entry *ident)
9098 /* Clean up the storage types used */
9099 switch (type->type & STOR_MASK) {
9102 /* These are the good types I am aiming for */
9105 type->type &= ~STOR_MASK;
9106 type->type |= STOR_AUTO;
9109 type->type &= ~STOR_MASK;
9110 type->type |= STOR_STATIC;
9114 error(state, 0, "typedef without name");
9116 symbol(state, ident, &ident->sym_ident, 0, type);
9117 ident->tok = TOK_TYPE_NAME;
9121 internal_error(state, 0, "Undefined storage class");
9123 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9124 error(state, 0, "Function prototypes not supported");
9127 ((type->type & STOR_MASK) == STOR_STATIC) &&
9128 ((type->type & QUAL_CONST) == 0)) {
9129 error(state, 0, "non const static variables not supported");
9132 def = variable(state, type);
9133 symbol(state, ident, &ident->sym_ident, def, type);
9138 static void decl(struct compile_state *state, struct triple *first)
9140 struct type *base_type, *type;
9141 struct hash_entry *ident;
9144 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9145 base_type = decl_specifiers(state);
9147 type = declarator(state, base_type, &ident, 0);
9148 if (global && ident && (peek(state) == TOK_LBRACE)) {
9150 state->function = ident->name;
9151 def = function_definition(state, type);
9152 symbol(state, ident, &ident->sym_ident, def, type);
9153 state->function = 0;
9157 flatten(state, first, do_decl(state, type, ident));
9158 /* type or variable definition */
9161 if (peek(state) == TOK_EQ) {
9163 error(state, 0, "cannot assign to a type");
9166 flatten(state, first,
9168 ident->sym_ident->def,
9169 initializer(state, type)));
9171 arrays_complete(state, type);
9172 if (peek(state) == TOK_COMMA) {
9173 eat(state, TOK_COMMA);
9175 type = declarator(state, base_type, &ident, 0);
9176 flatten(state, first, do_decl(state, type, ident));
9180 eat(state, TOK_SEMI);
9184 static void decls(struct compile_state *state)
9186 struct triple *list;
9188 list = label(state);
9191 if (tok == TOK_EOF) {
9194 if (tok == TOK_SPACE) {
9195 eat(state, TOK_SPACE);
9198 if (list->next != list) {
9199 error(state, 0, "global variables not supported");
9205 * Data structurs for optimation.
9208 static void do_use_block(
9209 struct block *used, struct block_set **head, struct block *user,
9212 struct block_set **ptr, *new;
9219 if ((*ptr)->member == user) {
9222 ptr = &(*ptr)->next;
9224 new = xcmalloc(sizeof(*new), "block_set");
9235 static void do_unuse_block(
9236 struct block *used, struct block_set **head, struct block *unuser)
9238 struct block_set *use, **ptr;
9242 if (use->member == unuser) {
9244 memset(use, -1, sizeof(*use));
9253 static void use_block(struct block *used, struct block *user)
9255 /* Append new to the head of the list, print_block
9258 do_use_block(used, &used->use, user, 1);
9261 static void unuse_block(struct block *used, struct block *unuser)
9263 do_unuse_block(used, &used->use, unuser);
9267 static void idom_block(struct block *idom, struct block *user)
9269 do_use_block(idom, &idom->idominates, user, 0);
9272 static void unidom_block(struct block *idom, struct block *unuser)
9274 do_unuse_block(idom, &idom->idominates, unuser);
9277 static void domf_block(struct block *block, struct block *domf)
9279 do_use_block(block, &block->domfrontier, domf, 0);
9282 static void undomf_block(struct block *block, struct block *undomf)
9284 do_unuse_block(block, &block->domfrontier, undomf);
9287 static void ipdom_block(struct block *ipdom, struct block *user)
9289 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9292 static void unipdom_block(struct block *ipdom, struct block *unuser)
9294 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9297 static void ipdomf_block(struct block *block, struct block *ipdomf)
9299 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9302 static void unipdomf_block(struct block *block, struct block *unipdomf)
9304 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9309 static int do_walk_triple(struct compile_state *state,
9310 struct triple *ptr, int depth,
9311 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9314 result = cb(state, ptr, depth);
9315 if ((result == 0) && (ptr->op == OP_LIST)) {
9316 struct triple *list;
9320 result = do_walk_triple(state, ptr, depth + 1, cb);
9321 if (ptr->next->prev != ptr) {
9322 internal_error(state, ptr->next, "bad prev");
9326 } while((result == 0) && (ptr != RHS(list, 0)));
9331 static int walk_triple(
9332 struct compile_state *state,
9334 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9336 return do_walk_triple(state, ptr, 0, cb);
9339 static void do_print_prefix(int depth)
9342 for(i = 0; i < depth; i++) {
9347 #define PRINT_LIST 1
9348 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9352 if (op == OP_LIST) {
9357 if ((op == OP_LABEL) && (ins->use)) {
9358 printf("\n%p:\n", ins);
9360 do_print_prefix(depth);
9361 display_triple(stdout, ins);
9363 if ((ins->op == OP_BRANCH) && ins->use) {
9364 internal_error(state, ins, "branch used?");
9368 struct triple_set *user;
9369 for(user = ins->use; user; user = user->next) {
9370 printf("use: %p\n", user->member);
9374 if (triple_is_branch(state, ins)) {
9380 static void print_triple(struct compile_state *state, struct triple *ins)
9382 walk_triple(state, ins, do_print_triple);
9385 static void print_triples(struct compile_state *state)
9387 print_triple(state, state->main_function);
9391 struct block *block;
9393 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9395 if (!block || (cf[block->vertex].block == block)) {
9398 cf[block->vertex].block = block;
9399 find_cf_blocks(cf, block->left);
9400 find_cf_blocks(cf, block->right);
9403 static void print_control_flow(struct compile_state *state)
9405 struct cf_block *cf;
9407 printf("\ncontrol flow\n");
9408 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9409 find_cf_blocks(cf, state->first_block);
9411 for(i = 1; i <= state->last_vertex; i++) {
9412 struct block *block;
9413 block = cf[i].block;
9416 printf("(%p) %d:", block, block->vertex);
9418 printf(" %d", block->left->vertex);
9420 if (block->right && (block->right != block->left)) {
9421 printf(" %d", block->right->vertex);
9430 static struct block *basic_block(struct compile_state *state,
9431 struct triple *first)
9433 struct block *block;
9436 if (first->op != OP_LABEL) {
9437 internal_error(state, 0, "block does not start with a label");
9439 /* See if this basic block has already been setup */
9440 if (first->u.block != 0) {
9441 return first->u.block;
9443 /* Allocate another basic block structure */
9444 state->last_vertex += 1;
9445 block = xcmalloc(sizeof(*block), "block");
9446 block->first = block->last = first;
9447 block->vertex = state->last_vertex;
9450 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9454 /* If ptr->u is not used remember where the baic block is */
9455 if (triple_stores_block(state, ptr)) {
9456 ptr->u.block = block;
9458 if (ptr->op == OP_BRANCH) {
9462 } while (ptr != RHS(state->main_function, 0));
9463 if (ptr == RHS(state->main_function, 0))
9466 if (op == OP_LABEL) {
9467 block->left = basic_block(state, ptr);
9469 use_block(block->left, block);
9471 else if (op == OP_BRANCH) {
9473 /* Trace the branch target */
9474 block->right = basic_block(state, TARG(ptr, 0));
9475 use_block(block->right, block);
9476 /* If there is a test trace the branch as well */
9477 if (TRIPLE_RHS(ptr->sizes)) {
9478 block->left = basic_block(state, ptr->next);
9479 use_block(block->left, block);
9483 internal_error(state, 0, "Bad basic block split");
9489 static void walk_blocks(struct compile_state *state,
9490 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9493 struct triple *ptr, *first;
9494 struct block *last_block;
9496 first = RHS(state->main_function, 0);
9499 struct block *block;
9500 if (ptr->op == OP_LABEL) {
9501 block = ptr->u.block;
9502 if (block && (block != last_block)) {
9503 cb(state, block, arg);
9508 } while(ptr != first);
9511 static void print_block(
9512 struct compile_state *state, struct block *block, void *arg)
9517 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9521 block->left && block->left->use?block->left->use->member : 0,
9523 block->right && block->right->use?block->right->use->member : 0);
9524 if (block->first->op == OP_LABEL) {
9525 fprintf(fp, "%p:\n", block->first);
9527 for(ptr = block->first; ; ptr = ptr->next) {
9528 struct triple_set *user;
9531 if (triple_stores_block(state, ptr)) {
9532 if (ptr->u.block != block) {
9533 internal_error(state, ptr,
9534 "Wrong block pointer: %p\n",
9538 if (op == OP_ADECL) {
9539 for(user = ptr->use; user; user = user->next) {
9540 if (!user->member->u.block) {
9541 internal_error(state, user->member,
9542 "Use %p not in a block?\n",
9547 display_triple(fp, ptr);
9550 for(user = ptr->use; user; user = user->next) {
9551 fprintf(fp, "use: %p\n", user->member);
9555 /* Sanity checks... */
9556 valid_ins(state, ptr);
9557 for(user = ptr->use; user; user = user->next) {
9560 valid_ins(state, use);
9561 if (triple_stores_block(state, user->member) &&
9562 !user->member->u.block) {
9563 internal_error(state, user->member,
9564 "Use %p not in a block?",
9569 if (ptr == block->last)
9576 static void print_blocks(struct compile_state *state, FILE *fp)
9578 fprintf(fp, "--------------- blocks ---------------\n");
9579 walk_blocks(state, print_block, fp);
9582 static void prune_nonblock_triples(struct compile_state *state)
9584 struct block *block;
9585 struct triple *first, *ins, *next;
9586 /* Delete the triples not in a basic block */
9587 first = RHS(state->main_function, 0);
9592 if (ins->op == OP_LABEL) {
9593 block = ins->u.block;
9596 release_triple(state, ins);
9599 } while(ins != first);
9602 static void setup_basic_blocks(struct compile_state *state)
9604 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9605 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9606 internal_error(state, 0, "ins will not store block?");
9608 /* Find the basic blocks */
9609 state->last_vertex = 0;
9610 state->first_block = basic_block(state, RHS(state->main_function,0));
9611 /* Delete the triples not in a basic block */
9612 prune_nonblock_triples(state);
9613 /* Find the last basic block */
9614 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9615 if (!state->last_block) {
9616 internal_error(state, 0, "end not used?");
9618 /* Insert an extra unused edge from start to the end
9619 * This helps with reverse control flow calculations.
9621 use_block(state->first_block, state->last_block);
9622 /* If we are debugging print what I have just done */
9623 if (state->debug & DEBUG_BASIC_BLOCKS) {
9624 print_blocks(state, stdout);
9625 print_control_flow(state);
9629 static void free_basic_block(struct compile_state *state, struct block *block)
9631 struct block_set *entry, *next;
9632 struct block *child;
9636 if (block->vertex == -1) {
9641 unuse_block(block->left, block);
9644 unuse_block(block->right, block);
9647 unidom_block(block->idom, block);
9651 unipdom_block(block->ipdom, block);
9654 for(entry = block->use; entry; entry = next) {
9656 child = entry->member;
9657 unuse_block(block, child);
9658 if (child->left == block) {
9661 if (child->right == block) {
9665 for(entry = block->idominates; entry; entry = next) {
9667 child = entry->member;
9668 unidom_block(block, child);
9671 for(entry = block->domfrontier; entry; entry = next) {
9673 child = entry->member;
9674 undomf_block(block, child);
9676 for(entry = block->ipdominates; entry; entry = next) {
9678 child = entry->member;
9679 unipdom_block(block, child);
9682 for(entry = block->ipdomfrontier; entry; entry = next) {
9684 child = entry->member;
9685 unipdomf_block(block, child);
9687 if (block->users != 0) {
9688 internal_error(state, 0, "block still has users");
9690 free_basic_block(state, block->left);
9692 free_basic_block(state, block->right);
9694 memset(block, -1, sizeof(*block));
9698 static void free_basic_blocks(struct compile_state *state)
9700 struct triple *first, *ins;
9701 free_basic_block(state, state->first_block);
9702 state->last_vertex = 0;
9703 state->first_block = state->last_block = 0;
9704 first = RHS(state->main_function, 0);
9707 if (triple_stores_block(state, ins)) {
9711 } while(ins != first);
9716 struct block *block;
9717 struct sdom_block *sdominates;
9718 struct sdom_block *sdom_next;
9719 struct sdom_block *sdom;
9720 struct sdom_block *label;
9721 struct sdom_block *parent;
9722 struct sdom_block *ancestor;
9727 static void unsdom_block(struct sdom_block *block)
9729 struct sdom_block **ptr;
9730 if (!block->sdom_next) {
9733 ptr = &block->sdom->sdominates;
9735 if ((*ptr) == block) {
9736 *ptr = block->sdom_next;
9739 ptr = &(*ptr)->sdom_next;
9743 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9745 unsdom_block(block);
9747 block->sdom_next = sdom->sdominates;
9748 sdom->sdominates = block;
9753 static int initialize_sdblock(struct sdom_block *sd,
9754 struct block *parent, struct block *block, int vertex)
9756 if (!block || (sd[block->vertex].block == block)) {
9760 /* Renumber the blocks in a convinient fashion */
9761 block->vertex = vertex;
9762 sd[vertex].block = block;
9763 sd[vertex].sdom = &sd[vertex];
9764 sd[vertex].label = &sd[vertex];
9765 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9766 sd[vertex].ancestor = 0;
9767 sd[vertex].vertex = vertex;
9768 vertex = initialize_sdblock(sd, block, block->left, vertex);
9769 vertex = initialize_sdblock(sd, block, block->right, vertex);
9773 static int initialize_sdpblock(struct sdom_block *sd,
9774 struct block *parent, struct block *block, int vertex)
9776 struct block_set *user;
9777 if (!block || (sd[block->vertex].block == block)) {
9781 /* Renumber the blocks in a convinient fashion */
9782 block->vertex = vertex;
9783 sd[vertex].block = block;
9784 sd[vertex].sdom = &sd[vertex];
9785 sd[vertex].label = &sd[vertex];
9786 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9787 sd[vertex].ancestor = 0;
9788 sd[vertex].vertex = vertex;
9789 for(user = block->use; user; user = user->next) {
9790 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9795 static void compress_ancestors(struct sdom_block *v)
9797 /* This procedure assumes ancestor(v) != 0 */
9798 /* if (ancestor(ancestor(v)) != 0) {
9799 * compress(ancestor(ancestor(v)));
9800 * if (semi(label(ancestor(v))) < semi(label(v))) {
9801 * label(v) = label(ancestor(v));
9803 * ancestor(v) = ancestor(ancestor(v));
9809 if (v->ancestor->ancestor) {
9810 compress_ancestors(v->ancestor->ancestor);
9811 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9812 v->label = v->ancestor->label;
9814 v->ancestor = v->ancestor->ancestor;
9818 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9822 * for each v <= pred(w) {
9824 * if (semi[u] < semi[w] {
9825 * semi[w] = semi[u];
9828 * add w to bucket(vertex(semi[w]));
9829 * LINK(parent(w), w);
9832 * for each v <= bucket(parent(w)) {
9833 * delete v from bucket(parent(w));
9835 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9838 for(i = state->last_vertex; i >= 2; i--) {
9839 struct sdom_block *v, *parent, *next;
9840 struct block_set *user;
9841 struct block *block;
9842 block = sd[i].block;
9843 parent = sd[i].parent;
9845 for(user = block->use; user; user = user->next) {
9846 struct sdom_block *v, *u;
9847 v = &sd[user->member->vertex];
9848 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9849 if (u->sdom->vertex < sd[i].sdom->vertex) {
9850 sd[i].sdom = u->sdom;
9853 sdom_block(sd[i].sdom, &sd[i]);
9854 sd[i].ancestor = parent;
9856 for(v = parent->sdominates; v; v = next) {
9857 struct sdom_block *u;
9858 next = v->sdom_next;
9860 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9861 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9862 u->block : parent->block;
9867 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9871 * for each v <= pred(w) {
9873 * if (semi[u] < semi[w] {
9874 * semi[w] = semi[u];
9877 * add w to bucket(vertex(semi[w]));
9878 * LINK(parent(w), w);
9881 * for each v <= bucket(parent(w)) {
9882 * delete v from bucket(parent(w));
9884 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9887 for(i = state->last_vertex; i >= 2; i--) {
9888 struct sdom_block *u, *v, *parent, *next;
9889 struct block *block;
9890 block = sd[i].block;
9891 parent = sd[i].parent;
9894 v = &sd[block->left->vertex];
9895 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9896 if (u->sdom->vertex < sd[i].sdom->vertex) {
9897 sd[i].sdom = u->sdom;
9900 if (block->right && (block->right != block->left)) {
9901 v = &sd[block->right->vertex];
9902 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9903 if (u->sdom->vertex < sd[i].sdom->vertex) {
9904 sd[i].sdom = u->sdom;
9907 sdom_block(sd[i].sdom, &sd[i]);
9908 sd[i].ancestor = parent;
9910 for(v = parent->sdominates; v; v = next) {
9911 struct sdom_block *u;
9912 next = v->sdom_next;
9914 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9915 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9916 u->block : parent->block;
9921 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9924 for(i = 2; i <= state->last_vertex; i++) {
9925 struct block *block;
9926 block = sd[i].block;
9927 if (block->idom->vertex != sd[i].sdom->vertex) {
9928 block->idom = block->idom->idom;
9930 idom_block(block->idom, block);
9932 sd[1].block->idom = 0;
9935 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9938 for(i = 2; i <= state->last_vertex; i++) {
9939 struct block *block;
9940 block = sd[i].block;
9941 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9942 block->ipdom = block->ipdom->ipdom;
9944 ipdom_block(block->ipdom, block);
9946 sd[1].block->ipdom = 0;
9950 * Every vertex of a flowgraph G = (V, E, r) except r has
9951 * a unique immediate dominator.
9952 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9953 * rooted at r, called the dominator tree of G, such that
9954 * v dominates w if and only if v is a proper ancestor of w in
9955 * the dominator tree.
9958 * If v and w are vertices of G such that v <= w,
9959 * than any path from v to w must contain a common ancestor
9962 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9963 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9964 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9966 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9967 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9970 * Let w != r and let u be a vertex for which sdom(u) is
9971 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9972 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9974 /* Lemma 5: Let vertices v,w satisfy v -> w.
9975 * Then v -> idom(w) or idom(w) -> idom(v)
9978 static void find_immediate_dominators(struct compile_state *state)
9980 struct sdom_block *sd;
9981 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9982 * vi > w for (1 <= i <= k - 1}
9985 * For any vertex w != r.
9987 * {v|(v,w) <= E and v < w } U
9988 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9991 * Let w != r and let u be a vertex for which sdom(u) is
9992 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9994 * { sdom(w) if sdom(w) = sdom(u),
9996 * { idom(u) otherwise
9998 /* The algorithm consists of the following 4 steps.
9999 * Step 1. Carry out a depth-first search of the problem graph.
10000 * Number the vertices from 1 to N as they are reached during
10001 * the search. Initialize the variables used in succeeding steps.
10002 * Step 2. Compute the semidominators of all vertices by applying
10003 * theorem 4. Carry out the computation vertex by vertex in
10004 * decreasing order by number.
10005 * Step 3. Implicitly define the immediate dominator of each vertex
10006 * by applying Corollary 1.
10007 * Step 4. Explicitly define the immediate dominator of each vertex,
10008 * carrying out the computation vertex by vertex in increasing order
10011 /* Step 1 initialize the basic block information */
10012 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10013 initialize_sdblock(sd, 0, state->first_block, 0);
10019 /* Step 2 compute the semidominators */
10020 /* Step 3 implicitly define the immediate dominator of each vertex */
10021 compute_sdom(state, sd);
10022 /* Step 4 explicitly define the immediate dominator of each vertex */
10023 compute_idom(state, sd);
10027 static void find_post_dominators(struct compile_state *state)
10029 struct sdom_block *sd;
10030 /* Step 1 initialize the basic block information */
10031 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10033 initialize_sdpblock(sd, 0, state->last_block, 0);
10035 /* Step 2 compute the semidominators */
10036 /* Step 3 implicitly define the immediate dominator of each vertex */
10037 compute_spdom(state, sd);
10038 /* Step 4 explicitly define the immediate dominator of each vertex */
10039 compute_ipdom(state, sd);
10045 static void find_block_domf(struct compile_state *state, struct block *block)
10047 struct block *child;
10048 struct block_set *user;
10049 if (block->domfrontier != 0) {
10050 internal_error(state, block->first, "domfrontier present?");
10052 for(user = block->idominates; user; user = user->next) {
10053 child = user->member;
10054 if (child->idom != block) {
10055 internal_error(state, block->first, "bad idom");
10057 find_block_domf(state, child);
10059 if (block->left && block->left->idom != block) {
10060 domf_block(block, block->left);
10062 if (block->right && block->right->idom != block) {
10063 domf_block(block, block->right);
10065 for(user = block->idominates; user; user = user->next) {
10066 struct block_set *frontier;
10067 child = user->member;
10068 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10069 if (frontier->member->idom != block) {
10070 domf_block(block, frontier->member);
10076 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10078 struct block *child;
10079 struct block_set *user;
10080 if (block->ipdomfrontier != 0) {
10081 internal_error(state, block->first, "ipdomfrontier present?");
10083 for(user = block->ipdominates; user; user = user->next) {
10084 child = user->member;
10085 if (child->ipdom != block) {
10086 internal_error(state, block->first, "bad ipdom");
10088 find_block_ipdomf(state, child);
10090 if (block->left && block->left->ipdom != block) {
10091 ipdomf_block(block, block->left);
10093 if (block->right && block->right->ipdom != block) {
10094 ipdomf_block(block, block->right);
10096 for(user = block->idominates; user; user = user->next) {
10097 struct block_set *frontier;
10098 child = user->member;
10099 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10100 if (frontier->member->ipdom != block) {
10101 ipdomf_block(block, frontier->member);
10107 static void print_dominated(
10108 struct compile_state *state, struct block *block, void *arg)
10110 struct block_set *user;
10113 fprintf(fp, "%d:", block->vertex);
10114 for(user = block->idominates; user; user = user->next) {
10115 fprintf(fp, " %d", user->member->vertex);
10116 if (user->member->idom != block) {
10117 internal_error(state, user->member->first, "bad idom");
10123 static void print_dominators(struct compile_state *state, FILE *fp)
10125 fprintf(fp, "\ndominates\n");
10126 walk_blocks(state, print_dominated, fp);
10130 static int print_frontiers(
10131 struct compile_state *state, struct block *block, int vertex)
10133 struct block_set *user;
10135 if (!block || (block->vertex != vertex + 1)) {
10140 printf("%d:", block->vertex);
10141 for(user = block->domfrontier; user; user = user->next) {
10142 printf(" %d", user->member->vertex);
10146 vertex = print_frontiers(state, block->left, vertex);
10147 vertex = print_frontiers(state, block->right, vertex);
10150 static void print_dominance_frontiers(struct compile_state *state)
10152 printf("\ndominance frontiers\n");
10153 print_frontiers(state, state->first_block, 0);
10157 static void analyze_idominators(struct compile_state *state)
10159 /* Find the immediate dominators */
10160 find_immediate_dominators(state);
10161 /* Find the dominance frontiers */
10162 find_block_domf(state, state->first_block);
10163 /* If debuging print the print what I have just found */
10164 if (state->debug & DEBUG_FDOMINATORS) {
10165 print_dominators(state, stdout);
10166 print_dominance_frontiers(state);
10167 print_control_flow(state);
10173 static void print_ipdominated(
10174 struct compile_state *state, struct block *block, void *arg)
10176 struct block_set *user;
10179 fprintf(fp, "%d:", block->vertex);
10180 for(user = block->ipdominates; user; user = user->next) {
10181 fprintf(fp, " %d", user->member->vertex);
10182 if (user->member->ipdom != block) {
10183 internal_error(state, user->member->first, "bad ipdom");
10189 static void print_ipdominators(struct compile_state *state, FILE *fp)
10191 fprintf(fp, "\nipdominates\n");
10192 walk_blocks(state, print_ipdominated, fp);
10195 static int print_pfrontiers(
10196 struct compile_state *state, struct block *block, int vertex)
10198 struct block_set *user;
10200 if (!block || (block->vertex != vertex + 1)) {
10205 printf("%d:", block->vertex);
10206 for(user = block->ipdomfrontier; user; user = user->next) {
10207 printf(" %d", user->member->vertex);
10210 for(user = block->use; user; user = user->next) {
10211 vertex = print_pfrontiers(state, user->member, vertex);
10215 static void print_ipdominance_frontiers(struct compile_state *state)
10217 printf("\nipdominance frontiers\n");
10218 print_pfrontiers(state, state->last_block, 0);
10222 static void analyze_ipdominators(struct compile_state *state)
10224 /* Find the post dominators */
10225 find_post_dominators(state);
10226 /* Find the control dependencies (post dominance frontiers) */
10227 find_block_ipdomf(state, state->last_block);
10228 /* If debuging print the print what I have just found */
10229 if (state->debug & DEBUG_RDOMINATORS) {
10230 print_ipdominators(state, stdout);
10231 print_ipdominance_frontiers(state);
10232 print_control_flow(state);
10236 static int bdominates(struct compile_state *state,
10237 struct block *dom, struct block *sub)
10239 while(sub && (sub != dom)) {
10245 static int tdominates(struct compile_state *state,
10246 struct triple *dom, struct triple *sub)
10248 struct block *bdom, *bsub;
10250 bdom = block_of_triple(state, dom);
10251 bsub = block_of_triple(state, sub);
10252 if (bdom != bsub) {
10253 result = bdominates(state, bdom, bsub);
10256 struct triple *ins;
10258 while((ins != bsub->first) && (ins != dom)) {
10261 result = (ins == dom);
10266 static void insert_phi_operations(struct compile_state *state)
10269 struct triple *first;
10270 int *has_already, *work;
10271 struct block *work_list, **work_list_tail;
10273 struct triple *var, *vnext;
10275 size = sizeof(int) * (state->last_vertex + 1);
10276 has_already = xcmalloc(size, "has_already");
10277 work = xcmalloc(size, "work");
10280 first = RHS(state->main_function, 0);
10281 for(var = first->next; var != first ; var = vnext) {
10282 struct block *block;
10283 struct triple_set *user, *unext;
10285 if ((var->op != OP_ADECL) || !var->use) {
10290 work_list_tail = &work_list;
10291 for(user = var->use; user; user = unext) {
10292 unext = user->next;
10293 if (user->member->op == OP_READ) {
10296 if (user->member->op != OP_WRITE) {
10297 internal_error(state, user->member,
10298 "bad variable access");
10300 block = user->member->u.block;
10302 warning(state, user->member, "dead code");
10303 release_triple(state, user->member);
10306 if (work[block->vertex] >= iter) {
10309 work[block->vertex] = iter;
10310 *work_list_tail = block;
10311 block->work_next = 0;
10312 work_list_tail = &block->work_next;
10314 for(block = work_list; block; block = block->work_next) {
10315 struct block_set *df;
10316 for(df = block->domfrontier; df; df = df->next) {
10317 struct triple *phi;
10318 struct block *front;
10320 front = df->member;
10322 if (has_already[front->vertex] >= iter) {
10325 /* Count how many edges flow into this block */
10326 in_edges = front->users;
10327 /* Insert a phi function for this variable */
10328 get_occurance(front->first->occurance);
10329 phi = alloc_triple(
10330 state, OP_PHI, var->type, -1, in_edges,
10331 front->first->occurance);
10332 phi->u.block = front;
10333 MISC(phi, 0) = var;
10334 use_triple(var, phi);
10335 /* Insert the phi functions immediately after the label */
10336 insert_triple(state, front->first->next, phi);
10337 if (front->first == front->last) {
10338 front->last = front->first->next;
10340 has_already[front->vertex] = iter;
10342 /* If necessary plan to visit the basic block */
10343 if (work[front->vertex] >= iter) {
10346 work[front->vertex] = iter;
10347 *work_list_tail = front;
10348 front->work_next = 0;
10349 work_list_tail = &front->work_next;
10353 xfree(has_already);
10361 static void fixup_block_phi_variables(
10362 struct compile_state *state, struct block *parent, struct block *block)
10364 struct block_set *set;
10365 struct triple *ptr;
10367 if (!parent || !block)
10369 /* Find the edge I am coming in on */
10371 for(set = block->use; set; set = set->next, edge++) {
10372 if (set->member == parent) {
10377 internal_error(state, 0, "phi input is not on a control predecessor");
10379 for(ptr = block->first; ; ptr = ptr->next) {
10380 if (ptr->op == OP_PHI) {
10381 struct triple *var, *val, **slot;
10382 var = MISC(ptr, 0);
10384 internal_error(state, ptr, "no var???");
10386 /* Find the current value of the variable */
10387 val = var->use->member;
10388 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10389 internal_error(state, val, "bad value in phi");
10391 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10392 internal_error(state, ptr, "edges > phi rhs");
10394 slot = &RHS(ptr, edge);
10395 if ((*slot != 0) && (*slot != val)) {
10396 internal_error(state, ptr, "phi already bound on this edge");
10399 use_triple(val, ptr);
10401 if (ptr == block->last) {
10408 static void rename_block_variables(
10409 struct compile_state *state, struct block *block)
10411 struct block_set *user;
10412 struct triple *ptr, *next, *last;
10416 last = block->first;
10418 for(ptr = block->first; !done; ptr = next) {
10420 if (ptr == block->last) {
10424 if (ptr->op == OP_READ) {
10425 struct triple *var, *val;
10427 unuse_triple(var, ptr);
10429 error(state, ptr, "variable used without being set");
10431 /* Find the current value of the variable */
10432 val = var->use->member;
10433 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10434 internal_error(state, val, "bad value in read");
10436 propogate_use(state, ptr, val);
10437 release_triple(state, ptr);
10441 if (ptr->op == OP_WRITE) {
10442 struct triple *var, *val, *tval;
10444 tval = val = RHS(ptr, 0);
10445 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10446 internal_error(state, val, "bad value in write");
10448 /* Insert a copy if the types differ */
10449 if (!equiv_types(ptr->type, val->type)) {
10450 if (val->op == OP_INTCONST) {
10451 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10452 tval->u.cval = val->u.cval;
10455 tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10456 use_triple(val, tval);
10458 unuse_triple(val, ptr);
10459 RHS(ptr, 0) = tval;
10460 use_triple(tval, ptr);
10462 propogate_use(state, ptr, tval);
10463 unuse_triple(var, ptr);
10464 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10465 push_triple(var, tval);
10467 if (ptr->op == OP_PHI) {
10468 struct triple *var;
10469 var = MISC(ptr, 0);
10470 /* Push OP_PHI onto a stack of variable uses */
10471 push_triple(var, ptr);
10475 block->last = last;
10477 /* Fixup PHI functions in the cf successors */
10478 fixup_block_phi_variables(state, block, block->left);
10479 fixup_block_phi_variables(state, block, block->right);
10480 /* rename variables in the dominated nodes */
10481 for(user = block->idominates; user; user = user->next) {
10482 rename_block_variables(state, user->member);
10484 /* pop the renamed variable stack */
10485 last = block->first;
10487 for(ptr = block->first; !done ; ptr = next) {
10489 if (ptr == block->last) {
10492 if (ptr->op == OP_WRITE) {
10493 struct triple *var;
10495 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10496 pop_triple(var, RHS(ptr, 0));
10497 release_triple(state, ptr);
10500 if (ptr->op == OP_PHI) {
10501 struct triple *var;
10502 var = MISC(ptr, 0);
10503 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10504 pop_triple(var, ptr);
10508 block->last = last;
10511 static void prune_block_variables(struct compile_state *state,
10512 struct block *block)
10514 struct block_set *user;
10515 struct triple *next, *last, *ptr;
10517 last = block->first;
10519 for(ptr = block->first; !done; ptr = next) {
10521 if (ptr == block->last) {
10524 if (ptr->op == OP_ADECL) {
10525 struct triple_set *user, *next;
10526 for(user = ptr->use; user; user = next) {
10527 struct triple *use;
10529 use = user->member;
10530 if (use->op != OP_PHI) {
10531 internal_error(state, use, "decl still used");
10533 if (MISC(use, 0) != ptr) {
10534 internal_error(state, use, "bad phi use of decl");
10536 unuse_triple(ptr, use);
10539 release_triple(state, ptr);
10544 block->last = last;
10545 for(user = block->idominates; user; user = user->next) {
10546 prune_block_variables(state, user->member);
10550 static void transform_to_ssa_form(struct compile_state *state)
10552 insert_phi_operations(state);
10554 printf("@%s:%d\n", __FILE__, __LINE__);
10555 print_blocks(state, stdout);
10557 rename_block_variables(state, state->first_block);
10558 prune_block_variables(state, state->first_block);
10562 static void clear_vertex(
10563 struct compile_state *state, struct block *block, void *arg)
10568 static void mark_live_block(
10569 struct compile_state *state, struct block *block, int *next_vertex)
10571 /* See if this is a block that has not been marked */
10572 if (block->vertex != 0) {
10575 block->vertex = *next_vertex;
10577 if (triple_is_branch(state, block->last)) {
10578 struct triple **targ;
10579 targ = triple_targ(state, block->last, 0);
10580 for(; targ; targ = triple_targ(state, block->last, targ)) {
10584 if (!triple_stores_block(state, *targ)) {
10585 internal_error(state, 0, "bad targ");
10587 mark_live_block(state, (*targ)->u.block, next_vertex);
10590 else if (block->last->next != RHS(state->main_function, 0)) {
10591 struct triple *ins;
10592 ins = block->last->next;
10593 if (!triple_stores_block(state, ins)) {
10594 internal_error(state, 0, "bad block start");
10596 mark_live_block(state, ins->u.block, next_vertex);
10600 static void transform_from_ssa_form(struct compile_state *state)
10602 /* To get out of ssa form we insert moves on the incoming
10603 * edges to blocks containting phi functions.
10605 struct triple *first;
10606 struct triple *phi, *next;
10609 /* Walk the control flow to see which blocks remain alive */
10610 walk_blocks(state, clear_vertex, 0);
10612 mark_live_block(state, state->first_block, &next_vertex);
10614 /* Walk all of the operations to find the phi functions */
10615 first = RHS(state->main_function, 0);
10616 for(phi = first->next; phi != first ; phi = next) {
10617 struct block_set *set;
10618 struct block *block;
10619 struct triple **slot;
10620 struct triple *var, *read;
10621 struct triple_set *use, *use_next;
10624 if (phi->op != OP_PHI) {
10627 block = phi->u.block;
10628 slot = &RHS(phi, 0);
10630 /* Forget uses from code in dead blocks */
10631 for(use = phi->use; use; use = use_next) {
10632 struct block *ublock;
10633 struct triple **expr;
10634 use_next = use->next;
10635 ublock = block_of_triple(state, use->member);
10636 if ((use->member == phi) || (ublock->vertex != 0)) {
10639 expr = triple_rhs(state, use->member, 0);
10640 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10641 if (*expr == phi) {
10645 unuse_triple(phi, use->member);
10648 /* A variable to replace the phi function */
10649 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10650 /* A read of the single value that is set into the variable */
10651 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10652 use_triple(var, read);
10654 /* Replaces uses of the phi with variable reads */
10655 propogate_use(state, phi, read);
10657 /* Walk all of the incoming edges/blocks and insert moves.
10659 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10660 struct block *eblock;
10661 struct triple *move;
10662 struct triple *val;
10663 eblock = set->member;
10666 unuse_triple(val, phi);
10668 if (!val || (val == &zero_triple) ||
10669 (block->vertex == 0) || (eblock->vertex == 0) ||
10670 (val == phi) || (val == read)) {
10674 move = post_triple(state,
10675 val, OP_WRITE, phi->type, var, val);
10676 use_triple(val, move);
10677 use_triple(var, move);
10679 /* See if there are any writers of var */
10681 for(use = var->use; use; use = use->next) {
10682 struct triple **expr;
10683 expr = triple_lhs(state, use->member, 0);
10684 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10685 if (*expr == var) {
10690 /* If var is not used free it */
10692 unuse_triple(var, read);
10693 free_triple(state, read);
10694 free_triple(state, var);
10697 /* Release the phi function */
10698 release_triple(state, phi);
10705 * Register conflict resolution
10706 * =========================================================
10709 static struct reg_info find_def_color(
10710 struct compile_state *state, struct triple *def)
10712 struct triple_set *set;
10713 struct reg_info info;
10714 info.reg = REG_UNSET;
10716 if (!triple_is_def(state, def)) {
10719 info = arch_reg_lhs(state, def, 0);
10720 if (info.reg >= MAX_REGISTERS) {
10721 info.reg = REG_UNSET;
10723 for(set = def->use; set; set = set->next) {
10724 struct reg_info tinfo;
10726 i = find_rhs_use(state, set->member, def);
10730 tinfo = arch_reg_rhs(state, set->member, i);
10731 if (tinfo.reg >= MAX_REGISTERS) {
10732 tinfo.reg = REG_UNSET;
10734 if ((tinfo.reg != REG_UNSET) &&
10735 (info.reg != REG_UNSET) &&
10736 (tinfo.reg != info.reg)) {
10737 internal_error(state, def, "register conflict");
10739 if ((info.regcm & tinfo.regcm) == 0) {
10740 internal_error(state, def, "regcm conflict %x & %x == 0",
10741 info.regcm, tinfo.regcm);
10743 if (info.reg == REG_UNSET) {
10744 info.reg = tinfo.reg;
10746 info.regcm &= tinfo.regcm;
10748 if (info.reg >= MAX_REGISTERS) {
10749 internal_error(state, def, "register out of range");
10754 static struct reg_info find_lhs_pre_color(
10755 struct compile_state *state, struct triple *ins, int index)
10757 struct reg_info info;
10759 zrhs = TRIPLE_RHS(ins->sizes);
10760 zlhs = TRIPLE_LHS(ins->sizes);
10761 if (!zlhs && triple_is_def(state, ins)) {
10764 if (index >= zlhs) {
10765 internal_error(state, ins, "Bad lhs %d", index);
10767 info = arch_reg_lhs(state, ins, index);
10768 for(i = 0; i < zrhs; i++) {
10769 struct reg_info rinfo;
10770 rinfo = arch_reg_rhs(state, ins, i);
10771 if ((info.reg == rinfo.reg) &&
10772 (rinfo.reg >= MAX_REGISTERS)) {
10773 struct reg_info tinfo;
10774 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10775 info.reg = tinfo.reg;
10776 info.regcm &= tinfo.regcm;
10780 if (info.reg >= MAX_REGISTERS) {
10781 info.reg = REG_UNSET;
10786 static struct reg_info find_rhs_post_color(
10787 struct compile_state *state, struct triple *ins, int index);
10789 static struct reg_info find_lhs_post_color(
10790 struct compile_state *state, struct triple *ins, int index)
10792 struct triple_set *set;
10793 struct reg_info info;
10794 struct triple *lhs;
10796 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10799 if ((index == 0) && triple_is_def(state, ins)) {
10802 else if (index < TRIPLE_LHS(ins->sizes)) {
10803 lhs = LHS(ins, index);
10806 internal_error(state, ins, "Bad lhs %d", index);
10809 info = arch_reg_lhs(state, ins, index);
10810 if (info.reg >= MAX_REGISTERS) {
10811 info.reg = REG_UNSET;
10813 for(set = lhs->use; set; set = set->next) {
10814 struct reg_info rinfo;
10815 struct triple *user;
10817 user = set->member;
10818 zrhs = TRIPLE_RHS(user->sizes);
10819 for(i = 0; i < zrhs; i++) {
10820 if (RHS(user, i) != lhs) {
10823 rinfo = find_rhs_post_color(state, user, i);
10824 if ((info.reg != REG_UNSET) &&
10825 (rinfo.reg != REG_UNSET) &&
10826 (info.reg != rinfo.reg)) {
10827 internal_error(state, ins, "register conflict");
10829 if ((info.regcm & rinfo.regcm) == 0) {
10830 internal_error(state, ins, "regcm conflict %x & %x == 0",
10831 info.regcm, rinfo.regcm);
10833 if (info.reg == REG_UNSET) {
10834 info.reg = rinfo.reg;
10836 info.regcm &= rinfo.regcm;
10840 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10841 ins, index, info.reg, info.regcm);
10846 static struct reg_info find_rhs_post_color(
10847 struct compile_state *state, struct triple *ins, int index)
10849 struct reg_info info, rinfo;
10852 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10855 rinfo = arch_reg_rhs(state, ins, index);
10856 zlhs = TRIPLE_LHS(ins->sizes);
10857 if (!zlhs && triple_is_def(state, ins)) {
10861 if (info.reg >= MAX_REGISTERS) {
10862 info.reg = REG_UNSET;
10864 for(i = 0; i < zlhs; i++) {
10865 struct reg_info linfo;
10866 linfo = arch_reg_lhs(state, ins, i);
10867 if ((linfo.reg == rinfo.reg) &&
10868 (linfo.reg >= MAX_REGISTERS)) {
10869 struct reg_info tinfo;
10870 tinfo = find_lhs_post_color(state, ins, i);
10871 if (tinfo.reg >= MAX_REGISTERS) {
10872 tinfo.reg = REG_UNSET;
10874 info.regcm &= linfo.reg;
10875 info.regcm &= tinfo.regcm;
10876 if (info.reg != REG_UNSET) {
10877 internal_error(state, ins, "register conflict");
10879 if (info.regcm == 0) {
10880 internal_error(state, ins, "regcm conflict");
10882 info.reg = tinfo.reg;
10886 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10887 ins, index, info.reg, info.regcm);
10892 static struct reg_info find_lhs_color(
10893 struct compile_state *state, struct triple *ins, int index)
10895 struct reg_info pre, post, info;
10897 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10900 pre = find_lhs_pre_color(state, ins, index);
10901 post = find_lhs_post_color(state, ins, index);
10902 if ((pre.reg != post.reg) &&
10903 (pre.reg != REG_UNSET) &&
10904 (post.reg != REG_UNSET)) {
10905 internal_error(state, ins, "register conflict");
10907 info.regcm = pre.regcm & post.regcm;
10908 info.reg = pre.reg;
10909 if (info.reg == REG_UNSET) {
10910 info.reg = post.reg;
10913 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10914 ins, index, info.reg, info.regcm);
10919 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10921 struct triple_set *entry, *next;
10922 struct triple *out;
10923 struct reg_info info, rinfo;
10925 info = arch_reg_lhs(state, ins, 0);
10926 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10927 use_triple(RHS(out, 0), out);
10928 /* Get the users of ins to use out instead */
10929 for(entry = ins->use; entry; entry = next) {
10931 next = entry->next;
10932 if (entry->member == out) {
10935 i = find_rhs_use(state, entry->member, ins);
10939 rinfo = arch_reg_rhs(state, entry->member, i);
10940 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10943 replace_rhs_use(state, ins, out, entry->member);
10945 transform_to_arch_instruction(state, out);
10949 static struct triple *typed_pre_copy(
10950 struct compile_state *state, struct type *type, struct triple *ins, int index)
10952 /* Carefully insert enough operations so that I can
10953 * enter any operation with a GPR32.
10956 struct triple **expr;
10958 struct reg_info info;
10959 if (ins->op == OP_PHI) {
10960 internal_error(state, ins, "pre_copy on a phi?");
10962 classes = arch_type_to_regcm(state, type);
10963 info = arch_reg_rhs(state, ins, index);
10964 expr = &RHS(ins, index);
10965 if ((info.regcm & classes) == 0) {
10966 internal_error(state, ins, "pre_copy with no register classes");
10968 in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
10969 unuse_triple(*expr, ins);
10971 use_triple(RHS(in, 0), in);
10972 use_triple(in, ins);
10973 transform_to_arch_instruction(state, in);
10977 static struct triple *pre_copy(
10978 struct compile_state *state, struct triple *ins, int index)
10980 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
10984 static void insert_copies_to_phi(struct compile_state *state)
10986 /* To get out of ssa form we insert moves on the incoming
10987 * edges to blocks containting phi functions.
10989 struct triple *first;
10990 struct triple *phi;
10992 /* Walk all of the operations to find the phi functions */
10993 first = RHS(state->main_function, 0);
10994 for(phi = first->next; phi != first ; phi = phi->next) {
10995 struct block_set *set;
10996 struct block *block;
10997 struct triple **slot, *copy;
10999 if (phi->op != OP_PHI) {
11002 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11003 block = phi->u.block;
11004 slot = &RHS(phi, 0);
11005 /* Phi's that feed into mandatory live range joins
11006 * cause nasty complications. Insert a copy of
11007 * the phi value so I never have to deal with
11008 * that in the rest of the code.
11010 copy = post_copy(state, phi);
11011 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11012 /* Walk all of the incoming edges/blocks and insert moves.
11014 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11015 struct block *eblock;
11016 struct triple *move;
11017 struct triple *val;
11018 struct triple *ptr;
11019 eblock = set->member;
11026 get_occurance(val->occurance);
11027 move = build_triple(state, OP_COPY, phi->type, val, 0,
11029 move->u.block = eblock;
11030 move->id |= TRIPLE_FLAG_PRE_SPLIT;
11031 use_triple(val, move);
11034 unuse_triple(val, phi);
11035 use_triple(move, phi);
11037 /* Walk through the block backwards to find
11038 * an appropriate location for the OP_COPY.
11040 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11041 struct triple **expr;
11042 if ((ptr == phi) || (ptr == val)) {
11045 expr = triple_rhs(state, ptr, 0);
11046 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11047 if ((*expr) == phi) {
11053 if (triple_is_branch(state, ptr)) {
11054 internal_error(state, ptr,
11055 "Could not insert write to phi");
11057 insert_triple(state, ptr->next, move);
11058 if (eblock->last == ptr) {
11059 eblock->last = move;
11061 transform_to_arch_instruction(state, move);
11066 struct triple_reg_set {
11067 struct triple_reg_set *next;
11068 struct triple *member;
11069 struct triple *new;
11073 struct block *block;
11074 struct triple_reg_set *in;
11075 struct triple_reg_set *out;
11079 static int do_triple_set(struct triple_reg_set **head,
11080 struct triple *member, struct triple *new_member)
11082 struct triple_reg_set **ptr, *new;
11087 if ((*ptr)->member == member) {
11090 ptr = &(*ptr)->next;
11092 new = xcmalloc(sizeof(*new), "triple_set");
11093 new->member = member;
11094 new->new = new_member;
11100 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11102 struct triple_reg_set *entry, **ptr;
11106 if (entry->member == member) {
11107 *ptr = entry->next;
11112 ptr = &entry->next;
11117 static int in_triple(struct reg_block *rb, struct triple *in)
11119 return do_triple_set(&rb->in, in, 0);
11121 static void unin_triple(struct reg_block *rb, struct triple *unin)
11123 do_triple_unset(&rb->in, unin);
11126 static int out_triple(struct reg_block *rb, struct triple *out)
11128 return do_triple_set(&rb->out, out, 0);
11130 static void unout_triple(struct reg_block *rb, struct triple *unout)
11132 do_triple_unset(&rb->out, unout);
11135 static int initialize_regblock(struct reg_block *blocks,
11136 struct block *block, int vertex)
11138 struct block_set *user;
11139 if (!block || (blocks[block->vertex].block == block)) {
11143 /* Renumber the blocks in a convinient fashion */
11144 block->vertex = vertex;
11145 blocks[vertex].block = block;
11146 blocks[vertex].vertex = vertex;
11147 for(user = block->use; user; user = user->next) {
11148 vertex = initialize_regblock(blocks, user->member, vertex);
11153 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11154 struct reg_block *rb, struct block *suc)
11156 /* Read the conditional input set of a successor block
11157 * (i.e. the input to the phi nodes) and place it in the
11158 * current blocks output set.
11160 struct block_set *set;
11161 struct triple *ptr;
11165 /* Find the edge I am coming in on */
11166 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11167 if (set->member == rb->block) {
11172 internal_error(state, 0, "Not coming on a control edge?");
11174 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11175 struct triple **slot, *expr, *ptr2;
11176 int out_change, done2;
11177 done = (ptr == suc->last);
11178 if (ptr->op != OP_PHI) {
11181 slot = &RHS(ptr, 0);
11183 out_change = out_triple(rb, expr);
11187 /* If we don't define the variable also plast it
11188 * in the current blocks input set.
11190 ptr2 = rb->block->first;
11191 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11192 if (ptr2 == expr) {
11195 done2 = (ptr2 == rb->block->last);
11200 change |= in_triple(rb, expr);
11205 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11206 struct reg_block *rb, struct block *suc)
11208 struct triple_reg_set *in_set;
11211 /* Read the input set of a successor block
11212 * and place it in the current blocks output set.
11214 in_set = blocks[suc->vertex].in;
11215 for(; in_set; in_set = in_set->next) {
11216 int out_change, done;
11217 struct triple *first, *last, *ptr;
11218 out_change = out_triple(rb, in_set->member);
11222 /* If we don't define the variable also place it
11223 * in the current blocks input set.
11225 first = rb->block->first;
11226 last = rb->block->last;
11228 for(ptr = first; !done; ptr = ptr->next) {
11229 if (ptr == in_set->member) {
11232 done = (ptr == last);
11237 change |= in_triple(rb, in_set->member);
11239 change |= phi_in(state, blocks, rb, suc);
11244 static int use_in(struct compile_state *state, struct reg_block *rb)
11246 /* Find the variables we use but don't define and add
11247 * it to the current blocks input set.
11249 #warning "FIXME is this O(N^2) algorithm bad?"
11250 struct block *block;
11251 struct triple *ptr;
11256 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11257 struct triple **expr;
11258 done = (ptr == block->first);
11259 /* The variable a phi function uses depends on the
11260 * control flow, and is handled in phi_in, not
11263 if (ptr->op == OP_PHI) {
11266 expr = triple_rhs(state, ptr, 0);
11267 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11268 struct triple *rhs, *test;
11274 /* See if rhs is defined in this block */
11275 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11276 tdone = (test == block->first);
11282 /* If I still have a valid rhs add it to in */
11283 change |= in_triple(rb, rhs);
11289 static struct reg_block *compute_variable_lifetimes(
11290 struct compile_state *state)
11292 struct reg_block *blocks;
11295 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11296 initialize_regblock(blocks, state->last_block, 0);
11300 for(i = 1; i <= state->last_vertex; i++) {
11301 struct reg_block *rb;
11303 /* Add the left successor's input set to in */
11304 if (rb->block->left) {
11305 change |= reg_in(state, blocks, rb, rb->block->left);
11307 /* Add the right successor's input set to in */
11308 if ((rb->block->right) &&
11309 (rb->block->right != rb->block->left)) {
11310 change |= reg_in(state, blocks, rb, rb->block->right);
11312 /* Add use to in... */
11313 change |= use_in(state, rb);
11319 static void free_variable_lifetimes(
11320 struct compile_state *state, struct reg_block *blocks)
11323 /* free in_set && out_set on each block */
11324 for(i = 1; i <= state->last_vertex; i++) {
11325 struct triple_reg_set *entry, *next;
11326 struct reg_block *rb;
11328 for(entry = rb->in; entry ; entry = next) {
11329 next = entry->next;
11330 do_triple_unset(&rb->in, entry->member);
11332 for(entry = rb->out; entry; entry = next) {
11333 next = entry->next;
11334 do_triple_unset(&rb->out, entry->member);
11341 typedef void (*wvl_cb_t)(
11342 struct compile_state *state,
11343 struct reg_block *blocks, struct triple_reg_set *live,
11344 struct reg_block *rb, struct triple *ins, void *arg);
11346 static void walk_variable_lifetimes(struct compile_state *state,
11347 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11351 for(i = 1; i <= state->last_vertex; i++) {
11352 struct triple_reg_set *live;
11353 struct triple_reg_set *entry, *next;
11354 struct triple *ptr, *prev;
11355 struct reg_block *rb;
11356 struct block *block;
11359 /* Get the blocks */
11363 /* Copy out into live */
11365 for(entry = rb->out; entry; entry = next) {
11366 next = entry->next;
11367 do_triple_set(&live, entry->member, entry->new);
11369 /* Walk through the basic block calculating live */
11370 for(done = 0, ptr = block->last; !done; ptr = prev) {
11371 struct triple **expr;
11374 done = (ptr == block->first);
11376 /* Ensure the current definition is in live */
11377 if (triple_is_def(state, ptr)) {
11378 do_triple_set(&live, ptr, 0);
11381 /* Inform the callback function of what is
11384 cb(state, blocks, live, rb, ptr, arg);
11386 /* Remove the current definition from live */
11387 do_triple_unset(&live, ptr);
11389 /* Add the current uses to live.
11391 * It is safe to skip phi functions because they do
11392 * not have any block local uses, and the block
11393 * output sets already properly account for what
11394 * control flow depedent uses phi functions do have.
11396 if (ptr->op == OP_PHI) {
11399 expr = triple_rhs(state, ptr, 0);
11400 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11401 /* If the triple is not a definition skip it. */
11402 if (!*expr || !triple_is_def(state, *expr)) {
11405 do_triple_set(&live, *expr, 0);
11409 for(entry = live; entry; entry = next) {
11410 next = entry->next;
11411 do_triple_unset(&live, entry->member);
11416 static int count_triples(struct compile_state *state)
11418 struct triple *first, *ins;
11420 first = RHS(state->main_function, 0);
11425 } while (ins != first);
11428 struct dead_triple {
11429 struct triple *triple;
11430 struct dead_triple *work_next;
11431 struct block *block;
11434 #define TRIPLE_FLAG_ALIVE 1
11438 static void awaken(
11439 struct compile_state *state,
11440 struct dead_triple *dtriple, struct triple **expr,
11441 struct dead_triple ***work_list_tail)
11443 struct triple *triple;
11444 struct dead_triple *dt;
11452 if (triple->id <= 0) {
11453 internal_error(state, triple, "bad triple id: %d",
11456 if (triple->op == OP_NOOP) {
11457 internal_warning(state, triple, "awakening noop?");
11460 dt = &dtriple[triple->id];
11461 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11462 dt->flags |= TRIPLE_FLAG_ALIVE;
11463 if (!dt->work_next) {
11464 **work_list_tail = dt;
11465 *work_list_tail = &dt->work_next;
11470 static void eliminate_inefectual_code(struct compile_state *state)
11472 struct block *block;
11473 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11475 struct triple *first, *ins;
11477 /* Setup the work list */
11479 work_list_tail = &work_list;
11481 first = RHS(state->main_function, 0);
11483 /* Count how many triples I have */
11484 triples = count_triples(state);
11486 /* Now put then in an array and mark all of the triples dead */
11487 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11493 if (ins->op == OP_LABEL) {
11494 block = ins->u.block;
11496 dtriple[i].triple = ins;
11497 dtriple[i].block = block;
11498 dtriple[i].flags = 0;
11499 dtriple[i].color = ins->id;
11501 /* See if it is an operation we always keep */
11502 #warning "FIXME handle the case of killing a branch instruction"
11503 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11504 awaken(state, dtriple, &ins, &work_list_tail);
11508 } while(ins != first);
11510 struct dead_triple *dt;
11511 struct block_set *user;
11512 struct triple **expr;
11514 work_list = dt->work_next;
11516 work_list_tail = &work_list;
11518 /* Wake up the data depencencies of this triple */
11521 expr = triple_rhs(state, dt->triple, expr);
11522 awaken(state, dtriple, expr, &work_list_tail);
11525 expr = triple_lhs(state, dt->triple, expr);
11526 awaken(state, dtriple, expr, &work_list_tail);
11529 expr = triple_misc(state, dt->triple, expr);
11530 awaken(state, dtriple, expr, &work_list_tail);
11532 /* Wake up the forward control dependencies */
11534 expr = triple_targ(state, dt->triple, expr);
11535 awaken(state, dtriple, expr, &work_list_tail);
11537 /* Wake up the reverse control dependencies of this triple */
11538 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11539 awaken(state, dtriple, &user->member->last, &work_list_tail);
11542 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11543 if ((dt->triple->op == OP_NOOP) &&
11544 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11545 internal_error(state, dt->triple, "noop effective?");
11547 dt->triple->id = dt->color; /* Restore the color */
11548 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11549 #warning "FIXME handle the case of killing a basic block"
11550 if (dt->block->first == dt->triple) {
11553 if (dt->block->last == dt->triple) {
11554 dt->block->last = dt->triple->prev;
11556 release_triple(state, dt->triple);
11563 static void insert_mandatory_copies(struct compile_state *state)
11565 struct triple *ins, *first;
11567 /* The object is with a minimum of inserted copies,
11568 * to resolve in fundamental register conflicts between
11569 * register value producers and consumers.
11570 * Theoretically we may be greater than minimal when we
11571 * are inserting copies before instructions but that
11572 * case should be rare.
11574 first = RHS(state->main_function, 0);
11577 struct triple_set *entry, *next;
11578 struct triple *tmp;
11579 struct reg_info info;
11580 unsigned reg, regcm;
11581 int do_post_copy, do_pre_copy;
11583 if (!triple_is_def(state, ins)) {
11586 /* Find the architecture specific color information */
11587 info = arch_reg_lhs(state, ins, 0);
11588 if (info.reg >= MAX_REGISTERS) {
11589 info.reg = REG_UNSET;
11593 regcm = arch_type_to_regcm(state, ins->type);
11594 do_post_copy = do_pre_copy = 0;
11596 /* Walk through the uses of ins and check for conflicts */
11597 for(entry = ins->use; entry; entry = next) {
11598 struct reg_info rinfo;
11600 next = entry->next;
11601 i = find_rhs_use(state, entry->member, ins);
11606 /* Find the users color requirements */
11607 rinfo = arch_reg_rhs(state, entry->member, i);
11608 if (rinfo.reg >= MAX_REGISTERS) {
11609 rinfo.reg = REG_UNSET;
11612 /* See if I need a pre_copy */
11613 if (rinfo.reg != REG_UNSET) {
11614 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11619 regcm &= rinfo.regcm;
11620 regcm = arch_regcm_normalize(state, regcm);
11624 /* Always use pre_copies for constants.
11625 * They do not take up any registers until a
11626 * copy places them in one.
11628 if ((info.reg == REG_UNNEEDED) &&
11629 (rinfo.reg != REG_UNNEEDED)) {
11635 (((info.reg != REG_UNSET) &&
11636 (reg != REG_UNSET) &&
11637 (info.reg != reg)) ||
11638 ((info.regcm & regcm) == 0));
11641 regcm = info.regcm;
11642 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11643 for(entry = ins->use; entry; entry = next) {
11644 struct reg_info rinfo;
11646 next = entry->next;
11647 i = find_rhs_use(state, entry->member, ins);
11652 /* Find the users color requirements */
11653 rinfo = arch_reg_rhs(state, entry->member, i);
11654 if (rinfo.reg >= MAX_REGISTERS) {
11655 rinfo.reg = REG_UNSET;
11658 /* Now see if it is time to do the pre_copy */
11659 if (rinfo.reg != REG_UNSET) {
11660 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11661 ((regcm & rinfo.regcm) == 0) ||
11662 /* Don't let a mandatory coalesce sneak
11663 * into a operation that is marked to prevent
11666 ((reg != REG_UNNEEDED) &&
11667 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11668 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11671 struct triple *user;
11672 user = entry->member;
11673 if (RHS(user, i) != ins) {
11674 internal_error(state, user, "bad rhs");
11676 tmp = pre_copy(state, user, i);
11677 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11685 if ((regcm & rinfo.regcm) == 0) {
11687 struct triple *user;
11688 user = entry->member;
11689 if (RHS(user, i) != ins) {
11690 internal_error(state, user, "bad rhs");
11692 tmp = pre_copy(state, user, i);
11693 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11699 regcm &= rinfo.regcm;
11702 if (do_post_copy) {
11703 struct reg_info pre, post;
11704 tmp = post_copy(state, ins);
11705 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11706 pre = arch_reg_lhs(state, ins, 0);
11707 post = arch_reg_lhs(state, tmp, 0);
11708 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11709 internal_error(state, tmp, "useless copy");
11714 } while(ins != first);
11718 struct live_range_edge;
11719 struct live_range_def;
11720 struct live_range {
11721 struct live_range_edge *edges;
11722 struct live_range_def *defs;
11723 /* Note. The list pointed to by defs is kept in order.
11724 * That is baring splits in the flow control
11725 * defs dominates defs->next wich dominates defs->next->next
11732 struct live_range *group_next, **group_prev;
11735 struct live_range_edge {
11736 struct live_range_edge *next;
11737 struct live_range *node;
11740 struct live_range_def {
11741 struct live_range_def *next;
11742 struct live_range_def *prev;
11743 struct live_range *lr;
11744 struct triple *def;
11748 #define LRE_HASH_SIZE 2048
11750 struct lre_hash *next;
11751 struct live_range *left;
11752 struct live_range *right;
11757 struct lre_hash *hash[LRE_HASH_SIZE];
11758 struct reg_block *blocks;
11759 struct live_range_def *lrd;
11760 struct live_range *lr;
11761 struct live_range *low, **low_tail;
11762 struct live_range *high, **high_tail;
11765 int passes, max_passes;
11766 #define MAX_ALLOCATION_PASSES 100
11771 struct print_interference_block_info {
11772 struct reg_state *rstate;
11776 static void print_interference_block(
11777 struct compile_state *state, struct block *block, void *arg)
11780 struct print_interference_block_info *info = arg;
11781 struct reg_state *rstate = info->rstate;
11782 FILE *fp = info->fp;
11783 struct reg_block *rb;
11784 struct triple *ptr;
11787 rb = &rstate->blocks[block->vertex];
11789 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
11793 block->left && block->left->use?block->left->use->member : 0,
11795 block->right && block->right->use?block->right->use->member : 0);
11797 struct triple_reg_set *in_set;
11798 fprintf(fp, " in:");
11799 for(in_set = rb->in; in_set; in_set = in_set->next) {
11800 fprintf(fp, " %-10p", in_set->member);
11805 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11806 done = (ptr == block->last);
11807 if (ptr->op == OP_PHI) {
11814 for(edge = 0; edge < block->users; edge++) {
11815 fprintf(fp, " in(%d):", edge);
11816 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11817 struct triple **slot;
11818 done = (ptr == block->last);
11819 if (ptr->op != OP_PHI) {
11822 slot = &RHS(ptr, 0);
11823 fprintf(fp, " %-10p", slot[edge]);
11828 if (block->first->op == OP_LABEL) {
11829 fprintf(fp, "%p:\n", block->first);
11831 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11832 struct triple_set *user;
11833 struct live_range *lr;
11837 done = (ptr == block->last);
11838 lr = rstate->lrd[ptr->id].lr;
11840 if (triple_stores_block(state, ptr)) {
11841 if (ptr->u.block != block) {
11842 internal_error(state, ptr,
11843 "Wrong block pointer: %p",
11847 if (op == OP_ADECL) {
11848 for(user = ptr->use; user; user = user->next) {
11849 if (!user->member->u.block) {
11850 internal_error(state, user->member,
11851 "Use %p not in a block?",
11858 ptr->id = rstate->lrd[id].orig_id;
11859 SET_REG(ptr->id, lr->color);
11860 display_triple(fp, ptr);
11863 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
11864 internal_error(state, ptr, "lr has no defs!");
11866 if (info->need_edges) {
11868 struct live_range_def *lrd;
11869 fprintf(fp, " range:");
11872 fprintf(fp, " %-10p", lrd->def);
11874 } while(lrd != lr->defs);
11877 if (lr->edges > 0) {
11878 struct live_range_edge *edge;
11879 fprintf(fp, " edges:");
11880 for(edge = lr->edges; edge; edge = edge->next) {
11881 struct live_range_def *lrd;
11882 lrd = edge->node->defs;
11884 fprintf(fp, " %-10p", lrd->def);
11886 } while(lrd != edge->node->defs);
11892 /* Do a bunch of sanity checks */
11893 valid_ins(state, ptr);
11894 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
11895 internal_error(state, ptr, "Invalid triple id: %d",
11898 for(user = ptr->use; user; user = user->next) {
11899 struct triple *use;
11900 struct live_range *ulr;
11901 use = user->member;
11902 valid_ins(state, use);
11903 if ((use->id < 0) || (use->id > rstate->defs)) {
11904 internal_error(state, use, "Invalid triple id: %d",
11907 ulr = rstate->lrd[user->member->id].lr;
11908 if (triple_stores_block(state, user->member) &&
11909 !user->member->u.block) {
11910 internal_error(state, user->member,
11911 "Use %p not in a block?",
11917 struct triple_reg_set *out_set;
11918 fprintf(fp, " out:");
11919 for(out_set = rb->out; out_set; out_set = out_set->next) {
11920 fprintf(fp, " %-10p", out_set->member);
11927 static void print_interference_blocks(
11928 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
11930 struct print_interference_block_info info;
11931 info.rstate = rstate;
11933 info.need_edges = need_edges;
11934 fprintf(fp, "\nlive variables by block\n");
11935 walk_blocks(state, print_interference_block, &info);
11939 static unsigned regc_max_size(struct compile_state *state, int classes)
11944 for(i = 0; i < MAX_REGC; i++) {
11945 if (classes & (1 << i)) {
11947 size = arch_regc_size(state, i);
11948 if (size > max_size) {
11956 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11958 unsigned equivs[MAX_REG_EQUIVS];
11960 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11961 internal_error(state, 0, "invalid register");
11963 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11964 internal_error(state, 0, "invalid register");
11966 arch_reg_equivs(state, equivs, reg1);
11967 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11968 if (equivs[i] == reg2) {
11975 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11977 unsigned equivs[MAX_REG_EQUIVS];
11979 if (reg == REG_UNNEEDED) {
11982 arch_reg_equivs(state, equivs, reg);
11983 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11984 used[equivs[i]] = 1;
11989 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11991 unsigned equivs[MAX_REG_EQUIVS];
11993 if (reg == REG_UNNEEDED) {
11996 arch_reg_equivs(state, equivs, reg);
11997 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11998 used[equivs[i]] += 1;
12003 static unsigned int hash_live_edge(
12004 struct live_range *left, struct live_range *right)
12006 unsigned int hash, val;
12007 unsigned long lval, rval;
12008 lval = ((unsigned long)left)/sizeof(struct live_range);
12009 rval = ((unsigned long)right)/sizeof(struct live_range);
12014 hash = (hash *263) + val;
12019 hash = (hash *263) + val;
12021 hash = hash & (LRE_HASH_SIZE - 1);
12025 static struct lre_hash **lre_probe(struct reg_state *rstate,
12026 struct live_range *left, struct live_range *right)
12028 struct lre_hash **ptr;
12029 unsigned int index;
12030 /* Ensure left <= right */
12031 if (left > right) {
12032 struct live_range *tmp;
12037 index = hash_live_edge(left, right);
12039 ptr = &rstate->hash[index];
12041 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12044 ptr = &(*ptr)->next;
12049 static int interfere(struct reg_state *rstate,
12050 struct live_range *left, struct live_range *right)
12052 struct lre_hash **ptr;
12053 ptr = lre_probe(rstate, left, right);
12054 return ptr && *ptr;
12057 static void add_live_edge(struct reg_state *rstate,
12058 struct live_range *left, struct live_range *right)
12060 /* FIXME the memory allocation overhead is noticeable here... */
12061 struct lre_hash **ptr, *new_hash;
12062 struct live_range_edge *edge;
12064 if (left == right) {
12067 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12070 /* Ensure left <= right */
12071 if (left > right) {
12072 struct live_range *tmp;
12077 ptr = lre_probe(rstate, left, right);
12082 fprintf(stderr, "new_live_edge(%p, %p)\n",
12085 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12086 new_hash->next = *ptr;
12087 new_hash->left = left;
12088 new_hash->right = right;
12091 edge = xmalloc(sizeof(*edge), "live_range_edge");
12092 edge->next = left->edges;
12093 edge->node = right;
12094 left->edges = edge;
12097 edge = xmalloc(sizeof(*edge), "live_range_edge");
12098 edge->next = right->edges;
12100 right->edges = edge;
12101 right->degree += 1;
12104 static void remove_live_edge(struct reg_state *rstate,
12105 struct live_range *left, struct live_range *right)
12107 struct live_range_edge *edge, **ptr;
12108 struct lre_hash **hptr, *entry;
12109 hptr = lre_probe(rstate, left, right);
12110 if (!hptr || !*hptr) {
12114 *hptr = entry->next;
12117 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12119 if (edge->node == right) {
12121 memset(edge, 0, sizeof(*edge));
12127 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12129 if (edge->node == left) {
12131 memset(edge, 0, sizeof(*edge));
12139 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12141 struct live_range_edge *edge, *next;
12142 for(edge = range->edges; edge; edge = next) {
12144 remove_live_edge(rstate, range, edge->node);
12148 static void transfer_live_edges(struct reg_state *rstate,
12149 struct live_range *dest, struct live_range *src)
12151 struct live_range_edge *edge, *next;
12152 for(edge = src->edges; edge; edge = next) {
12153 struct live_range *other;
12155 other = edge->node;
12156 remove_live_edge(rstate, src, other);
12157 add_live_edge(rstate, dest, other);
12162 /* Interference graph...
12164 * new(n) --- Return a graph with n nodes but no edges.
12165 * add(g,x,y) --- Return a graph including g with an between x and y
12166 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12167 * x and y in the graph g
12168 * degree(g, x) --- Return the degree of the node x in the graph g
12169 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12171 * Implement with a hash table && a set of adjcency vectors.
12172 * The hash table supports constant time implementations of add and interfere.
12173 * The adjacency vectors support an efficient implementation of neighbors.
12177 * +---------------------------------------------------+
12178 * | +--------------+ |
12180 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
12182 * -- In simplify implment optimistic coloring... (No backtracking)
12183 * -- Implement Rematerialization it is the only form of spilling we can perform
12184 * Essentially this means dropping a constant from a register because
12185 * we can regenerate it later.
12187 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12188 * coalesce at phi points...
12189 * --- Bias coloring if at all possible do the coalesing a compile time.
12194 static void different_colored(
12195 struct compile_state *state, struct reg_state *rstate,
12196 struct triple *parent, struct triple *ins)
12198 struct live_range *lr;
12199 struct triple **expr;
12200 lr = rstate->lrd[ins->id].lr;
12201 expr = triple_rhs(state, ins, 0);
12202 for(;expr; expr = triple_rhs(state, ins, expr)) {
12203 struct live_range *lr2;
12204 if (!*expr || (*expr == parent) || (*expr == ins)) {
12207 lr2 = rstate->lrd[(*expr)->id].lr;
12208 if (lr->color == lr2->color) {
12209 internal_error(state, ins, "live range too big");
12215 static struct live_range *coalesce_ranges(
12216 struct compile_state *state, struct reg_state *rstate,
12217 struct live_range *lr1, struct live_range *lr2)
12219 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12225 if (!lr1->defs || !lr2->defs) {
12226 internal_error(state, 0,
12227 "cannot coalese dead live ranges");
12229 if ((lr1->color == REG_UNNEEDED) ||
12230 (lr2->color == REG_UNNEEDED)) {
12231 internal_error(state, 0,
12232 "cannot coalesce live ranges without a possible color");
12234 if ((lr1->color != lr2->color) &&
12235 (lr1->color != REG_UNSET) &&
12236 (lr2->color != REG_UNSET)) {
12237 internal_error(state, lr1->defs->def,
12238 "cannot coalesce live ranges of different colors");
12240 color = lr1->color;
12241 if (color == REG_UNSET) {
12242 color = lr2->color;
12244 classes = lr1->classes & lr2->classes;
12246 internal_error(state, lr1->defs->def,
12247 "cannot coalesce live ranges with dissimilar register classes");
12249 #if DEBUG_COALESCING
12250 fprintf(stderr, "coalescing:");
12253 fprintf(stderr, " %p", lrd->def);
12255 } while(lrd != lr1->defs);
12256 fprintf(stderr, " |");
12259 fprintf(stderr, " %p", lrd->def);
12261 } while(lrd != lr2->defs);
12262 fprintf(stderr, "\n");
12264 /* If there is a clear dominate live range put it in lr1,
12265 * For purposes of this test phi functions are
12266 * considered dominated by the definitions that feed into
12269 if ((lr1->defs->prev->def->op == OP_PHI) ||
12270 ((lr2->defs->prev->def->op != OP_PHI) &&
12271 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12272 struct live_range *tmp;
12278 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12279 fprintf(stderr, "lr1 post\n");
12281 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12282 fprintf(stderr, "lr1 pre\n");
12284 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12285 fprintf(stderr, "lr2 post\n");
12287 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12288 fprintf(stderr, "lr2 pre\n");
12292 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12299 /* Append lr2 onto lr1 */
12300 #warning "FIXME should this be a merge instead of a splice?"
12301 /* This FIXME item applies to the correctness of live_range_end
12302 * and to the necessity of making multiple passes of coalesce_live_ranges.
12303 * A failure to find some coalesce opportunities in coaleace_live_ranges
12304 * does not impact the correct of the compiler just the efficiency with
12305 * which registers are allocated.
12308 mid1 = lr1->defs->prev;
12310 end = lr2->defs->prev;
12318 /* Fixup the live range in the added live range defs */
12323 } while(lrd != head);
12325 /* Mark lr2 as free. */
12327 lr2->color = REG_UNNEEDED;
12331 internal_error(state, 0, "lr1->defs == 0 ?");
12334 lr1->color = color;
12335 lr1->classes = classes;
12337 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12338 transfer_live_edges(rstate, lr1, lr2);
12343 static struct live_range_def *live_range_head(
12344 struct compile_state *state, struct live_range *lr,
12345 struct live_range_def *last)
12347 struct live_range_def *result;
12352 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12353 result = last->next;
12358 static struct live_range_def *live_range_end(
12359 struct compile_state *state, struct live_range *lr,
12360 struct live_range_def *last)
12362 struct live_range_def *result;
12365 result = lr->defs->prev;
12367 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12368 result = last->prev;
12374 static void initialize_live_ranges(
12375 struct compile_state *state, struct reg_state *rstate)
12377 struct triple *ins, *first;
12378 size_t count, size;
12381 first = RHS(state->main_function, 0);
12382 /* First count how many instructions I have.
12384 count = count_triples(state);
12385 /* Potentially I need one live range definitions for each
12388 rstate->defs = count;
12389 /* Potentially I need one live range for each instruction
12390 * plus an extra for the dummy live range.
12392 rstate->ranges = count + 1;
12393 size = sizeof(rstate->lrd[0]) * rstate->defs;
12394 rstate->lrd = xcmalloc(size, "live_range_def");
12395 size = sizeof(rstate->lr[0]) * rstate->ranges;
12396 rstate->lr = xcmalloc(size, "live_range");
12398 /* Setup the dummy live range */
12399 rstate->lr[0].classes = 0;
12400 rstate->lr[0].color = REG_UNSET;
12401 rstate->lr[0].defs = 0;
12405 /* If the triple is a variable give it a live range */
12406 if (triple_is_def(state, ins)) {
12407 struct reg_info info;
12408 /* Find the architecture specific color information */
12409 info = find_def_color(state, ins);
12411 rstate->lr[i].defs = &rstate->lrd[j];
12412 rstate->lr[i].color = info.reg;
12413 rstate->lr[i].classes = info.regcm;
12414 rstate->lr[i].degree = 0;
12415 rstate->lrd[j].lr = &rstate->lr[i];
12417 /* Otherwise give the triple the dummy live range. */
12419 rstate->lrd[j].lr = &rstate->lr[0];
12422 /* Initalize the live_range_def */
12423 rstate->lrd[j].next = &rstate->lrd[j];
12424 rstate->lrd[j].prev = &rstate->lrd[j];
12425 rstate->lrd[j].def = ins;
12426 rstate->lrd[j].orig_id = ins->id;
12431 } while(ins != first);
12432 rstate->ranges = i;
12434 /* Make a second pass to handle achitecture specific register
12439 int zlhs, zrhs, i, j;
12440 if (ins->id > rstate->defs) {
12441 internal_error(state, ins, "bad id");
12444 /* Walk through the template of ins and coalesce live ranges */
12445 zlhs = TRIPLE_LHS(ins->sizes);
12446 if ((zlhs == 0) && triple_is_def(state, ins)) {
12449 zrhs = TRIPLE_RHS(ins->sizes);
12451 #if DEBUG_COALESCING > 1
12452 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12456 for(i = 0; i < zlhs; i++) {
12457 struct reg_info linfo;
12458 struct live_range_def *lhs;
12459 linfo = arch_reg_lhs(state, ins, i);
12460 if (linfo.reg < MAX_REGISTERS) {
12463 if (triple_is_def(state, ins)) {
12464 lhs = &rstate->lrd[ins->id];
12466 lhs = &rstate->lrd[LHS(ins, i)->id];
12468 #if DEBUG_COALESCING > 1
12469 fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12470 i, lhs, linfo.reg);
12473 for(j = 0; j < zrhs; j++) {
12474 struct reg_info rinfo;
12475 struct live_range_def *rhs;
12476 rinfo = arch_reg_rhs(state, ins, j);
12477 if (rinfo.reg < MAX_REGISTERS) {
12480 rhs = &rstate->lrd[RHS(ins, j)->id];
12481 #if DEBUG_COALESCING > 1
12482 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12483 j, rhs, rinfo.reg);
12486 if (rinfo.reg == linfo.reg) {
12487 coalesce_ranges(state, rstate,
12493 } while(ins != first);
12496 static void graph_ins(
12497 struct compile_state *state,
12498 struct reg_block *blocks, struct triple_reg_set *live,
12499 struct reg_block *rb, struct triple *ins, void *arg)
12501 struct reg_state *rstate = arg;
12502 struct live_range *def;
12503 struct triple_reg_set *entry;
12505 /* If the triple is not a definition
12506 * we do not have a definition to add to
12507 * the interference graph.
12509 if (!triple_is_def(state, ins)) {
12512 def = rstate->lrd[ins->id].lr;
12514 /* Create an edge between ins and everything that is
12515 * alive, unless the live_range cannot share
12516 * a physical register with ins.
12518 for(entry = live; entry; entry = entry->next) {
12519 struct live_range *lr;
12520 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12521 internal_error(state, 0, "bad entry?");
12523 lr = rstate->lrd[entry->member->id].lr;
12527 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12530 add_live_edge(rstate, def, lr);
12535 static struct live_range *get_verify_live_range(
12536 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12538 struct live_range *lr;
12539 struct live_range_def *lrd;
12541 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12542 internal_error(state, ins, "bad ins?");
12544 lr = rstate->lrd[ins->id].lr;
12548 if (lrd->def == ins) {
12552 } while(lrd != lr->defs);
12554 internal_error(state, ins, "ins not in live range");
12559 static void verify_graph_ins(
12560 struct compile_state *state,
12561 struct reg_block *blocks, struct triple_reg_set *live,
12562 struct reg_block *rb, struct triple *ins, void *arg)
12564 struct reg_state *rstate = arg;
12565 struct triple_reg_set *entry1, *entry2;
12568 /* Compare live against edges and make certain the code is working */
12569 for(entry1 = live; entry1; entry1 = entry1->next) {
12570 struct live_range *lr1;
12571 lr1 = get_verify_live_range(state, rstate, entry1->member);
12572 for(entry2 = live; entry2; entry2 = entry2->next) {
12573 struct live_range *lr2;
12574 struct live_range_edge *edge2;
12577 if (entry2 == entry1) {
12580 lr2 = get_verify_live_range(state, rstate, entry2->member);
12582 internal_error(state, entry2->member,
12583 "live range with 2 values simultaneously alive");
12585 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12588 if (!interfere(rstate, lr1, lr2)) {
12589 internal_error(state, entry2->member,
12590 "edges don't interfere?");
12595 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12597 if (edge2->node == lr1) {
12601 if (lr2_degree != lr2->degree) {
12602 internal_error(state, entry2->member,
12603 "computed degree: %d does not match reported degree: %d\n",
12604 lr2_degree, lr2->degree);
12607 internal_error(state, entry2->member, "missing edge");
12615 static void print_interference_ins(
12616 struct compile_state *state,
12617 struct reg_block *blocks, struct triple_reg_set *live,
12618 struct reg_block *rb, struct triple *ins, void *arg)
12620 struct reg_state *rstate = arg;
12621 struct live_range *lr;
12624 lr = rstate->lrd[ins->id].lr;
12626 ins->id = rstate->lrd[id].orig_id;
12627 SET_REG(ins->id, lr->color);
12628 display_triple(stdout, ins);
12632 struct live_range_def *lrd;
12636 printf(" %-10p", lrd->def);
12638 } while(lrd != lr->defs);
12642 struct triple_reg_set *entry;
12644 for(entry = live; entry; entry = entry->next) {
12645 printf(" %-10p", entry->member);
12650 struct live_range_edge *entry;
12652 for(entry = lr->edges; entry; entry = entry->next) {
12653 struct live_range_def *lrd;
12654 lrd = entry->node->defs;
12656 printf(" %-10p", lrd->def);
12658 } while(lrd != entry->node->defs);
12663 if (triple_is_branch(state, ins)) {
12669 static int coalesce_live_ranges(
12670 struct compile_state *state, struct reg_state *rstate)
12672 /* At the point where a value is moved from one
12673 * register to another that value requires two
12674 * registers, thus increasing register pressure.
12675 * Live range coaleescing reduces the register
12676 * pressure by keeping a value in one register
12679 * In the case of a phi function all paths leading
12680 * into it must be allocated to the same register
12681 * otherwise the phi function may not be removed.
12683 * Forcing a value to stay in a single register
12684 * for an extended period of time does have
12685 * limitations when applied to non homogenous
12688 * The two cases I have identified are:
12689 * 1) Two forced register assignments may
12691 * 2) Registers may go unused because they
12692 * are only good for storing the value
12693 * and not manipulating it.
12695 * Because of this I need to split live ranges,
12696 * even outside of the context of coalesced live
12697 * ranges. The need to split live ranges does
12698 * impose some constraints on live range coalescing.
12700 * - Live ranges may not be coalesced across phi
12701 * functions. This creates a 2 headed live
12702 * range that cannot be sanely split.
12704 * - phi functions (coalesced in initialize_live_ranges)
12705 * are handled as pre split live ranges so we will
12706 * never attempt to split them.
12712 for(i = 0; i <= rstate->ranges; i++) {
12713 struct live_range *lr1;
12714 struct live_range_def *lrd1;
12715 lr1 = &rstate->lr[i];
12719 lrd1 = live_range_end(state, lr1, 0);
12720 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12721 struct triple_set *set;
12722 if (lrd1->def->op != OP_COPY) {
12725 /* Skip copies that are the result of a live range split. */
12726 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12729 for(set = lrd1->def->use; set; set = set->next) {
12730 struct live_range_def *lrd2;
12731 struct live_range *lr2, *res;
12733 lrd2 = &rstate->lrd[set->member->id];
12735 /* Don't coalesce with instructions
12736 * that are the result of a live range
12739 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12742 lr2 = rstate->lrd[set->member->id].lr;
12746 if ((lr1->color != lr2->color) &&
12747 (lr1->color != REG_UNSET) &&
12748 (lr2->color != REG_UNSET)) {
12751 if ((lr1->classes & lr2->classes) == 0) {
12755 if (interfere(rstate, lr1, lr2)) {
12759 res = coalesce_ranges(state, rstate, lr1, lr2);
12773 static void fix_coalesce_conflicts(struct compile_state *state,
12774 struct reg_block *blocks, struct triple_reg_set *live,
12775 struct reg_block *rb, struct triple *ins, void *arg)
12777 int *conflicts = arg;
12778 int zlhs, zrhs, i, j;
12780 /* See if we have a mandatory coalesce operation between
12781 * a lhs and a rhs value. If so and the rhs value is also
12782 * alive then this triple needs to be pre copied. Otherwise
12783 * we would have two definitions in the same live range simultaneously
12786 zlhs = TRIPLE_LHS(ins->sizes);
12787 if ((zlhs == 0) && triple_is_def(state, ins)) {
12790 zrhs = TRIPLE_RHS(ins->sizes);
12791 for(i = 0; i < zlhs; i++) {
12792 struct reg_info linfo;
12793 linfo = arch_reg_lhs(state, ins, i);
12794 if (linfo.reg < MAX_REGISTERS) {
12797 for(j = 0; j < zrhs; j++) {
12798 struct reg_info rinfo;
12799 struct triple *rhs;
12800 struct triple_reg_set *set;
12803 rinfo = arch_reg_rhs(state, ins, j);
12804 if (rinfo.reg != linfo.reg) {
12808 for(set = live; set && !found; set = set->next) {
12809 if (set->member == rhs) {
12814 struct triple *copy;
12815 copy = pre_copy(state, ins, j);
12816 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12824 static int correct_coalesce_conflicts(
12825 struct compile_state *state, struct reg_block *blocks)
12829 walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
12833 static void replace_set_use(struct compile_state *state,
12834 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12836 struct triple_reg_set *set;
12837 for(set = head; set; set = set->next) {
12838 if (set->member == orig) {
12844 static void replace_block_use(struct compile_state *state,
12845 struct reg_block *blocks, struct triple *orig, struct triple *new)
12848 #warning "WISHLIST visit just those blocks that need it *"
12849 for(i = 1; i <= state->last_vertex; i++) {
12850 struct reg_block *rb;
12852 replace_set_use(state, rb->in, orig, new);
12853 replace_set_use(state, rb->out, orig, new);
12857 static void color_instructions(struct compile_state *state)
12859 struct triple *ins, *first;
12860 first = RHS(state->main_function, 0);
12863 if (triple_is_def(state, ins)) {
12864 struct reg_info info;
12865 info = find_lhs_color(state, ins, 0);
12866 if (info.reg >= MAX_REGISTERS) {
12867 info.reg = REG_UNSET;
12869 SET_INFO(ins->id, info);
12872 } while(ins != first);
12875 static struct reg_info read_lhs_color(
12876 struct compile_state *state, struct triple *ins, int index)
12878 struct reg_info info;
12879 if ((index == 0) && triple_is_def(state, ins)) {
12880 info.reg = ID_REG(ins->id);
12881 info.regcm = ID_REGCM(ins->id);
12883 else if (index < TRIPLE_LHS(ins->sizes)) {
12884 info = read_lhs_color(state, LHS(ins, index), 0);
12887 internal_error(state, ins, "Bad lhs %d", index);
12888 info.reg = REG_UNSET;
12894 static struct triple *resolve_tangle(
12895 struct compile_state *state, struct triple *tangle)
12897 struct reg_info info, uinfo;
12898 struct triple_set *set, *next;
12899 struct triple *copy;
12901 #warning "WISHLIST recalculate all affected instructions colors"
12902 info = find_lhs_color(state, tangle, 0);
12903 for(set = tangle->use; set; set = next) {
12904 struct triple *user;
12907 user = set->member;
12908 zrhs = TRIPLE_RHS(user->sizes);
12909 for(i = 0; i < zrhs; i++) {
12910 if (RHS(user, i) != tangle) {
12913 uinfo = find_rhs_post_color(state, user, i);
12914 if (uinfo.reg == info.reg) {
12915 copy = pre_copy(state, user, i);
12916 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12917 SET_INFO(copy->id, uinfo);
12922 uinfo = find_lhs_pre_color(state, tangle, 0);
12923 if (uinfo.reg == info.reg) {
12924 struct reg_info linfo;
12925 copy = post_copy(state, tangle);
12926 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12927 linfo = find_lhs_color(state, copy, 0);
12928 SET_INFO(copy->id, linfo);
12930 info = find_lhs_color(state, tangle, 0);
12931 SET_INFO(tangle->id, info);
12937 static void fix_tangles(struct compile_state *state,
12938 struct reg_block *blocks, struct triple_reg_set *live,
12939 struct reg_block *rb, struct triple *ins, void *arg)
12941 int *tangles = arg;
12942 struct triple *tangle;
12944 char used[MAX_REGISTERS];
12945 struct triple_reg_set *set;
12948 /* Find out which registers have multiple uses at this point */
12949 memset(used, 0, sizeof(used));
12950 for(set = live; set; set = set->next) {
12951 struct reg_info info;
12952 info = read_lhs_color(state, set->member, 0);
12953 if (info.reg == REG_UNSET) {
12956 reg_inc_used(state, used, info.reg);
12959 /* Now find the least dominated definition of a register in
12960 * conflict I have seen so far.
12962 for(set = live; set; set = set->next) {
12963 struct reg_info info;
12964 info = read_lhs_color(state, set->member, 0);
12965 if (used[info.reg] < 2) {
12968 /* Changing copies that feed into phi functions
12971 if (set->member->use &&
12972 (set->member->use->member->op == OP_PHI)) {
12975 if (!tangle || tdominates(state, set->member, tangle)) {
12976 tangle = set->member;
12979 /* If I have found a tangle resolve it */
12981 struct triple *post_copy;
12983 post_copy = resolve_tangle(state, tangle);
12985 replace_block_use(state, blocks, tangle, post_copy);
12987 if (post_copy && (tangle != ins)) {
12988 replace_set_use(state, live, tangle, post_copy);
12995 static int correct_tangles(
12996 struct compile_state *state, struct reg_block *blocks)
13000 color_instructions(state);
13001 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13006 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13007 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13009 struct triple *find_constrained_def(
13010 struct compile_state *state, struct live_range *range, struct triple *constrained)
13012 struct live_range_def *lrd;
13015 struct reg_info info;
13017 int is_constrained;
13018 regcm = arch_type_to_regcm(state, lrd->def->type);
13019 info = find_lhs_color(state, lrd->def, 0);
13020 regcm = arch_regcm_reg_normalize(state, regcm);
13021 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13022 /* If the 2 register class masks are not equal the
13023 * the current register class is constrained.
13025 is_constrained = regcm != info.regcm;
13027 /* Of the constrained live ranges deal with the
13028 * least dominated one first.
13030 if (is_constrained) {
13031 if (!constrained ||
13032 tdominates(state, lrd->def, constrained))
13034 constrained = lrd->def;
13038 } while(lrd != range->defs);
13039 return constrained;
13042 static int split_constrained_ranges(
13043 struct compile_state *state, struct reg_state *rstate,
13044 struct live_range *range)
13046 /* Walk through the edges in conflict and our current live
13047 * range, and find definitions that are more severly constrained
13048 * than they type of data they contain require.
13050 * Then pick one of those ranges and relax the constraints.
13052 struct live_range_edge *edge;
13053 struct triple *constrained;
13056 for(edge = range->edges; edge; edge = edge->next) {
13057 constrained = find_constrained_def(state, edge->node, constrained);
13059 if (!constrained) {
13060 constrained = find_constrained_def(state, range, constrained);
13062 #if DEBUG_RANGE_CONFLICTS
13063 fprintf(stderr, "constrained: %s %p\n",
13064 tops(constrained->op), constrained);
13067 ids_from_rstate(state, rstate);
13068 cleanup_rstate(state, rstate);
13069 resolve_tangle(state, constrained);
13071 return !!constrained;
13074 static int split_ranges(
13075 struct compile_state *state, struct reg_state *rstate,
13076 char *used, struct live_range *range)
13079 #if DEBUG_RANGE_CONFLICTS
13080 fprintf(stderr, "split_ranges %d %s %p\n",
13081 rstate->passes, tops(range->defs->def->op), range->defs->def);
13083 if ((range->color == REG_UNNEEDED) ||
13084 (rstate->passes >= rstate->max_passes)) {
13087 split = split_constrained_ranges(state, rstate, range);
13089 /* Ideally I would split the live range that will not be used
13090 * for the longest period of time in hopes that this will
13091 * (a) allow me to spill a register or
13092 * (b) allow me to place a value in another register.
13094 * So far I don't have a test case for this, the resolving
13095 * of mandatory constraints has solved all of my
13096 * know issues. So I have choosen not to write any
13097 * code until I cat get a better feel for cases where
13098 * it would be useful to have.
13101 #warning "WISHLIST implement live range splitting..."
13102 if ((DEBUG_RANGE_CONFLICTS > 1) &&
13103 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13104 print_interference_blocks(state, rstate, stderr, 0);
13105 print_dominators(state, stderr);
13111 #if DEBUG_COLOR_GRAPH > 1
13112 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13113 #define cgdebug_flush() fflush(stdout)
13114 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13115 #elif DEBUG_COLOR_GRAPH == 1
13116 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13117 #define cgdebug_flush() fflush(stderr)
13118 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13120 #define cgdebug_printf(...)
13121 #define cgdebug_flush()
13122 #define cgdebug_loc(STATE, TRIPLE)
13126 static int select_free_color(struct compile_state *state,
13127 struct reg_state *rstate, struct live_range *range)
13129 struct triple_set *entry;
13130 struct live_range_def *lrd;
13131 struct live_range_def *phi;
13132 struct live_range_edge *edge;
13133 char used[MAX_REGISTERS];
13134 struct triple **expr;
13136 /* Instead of doing just the trivial color select here I try
13137 * a few extra things because a good color selection will help reduce
13141 /* Find the registers currently in use */
13142 memset(used, 0, sizeof(used));
13143 for(edge = range->edges; edge; edge = edge->next) {
13144 if (edge->node->color == REG_UNSET) {
13147 reg_fill_used(state, used, edge->node->color);
13149 #if DEBUG_COLOR_GRAPH > 1
13153 for(edge = range->edges; edge; edge = edge->next) {
13156 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13157 tops(range->def->op), i,
13158 range->def->filename, range->def->line, range->def->col);
13159 for(i = 0; i < MAX_REGISTERS; i++) {
13161 cgdebug_printf("used: %s\n",
13168 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13170 /* If a color is already assigned see if it will work */
13171 if (range->color != REG_UNSET) {
13172 struct live_range_def *lrd;
13173 if (!used[range->color]) {
13176 for(edge = range->edges; edge; edge = edge->next) {
13177 if (edge->node->color != range->color) {
13180 warning(state, edge->node->defs->def, "edge: ");
13181 lrd = edge->node->defs;
13183 warning(state, lrd->def, " %p %s",
13184 lrd->def, tops(lrd->def->op));
13186 } while(lrd != edge->node->defs);
13189 warning(state, range->defs->def, "def: ");
13191 warning(state, lrd->def, " %p %s",
13192 lrd->def, tops(lrd->def->op));
13194 } while(lrd != range->defs);
13195 internal_error(state, range->defs->def,
13196 "live range with already used color %s",
13197 arch_reg_str(range->color));
13200 /* If I feed into an expression reuse it's color.
13201 * This should help remove copies in the case of 2 register instructions
13202 * and phi functions.
13205 lrd = live_range_end(state, range, 0);
13206 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13207 entry = lrd->def->use;
13208 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13209 struct live_range_def *insd;
13210 insd = &rstate->lrd[entry->member->id];
13211 if (insd->lr->defs == 0) {
13214 if (!phi && (insd->def->op == OP_PHI) &&
13215 !interfere(rstate, range, insd->lr)) {
13218 if ((insd->lr->color == REG_UNSET) ||
13219 ((insd->lr->classes & range->classes) == 0) ||
13220 (used[insd->lr->color])) {
13223 if (interfere(rstate, range, insd->lr)) {
13226 range->color = insd->lr->color;
13229 /* If I feed into a phi function reuse it's color or the color
13230 * of something else that feeds into the phi function.
13233 if (phi->lr->color != REG_UNSET) {
13234 if (used[phi->lr->color]) {
13235 range->color = phi->lr->color;
13239 expr = triple_rhs(state, phi->def, 0);
13240 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13241 struct live_range *lr;
13245 lr = rstate->lrd[(*expr)->id].lr;
13246 if ((lr->color == REG_UNSET) ||
13247 ((lr->classes & range->classes) == 0) ||
13248 (used[lr->color])) {
13251 if (interfere(rstate, range, lr)) {
13254 range->color = lr->color;
13258 /* If I don't interfere with a rhs node reuse it's color */
13259 lrd = live_range_head(state, range, 0);
13260 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13261 expr = triple_rhs(state, lrd->def, 0);
13262 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13263 struct live_range *lr;
13267 lr = rstate->lrd[(*expr)->id].lr;
13268 if ((lr->color == -1) ||
13269 ((lr->classes & range->classes) == 0) ||
13270 (used[lr->color])) {
13273 if (interfere(rstate, range, lr)) {
13276 range->color = lr->color;
13280 /* If I have not opportunitically picked a useful color
13281 * pick the first color that is free.
13283 if (range->color == REG_UNSET) {
13285 arch_select_free_register(state, used, range->classes);
13287 if (range->color == REG_UNSET) {
13288 struct live_range_def *lrd;
13290 if (split_ranges(state, rstate, used, range)) {
13293 for(edge = range->edges; edge; edge = edge->next) {
13294 warning(state, edge->node->defs->def, "edge reg %s",
13295 arch_reg_str(edge->node->color));
13296 lrd = edge->node->defs;
13298 warning(state, lrd->def, " %s %p",
13299 tops(lrd->def->op), lrd->def);
13301 } while(lrd != edge->node->defs);
13303 warning(state, range->defs->def, "range: ");
13306 warning(state, lrd->def, " %s %p",
13307 tops(lrd->def->op), lrd->def);
13309 } while(lrd != range->defs);
13311 warning(state, range->defs->def, "classes: %x",
13313 for(i = 0; i < MAX_REGISTERS; i++) {
13315 warning(state, range->defs->def, "used: %s",
13319 #if DEBUG_COLOR_GRAPH < 2
13320 error(state, range->defs->def, "too few registers");
13322 internal_error(state, range->defs->def, "too few registers");
13325 range->classes = arch_reg_regcm(state, range->color);
13326 if (range->color == -1) {
13327 internal_error(state, range->defs->def, "select_free_color did not?");
13332 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13335 struct live_range_edge *edge;
13336 struct live_range *range;
13338 cgdebug_printf("Lo: ");
13339 range = rstate->low;
13340 if (*range->group_prev != range) {
13341 internal_error(state, 0, "lo: *prev != range?");
13343 *range->group_prev = range->group_next;
13344 if (range->group_next) {
13345 range->group_next->group_prev = range->group_prev;
13347 if (&range->group_next == rstate->low_tail) {
13348 rstate->low_tail = range->group_prev;
13350 if (rstate->low == range) {
13351 internal_error(state, 0, "low: next != prev?");
13354 else if (rstate->high) {
13355 cgdebug_printf("Hi: ");
13356 range = rstate->high;
13357 if (*range->group_prev != range) {
13358 internal_error(state, 0, "hi: *prev != range?");
13360 *range->group_prev = range->group_next;
13361 if (range->group_next) {
13362 range->group_next->group_prev = range->group_prev;
13364 if (&range->group_next == rstate->high_tail) {
13365 rstate->high_tail = range->group_prev;
13367 if (rstate->high == range) {
13368 internal_error(state, 0, "high: next != prev?");
13374 cgdebug_printf(" %d\n", range - rstate->lr);
13375 range->group_prev = 0;
13376 for(edge = range->edges; edge; edge = edge->next) {
13377 struct live_range *node;
13379 /* Move nodes from the high to the low list */
13380 if (node->group_prev && (node->color == REG_UNSET) &&
13381 (node->degree == regc_max_size(state, node->classes))) {
13382 if (*node->group_prev != node) {
13383 internal_error(state, 0, "move: *prev != node?");
13385 *node->group_prev = node->group_next;
13386 if (node->group_next) {
13387 node->group_next->group_prev = node->group_prev;
13389 if (&node->group_next == rstate->high_tail) {
13390 rstate->high_tail = node->group_prev;
13392 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13393 node->group_prev = rstate->low_tail;
13394 node->group_next = 0;
13395 *rstate->low_tail = node;
13396 rstate->low_tail = &node->group_next;
13397 if (*node->group_prev != node) {
13398 internal_error(state, 0, "move2: *prev != node?");
13403 colored = color_graph(state, rstate);
13405 cgdebug_printf("Coloring %d @", range - rstate->lr);
13406 cgdebug_loc(state, range->defs->def);
13408 colored = select_free_color(state, rstate, range);
13409 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13414 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13416 struct live_range *lr;
13417 struct live_range_edge *edge;
13418 struct triple *ins, *first;
13419 char used[MAX_REGISTERS];
13420 first = RHS(state->main_function, 0);
13423 if (triple_is_def(state, ins)) {
13424 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13425 internal_error(state, ins,
13426 "triple without a live range def");
13428 lr = rstate->lrd[ins->id].lr;
13429 if (lr->color == REG_UNSET) {
13430 internal_error(state, ins,
13431 "triple without a color");
13433 /* Find the registers used by the edges */
13434 memset(used, 0, sizeof(used));
13435 for(edge = lr->edges; edge; edge = edge->next) {
13436 if (edge->node->color == REG_UNSET) {
13437 internal_error(state, 0,
13438 "live range without a color");
13440 reg_fill_used(state, used, edge->node->color);
13442 if (used[lr->color]) {
13443 internal_error(state, ins,
13444 "triple with already used color");
13448 } while(ins != first);
13451 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13453 struct live_range *lr;
13454 struct triple *first, *ins;
13455 first = RHS(state->main_function, 0);
13458 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13459 internal_error(state, ins,
13460 "triple without a live range");
13462 lr = rstate->lrd[ins->id].lr;
13463 SET_REG(ins->id, lr->color);
13465 } while (ins != first);
13468 static struct live_range *merge_sort_lr(
13469 struct live_range *first, struct live_range *last)
13471 struct live_range *mid, *join, **join_tail, *pick;
13473 size = (last - first) + 1;
13475 mid = first + size/2;
13476 first = merge_sort_lr(first, mid -1);
13477 mid = merge_sort_lr(mid, last);
13481 /* merge the two lists */
13482 while(first && mid) {
13483 if ((first->degree < mid->degree) ||
13484 ((first->degree == mid->degree) &&
13485 (first->length < mid->length))) {
13487 first = first->group_next;
13489 first->group_prev = 0;
13494 mid = mid->group_next;
13496 mid->group_prev = 0;
13499 pick->group_next = 0;
13500 pick->group_prev = join_tail;
13502 join_tail = &pick->group_next;
13504 /* Splice the remaining list */
13505 pick = (first)? first : mid;
13508 pick->group_prev = join_tail;
13512 if (!first->defs) {
13520 static void ids_from_rstate(struct compile_state *state,
13521 struct reg_state *rstate)
13523 struct triple *ins, *first;
13524 if (!rstate->defs) {
13527 /* Display the graph if desired */
13528 if (state->debug & DEBUG_INTERFERENCE) {
13529 print_blocks(state, stdout);
13530 print_control_flow(state);
13532 first = RHS(state->main_function, 0);
13536 struct live_range_def *lrd;
13537 lrd = &rstate->lrd[ins->id];
13538 ins->id = lrd->orig_id;
13541 } while(ins != first);
13544 static void cleanup_live_edges(struct reg_state *rstate)
13547 /* Free the edges on each node */
13548 for(i = 1; i <= rstate->ranges; i++) {
13549 remove_live_edges(rstate, &rstate->lr[i]);
13553 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13555 cleanup_live_edges(rstate);
13556 xfree(rstate->lrd);
13559 /* Free the variable lifetime information */
13560 if (rstate->blocks) {
13561 free_variable_lifetimes(state, rstate->blocks);
13564 rstate->ranges = 0;
13567 rstate->blocks = 0;
13570 static void verify_consistency(struct compile_state *state);
13571 static void allocate_registers(struct compile_state *state)
13573 struct reg_state rstate;
13576 /* Clear out the reg_state */
13577 memset(&rstate, 0, sizeof(rstate));
13578 rstate.max_passes = MAX_ALLOCATION_PASSES;
13581 struct live_range **point, **next;
13586 #if DEBUG_RANGE_CONFLICTS
13587 fprintf(stderr, "pass: %d\n", rstate.passes);
13591 ids_from_rstate(state, &rstate);
13593 /* Cleanup the temporary data structures */
13594 cleanup_rstate(state, &rstate);
13596 /* Compute the variable lifetimes */
13597 rstate.blocks = compute_variable_lifetimes(state);
13599 /* Fix invalid mandatory live range coalesce conflicts */
13600 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13602 /* Fix two simultaneous uses of the same register.
13603 * In a few pathlogical cases a partial untangle moves
13604 * the tangle to a part of the graph we won't revisit.
13605 * So we keep looping until we have no more tangle fixes
13609 tangles = correct_tangles(state, rstate.blocks);
13612 if (state->debug & DEBUG_INSERTED_COPIES) {
13613 printf("After resolve_tangles\n");
13614 print_blocks(state, stdout);
13615 print_control_flow(state);
13617 verify_consistency(state);
13619 /* Allocate and initialize the live ranges */
13620 initialize_live_ranges(state, &rstate);
13622 /* Note current doing coalescing in a loop appears to
13623 * buys me nothing. The code is left this way in case
13624 * there is some value in it. Or if a future bugfix
13625 * yields some benefit.
13628 #if DEBUG_COALESCING
13629 fprintf(stderr, "coalescing\n");
13631 /* Remove any previous live edge calculations */
13632 cleanup_live_edges(&rstate);
13634 /* Compute the interference graph */
13635 walk_variable_lifetimes(
13636 state, rstate.blocks, graph_ins, &rstate);
13638 /* Display the interference graph if desired */
13639 if (state->debug & DEBUG_INTERFERENCE) {
13640 print_interference_blocks(state, &rstate, stdout, 1);
13641 printf("\nlive variables by instruction\n");
13642 walk_variable_lifetimes(
13643 state, rstate.blocks,
13644 print_interference_ins, &rstate);
13647 coalesced = coalesce_live_ranges(state, &rstate);
13649 #if DEBUG_COALESCING
13650 fprintf(stderr, "coalesced: %d\n", coalesced);
13652 } while(coalesced);
13654 #if DEBUG_CONSISTENCY > 1
13656 fprintf(stderr, "verify_graph_ins...\n");
13658 /* Verify the interference graph */
13659 walk_variable_lifetimes(
13660 state, rstate.blocks, verify_graph_ins, &rstate);
13662 fprintf(stderr, "verify_graph_ins done\n");
13666 /* Build the groups low and high. But with the nodes
13667 * first sorted by degree order.
13669 rstate.low_tail = &rstate.low;
13670 rstate.high_tail = &rstate.high;
13671 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13673 rstate.high->group_prev = &rstate.high;
13675 for(point = &rstate.high; *point; point = &(*point)->group_next)
13677 rstate.high_tail = point;
13678 /* Walk through the high list and move everything that needs
13681 for(point = &rstate.high; *point; point = next) {
13682 struct live_range *range;
13683 next = &(*point)->group_next;
13686 /* If it has a low degree or it already has a color
13687 * place the node in low.
13689 if ((range->degree < regc_max_size(state, range->classes)) ||
13690 (range->color != REG_UNSET)) {
13691 cgdebug_printf("Lo: %5d degree %5d%s\n",
13692 range - rstate.lr, range->degree,
13693 (range->color != REG_UNSET) ? " (colored)": "");
13694 *range->group_prev = range->group_next;
13695 if (range->group_next) {
13696 range->group_next->group_prev = range->group_prev;
13698 if (&range->group_next == rstate.high_tail) {
13699 rstate.high_tail = range->group_prev;
13701 range->group_prev = rstate.low_tail;
13702 range->group_next = 0;
13703 *rstate.low_tail = range;
13704 rstate.low_tail = &range->group_next;
13708 cgdebug_printf("hi: %5d degree %5d%s\n",
13709 range - rstate.lr, range->degree,
13710 (range->color != REG_UNSET) ? " (colored)": "");
13713 /* Color the live_ranges */
13714 colored = color_graph(state, &rstate);
13716 } while (!colored);
13718 /* Verify the graph was properly colored */
13719 verify_colors(state, &rstate);
13721 /* Move the colors from the graph to the triples */
13722 color_triples(state, &rstate);
13724 /* Cleanup the temporary data structures */
13725 cleanup_rstate(state, &rstate);
13728 /* Sparce Conditional Constant Propogation
13729 * =========================================
13733 struct lattice_node {
13735 struct triple *def;
13736 struct ssa_edge *out;
13737 struct flow_block *fblock;
13738 struct triple *val;
13739 /* lattice high val && !is_const(val)
13740 * lattice const is_const(val)
13741 * lattice low val == 0
13745 struct lattice_node *src;
13746 struct lattice_node *dst;
13747 struct ssa_edge *work_next;
13748 struct ssa_edge *work_prev;
13749 struct ssa_edge *out_next;
13752 struct flow_block *src;
13753 struct flow_block *dst;
13754 struct flow_edge *work_next;
13755 struct flow_edge *work_prev;
13756 struct flow_edge *in_next;
13757 struct flow_edge *out_next;
13760 struct flow_block {
13761 struct block *block;
13762 struct flow_edge *in;
13763 struct flow_edge *out;
13764 struct flow_edge left, right;
13769 struct lattice_node *lattice;
13770 struct ssa_edge *ssa_edges;
13771 struct flow_block *flow_blocks;
13772 struct flow_edge *flow_work_list;
13773 struct ssa_edge *ssa_work_list;
13777 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13778 struct flow_edge *fedge)
13780 if (!scc->flow_work_list) {
13781 scc->flow_work_list = fedge;
13782 fedge->work_next = fedge->work_prev = fedge;
13785 struct flow_edge *ftail;
13786 ftail = scc->flow_work_list->work_prev;
13787 fedge->work_next = ftail->work_next;
13788 fedge->work_prev = ftail;
13789 fedge->work_next->work_prev = fedge;
13790 fedge->work_prev->work_next = fedge;
13794 static struct flow_edge *scc_next_fedge(
13795 struct compile_state *state, struct scc_state *scc)
13797 struct flow_edge *fedge;
13798 fedge = scc->flow_work_list;
13800 fedge->work_next->work_prev = fedge->work_prev;
13801 fedge->work_prev->work_next = fedge->work_next;
13802 if (fedge->work_next != fedge) {
13803 scc->flow_work_list = fedge->work_next;
13805 scc->flow_work_list = 0;
13811 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13812 struct ssa_edge *sedge)
13814 if (!scc->ssa_work_list) {
13815 scc->ssa_work_list = sedge;
13816 sedge->work_next = sedge->work_prev = sedge;
13819 struct ssa_edge *stail;
13820 stail = scc->ssa_work_list->work_prev;
13821 sedge->work_next = stail->work_next;
13822 sedge->work_prev = stail;
13823 sedge->work_next->work_prev = sedge;
13824 sedge->work_prev->work_next = sedge;
13828 static struct ssa_edge *scc_next_sedge(
13829 struct compile_state *state, struct scc_state *scc)
13831 struct ssa_edge *sedge;
13832 sedge = scc->ssa_work_list;
13834 sedge->work_next->work_prev = sedge->work_prev;
13835 sedge->work_prev->work_next = sedge->work_next;
13836 if (sedge->work_next != sedge) {
13837 scc->ssa_work_list = sedge->work_next;
13839 scc->ssa_work_list = 0;
13845 static void initialize_scc_state(
13846 struct compile_state *state, struct scc_state *scc)
13848 int ins_count, ssa_edge_count;
13849 int ins_index, ssa_edge_index, fblock_index;
13850 struct triple *first, *ins;
13851 struct block *block;
13852 struct flow_block *fblock;
13854 memset(scc, 0, sizeof(*scc));
13856 /* Inialize pass zero find out how much memory we need */
13857 first = RHS(state->main_function, 0);
13859 ins_count = ssa_edge_count = 0;
13861 struct triple_set *edge;
13863 for(edge = ins->use; edge; edge = edge->next) {
13867 } while(ins != first);
13869 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13870 ins_count, ssa_edge_count, state->last_vertex);
13872 scc->ins_count = ins_count;
13874 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13876 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13878 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
13881 /* Initialize pass one collect up the nodes */
13884 ins_index = ssa_edge_index = fblock_index = 0;
13887 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13888 block = ins->u.block;
13890 internal_error(state, ins, "label without block");
13893 block->vertex = fblock_index;
13894 fblock = &scc->flow_blocks[fblock_index];
13895 fblock->block = block;
13898 struct lattice_node *lnode;
13900 lnode = &scc->lattice[ins_index];
13903 lnode->fblock = fblock;
13904 lnode->val = ins; /* LATTICE HIGH */
13905 lnode->old_id = ins->id;
13906 ins->id = ins_index;
13909 } while(ins != first);
13910 /* Initialize pass two collect up the edges */
13915 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13916 struct flow_edge *fedge, **ftail;
13917 struct block_set *bedge;
13918 block = ins->u.block;
13919 fblock = &scc->flow_blocks[block->vertex];
13922 ftail = &fblock->out;
13924 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13925 if (fblock->left.dst->block != block->left) {
13926 internal_error(state, 0, "block mismatch");
13928 fblock->left.out_next = 0;
13929 *ftail = &fblock->left;
13930 ftail = &fblock->left.out_next;
13932 if (block->right) {
13933 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13934 if (fblock->right.dst->block != block->right) {
13935 internal_error(state, 0, "block mismatch");
13937 fblock->right.out_next = 0;
13938 *ftail = &fblock->right;
13939 ftail = &fblock->right.out_next;
13941 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13942 fedge->src = fblock;
13943 fedge->work_next = fedge->work_prev = fedge;
13944 fedge->executable = 0;
13946 ftail = &fblock->in;
13947 for(bedge = block->use; bedge; bedge = bedge->next) {
13948 struct block *src_block;
13949 struct flow_block *sfblock;
13950 struct flow_edge *sfedge;
13951 src_block = bedge->member;
13952 sfblock = &scc->flow_blocks[src_block->vertex];
13954 if (src_block->left == block) {
13955 sfedge = &sfblock->left;
13957 sfedge = &sfblock->right;
13960 ftail = &sfedge->in_next;
13961 sfedge->in_next = 0;
13965 struct triple_set *edge;
13966 struct ssa_edge **stail;
13967 struct lattice_node *lnode;
13968 lnode = &scc->lattice[ins->id];
13970 stail = &lnode->out;
13971 for(edge = ins->use; edge; edge = edge->next) {
13972 struct ssa_edge *sedge;
13973 ssa_edge_index += 1;
13974 sedge = &scc->ssa_edges[ssa_edge_index];
13976 stail = &sedge->out_next;
13977 sedge->src = lnode;
13978 sedge->dst = &scc->lattice[edge->member->id];
13979 sedge->work_next = sedge->work_prev = sedge;
13980 sedge->out_next = 0;
13984 } while(ins != first);
13985 /* Setup a dummy block 0 as a node above the start node */
13987 struct flow_block *fblock, *dst;
13988 struct flow_edge *fedge;
13989 fblock = &scc->flow_blocks[0];
13992 fblock->out = &fblock->left;
13993 dst = &scc->flow_blocks[state->first_block->vertex];
13994 fedge = &fblock->left;
13995 fedge->src = fblock;
13997 fedge->work_next = fedge;
13998 fedge->work_prev = fedge;
13999 fedge->in_next = fedge->dst->in;
14000 fedge->out_next = 0;
14001 fedge->executable = 0;
14002 fedge->dst->in = fedge;
14004 /* Initialize the work lists */
14005 scc->flow_work_list = 0;
14006 scc->ssa_work_list = 0;
14007 scc_add_fedge(state, scc, fedge);
14010 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14011 ins_index, ssa_edge_index, fblock_index);
14016 static void free_scc_state(
14017 struct compile_state *state, struct scc_state *scc)
14019 xfree(scc->flow_blocks);
14020 xfree(scc->ssa_edges);
14021 xfree(scc->lattice);
14025 static struct lattice_node *triple_to_lattice(
14026 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14028 if (ins->id <= 0) {
14029 internal_error(state, ins, "bad id");
14031 return &scc->lattice[ins->id];
14034 static struct triple *preserve_lval(
14035 struct compile_state *state, struct lattice_node *lnode)
14037 struct triple *old;
14038 /* Preserve the original value */
14040 old = dup_triple(state, lnode->val);
14041 if (lnode->val != lnode->def) {
14051 static int lval_changed(struct compile_state *state,
14052 struct triple *old, struct lattice_node *lnode)
14055 /* See if the lattice value has changed */
14057 if (!old && !lnode->val) {
14060 if (changed && lnode->val && !is_const(lnode->val)) {
14064 lnode->val && old &&
14065 (memcmp(lnode->val->param, old->param,
14066 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14067 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14077 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14078 struct lattice_node *lnode)
14080 struct lattice_node *tmp;
14081 struct triple **slot, *old;
14082 struct flow_edge *fedge;
14084 if (lnode->def->op != OP_PHI) {
14085 internal_error(state, lnode->def, "not phi");
14087 /* Store the original value */
14088 old = preserve_lval(state, lnode);
14090 /* default to lattice high */
14091 lnode->val = lnode->def;
14092 slot = &RHS(lnode->def, 0);
14094 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14095 if (!fedge->executable) {
14098 if (!slot[index]) {
14099 internal_error(state, lnode->def, "no phi value");
14101 tmp = triple_to_lattice(state, scc, slot[index]);
14102 /* meet(X, lattice low) = lattice low */
14106 /* meet(X, lattice high) = X */
14107 else if (!tmp->val) {
14108 lnode->val = lnode->val;
14110 /* meet(lattice high, X) = X */
14111 else if (!is_const(lnode->val)) {
14112 lnode->val = dup_triple(state, tmp->val);
14113 lnode->val->type = lnode->def->type;
14115 /* meet(const, const) = const or lattice low */
14116 else if (!constants_equal(state, lnode->val, tmp->val)) {
14124 fprintf(stderr, "phi: %d -> %s\n",
14126 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14128 /* If the lattice value has changed update the work lists. */
14129 if (lval_changed(state, old, lnode)) {
14130 struct ssa_edge *sedge;
14131 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14132 scc_add_sedge(state, scc, sedge);
14137 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14138 struct lattice_node *lnode)
14141 struct triple *old, *scratch;
14142 struct triple **dexpr, **vexpr;
14145 /* Store the original value */
14146 old = preserve_lval(state, lnode);
14148 /* Reinitialize the value */
14149 lnode->val = scratch = dup_triple(state, lnode->def);
14150 scratch->id = lnode->old_id;
14151 scratch->next = scratch;
14152 scratch->prev = scratch;
14155 count = TRIPLE_SIZE(scratch->sizes);
14156 for(i = 0; i < count; i++) {
14157 dexpr = &lnode->def->param[i];
14158 vexpr = &scratch->param[i];
14160 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14161 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14163 struct lattice_node *tmp;
14164 tmp = triple_to_lattice(state, scc, *dexpr);
14165 *vexpr = (tmp->val)? tmp->val : tmp->def;
14168 if (scratch->op == OP_BRANCH) {
14169 scratch->next = lnode->def->next;
14171 /* Recompute the value */
14172 #warning "FIXME see if simplify does anything bad"
14173 /* So far it looks like only the strength reduction
14174 * optimization are things I need to worry about.
14176 simplify(state, scratch);
14177 /* Cleanup my value */
14178 if (scratch->use) {
14179 internal_error(state, lnode->def, "scratch used?");
14181 if ((scratch->prev != scratch) ||
14182 ((scratch->next != scratch) &&
14183 ((lnode->def->op != OP_BRANCH) ||
14184 (scratch->next != lnode->def->next)))) {
14185 internal_error(state, lnode->def, "scratch in list?");
14187 /* undo any uses... */
14188 count = TRIPLE_SIZE(scratch->sizes);
14189 for(i = 0; i < count; i++) {
14190 vexpr = &scratch->param[i];
14192 unuse_triple(*vexpr, scratch);
14195 if (!is_const(scratch)) {
14196 for(i = 0; i < count; i++) {
14197 dexpr = &lnode->def->param[i];
14198 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14199 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14201 struct lattice_node *tmp;
14202 tmp = triple_to_lattice(state, scc, *dexpr);
14210 (lnode->val->op == lnode->def->op) &&
14211 (memcmp(lnode->val->param, lnode->def->param,
14212 count * sizeof(lnode->val->param[0])) == 0) &&
14213 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14214 lnode->val = lnode->def;
14216 /* Find the cases that are always lattice lo */
14218 triple_is_def(state, lnode->val) &&
14219 !triple_is_pure(state, lnode->val)) {
14223 (lnode->val->op == OP_SDECL) &&
14224 (lnode->val != lnode->def)) {
14225 internal_error(state, lnode->def, "bad sdecl");
14227 /* See if the lattice value has changed */
14228 changed = lval_changed(state, old, lnode);
14229 if (lnode->val != scratch) {
14235 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14236 struct lattice_node *lnode)
14238 struct lattice_node *cond;
14241 struct flow_edge *fedge;
14242 fprintf(stderr, "branch: %d (",
14245 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14246 fprintf(stderr, " %d", fedge->dst->block->vertex);
14248 fprintf(stderr, " )");
14249 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14250 fprintf(stderr, " <- %d",
14251 RHS(lnode->def, 0)->id);
14253 fprintf(stderr, "\n");
14256 if (lnode->def->op != OP_BRANCH) {
14257 internal_error(state, lnode->def, "not branch");
14259 /* This only applies to conditional branches */
14260 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14263 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14264 if (cond->val && !is_const(cond->val)) {
14265 #warning "FIXME do I need to do something here?"
14266 warning(state, cond->def, "condition not constant?");
14269 if (cond->val == 0) {
14270 scc_add_fedge(state, scc, cond->fblock->out);
14271 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14273 else if (cond->val->u.cval) {
14274 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14277 scc_add_fedge(state, scc, cond->fblock->out);
14282 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14283 struct lattice_node *lnode)
14287 changed = compute_lnode_val(state, scc, lnode);
14290 struct triple **expr;
14291 fprintf(stderr, "expr: %3d %10s (",
14292 lnode->def->id, tops(lnode->def->op));
14293 expr = triple_rhs(state, lnode->def, 0);
14294 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14296 fprintf(stderr, " %d", (*expr)->id);
14299 fprintf(stderr, " ) -> %s\n",
14300 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14303 if (lnode->def->op == OP_BRANCH) {
14304 scc_visit_branch(state, scc, lnode);
14307 else if (changed) {
14308 struct ssa_edge *sedge;
14309 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14310 scc_add_sedge(state, scc, sedge);
14315 static void scc_writeback_values(
14316 struct compile_state *state, struct scc_state *scc)
14318 struct triple *first, *ins;
14319 first = RHS(state->main_function, 0);
14322 struct lattice_node *lnode;
14323 lnode = triple_to_lattice(state, scc, ins);
14325 ins->id = lnode->old_id;
14327 if (lnode->val && !is_const(lnode->val)) {
14328 warning(state, lnode->def,
14329 "lattice node still high?");
14332 if (lnode->val && (lnode->val != ins)) {
14333 /* See if it something I know how to write back */
14334 switch(lnode->val->op) {
14336 mkconst(state, ins, lnode->val->u.cval);
14339 mkaddr_const(state, ins,
14340 MISC(lnode->val, 0), lnode->val->u.cval);
14343 /* By default don't copy the changes,
14344 * recompute them in place instead.
14346 simplify(state, ins);
14349 if (is_const(lnode->val) &&
14350 !constants_equal(state, lnode->val, ins)) {
14351 internal_error(state, 0, "constants not equal");
14353 /* Free the lattice nodes */
14358 } while(ins != first);
14361 static void scc_transform(struct compile_state *state)
14363 struct scc_state scc;
14365 initialize_scc_state(state, &scc);
14367 while(scc.flow_work_list || scc.ssa_work_list) {
14368 struct flow_edge *fedge;
14369 struct ssa_edge *sedge;
14370 struct flow_edge *fptr;
14371 while((fedge = scc_next_fedge(state, &scc))) {
14372 struct block *block;
14373 struct triple *ptr;
14374 struct flow_block *fblock;
14377 if (fedge->executable) {
14381 internal_error(state, 0, "fedge without dst");
14384 internal_error(state, 0, "fedge without src");
14386 fedge->executable = 1;
14387 fblock = fedge->dst;
14388 block = fblock->block;
14390 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14391 if (fptr->executable) {
14396 fprintf(stderr, "vertex: %d time: %d\n",
14397 block->vertex, time);
14401 for(ptr = block->first; !done; ptr = ptr->next) {
14402 struct lattice_node *lnode;
14403 done = (ptr == block->last);
14404 lnode = &scc.lattice[ptr->id];
14405 if (ptr->op == OP_PHI) {
14406 scc_visit_phi(state, &scc, lnode);
14408 else if (time == 1) {
14409 scc_visit_expr(state, &scc, lnode);
14412 if (fblock->out && !fblock->out->out_next) {
14413 scc_add_fedge(state, &scc, fblock->out);
14416 while((sedge = scc_next_sedge(state, &scc))) {
14417 struct lattice_node *lnode;
14418 struct flow_block *fblock;
14419 lnode = sedge->dst;
14420 fblock = lnode->fblock;
14422 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14423 sedge - scc.ssa_edges,
14424 sedge->src->def->id,
14425 sedge->dst->def->id);
14427 if (lnode->def->op == OP_PHI) {
14428 scc_visit_phi(state, &scc, lnode);
14431 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14432 if (fptr->executable) {
14437 scc_visit_expr(state, &scc, lnode);
14443 scc_writeback_values(state, &scc);
14444 free_scc_state(state, &scc);
14448 static void transform_to_arch_instructions(struct compile_state *state)
14450 struct triple *ins, *first;
14451 first = RHS(state->main_function, 0);
14454 ins = transform_to_arch_instruction(state, ins);
14455 } while(ins != first);
14458 #if DEBUG_CONSISTENCY
14459 static void verify_uses(struct compile_state *state)
14461 struct triple *first, *ins;
14462 struct triple_set *set;
14463 first = RHS(state->main_function, 0);
14466 struct triple **expr;
14467 expr = triple_rhs(state, ins, 0);
14468 for(; expr; expr = triple_rhs(state, ins, expr)) {
14469 struct triple *rhs;
14471 for(set = rhs?rhs->use:0; set; set = set->next) {
14472 if (set->member == ins) {
14477 internal_error(state, ins, "rhs not used");
14480 expr = triple_lhs(state, ins, 0);
14481 for(; expr; expr = triple_lhs(state, ins, expr)) {
14482 struct triple *lhs;
14484 for(set = lhs?lhs->use:0; set; set = set->next) {
14485 if (set->member == ins) {
14490 internal_error(state, ins, "lhs not used");
14494 } while(ins != first);
14497 static void verify_blocks_present(struct compile_state *state)
14499 struct triple *first, *ins;
14500 if (!state->first_block) {
14503 first = RHS(state->main_function, 0);
14506 if (triple_stores_block(state, ins)) {
14507 if (!ins->u.block) {
14508 internal_error(state, ins,
14509 "%p not in a block?\n", ins);
14513 } while(ins != first);
14517 static void verify_blocks(struct compile_state *state)
14519 struct triple *ins;
14520 struct block *block;
14521 block = state->first_block;
14526 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14527 if (!triple_stores_block(state, ins)) {
14530 if (ins->u.block != block) {
14531 internal_error(state, ins, "inconsitent block specified");
14534 if (!triple_stores_block(state, block->last->next)) {
14535 internal_error(state, block->last->next,
14536 "cannot find next block");
14538 block = block->last->next->u.block;
14540 internal_error(state, block->last->next,
14543 } while(block != state->first_block);
14546 static void verify_domination(struct compile_state *state)
14548 struct triple *first, *ins;
14549 struct triple_set *set;
14550 if (!state->first_block) {
14554 first = RHS(state->main_function, 0);
14557 for(set = ins->use; set; set = set->next) {
14558 struct triple **expr;
14559 if (set->member->op == OP_PHI) {
14562 /* See if the use is on the righ hand side */
14563 expr = triple_rhs(state, set->member, 0);
14564 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14565 if (*expr == ins) {
14570 !tdominates(state, ins, set->member)) {
14571 internal_error(state, set->member,
14572 "non dominated rhs use?");
14576 } while(ins != first);
14579 static void verify_piece(struct compile_state *state)
14581 struct triple *first, *ins;
14582 first = RHS(state->main_function, 0);
14585 struct triple *ptr;
14587 lhs = TRIPLE_LHS(ins->sizes);
14588 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14591 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14592 if (ptr != LHS(ins, i)) {
14593 internal_error(state, ins, "malformed lhs on %s",
14596 if (ptr->op != OP_PIECE) {
14597 internal_error(state, ins, "bad lhs op %s at %d on %s",
14598 tops(ptr->op), i, tops(ins->op));
14600 if (ptr->u.cval != i) {
14601 internal_error(state, ins, "bad u.cval of %d %d expected",
14606 } while(ins != first);
14608 static void verify_ins_colors(struct compile_state *state)
14610 struct triple *first, *ins;
14612 first = RHS(state->main_function, 0);
14616 } while(ins != first);
14618 static void verify_consistency(struct compile_state *state)
14620 verify_uses(state);
14621 verify_blocks_present(state);
14622 verify_blocks(state);
14623 verify_domination(state);
14624 verify_piece(state);
14625 verify_ins_colors(state);
14628 static void verify_consistency(struct compile_state *state) {}
14629 #endif /* DEBUG_USES */
14631 static void optimize(struct compile_state *state)
14633 if (state->debug & DEBUG_TRIPLES) {
14634 print_triples(state);
14636 /* Replace structures with simpler data types */
14637 flatten_structures(state);
14638 if (state->debug & DEBUG_TRIPLES) {
14639 print_triples(state);
14641 verify_consistency(state);
14642 /* Analize the intermediate code */
14643 setup_basic_blocks(state);
14644 analyze_idominators(state);
14645 analyze_ipdominators(state);
14647 /* Transform the code to ssa form */
14648 transform_to_ssa_form(state);
14649 verify_consistency(state);
14650 if (state->debug & DEBUG_CODE_ELIMINATION) {
14651 fprintf(stdout, "After transform_to_ssa_form\n");
14652 print_blocks(state, stdout);
14654 /* Do strength reduction and simple constant optimizations */
14655 if (state->optimize >= 1) {
14656 simplify_all(state);
14658 verify_consistency(state);
14659 /* Propogate constants throughout the code */
14660 if (state->optimize >= 2) {
14661 #warning "FIXME fix scc_transform"
14662 scc_transform(state);
14663 transform_from_ssa_form(state);
14664 free_basic_blocks(state);
14665 setup_basic_blocks(state);
14666 analyze_idominators(state);
14667 analyze_ipdominators(state);
14668 transform_to_ssa_form(state);
14670 verify_consistency(state);
14671 #warning "WISHLIST implement single use constants (least possible register pressure)"
14672 #warning "WISHLIST implement induction variable elimination"
14673 /* Select architecture instructions and an initial partial
14674 * coloring based on architecture constraints.
14676 transform_to_arch_instructions(state);
14677 verify_consistency(state);
14678 if (state->debug & DEBUG_ARCH_CODE) {
14679 printf("After transform_to_arch_instructions\n");
14680 print_blocks(state, stdout);
14681 print_control_flow(state);
14683 eliminate_inefectual_code(state);
14684 verify_consistency(state);
14685 if (state->debug & DEBUG_CODE_ELIMINATION) {
14686 printf("After eliminate_inefectual_code\n");
14687 print_blocks(state, stdout);
14688 print_control_flow(state);
14690 verify_consistency(state);
14691 /* Color all of the variables to see if they will fit in registers */
14692 insert_copies_to_phi(state);
14693 if (state->debug & DEBUG_INSERTED_COPIES) {
14694 printf("After insert_copies_to_phi\n");
14695 print_blocks(state, stdout);
14696 print_control_flow(state);
14698 verify_consistency(state);
14699 insert_mandatory_copies(state);
14700 if (state->debug & DEBUG_INSERTED_COPIES) {
14701 printf("After insert_mandatory_copies\n");
14702 print_blocks(state, stdout);
14703 print_control_flow(state);
14705 verify_consistency(state);
14706 allocate_registers(state);
14707 verify_consistency(state);
14708 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14709 print_blocks(state, stdout);
14711 if (state->debug & DEBUG_CONTROL_FLOW) {
14712 print_control_flow(state);
14714 /* Remove the optimization information.
14715 * This is more to check for memory consistency than to free memory.
14717 free_basic_blocks(state);
14720 static void print_op_asm(struct compile_state *state,
14721 struct triple *ins, FILE *fp)
14723 struct asm_info *info;
14725 unsigned lhs, rhs, i;
14726 info = ins->u.ainfo;
14727 lhs = TRIPLE_LHS(ins->sizes);
14728 rhs = TRIPLE_RHS(ins->sizes);
14729 /* Don't count the clobbers in lhs */
14730 for(i = 0; i < lhs; i++) {
14731 if (LHS(ins, i)->type == &void_type) {
14736 fprintf(fp, "#ASM\n");
14738 for(ptr = info->str; *ptr; ptr++) {
14740 unsigned long param;
14741 struct triple *piece;
14751 param = strtoul(ptr, &next, 10);
14753 error(state, ins, "Invalid asm template");
14755 if (param >= (lhs + rhs)) {
14756 error(state, ins, "Invalid param %%%u in asm template",
14759 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14761 arch_reg_str(ID_REG(piece->id)));
14764 fprintf(fp, "\n#NOT ASM\n");
14768 /* Only use the low x86 byte registers. This allows me
14769 * allocate the entire register when a byte register is used.
14771 #define X86_4_8BIT_GPRS 1
14773 /* Recognized x86 cpu variants */
14781 #define CPU_DEFAULT CPU_I386
14783 /* The x86 register classes */
14784 #define REGC_FLAGS 0
14785 #define REGC_GPR8 1
14786 #define REGC_GPR16 2
14787 #define REGC_GPR32 3
14788 #define REGC_GPR64 4
14791 #define REGC_GPR32_8 7
14792 #define REGC_GPR16_8 8
14793 #define REGC_IMM32 9
14794 #define REGC_IMM16 10
14795 #define REGC_IMM8 11
14796 #define LAST_REGC REGC_IMM8
14797 #if LAST_REGC >= MAX_REGC
14798 #error "MAX_REGC is to low"
14801 /* Register class masks */
14802 #define REGCM_FLAGS (1 << REGC_FLAGS)
14803 #define REGCM_GPR8 (1 << REGC_GPR8)
14804 #define REGCM_GPR16 (1 << REGC_GPR16)
14805 #define REGCM_GPR32 (1 << REGC_GPR32)
14806 #define REGCM_GPR64 (1 << REGC_GPR64)
14807 #define REGCM_MMX (1 << REGC_MMX)
14808 #define REGCM_XMM (1 << REGC_XMM)
14809 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14810 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14811 #define REGCM_IMM32 (1 << REGC_IMM32)
14812 #define REGCM_IMM16 (1 << REGC_IMM16)
14813 #define REGCM_IMM8 (1 << REGC_IMM8)
14814 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14816 /* The x86 registers */
14817 #define REG_EFLAGS 2
14818 #define REGC_FLAGS_FIRST REG_EFLAGS
14819 #define REGC_FLAGS_LAST REG_EFLAGS
14828 #define REGC_GPR8_FIRST REG_AL
14829 #if X86_4_8BIT_GPRS
14830 #define REGC_GPR8_LAST REG_DL
14832 #define REGC_GPR8_LAST REG_DH
14842 #define REGC_GPR16_FIRST REG_AX
14843 #define REGC_GPR16_LAST REG_SP
14852 #define REGC_GPR32_FIRST REG_EAX
14853 #define REGC_GPR32_LAST REG_ESP
14854 #define REG_EDXEAX 27
14855 #define REGC_GPR64_FIRST REG_EDXEAX
14856 #define REGC_GPR64_LAST REG_EDXEAX
14857 #define REG_MMX0 28
14858 #define REG_MMX1 29
14859 #define REG_MMX2 30
14860 #define REG_MMX3 31
14861 #define REG_MMX4 32
14862 #define REG_MMX5 33
14863 #define REG_MMX6 34
14864 #define REG_MMX7 35
14865 #define REGC_MMX_FIRST REG_MMX0
14866 #define REGC_MMX_LAST REG_MMX7
14867 #define REG_XMM0 36
14868 #define REG_XMM1 37
14869 #define REG_XMM2 38
14870 #define REG_XMM3 39
14871 #define REG_XMM4 40
14872 #define REG_XMM5 41
14873 #define REG_XMM6 42
14874 #define REG_XMM7 43
14875 #define REGC_XMM_FIRST REG_XMM0
14876 #define REGC_XMM_LAST REG_XMM7
14877 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14878 #define LAST_REG REG_XMM7
14880 #define REGC_GPR32_8_FIRST REG_EAX
14881 #define REGC_GPR32_8_LAST REG_EDX
14882 #define REGC_GPR16_8_FIRST REG_AX
14883 #define REGC_GPR16_8_LAST REG_DX
14885 #define REGC_IMM8_FIRST -1
14886 #define REGC_IMM8_LAST -1
14887 #define REGC_IMM16_FIRST -2
14888 #define REGC_IMM16_LAST -1
14889 #define REGC_IMM32_FIRST -4
14890 #define REGC_IMM32_LAST -1
14892 #if LAST_REG >= MAX_REGISTERS
14893 #error "MAX_REGISTERS to low"
14897 static unsigned regc_size[LAST_REGC +1] = {
14898 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
14899 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
14900 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
14901 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
14902 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
14903 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
14904 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
14905 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14906 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14912 static const struct {
14914 } regcm_bound[LAST_REGC + 1] = {
14915 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
14916 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
14917 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
14918 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
14919 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
14920 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
14921 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
14922 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14923 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14924 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
14925 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
14926 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
14929 static int arch_encode_cpu(const char *cpu)
14935 { "i386", CPU_I386 },
14943 for(ptr = cpus; ptr->name; ptr++) {
14944 if (strcmp(ptr->name, cpu) == 0) {
14951 static unsigned arch_regc_size(struct compile_state *state, int class)
14953 if ((class < 0) || (class > LAST_REGC)) {
14956 return regc_size[class];
14959 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14961 /* See if two register classes may have overlapping registers */
14962 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14963 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14965 /* Special case for the immediates */
14966 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14967 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14968 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14969 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
14972 return (regcm1 & regcm2) ||
14973 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14976 static void arch_reg_equivs(
14977 struct compile_state *state, unsigned *equiv, int reg)
14979 if ((reg < 0) || (reg > LAST_REG)) {
14980 internal_error(state, 0, "invalid register");
14985 #if X86_4_8BIT_GPRS
14989 *equiv++ = REG_EAX;
14990 *equiv++ = REG_EDXEAX;
14993 #if X86_4_8BIT_GPRS
14997 *equiv++ = REG_EAX;
14998 *equiv++ = REG_EDXEAX;
15001 #if X86_4_8BIT_GPRS
15005 *equiv++ = REG_EBX;
15009 #if X86_4_8BIT_GPRS
15013 *equiv++ = REG_EBX;
15016 #if X86_4_8BIT_GPRS
15020 *equiv++ = REG_ECX;
15024 #if X86_4_8BIT_GPRS
15028 *equiv++ = REG_ECX;
15031 #if X86_4_8BIT_GPRS
15035 *equiv++ = REG_EDX;
15036 *equiv++ = REG_EDXEAX;
15039 #if X86_4_8BIT_GPRS
15043 *equiv++ = REG_EDX;
15044 *equiv++ = REG_EDXEAX;
15049 *equiv++ = REG_EAX;
15050 *equiv++ = REG_EDXEAX;
15055 *equiv++ = REG_EBX;
15060 *equiv++ = REG_ECX;
15065 *equiv++ = REG_EDX;
15066 *equiv++ = REG_EDXEAX;
15069 *equiv++ = REG_ESI;
15072 *equiv++ = REG_EDI;
15075 *equiv++ = REG_EBP;
15078 *equiv++ = REG_ESP;
15084 *equiv++ = REG_EDXEAX;
15100 *equiv++ = REG_EDXEAX;
15121 *equiv++ = REG_EAX;
15122 *equiv++ = REG_EDX;
15125 *equiv++ = REG_UNSET;
15128 static unsigned arch_avail_mask(struct compile_state *state)
15130 unsigned avail_mask;
15131 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15132 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15133 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15134 switch(state->cpu) {
15137 avail_mask |= REGCM_MMX;
15141 avail_mask |= REGCM_MMX | REGCM_XMM;
15145 /* Don't enable 8 bit values until I can force both operands
15146 * to be 8bits simultaneously.
15148 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15153 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15155 unsigned mask, result;
15158 result &= arch_avail_mask(state);
15160 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15161 if ((result & mask) == 0) {
15164 if (class > LAST_REGC) {
15167 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15168 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15169 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15170 result |= (1 << class2);
15177 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15179 /* Like arch_regcm_normalize except immediate register classes are excluded */
15180 regcm = arch_regcm_normalize(state, regcm);
15181 /* Remove the immediate register classes */
15182 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15187 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15192 for(class = 0; class <= LAST_REGC; class++) {
15193 if ((reg >= regcm_bound[class].first) &&
15194 (reg <= regcm_bound[class].last)) {
15195 mask |= (1 << class);
15199 internal_error(state, 0, "reg %d not in any class", reg);
15204 static struct reg_info arch_reg_constraint(
15205 struct compile_state *state, struct type *type, const char *constraint)
15207 static const struct {
15211 } constraints[] = {
15212 { 'r', REGCM_GPR32, REG_UNSET },
15213 { 'g', REGCM_GPR32, REG_UNSET },
15214 { 'p', REGCM_GPR32, REG_UNSET },
15215 { 'q', REGCM_GPR8, REG_UNSET },
15216 { 'Q', REGCM_GPR32_8, REG_UNSET },
15217 { 'x', REGCM_XMM, REG_UNSET },
15218 { 'y', REGCM_MMX, REG_UNSET },
15219 { 'a', REGCM_GPR32, REG_EAX },
15220 { 'b', REGCM_GPR32, REG_EBX },
15221 { 'c', REGCM_GPR32, REG_ECX },
15222 { 'd', REGCM_GPR32, REG_EDX },
15223 { 'D', REGCM_GPR32, REG_EDI },
15224 { 'S', REGCM_GPR32, REG_ESI },
15225 { '\0', 0, REG_UNSET },
15227 unsigned int regcm;
15228 unsigned int mask, reg;
15229 struct reg_info result;
15231 regcm = arch_type_to_regcm(state, type);
15234 for(ptr = constraint; *ptr; ptr++) {
15239 for(i = 0; constraints[i].class != '\0'; i++) {
15240 if (constraints[i].class == *ptr) {
15244 if (constraints[i].class == '\0') {
15245 error(state, 0, "invalid register constraint ``%c''", *ptr);
15248 if ((constraints[i].mask & regcm) == 0) {
15249 error(state, 0, "invalid register class %c specified",
15252 mask |= constraints[i].mask;
15253 if (constraints[i].reg != REG_UNSET) {
15254 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15255 error(state, 0, "Only one register may be specified");
15257 reg = constraints[i].reg;
15261 result.regcm = mask;
15265 static struct reg_info arch_reg_clobber(
15266 struct compile_state *state, const char *clobber)
15268 struct reg_info result;
15269 if (strcmp(clobber, "memory") == 0) {
15270 result.reg = REG_UNSET;
15273 else if (strcmp(clobber, "%eax") == 0) {
15274 result.reg = REG_EAX;
15275 result.regcm = REGCM_GPR32;
15277 else if (strcmp(clobber, "%ebx") == 0) {
15278 result.reg = REG_EBX;
15279 result.regcm = REGCM_GPR32;
15281 else if (strcmp(clobber, "%ecx") == 0) {
15282 result.reg = REG_ECX;
15283 result.regcm = REGCM_GPR32;
15285 else if (strcmp(clobber, "%edx") == 0) {
15286 result.reg = REG_EDX;
15287 result.regcm = REGCM_GPR32;
15289 else if (strcmp(clobber, "%esi") == 0) {
15290 result.reg = REG_ESI;
15291 result.regcm = REGCM_GPR32;
15293 else if (strcmp(clobber, "%edi") == 0) {
15294 result.reg = REG_EDI;
15295 result.regcm = REGCM_GPR32;
15297 else if (strcmp(clobber, "%ebp") == 0) {
15298 result.reg = REG_EBP;
15299 result.regcm = REGCM_GPR32;
15301 else if (strcmp(clobber, "%esp") == 0) {
15302 result.reg = REG_ESP;
15303 result.regcm = REGCM_GPR32;
15305 else if (strcmp(clobber, "cc") == 0) {
15306 result.reg = REG_EFLAGS;
15307 result.regcm = REGCM_FLAGS;
15309 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15310 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15311 result.reg = REG_XMM0 + octdigval(clobber[3]);
15312 result.regcm = REGCM_XMM;
15314 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15315 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15316 result.reg = REG_MMX0 + octdigval(clobber[3]);
15317 result.regcm = REGCM_MMX;
15320 error(state, 0, "Invalid register clobber");
15321 result.reg = REG_UNSET;
15327 static int do_select_reg(struct compile_state *state,
15328 char *used, int reg, unsigned classes)
15334 mask = arch_reg_regcm(state, reg);
15335 return (classes & mask) ? reg : REG_UNSET;
15338 static int arch_select_free_register(
15339 struct compile_state *state, char *used, int classes)
15341 /* Live ranges with the most neighbors are colored first.
15343 * Generally it does not matter which colors are given
15344 * as the register allocator attempts to color live ranges
15345 * in an order where you are guaranteed not to run out of colors.
15347 * Occasionally the register allocator cannot find an order
15348 * of register selection that will find a free color. To
15349 * increase the odds the register allocator will work when
15350 * it guesses first give out registers from register classes
15351 * least likely to run out of registers.
15356 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15357 reg = do_select_reg(state, used, i, classes);
15359 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15360 reg = do_select_reg(state, used, i, classes);
15362 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15363 reg = do_select_reg(state, used, i, classes);
15365 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15366 reg = do_select_reg(state, used, i, classes);
15368 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15369 reg = do_select_reg(state, used, i, classes);
15371 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15372 reg = do_select_reg(state, used, i, classes);
15374 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15375 reg = do_select_reg(state, used, i, classes);
15381 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15383 #warning "FIXME force types smaller (if legal) before I get here"
15386 switch(type->type & TYPE_MASK) {
15393 mask = REGCM_GPR8 |
15394 REGCM_GPR16 | REGCM_GPR16_8 |
15395 REGCM_GPR32 | REGCM_GPR32_8 |
15397 REGCM_MMX | REGCM_XMM |
15398 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15402 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15403 REGCM_GPR32 | REGCM_GPR32_8 |
15405 REGCM_MMX | REGCM_XMM |
15406 REGCM_IMM32 | REGCM_IMM16;
15413 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15414 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15418 internal_error(state, 0, "no register class for type");
15421 mask = arch_regcm_normalize(state, mask);
15425 static int is_imm32(struct triple *imm)
15427 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15428 (imm->op == OP_ADDRCONST);
15431 static int is_imm16(struct triple *imm)
15433 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15435 static int is_imm8(struct triple *imm)
15437 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15440 static int get_imm32(struct triple *ins, struct triple **expr)
15442 struct triple *imm;
15444 while(imm->op == OP_COPY) {
15447 if (!is_imm32(imm)) {
15450 unuse_triple(*expr, ins);
15451 use_triple(imm, ins);
15456 static int get_imm8(struct triple *ins, struct triple **expr)
15458 struct triple *imm;
15460 while(imm->op == OP_COPY) {
15463 if (!is_imm8(imm)) {
15466 unuse_triple(*expr, ins);
15467 use_triple(imm, ins);
15472 #define TEMPLATE_NOP 0
15473 #define TEMPLATE_INTCONST8 1
15474 #define TEMPLATE_INTCONST32 2
15475 #define TEMPLATE_COPY8_REG 3
15476 #define TEMPLATE_COPY16_REG 4
15477 #define TEMPLATE_COPY32_REG 5
15478 #define TEMPLATE_COPY_IMM8 6
15479 #define TEMPLATE_COPY_IMM16 7
15480 #define TEMPLATE_COPY_IMM32 8
15481 #define TEMPLATE_PHI8 9
15482 #define TEMPLATE_PHI16 10
15483 #define TEMPLATE_PHI32 11
15484 #define TEMPLATE_STORE8 12
15485 #define TEMPLATE_STORE16 13
15486 #define TEMPLATE_STORE32 14
15487 #define TEMPLATE_LOAD8 15
15488 #define TEMPLATE_LOAD16 16
15489 #define TEMPLATE_LOAD32 17
15490 #define TEMPLATE_BINARY_REG 18
15491 #define TEMPLATE_BINARY_IMM 19
15492 #define TEMPLATE_SL_CL 20
15493 #define TEMPLATE_SL_IMM 21
15494 #define TEMPLATE_UNARY 22
15495 #define TEMPLATE_CMP_REG 23
15496 #define TEMPLATE_CMP_IMM 24
15497 #define TEMPLATE_TEST 25
15498 #define TEMPLATE_SET 26
15499 #define TEMPLATE_JMP 27
15500 #define TEMPLATE_INB_DX 28
15501 #define TEMPLATE_INB_IMM 29
15502 #define TEMPLATE_INW_DX 30
15503 #define TEMPLATE_INW_IMM 31
15504 #define TEMPLATE_INL_DX 32
15505 #define TEMPLATE_INL_IMM 33
15506 #define TEMPLATE_OUTB_DX 34
15507 #define TEMPLATE_OUTB_IMM 35
15508 #define TEMPLATE_OUTW_DX 36
15509 #define TEMPLATE_OUTW_IMM 37
15510 #define TEMPLATE_OUTL_DX 38
15511 #define TEMPLATE_OUTL_IMM 39
15512 #define TEMPLATE_BSF 40
15513 #define TEMPLATE_RDMSR 41
15514 #define TEMPLATE_WRMSR 42
15515 #define TEMPLATE_UMUL 43
15516 #define TEMPLATE_DIV 44
15517 #define TEMPLATE_MOD 45
15518 #define LAST_TEMPLATE TEMPLATE_MOD
15519 #if LAST_TEMPLATE >= MAX_TEMPLATES
15520 #error "MAX_TEMPLATES to low"
15523 #define COPY8_REGCM (REGCM_GPR64 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15524 #define COPY16_REGCM (REGCM_GPR64 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
15525 #define COPY32_REGCM (REGCM_GPR64 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15526 #define COPYIMM8_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8)
15527 #define COPYIMM16_REGCM (REGCM_GPR32 | REGCM_GPR16)
15528 #define COPYIMM32_REGCM (REGCM_GPR32)
15531 static struct ins_template templates[] = {
15532 [TEMPLATE_NOP] = {},
15533 [TEMPLATE_INTCONST8] = {
15534 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15536 [TEMPLATE_INTCONST32] = {
15537 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15539 [TEMPLATE_COPY8_REG] = {
15540 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15541 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15543 [TEMPLATE_COPY16_REG] = {
15544 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15545 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15547 [TEMPLATE_COPY32_REG] = {
15548 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15549 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15551 [TEMPLATE_COPY_IMM8] = {
15552 .lhs = { [0] = { REG_UNSET, COPYIMM8_REGCM } },
15553 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15555 [TEMPLATE_COPY_IMM16] = {
15556 .lhs = { [0] = { REG_UNSET, COPYIMM16_REGCM } },
15557 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
15559 [TEMPLATE_COPY_IMM32] = {
15560 .lhs = { [0] = { REG_UNSET, COPYIMM32_REGCM } },
15561 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
15563 [TEMPLATE_PHI8] = {
15564 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
15566 [ 0] = { REG_VIRT0, COPY8_REGCM },
15567 [ 1] = { REG_VIRT0, COPY8_REGCM },
15568 [ 2] = { REG_VIRT0, COPY8_REGCM },
15569 [ 3] = { REG_VIRT0, COPY8_REGCM },
15570 [ 4] = { REG_VIRT0, COPY8_REGCM },
15571 [ 5] = { REG_VIRT0, COPY8_REGCM },
15572 [ 6] = { REG_VIRT0, COPY8_REGCM },
15573 [ 7] = { REG_VIRT0, COPY8_REGCM },
15574 [ 8] = { REG_VIRT0, COPY8_REGCM },
15575 [ 9] = { REG_VIRT0, COPY8_REGCM },
15576 [10] = { REG_VIRT0, COPY8_REGCM },
15577 [11] = { REG_VIRT0, COPY8_REGCM },
15578 [12] = { REG_VIRT0, COPY8_REGCM },
15579 [13] = { REG_VIRT0, COPY8_REGCM },
15580 [14] = { REG_VIRT0, COPY8_REGCM },
15581 [15] = { REG_VIRT0, COPY8_REGCM },
15583 [TEMPLATE_PHI16] = {
15584 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
15586 [ 0] = { REG_VIRT0, COPY16_REGCM },
15587 [ 1] = { REG_VIRT0, COPY16_REGCM },
15588 [ 2] = { REG_VIRT0, COPY16_REGCM },
15589 [ 3] = { REG_VIRT0, COPY16_REGCM },
15590 [ 4] = { REG_VIRT0, COPY16_REGCM },
15591 [ 5] = { REG_VIRT0, COPY16_REGCM },
15592 [ 6] = { REG_VIRT0, COPY16_REGCM },
15593 [ 7] = { REG_VIRT0, COPY16_REGCM },
15594 [ 8] = { REG_VIRT0, COPY16_REGCM },
15595 [ 9] = { REG_VIRT0, COPY16_REGCM },
15596 [10] = { REG_VIRT0, COPY16_REGCM },
15597 [11] = { REG_VIRT0, COPY16_REGCM },
15598 [12] = { REG_VIRT0, COPY16_REGCM },
15599 [13] = { REG_VIRT0, COPY16_REGCM },
15600 [14] = { REG_VIRT0, COPY16_REGCM },
15601 [15] = { REG_VIRT0, COPY16_REGCM },
15603 [TEMPLATE_PHI32] = {
15604 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
15606 [ 0] = { REG_VIRT0, COPY32_REGCM },
15607 [ 1] = { REG_VIRT0, COPY32_REGCM },
15608 [ 2] = { REG_VIRT0, COPY32_REGCM },
15609 [ 3] = { REG_VIRT0, COPY32_REGCM },
15610 [ 4] = { REG_VIRT0, COPY32_REGCM },
15611 [ 5] = { REG_VIRT0, COPY32_REGCM },
15612 [ 6] = { REG_VIRT0, COPY32_REGCM },
15613 [ 7] = { REG_VIRT0, COPY32_REGCM },
15614 [ 8] = { REG_VIRT0, COPY32_REGCM },
15615 [ 9] = { REG_VIRT0, COPY32_REGCM },
15616 [10] = { REG_VIRT0, COPY32_REGCM },
15617 [11] = { REG_VIRT0, COPY32_REGCM },
15618 [12] = { REG_VIRT0, COPY32_REGCM },
15619 [13] = { REG_VIRT0, COPY32_REGCM },
15620 [14] = { REG_VIRT0, COPY32_REGCM },
15621 [15] = { REG_VIRT0, COPY32_REGCM },
15623 [TEMPLATE_STORE8] = {
15624 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15625 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15627 [TEMPLATE_STORE16] = {
15628 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15629 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15631 [TEMPLATE_STORE32] = {
15632 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15633 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15635 [TEMPLATE_LOAD8] = {
15636 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15637 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15639 [TEMPLATE_LOAD16] = {
15640 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15641 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15643 [TEMPLATE_LOAD32] = {
15644 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15645 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15647 [TEMPLATE_BINARY_REG] = {
15648 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15650 [0] = { REG_VIRT0, REGCM_GPR32 },
15651 [1] = { REG_UNSET, REGCM_GPR32 },
15654 [TEMPLATE_BINARY_IMM] = {
15655 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15657 [0] = { REG_VIRT0, REGCM_GPR32 },
15658 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15661 [TEMPLATE_SL_CL] = {
15662 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15664 [0] = { REG_VIRT0, REGCM_GPR32 },
15665 [1] = { REG_CL, REGCM_GPR8 },
15668 [TEMPLATE_SL_IMM] = {
15669 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15671 [0] = { REG_VIRT0, REGCM_GPR32 },
15672 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15675 [TEMPLATE_UNARY] = {
15676 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15677 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15679 [TEMPLATE_CMP_REG] = {
15680 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15682 [0] = { REG_UNSET, REGCM_GPR32 },
15683 [1] = { REG_UNSET, REGCM_GPR32 },
15686 [TEMPLATE_CMP_IMM] = {
15687 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15689 [0] = { REG_UNSET, REGCM_GPR32 },
15690 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15693 [TEMPLATE_TEST] = {
15694 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15695 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15698 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15699 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15702 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15704 [TEMPLATE_INB_DX] = {
15705 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15706 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15708 [TEMPLATE_INB_IMM] = {
15709 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15710 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15712 [TEMPLATE_INW_DX] = {
15713 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15714 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15716 [TEMPLATE_INW_IMM] = {
15717 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15718 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15720 [TEMPLATE_INL_DX] = {
15721 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15722 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15724 [TEMPLATE_INL_IMM] = {
15725 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15726 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15728 [TEMPLATE_OUTB_DX] = {
15730 [0] = { REG_AL, REGCM_GPR8 },
15731 [1] = { REG_DX, REGCM_GPR16 },
15734 [TEMPLATE_OUTB_IMM] = {
15736 [0] = { REG_AL, REGCM_GPR8 },
15737 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15740 [TEMPLATE_OUTW_DX] = {
15742 [0] = { REG_AX, REGCM_GPR16 },
15743 [1] = { REG_DX, REGCM_GPR16 },
15746 [TEMPLATE_OUTW_IMM] = {
15748 [0] = { REG_AX, REGCM_GPR16 },
15749 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15752 [TEMPLATE_OUTL_DX] = {
15754 [0] = { REG_EAX, REGCM_GPR32 },
15755 [1] = { REG_DX, REGCM_GPR16 },
15758 [TEMPLATE_OUTL_IMM] = {
15760 [0] = { REG_EAX, REGCM_GPR32 },
15761 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15765 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15766 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15768 [TEMPLATE_RDMSR] = {
15770 [0] = { REG_EAX, REGCM_GPR32 },
15771 [1] = { REG_EDX, REGCM_GPR32 },
15773 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15775 [TEMPLATE_WRMSR] = {
15777 [0] = { REG_ECX, REGCM_GPR32 },
15778 [1] = { REG_EAX, REGCM_GPR32 },
15779 [2] = { REG_EDX, REGCM_GPR32 },
15782 [TEMPLATE_UMUL] = {
15783 .lhs = { [0] = { REG_EDXEAX, REGCM_GPR64 } },
15785 [0] = { REG_EAX, REGCM_GPR32 },
15786 [1] = { REG_UNSET, REGCM_GPR32 },
15791 [0] = { REG_EAX, REGCM_GPR32 },
15792 [1] = { REG_EDX, REGCM_GPR32 },
15795 [0] = { REG_EDXEAX, REGCM_GPR64 },
15796 [1] = { REG_UNSET, REGCM_GPR32 },
15801 [0] = { REG_EDX, REGCM_GPR32 },
15802 [1] = { REG_EAX, REGCM_GPR32 },
15805 [0] = { REG_EDXEAX, REGCM_GPR64 },
15806 [1] = { REG_UNSET, REGCM_GPR32 },
15811 static void fixup_branches(struct compile_state *state,
15812 struct triple *cmp, struct triple *use, int jmp_op)
15814 struct triple_set *entry, *next;
15815 for(entry = use->use; entry; entry = next) {
15816 next = entry->next;
15817 if (entry->member->op == OP_COPY) {
15818 fixup_branches(state, cmp, entry->member, jmp_op);
15820 else if (entry->member->op == OP_BRANCH) {
15821 struct triple *branch, *test;
15822 struct triple *left, *right;
15824 left = RHS(cmp, 0);
15825 if (TRIPLE_RHS(cmp->sizes) > 1) {
15826 right = RHS(cmp, 1);
15828 branch = entry->member;
15829 test = pre_triple(state, branch,
15830 cmp->op, cmp->type, left, right);
15831 test->template_id = TEMPLATE_TEST;
15832 if (cmp->op == OP_CMP) {
15833 test->template_id = TEMPLATE_CMP_REG;
15834 if (get_imm32(test, &RHS(test, 1))) {
15835 test->template_id = TEMPLATE_CMP_IMM;
15838 use_triple(RHS(test, 0), test);
15839 use_triple(RHS(test, 1), test);
15840 unuse_triple(RHS(branch, 0), branch);
15841 RHS(branch, 0) = test;
15842 branch->op = jmp_op;
15843 branch->template_id = TEMPLATE_JMP;
15844 use_triple(RHS(branch, 0), branch);
15849 static void bool_cmp(struct compile_state *state,
15850 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15852 struct triple_set *entry, *next;
15853 struct triple *set;
15855 /* Put a barrier up before the cmp which preceeds the
15856 * copy instruction. If a set actually occurs this gives
15857 * us a chance to move variables in registers out of the way.
15860 /* Modify the comparison operator */
15862 ins->template_id = TEMPLATE_TEST;
15863 if (cmp_op == OP_CMP) {
15864 ins->template_id = TEMPLATE_CMP_REG;
15865 if (get_imm32(ins, &RHS(ins, 1))) {
15866 ins->template_id = TEMPLATE_CMP_IMM;
15869 /* Generate the instruction sequence that will transform the
15870 * result of the comparison into a logical value.
15872 set = post_triple(state, ins, set_op, &char_type, ins, 0);
15873 use_triple(ins, set);
15874 set->template_id = TEMPLATE_SET;
15876 for(entry = ins->use; entry; entry = next) {
15877 next = entry->next;
15878 if (entry->member == set) {
15881 replace_rhs_use(state, ins, set, entry->member);
15883 fixup_branches(state, ins, set, jmp_op);
15886 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15888 struct triple *next;
15890 lhs = TRIPLE_LHS(ins->sizes);
15891 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15892 if (next != LHS(ins, i)) {
15893 internal_error(state, ins, "malformed lhs on %s",
15896 if (next->op != OP_PIECE) {
15897 internal_error(state, ins, "bad lhs op %s at %d on %s",
15898 tops(next->op), i, tops(ins->op));
15900 if (next->u.cval != i) {
15901 internal_error(state, ins, "bad u.cval of %d %d expected",
15908 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15910 struct ins_template *template;
15911 struct reg_info result;
15913 if (ins->op == OP_PIECE) {
15914 index = ins->u.cval;
15915 ins = MISC(ins, 0);
15917 zlhs = TRIPLE_LHS(ins->sizes);
15918 if (triple_is_def(state, ins)) {
15921 if (index >= zlhs) {
15922 internal_error(state, ins, "index %d out of range for %s\n",
15923 index, tops(ins->op));
15927 template = &ins->u.ainfo->tmpl;
15930 if (ins->template_id > LAST_TEMPLATE) {
15931 internal_error(state, ins, "bad template number %d",
15934 template = &templates[ins->template_id];
15937 result = template->lhs[index];
15938 result.regcm = arch_regcm_normalize(state, result.regcm);
15939 if (result.reg != REG_UNNEEDED) {
15940 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15942 if (result.regcm == 0) {
15943 internal_error(state, ins, "lhs %d regcm == 0", index);
15948 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15950 struct reg_info result;
15951 struct ins_template *template;
15952 if ((index > TRIPLE_RHS(ins->sizes)) ||
15953 (ins->op == OP_PIECE)) {
15954 internal_error(state, ins, "index %d out of range for %s\n",
15955 index, tops(ins->op));
15959 template = &ins->u.ainfo->tmpl;
15962 if (ins->template_id > LAST_TEMPLATE) {
15963 internal_error(state, ins, "bad template number %d",
15966 template = &templates[ins->template_id];
15969 result = template->rhs[index];
15970 result.regcm = arch_regcm_normalize(state, result.regcm);
15971 if (result.regcm == 0) {
15972 internal_error(state, ins, "rhs %d regcm == 0", index);
15977 static struct triple *transform_to_arch_instruction(
15978 struct compile_state *state, struct triple *ins)
15980 /* Transform from generic 3 address instructions
15981 * to archtecture specific instructions.
15982 * And apply architecture specific constraints to instructions.
15983 * Copies are inserted to preserve the register flexibility
15984 * of 3 address instructions.
15986 struct triple *next;
15991 ins->template_id = TEMPLATE_INTCONST32;
15992 if (ins->u.cval < 256) {
15993 ins->template_id = TEMPLATE_INTCONST8;
15997 ins->template_id = TEMPLATE_INTCONST32;
16003 ins->template_id = TEMPLATE_NOP;
16006 size = size_of(state, ins->type);
16007 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16008 ins->template_id = TEMPLATE_COPY_IMM8;
16010 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16011 ins->template_id = TEMPLATE_COPY_IMM16;
16013 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16014 ins->template_id = TEMPLATE_COPY_IMM32;
16016 else if (is_const(RHS(ins, 0))) {
16017 internal_error(state, ins, "bad constant passed to copy");
16019 else if (size <= 1) {
16020 ins->template_id = TEMPLATE_COPY8_REG;
16022 else if (size <= 2) {
16023 ins->template_id = TEMPLATE_COPY16_REG;
16025 else if (size <= 4) {
16026 ins->template_id = TEMPLATE_COPY32_REG;
16029 internal_error(state, ins, "bad type passed to copy");
16033 size = size_of(state, ins->type);
16035 ins->template_id = TEMPLATE_PHI8;
16037 else if (size <= 2) {
16038 ins->template_id = TEMPLATE_PHI16;
16040 else if (size <= 4) {
16041 ins->template_id = TEMPLATE_PHI32;
16044 internal_error(state, ins, "bad type passed to phi");
16048 switch(ins->type->type & TYPE_MASK) {
16049 case TYPE_CHAR: case TYPE_UCHAR:
16050 ins->template_id = TEMPLATE_STORE8;
16052 case TYPE_SHORT: case TYPE_USHORT:
16053 ins->template_id = TEMPLATE_STORE16;
16055 case TYPE_INT: case TYPE_UINT:
16056 case TYPE_LONG: case TYPE_ULONG:
16058 ins->template_id = TEMPLATE_STORE32;
16061 internal_error(state, ins, "unknown type in store");
16066 switch(ins->type->type & TYPE_MASK) {
16067 case TYPE_CHAR: case TYPE_UCHAR:
16068 ins->template_id = TEMPLATE_LOAD8;
16072 ins->template_id = TEMPLATE_LOAD16;
16079 ins->template_id = TEMPLATE_LOAD32;
16082 internal_error(state, ins, "unknown type in load");
16092 ins->template_id = TEMPLATE_BINARY_REG;
16093 if (get_imm32(ins, &RHS(ins, 1))) {
16094 ins->template_id = TEMPLATE_BINARY_IMM;
16098 /* This code does not work yet */
16100 ins->template_id = TEMPLATE_UMUL;
16104 ins->template_id = TEMPLATE_DIV;
16108 ins->template_id = TEMPLATE_MOD;
16114 ins->template_id = TEMPLATE_SL_CL;
16115 if (get_imm8(ins, &RHS(ins, 1))) {
16116 ins->template_id = TEMPLATE_SL_IMM;
16117 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16118 typed_pre_copy(state, &char_type, ins, 1);
16123 ins->template_id = TEMPLATE_UNARY;
16126 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16129 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16132 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16135 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16138 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16141 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16144 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16147 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16150 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16153 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16156 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16159 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16162 if (TRIPLE_RHS(ins->sizes) > 0) {
16163 internal_error(state, ins, "bad branch test");
16166 ins->template_id = TEMPLATE_NOP;
16172 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16173 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16174 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16176 if (get_imm8(ins, &RHS(ins, 0))) {
16177 ins->template_id += 1;
16184 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16185 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16186 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16188 if (get_imm8(ins, &RHS(ins, 1))) {
16189 ins->template_id += 1;
16194 ins->template_id = TEMPLATE_BSF;
16197 ins->template_id = TEMPLATE_RDMSR;
16198 next = after_lhs(state, ins);
16201 ins->template_id = TEMPLATE_WRMSR;
16204 ins->template_id = TEMPLATE_NOP;
16207 ins->template_id = TEMPLATE_NOP;
16208 next = after_lhs(state, ins);
16210 /* Already transformed instructions */
16212 ins->template_id = TEMPLATE_TEST;
16215 ins->template_id = TEMPLATE_CMP_REG;
16216 if (get_imm32(ins, &RHS(ins, 1))) {
16217 ins->template_id = TEMPLATE_CMP_IMM;
16220 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16221 case OP_JMP_SLESS: case OP_JMP_ULESS:
16222 case OP_JMP_SMORE: case OP_JMP_UMORE:
16223 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16224 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16225 ins->template_id = TEMPLATE_JMP;
16227 case OP_SET_EQ: case OP_SET_NOTEQ:
16228 case OP_SET_SLESS: case OP_SET_ULESS:
16229 case OP_SET_SMORE: case OP_SET_UMORE:
16230 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16231 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16232 ins->template_id = TEMPLATE_SET;
16234 /* Unhandled instructions */
16237 internal_error(state, ins, "unhandled ins: %d %s\n",
16238 ins->op, tops(ins->op));
16244 static void generate_local_labels(struct compile_state *state)
16246 struct triple *first, *label;
16249 first = RHS(state->main_function, 0);
16252 if ((label->op == OP_LABEL) ||
16253 (label->op == OP_SDECL)) {
16255 label->u.cval = ++label_counter;
16261 label = label->next;
16262 } while(label != first);
16265 static int check_reg(struct compile_state *state,
16266 struct triple *triple, int classes)
16270 reg = ID_REG(triple->id);
16271 if (reg == REG_UNSET) {
16272 internal_error(state, triple, "register not set");
16274 mask = arch_reg_regcm(state, reg);
16275 if (!(classes & mask)) {
16276 internal_error(state, triple, "reg %d in wrong class",
16282 static const char *arch_reg_str(int reg)
16284 static const char *regs[] = {
16288 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16289 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16290 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16292 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16293 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16294 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16296 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16303 static const char *reg(struct compile_state *state, struct triple *triple,
16307 reg = check_reg(state, triple, classes);
16308 return arch_reg_str(reg);
16311 const char *type_suffix(struct compile_state *state, struct type *type)
16313 const char *suffix;
16314 switch(size_of(state, type)) {
16315 case 1: suffix = "b"; break;
16316 case 2: suffix = "w"; break;
16317 case 4: suffix = "l"; break;
16319 internal_error(state, 0, "unknown suffix");
16326 static void print_const_val(
16327 struct compile_state *state, struct triple *ins, FILE *fp)
16331 fprintf(fp, " $%ld ",
16332 (long_t)(ins->u.cval));
16335 fprintf(fp, " $L%s%lu+%lu ",
16336 state->label_prefix,
16337 MISC(ins, 0)->u.cval,
16341 internal_error(state, ins, "unknown constant type");
16346 static void print_binary_op(struct compile_state *state,
16347 const char *op, struct triple *ins, FILE *fp)
16350 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16351 if (RHS(ins, 0)->id != ins->id) {
16352 internal_error(state, ins, "invalid register assignment");
16354 if (is_const(RHS(ins, 1))) {
16355 fprintf(fp, "\t%s ", op);
16356 print_const_val(state, RHS(ins, 1), fp);
16357 fprintf(fp, ", %s\n",
16358 reg(state, RHS(ins, 0), mask));
16361 unsigned lmask, rmask;
16363 lreg = check_reg(state, RHS(ins, 0), mask);
16364 rreg = check_reg(state, RHS(ins, 1), mask);
16365 lmask = arch_reg_regcm(state, lreg);
16366 rmask = arch_reg_regcm(state, rreg);
16367 mask = lmask & rmask;
16368 fprintf(fp, "\t%s %s, %s\n",
16370 reg(state, RHS(ins, 1), mask),
16371 reg(state, RHS(ins, 0), mask));
16374 static void print_unary_op(struct compile_state *state,
16375 const char *op, struct triple *ins, FILE *fp)
16378 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16379 fprintf(fp, "\t%s %s\n",
16381 reg(state, RHS(ins, 0), mask));
16384 static void print_op_shift(struct compile_state *state,
16385 const char *op, struct triple *ins, FILE *fp)
16388 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16389 if (RHS(ins, 0)->id != ins->id) {
16390 internal_error(state, ins, "invalid register assignment");
16392 if (is_const(RHS(ins, 1))) {
16393 fprintf(fp, "\t%s ", op);
16394 print_const_val(state, RHS(ins, 1), fp);
16395 fprintf(fp, ", %s\n",
16396 reg(state, RHS(ins, 0), mask));
16399 fprintf(fp, "\t%s %s, %s\n",
16401 reg(state, RHS(ins, 1), REGCM_GPR8),
16402 reg(state, RHS(ins, 0), mask));
16406 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16413 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16414 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16415 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16417 internal_error(state, ins, "not an in operation");
16421 dreg = check_reg(state, ins, mask);
16422 if (!reg_is_reg(state, dreg, REG_EAX)) {
16423 internal_error(state, ins, "dst != %%eax");
16425 if (is_const(RHS(ins, 0))) {
16426 fprintf(fp, "\t%s ", op);
16427 print_const_val(state, RHS(ins, 0), fp);
16428 fprintf(fp, ", %s\n",
16429 reg(state, ins, mask));
16433 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16434 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16435 internal_error(state, ins, "src != %%dx");
16437 fprintf(fp, "\t%s %s, %s\n",
16439 reg(state, RHS(ins, 0), REGCM_GPR16),
16440 reg(state, ins, mask));
16444 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16451 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16452 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16453 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16455 internal_error(state, ins, "not an out operation");
16459 lreg = check_reg(state, RHS(ins, 0), mask);
16460 if (!reg_is_reg(state, lreg, REG_EAX)) {
16461 internal_error(state, ins, "src != %%eax");
16463 if (is_const(RHS(ins, 1))) {
16464 fprintf(fp, "\t%s %s,",
16465 op, reg(state, RHS(ins, 0), mask));
16466 print_const_val(state, RHS(ins, 1), fp);
16471 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16472 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16473 internal_error(state, ins, "dst != %%dx");
16475 fprintf(fp, "\t%s %s, %s\n",
16477 reg(state, RHS(ins, 0), mask),
16478 reg(state, RHS(ins, 1), REGCM_GPR16));
16482 static void print_op_move(struct compile_state *state,
16483 struct triple *ins, FILE *fp)
16485 /* op_move is complex because there are many types
16486 * of registers we can move between.
16487 * Because OP_COPY will be introduced in arbitrary locations
16488 * OP_COPY must not affect flags.
16490 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16491 struct triple *dst, *src;
16492 if (ins->op == OP_COPY) {
16496 else if (ins->op == OP_WRITE) {
16501 internal_error(state, ins, "unknown move operation");
16504 if (!is_const(src)) {
16505 int src_reg, dst_reg;
16506 int src_regcm, dst_regcm;
16507 src_reg = ID_REG(src->id);
16508 dst_reg = ID_REG(dst->id);
16509 src_regcm = arch_reg_regcm(state, src_reg);
16510 dst_regcm = arch_reg_regcm(state, dst_reg);
16511 /* If the class is the same just move the register */
16512 if (src_regcm & dst_regcm &
16513 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16514 if ((src_reg != dst_reg) || !omit_copy) {
16515 fprintf(fp, "\tmov %s, %s\n",
16516 reg(state, src, src_regcm),
16517 reg(state, dst, dst_regcm));
16520 /* Move 32bit to 16bit */
16521 else if ((src_regcm & REGCM_GPR32) &&
16522 (dst_regcm & REGCM_GPR16)) {
16523 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16524 if ((src_reg != dst_reg) || !omit_copy) {
16525 fprintf(fp, "\tmovw %s, %s\n",
16526 arch_reg_str(src_reg),
16527 arch_reg_str(dst_reg));
16530 /* Move from 32bit gprs to 16bit gprs */
16531 else if ((src_regcm & REGCM_GPR32) &&
16532 (dst_regcm & REGCM_GPR16)) {
16533 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16534 if ((src_reg != dst_reg) || !omit_copy) {
16535 fprintf(fp, "\tmov %s, %s\n",
16536 arch_reg_str(src_reg),
16537 arch_reg_str(dst_reg));
16540 /* Move 32bit to 8bit */
16541 else if ((src_regcm & REGCM_GPR32_8) &&
16542 (dst_regcm & REGCM_GPR8))
16544 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16545 if ((src_reg != dst_reg) || !omit_copy) {
16546 fprintf(fp, "\tmovb %s, %s\n",
16547 arch_reg_str(src_reg),
16548 arch_reg_str(dst_reg));
16551 /* Move 16bit to 8bit */
16552 else if ((src_regcm & REGCM_GPR16_8) &&
16553 (dst_regcm & REGCM_GPR8))
16555 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16556 if ((src_reg != dst_reg) || !omit_copy) {
16557 fprintf(fp, "\tmovb %s, %s\n",
16558 arch_reg_str(src_reg),
16559 arch_reg_str(dst_reg));
16562 /* Move 8/16bit to 16/32bit */
16563 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
16564 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16566 op = is_signed(src->type)? "movsx": "movzx";
16567 fprintf(fp, "\t%s %s, %s\n",
16569 reg(state, src, src_regcm),
16570 reg(state, dst, dst_regcm));
16572 /* Move between sse registers */
16573 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16574 if ((src_reg != dst_reg) || !omit_copy) {
16575 fprintf(fp, "\tmovdqa %s, %s\n",
16576 reg(state, src, src_regcm),
16577 reg(state, dst, dst_regcm));
16580 /* Move between mmx registers or mmx & sse registers */
16581 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16582 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16583 if ((src_reg != dst_reg) || !omit_copy) {
16584 fprintf(fp, "\tmovq %s, %s\n",
16585 reg(state, src, src_regcm),
16586 reg(state, dst, dst_regcm));
16589 /* Move between 32bit gprs & mmx/sse registers */
16590 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16591 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16592 fprintf(fp, "\tmovd %s, %s\n",
16593 reg(state, src, src_regcm),
16594 reg(state, dst, dst_regcm));
16596 /* Move from 16bit gprs & mmx/sse registers */
16597 else if ((src_regcm & REGCM_GPR16) &&
16598 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16601 op = is_signed(src->type)? "movsx":"movxz";
16602 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16603 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16605 arch_reg_str(src_reg),
16606 arch_reg_str(mid_reg),
16607 arch_reg_str(mid_reg),
16608 arch_reg_str(dst_reg));
16611 /* Move from mmx/sse registers to 16bit gprs */
16612 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16613 (dst_regcm & REGCM_GPR16)) {
16614 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16615 fprintf(fp, "\tmovd %s, %s\n",
16616 arch_reg_str(src_reg),
16617 arch_reg_str(dst_reg));
16620 #if X86_4_8BIT_GPRS
16621 /* Move from 8bit gprs to mmx/sse registers */
16622 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16623 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16626 op = is_signed(src->type)? "movsx":"movzx";
16627 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16628 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16630 reg(state, src, src_regcm),
16631 arch_reg_str(mid_reg),
16632 arch_reg_str(mid_reg),
16633 reg(state, dst, dst_regcm));
16635 /* Move from mmx/sse registers and 8bit gprs */
16636 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16637 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16639 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16640 fprintf(fp, "\tmovd %s, %s\n",
16641 reg(state, src, src_regcm),
16642 arch_reg_str(mid_reg));
16644 /* Move from 32bit gprs to 8bit gprs */
16645 else if ((src_regcm & REGCM_GPR32) &&
16646 (dst_regcm & REGCM_GPR8)) {
16647 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16648 if ((src_reg != dst_reg) || !omit_copy) {
16649 fprintf(fp, "\tmov %s, %s\n",
16650 arch_reg_str(src_reg),
16651 arch_reg_str(dst_reg));
16654 /* Move from 16bit gprs to 8bit gprs */
16655 else if ((src_regcm & REGCM_GPR16) &&
16656 (dst_regcm & REGCM_GPR8)) {
16657 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16658 if ((src_reg != dst_reg) || !omit_copy) {
16659 fprintf(fp, "\tmov %s, %s\n",
16660 arch_reg_str(src_reg),
16661 arch_reg_str(dst_reg));
16664 #endif /* X86_4_8BIT_GPRS */
16666 internal_error(state, ins, "unknown copy type");
16670 fprintf(fp, "\tmov ");
16671 print_const_val(state, src, fp);
16672 fprintf(fp, ", %s\n",
16673 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16677 static void print_op_load(struct compile_state *state,
16678 struct triple *ins, FILE *fp)
16680 struct triple *dst, *src;
16683 if (is_const(src) || is_const(dst)) {
16684 internal_error(state, ins, "unknown load operation");
16686 fprintf(fp, "\tmov (%s), %s\n",
16687 reg(state, src, REGCM_GPR32),
16688 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16692 static void print_op_store(struct compile_state *state,
16693 struct triple *ins, FILE *fp)
16695 struct triple *dst, *src;
16698 if (is_const(src) && (src->op == OP_INTCONST)) {
16700 value = (long_t)(src->u.cval);
16701 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16702 type_suffix(state, src->type),
16704 reg(state, dst, REGCM_GPR32));
16706 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16707 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16708 type_suffix(state, src->type),
16709 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16713 if (is_const(src) || is_const(dst)) {
16714 internal_error(state, ins, "unknown store operation");
16716 fprintf(fp, "\tmov%s %s, (%s)\n",
16717 type_suffix(state, src->type),
16718 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16719 reg(state, dst, REGCM_GPR32));
16725 static void print_op_smul(struct compile_state *state,
16726 struct triple *ins, FILE *fp)
16728 if (!is_const(RHS(ins, 1))) {
16729 fprintf(fp, "\timul %s, %s\n",
16730 reg(state, RHS(ins, 1), REGCM_GPR32),
16731 reg(state, RHS(ins, 0), REGCM_GPR32));
16734 fprintf(fp, "\timul ");
16735 print_const_val(state, RHS(ins, 1), fp);
16736 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16740 static void print_op_cmp(struct compile_state *state,
16741 struct triple *ins, FILE *fp)
16745 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16746 dreg = check_reg(state, ins, REGCM_FLAGS);
16747 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16748 internal_error(state, ins, "bad dest register for cmp");
16750 if (is_const(RHS(ins, 1))) {
16751 fprintf(fp, "\tcmp ");
16752 print_const_val(state, RHS(ins, 1), fp);
16753 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16756 unsigned lmask, rmask;
16758 lreg = check_reg(state, RHS(ins, 0), mask);
16759 rreg = check_reg(state, RHS(ins, 1), mask);
16760 lmask = arch_reg_regcm(state, lreg);
16761 rmask = arch_reg_regcm(state, rreg);
16762 mask = lmask & rmask;
16763 fprintf(fp, "\tcmp %s, %s\n",
16764 reg(state, RHS(ins, 1), mask),
16765 reg(state, RHS(ins, 0), mask));
16769 static void print_op_test(struct compile_state *state,
16770 struct triple *ins, FILE *fp)
16773 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16774 fprintf(fp, "\ttest %s, %s\n",
16775 reg(state, RHS(ins, 0), mask),
16776 reg(state, RHS(ins, 0), mask));
16779 static void print_op_branch(struct compile_state *state,
16780 struct triple *branch, FILE *fp)
16782 const char *bop = "j";
16783 if (branch->op == OP_JMP) {
16784 if (TRIPLE_RHS(branch->sizes) != 0) {
16785 internal_error(state, branch, "jmp with condition?");
16790 struct triple *ptr;
16791 if (TRIPLE_RHS(branch->sizes) != 1) {
16792 internal_error(state, branch, "jmpcc without condition?");
16794 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16795 if ((RHS(branch, 0)->op != OP_CMP) &&
16796 (RHS(branch, 0)->op != OP_TEST)) {
16797 internal_error(state, branch, "bad branch test");
16799 #warning "FIXME I have observed instructions between the test and branch instructions"
16800 ptr = RHS(branch, 0);
16801 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16802 if (ptr->op != OP_COPY) {
16803 internal_error(state, branch, "branch does not follow test");
16806 switch(branch->op) {
16807 case OP_JMP_EQ: bop = "jz"; break;
16808 case OP_JMP_NOTEQ: bop = "jnz"; break;
16809 case OP_JMP_SLESS: bop = "jl"; break;
16810 case OP_JMP_ULESS: bop = "jb"; break;
16811 case OP_JMP_SMORE: bop = "jg"; break;
16812 case OP_JMP_UMORE: bop = "ja"; break;
16813 case OP_JMP_SLESSEQ: bop = "jle"; break;
16814 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16815 case OP_JMP_SMOREEQ: bop = "jge"; break;
16816 case OP_JMP_UMOREEQ: bop = "jae"; break;
16818 internal_error(state, branch, "Invalid branch op");
16823 fprintf(fp, "\t%s L%s%lu\n",
16825 state->label_prefix,
16826 TARG(branch, 0)->u.cval);
16829 static void print_op_set(struct compile_state *state,
16830 struct triple *set, FILE *fp)
16832 const char *sop = "set";
16833 if (TRIPLE_RHS(set->sizes) != 1) {
16834 internal_error(state, set, "setcc without condition?");
16836 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16837 if ((RHS(set, 0)->op != OP_CMP) &&
16838 (RHS(set, 0)->op != OP_TEST)) {
16839 internal_error(state, set, "bad set test");
16841 if (RHS(set, 0)->next != set) {
16842 internal_error(state, set, "set does not follow test");
16845 case OP_SET_EQ: sop = "setz"; break;
16846 case OP_SET_NOTEQ: sop = "setnz"; break;
16847 case OP_SET_SLESS: sop = "setl"; break;
16848 case OP_SET_ULESS: sop = "setb"; break;
16849 case OP_SET_SMORE: sop = "setg"; break;
16850 case OP_SET_UMORE: sop = "seta"; break;
16851 case OP_SET_SLESSEQ: sop = "setle"; break;
16852 case OP_SET_ULESSEQ: sop = "setbe"; break;
16853 case OP_SET_SMOREEQ: sop = "setge"; break;
16854 case OP_SET_UMOREEQ: sop = "setae"; break;
16856 internal_error(state, set, "Invalid set op");
16859 fprintf(fp, "\t%s %s\n",
16860 sop, reg(state, set, REGCM_GPR8));
16863 static void print_op_bit_scan(struct compile_state *state,
16864 struct triple *ins, FILE *fp)
16868 case OP_BSF: op = "bsf"; break;
16869 case OP_BSR: op = "bsr"; break;
16871 internal_error(state, ins, "unknown bit scan");
16881 reg(state, RHS(ins, 0), REGCM_GPR32),
16882 reg(state, ins, REGCM_GPR32),
16883 reg(state, ins, REGCM_GPR32));
16886 static void print_const(struct compile_state *state,
16887 struct triple *ins, FILE *fp)
16891 switch(ins->type->type & TYPE_MASK) {
16894 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16898 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16904 fprintf(fp, ".int %lu\n", ins->u.cval);
16907 internal_error(state, ins, "Unknown constant type");
16912 unsigned char *blob;
16914 size = size_of(state, ins->type);
16915 blob = ins->u.blob;
16916 for(i = 0; i < size; i++) {
16917 fprintf(fp, ".byte 0x%02x\n",
16923 internal_error(state, ins, "Unknown constant type");
16928 #define TEXT_SECTION ".rom.text"
16929 #define DATA_SECTION ".rom.data"
16931 static void print_sdecl(struct compile_state *state,
16932 struct triple *ins, FILE *fp)
16934 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16935 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16936 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16937 print_const(state, MISC(ins, 0), fp);
16938 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16942 static void print_instruction(struct compile_state *state,
16943 struct triple *ins, FILE *fp)
16945 /* Assumption: after I have exted the register allocator
16946 * everything is in a valid register.
16950 print_op_asm(state, ins, fp);
16952 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16953 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16954 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16955 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16956 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16957 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16958 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16959 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16960 case OP_POS: break;
16961 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16962 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16966 /* Don't generate anything here for constants */
16968 /* Don't generate anything for variable declarations. */
16971 print_sdecl(state, ins, fp);
16975 print_op_move(state, ins, fp);
16978 print_op_load(state, ins, fp);
16981 print_op_store(state, ins, fp);
16984 print_op_smul(state, ins, fp);
16986 case OP_CMP: print_op_cmp(state, ins, fp); break;
16987 case OP_TEST: print_op_test(state, ins, fp); break;
16989 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16990 case OP_JMP_SLESS: case OP_JMP_ULESS:
16991 case OP_JMP_SMORE: case OP_JMP_UMORE:
16992 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16993 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16994 print_op_branch(state, ins, fp);
16996 case OP_SET_EQ: case OP_SET_NOTEQ:
16997 case OP_SET_SLESS: case OP_SET_ULESS:
16998 case OP_SET_SMORE: case OP_SET_UMORE:
16999 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17000 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17001 print_op_set(state, ins, fp);
17003 case OP_INB: case OP_INW: case OP_INL:
17004 print_op_in(state, ins, fp);
17006 case OP_OUTB: case OP_OUTW: case OP_OUTL:
17007 print_op_out(state, ins, fp);
17011 print_op_bit_scan(state, ins, fp);
17014 after_lhs(state, ins);
17015 fprintf(fp, "\trdmsr\n");
17018 fprintf(fp, "\twrmsr\n");
17021 fprintf(fp, "\thlt\n");
17027 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17029 /* Ignore OP_PIECE */
17032 /* Operations I am not yet certain how to handle */
17034 case OP_SDIV: case OP_UDIV:
17035 case OP_SMOD: case OP_UMOD:
17036 /* Operations that should never get here */
17037 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
17038 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
17039 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17041 internal_error(state, ins, "unknown op: %d %s",
17042 ins->op, tops(ins->op));
17047 static void print_instructions(struct compile_state *state)
17049 struct triple *first, *ins;
17050 int print_location;
17051 struct occurance *last_occurance;
17053 print_location = 1;
17054 last_occurance = 0;
17055 fp = state->output;
17056 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17057 first = RHS(state->main_function, 0);
17060 if (print_location &&
17061 last_occurance != ins->occurance) {
17062 if (!ins->occurance->parent) {
17063 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17064 ins->occurance->function,
17065 ins->occurance->filename,
17066 ins->occurance->line,
17067 ins->occurance->col);
17070 struct occurance *ptr;
17071 fprintf(fp, "\t/*\n");
17072 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17073 fprintf(fp, "\t * %s,%s:%d.%d\n",
17079 fprintf(fp, "\t */\n");
17082 if (last_occurance) {
17083 put_occurance(last_occurance);
17085 get_occurance(ins->occurance);
17086 last_occurance = ins->occurance;
17089 print_instruction(state, ins, fp);
17091 } while(ins != first);
17094 static void generate_code(struct compile_state *state)
17096 generate_local_labels(state);
17097 print_instructions(state);
17101 static void print_tokens(struct compile_state *state)
17104 tk = &state->token[0];
17109 next_token(state, 0);
17111 loc(stdout, state, 0);
17112 printf("%s <- `%s'\n",
17114 tk->ident ? tk->ident->name :
17115 tk->str_len ? tk->val.str : "");
17117 } while(tk->tok != TOK_EOF);
17120 static void compile(const char *filename, const char *ofilename,
17121 int cpu, int debug, int opt, const char *label_prefix)
17124 struct compile_state state;
17125 memset(&state, 0, sizeof(state));
17127 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17128 memset(&state.token[i], 0, sizeof(state.token[i]));
17129 state.token[i].tok = -1;
17131 /* Remember the debug settings */
17133 state.debug = debug;
17134 state.optimize = opt;
17135 /* Remember the output filename */
17136 state.ofilename = ofilename;
17137 state.output = fopen(state.ofilename, "w");
17138 if (!state.output) {
17139 error(&state, 0, "Cannot open output file %s\n",
17142 /* Remember the label prefix */
17143 state.label_prefix = label_prefix;
17144 /* Prep the preprocessor */
17145 state.if_depth = 0;
17146 state.if_value = 0;
17147 /* register the C keywords */
17148 register_keywords(&state);
17149 /* register the keywords the macro preprocessor knows */
17150 register_macro_keywords(&state);
17151 /* Memorize where some special keywords are. */
17152 state.i_continue = lookup(&state, "continue", 8);
17153 state.i_break = lookup(&state, "break", 5);
17154 /* Enter the globl definition scope */
17155 start_scope(&state);
17156 register_builtins(&state);
17157 compile_file(&state, filename, 1);
17159 print_tokens(&state);
17162 /* Exit the global definition scope */
17165 /* Now that basic compilation has happened
17166 * optimize the intermediate code
17170 generate_code(&state);
17172 fprintf(stderr, "done\n");
17176 static void version(void)
17178 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17181 static void usage(void)
17185 "Usage: romcc <source>.c\n"
17186 "Compile a C source file without using ram\n"
17190 static void arg_error(char *fmt, ...)
17193 va_start(args, fmt);
17194 vfprintf(stderr, fmt, args);
17200 int main(int argc, char **argv)
17202 const char *filename;
17203 const char *ofilename;
17204 const char *label_prefix;
17211 ofilename = "auto.inc";
17215 while((argc > 1) && (argc != last_argc)) {
17217 if (strncmp(argv[1], "--debug=", 8) == 0) {
17218 debug = atoi(argv[1] + 8);
17222 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17223 label_prefix= argv[1] + 15;
17227 else if ((strcmp(argv[1],"-O") == 0) ||
17228 (strcmp(argv[1], "-O1") == 0)) {
17233 else if (strcmp(argv[1],"-O2") == 0) {
17238 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17239 ofilename = argv[2];
17243 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17244 cpu = arch_encode_cpu(argv[1] + 6);
17245 if (cpu == BAD_CPU) {
17246 arg_error("Invalid cpu specified: %s\n",
17254 arg_error("Wrong argument count %d\n", argc);
17256 filename = argv[1];
17257 compile(filename, ofilename, cpu, debug, optimize, label_prefix);