14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_CONSISTENCY 2
19 #warning "FIXME boundary cases with small types in larger registers"
20 #warning "FIXME give clear error messages about unused variables"
22 /* Control flow graph of a loop without goto.
33 * |\ GGG HHH | continue;
61 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
62 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
65 * [] == DFlocal(X) U DF(X)
68 * Dominator graph of the same nodes.
72 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
74 * CCC CCC: [ ] ( BBB, JJJ )
76 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
78 * FFF FFF: [ ] ( BBB )
80 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
85 * BBB and JJJ are definitely the dominance frontier.
86 * Where do I place phi functions and how do I make that decision.
89 static void die(char *fmt, ...)
94 vfprintf(stderr, fmt, args);
101 #define MALLOC_STRONG_DEBUG
102 static void *xmalloc(size_t size, const char *name)
107 die("Cannot malloc %ld bytes to hold %s: %s\n",
108 size + 0UL, name, strerror(errno));
113 static void *xcmalloc(size_t size, const char *name)
116 buf = xmalloc(size, name);
117 memset(buf, 0, size);
121 static void xfree(const void *ptr)
126 static char *xstrdup(const char *str)
131 new = xmalloc(len + 1, "xstrdup string");
132 memcpy(new, str, len);
137 static void xchdir(const char *path)
139 if (chdir(path) != 0) {
140 die("chdir to %s failed: %s\n",
141 path, strerror(errno));
145 static int exists(const char *dirname, const char *filename)
149 if (access(filename, O_RDONLY) < 0) {
150 if ((errno != EACCES) && (errno != EROFS)) {
158 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
162 off_t size, progress;
171 fd = open(filename, O_RDONLY);
173 die("Cannot open '%s' : %s\n",
174 filename, strerror(errno));
176 result = fstat(fd, &stats);
178 die("Cannot stat: %s: %s\n",
179 filename, strerror(errno));
181 size = stats.st_size;
183 buf = xmalloc(size +2, filename);
184 buf[size] = '\n'; /* Make certain the file is newline terminated */
185 buf[size+1] = '\0'; /* Null terminate the file for good measure */
187 while(progress < size) {
188 result = read(fd, buf + progress, size - progress);
190 if ((errno == EINTR) || (errno == EAGAIN))
192 die("read on %s of %ld bytes failed: %s\n",
193 filename, (size - progress)+ 0UL, strerror(errno));
199 die("Close of %s failed: %s\n",
200 filename, strerror(errno));
205 /* Long on the destination platform */
206 typedef unsigned long ulong_t;
210 struct file_state *prev;
211 const char *basename;
219 const char *report_name;
220 const char *report_dir;
225 struct hash_entry *ident;
233 /* I have two classes of types:
235 * Logical types. (The type the C standard says the operation is of)
237 * The operational types are:
252 * No memory is useable by the compiler.
253 * There is no floating point support.
254 * All operations take place in general purpose registers.
255 * There is one type of general purpose register.
256 * Unsigned longs are stored in that general purpose register.
259 /* Operations on general purpose registers.
276 #define OP_POS 14 /* Dummy positive operator don't use it */
286 #define OP_SLESSEQ 26
287 #define OP_ULESSEQ 27
288 #define OP_SMOREEQ 28
289 #define OP_UMOREEQ 29
291 #define OP_LFALSE 30 /* Test if the expression is logically false */
292 #define OP_LTRUE 31 /* Test if the expression is logcially true */
299 #define OP_MIN_CONST 50
300 #define OP_MAX_CONST 59
301 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
302 #define OP_INTCONST 50
303 #define OP_BLOBCONST 51
304 /* For OP_BLOBCONST ->type holds the layout and size
305 * information. u.blob holds a pointer to the raw binary
306 * data for the constant initializer.
308 #define OP_ADDRCONST 52
309 /* For OP_ADDRCONST ->type holds the type.
310 * MISC(0) holds the reference to the static variable.
311 * ->u.cval holds an offset from that value.
315 /* OP_WRITE moves one pseudo register to another.
316 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
317 * RHS(0) holds the psuedo to move.
321 /* OP_READ reads the value of a variable and makes
322 * it available for the pseudo operation.
323 * Useful for things like def-use chains.
324 * RHS(0) holds points to the triple to read from.
327 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
330 /* OP_PIECE returns one piece of a instruction that returns a structure.
331 * MISC(0) is the instruction
332 * u.cval is the LHS piece of the instruction to return.
335 /* OP_ASM holds a sequence of assembly instructions, the result
336 * of a C asm directive.
337 * RHS(x) holds input value x to the assembly sequence.
338 * LHS(x) holds the output value x from the assembly sequence.
339 * u.blob holds the string of assembly instructions.
343 /* OP_DEREF generates an lvalue from a pointer.
344 * RHS(0) holds the pointer value.
345 * OP_DEREF serves as a place holder to indicate all necessary
346 * checks have been done to indicate a value is an lvalue.
349 /* OP_DOT references a submember of a structure lvalue.
350 * RHS(0) holds the lvalue.
351 * ->u.field holds the name of the field we want.
353 * Not seen outside of expressions.
356 /* OP_VAL returns the value of a subexpression of the current expression.
357 * Useful for operators that have side effects.
358 * RHS(0) holds the expression.
359 * MISC(0) holds the subexpression of RHS(0) that is the
360 * value of the expression.
362 * Not seen outside of expressions.
365 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
366 * Not seen outside of expressions.
369 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
370 * Not seen outside of expressions.
373 /* OP_CODE performas a C ? : operation.
374 * RHS(0) holds the test.
375 * RHS(1) holds the expression to evaluate if the test returns true.
376 * RHS(2) holds the expression to evaluate if the test returns false.
377 * Not seen outside of expressions.
380 /* OP_COMMA performacs a C comma operation.
381 * That is RHS(0) is evaluated, then RHS(1)
382 * and the value of RHS(1) is returned.
383 * Not seen outside of expressions.
387 /* OP_CALL performs a procedure call.
388 * MISC(0) holds a pointer to the OP_LIST of a function
389 * RHS(x) holds argument x of a function
391 * Currently not seen outside of expressions.
393 #define OP_VAL_VEC 74
394 /* OP_VAL_VEC is an array of triples that are either variable
395 * or values for a structure or an array.
396 * RHS(x) holds element x of the vector.
397 * triple->type->elements holds the size of the vector.
402 /* OP_LIST Holds a list of statements, and a result value.
403 * RHS(0) holds the list of statements.
404 * MISC(0) holds the value of the statements.
407 #define OP_BRANCH 81 /* branch */
408 /* For branch instructions
409 * TARG(0) holds the branch target.
410 * RHS(0) if present holds the branch condition.
411 * ->next holds where to branch to if the branch is not taken.
412 * The branch target can only be a decl...
416 /* OP_LABEL is a triple that establishes an target for branches.
417 * ->use is the list of all branches that use this label.
421 /* OP_DECL is a triple that establishes an lvalue for assignments.
422 * ->use is a list of statements that use the variable.
426 /* OP_SDECL is a triple that establishes a variable of static
428 * ->use is a list of statements that use the variable.
429 * MISC(0) holds the initializer expression.
434 /* OP_PHI is a triple used in SSA form code.
435 * It is used when multiple code paths merge and a variable needs
436 * a single assignment from any of those code paths.
437 * The operation is a cross between OP_DECL and OP_WRITE, which
438 * is what OP_PHI is geneared from.
440 * RHS(x) points to the value from code path x
441 * The number of RHS entries is the number of control paths into the block
442 * in which OP_PHI resides. The elements of the array point to point
443 * to the variables OP_PHI is derived from.
445 * MISC(0) holds a pointer to the orginal OP_DECL node.
448 /* Architecture specific instructions */
451 #define OP_SET_EQ 102
452 #define OP_SET_NOTEQ 103
453 #define OP_SET_SLESS 104
454 #define OP_SET_ULESS 105
455 #define OP_SET_SMORE 106
456 #define OP_SET_UMORE 107
457 #define OP_SET_SLESSEQ 108
458 #define OP_SET_ULESSEQ 109
459 #define OP_SET_SMOREEQ 110
460 #define OP_SET_UMOREEQ 111
463 #define OP_JMP_EQ 113
464 #define OP_JMP_NOTEQ 114
465 #define OP_JMP_SLESS 115
466 #define OP_JMP_ULESS 116
467 #define OP_JMP_SMORE 117
468 #define OP_JMP_UMORE 118
469 #define OP_JMP_SLESSEQ 119
470 #define OP_JMP_ULESSEQ 120
471 #define OP_JMP_SMOREEQ 121
472 #define OP_JMP_UMOREEQ 122
474 /* Builtin operators that it is just simpler to use the compiler for */
492 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
494 #define BLOCK 8 /* Triple stores the current block */
495 unsigned char lhs, rhs, misc, targ;
498 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
506 static const struct op_info table_ops[] = {
507 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
508 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
509 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
510 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
511 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
512 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
513 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
514 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
515 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
516 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
517 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
518 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
519 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
520 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
521 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
522 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
523 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
525 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
526 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
527 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
528 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
529 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
530 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
531 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
532 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
533 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
534 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
535 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
536 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
538 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
539 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE | BLOCK , "store"),
541 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
543 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
544 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
545 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
547 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE | BLOCK, "write"),
548 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
549 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
550 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
551 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
552 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
553 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
555 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
556 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
557 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
558 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
559 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
560 /* Call is special most it can stand in for anything so it depends on context */
561 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
562 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
563 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
565 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
566 /* The number of targets for OP_BRANCH depends on context */
567 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
568 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
569 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
570 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
571 /* The number of RHS elements of OP_PHI depend upon context */
572 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
574 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
575 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
576 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
577 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
578 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
579 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
580 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
581 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
582 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
583 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
584 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
585 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
586 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
587 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
588 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
589 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
590 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
591 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
592 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
593 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
594 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
595 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
596 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
598 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
599 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
600 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
601 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
602 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
603 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
604 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
605 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
606 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
607 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
608 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
611 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
613 static const char *tops(int index)
615 static const char unknown[] = "unknown op";
619 if (index > OP_MAX) {
622 return table_ops[index].name;
629 struct triple_set *next;
630 struct triple *member;
640 const char *filename;
641 const char *function;
644 struct occurance *parent;
647 struct triple *next, *prev;
648 struct triple_set *use;
651 unsigned char template_id;
652 unsigned short sizes;
653 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
654 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
655 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
656 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
657 #define TRIPLE_SIZE(SIZES) \
658 ((((SIZES) >> 0) & 0x0f) + \
659 (((SIZES) >> 4) & 0x0f) + \
660 (((SIZES) >> 8) & 0x0f) + \
661 (((SIZES) >> 12) & 0x0f))
662 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
663 ((((LHS) & 0x0f) << 0) | \
664 (((RHS) & 0x0f) << 4) | \
665 (((MISC) & 0x0f) << 8) | \
666 (((TARG) & 0x0f) << 12))
667 #define TRIPLE_LHS_OFF(SIZES) (0)
668 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
669 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
670 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
671 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
672 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
673 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
674 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
675 unsigned id; /* A scratch value and finally the register */
676 #define TRIPLE_FLAG_FLATTENED (1 << 31)
677 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
678 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
679 struct occurance *occurance;
684 struct hash_entry *field;
685 struct asm_info *ainfo;
687 struct triple *param[2];
694 struct ins_template {
695 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
699 struct ins_template tmpl;
704 struct block_set *next;
705 struct block *member;
708 struct block *work_next;
709 struct block *left, *right;
710 struct triple *first, *last;
712 struct block_set *use;
713 struct block_set *idominates;
714 struct block_set *domfrontier;
716 struct block_set *ipdominates;
717 struct block_set *ipdomfrontier;
725 struct hash_entry *ident;
732 struct hash_entry *ident;
738 struct hash_entry *next;
742 struct macro *sym_define;
743 struct symbol *sym_label;
744 struct symbol *sym_struct;
745 struct symbol *sym_ident;
748 #define HASH_TABLE_SIZE 2048
750 struct compile_state {
751 const char *label_prefix;
752 const char *ofilename;
755 struct file_state *file;
756 struct occurance *last_occurance;
757 const char *function;
758 struct token token[4];
759 struct hash_entry *hash_table[HASH_TABLE_SIZE];
760 struct hash_entry *i_continue;
761 struct hash_entry *i_break;
763 int if_depth, if_value;
765 struct file_state *macro_file;
766 struct triple *main_function;
767 struct block *first_block, *last_block;
774 /* visibility global/local */
775 /* static/auto duration */
776 /* typedef, register, inline */
778 #define STOR_MASK 0x000f
780 #define STOR_GLOBAL 0x0001
782 #define STOR_PERM 0x0002
783 /* Storage specifiers */
784 #define STOR_AUTO 0x0000
785 #define STOR_STATIC 0x0002
786 #define STOR_EXTERN 0x0003
787 #define STOR_REGISTER 0x0004
788 #define STOR_TYPEDEF 0x0008
789 #define STOR_INLINE 0x000c
792 #define QUAL_MASK 0x0070
793 #define QUAL_NONE 0x0000
794 #define QUAL_CONST 0x0010
795 #define QUAL_VOLATILE 0x0020
796 #define QUAL_RESTRICT 0x0040
799 #define TYPE_MASK 0x1f00
800 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
801 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
802 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
803 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
804 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
805 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
806 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
807 #define TYPE_DEFAULT 0x0000
808 #define TYPE_VOID 0x0100
809 #define TYPE_CHAR 0x0200
810 #define TYPE_UCHAR 0x0300
811 #define TYPE_SHORT 0x0400
812 #define TYPE_USHORT 0x0500
813 #define TYPE_INT 0x0600
814 #define TYPE_UINT 0x0700
815 #define TYPE_LONG 0x0800
816 #define TYPE_ULONG 0x0900
817 #define TYPE_LLONG 0x0a00 /* long long */
818 #define TYPE_ULLONG 0x0b00
819 #define TYPE_FLOAT 0x0c00
820 #define TYPE_DOUBLE 0x0d00
821 #define TYPE_LDOUBLE 0x0e00 /* long double */
822 #define TYPE_STRUCT 0x1000
823 #define TYPE_ENUM 0x1100
824 #define TYPE_POINTER 0x1200
826 * type->left holds the type pointed to.
828 #define TYPE_FUNCTION 0x1300
829 /* For TYPE_FUNCTION:
830 * type->left holds the return type.
831 * type->right holds the...
833 #define TYPE_PRODUCT 0x1400
834 /* TYPE_PRODUCT is a basic building block when defining structures
835 * type->left holds the type that appears first in memory.
836 * type->right holds the type that appears next in memory.
838 #define TYPE_OVERLAP 0x1500
839 /* TYPE_OVERLAP is a basic building block when defining unions
840 * type->left and type->right holds to types that overlap
841 * each other in memory.
843 #define TYPE_ARRAY 0x1600
844 /* TYPE_ARRAY is a basic building block when definitng arrays.
845 * type->left holds the type we are an array of.
846 * type-> holds the number of elements.
849 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
853 struct type *left, *right;
855 struct hash_entry *field_ident;
856 struct hash_entry *type_ident;
859 #define MAX_REGISTERS 75
860 #define MAX_REG_EQUIVS 16
861 #define REGISTER_BITS 16
862 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
863 #define TEMPLATE_BITS 6
864 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
867 #define REG_UNNEEDED 1
868 #define REG_VIRT0 (MAX_REGISTERS + 0)
869 #define REG_VIRT1 (MAX_REGISTERS + 1)
870 #define REG_VIRT2 (MAX_REGISTERS + 2)
871 #define REG_VIRT3 (MAX_REGISTERS + 3)
872 #define REG_VIRT4 (MAX_REGISTERS + 4)
873 #define REG_VIRT5 (MAX_REGISTERS + 5)
874 #define REG_VIRT6 (MAX_REGISTERS + 5)
875 #define REG_VIRT7 (MAX_REGISTERS + 5)
876 #define REG_VIRT8 (MAX_REGISTERS + 5)
877 #define REG_VIRT9 (MAX_REGISTERS + 5)
879 /* Provision for 8 register classes */
881 #define REGC_SHIFT REGISTER_BITS
882 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
883 #define REG_MASK (MAX_VIRT_REGISTERS -1)
884 #define ID_REG(ID) ((ID) & REG_MASK)
885 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
886 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
887 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
888 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
889 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
891 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
892 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
893 static void arch_reg_equivs(
894 struct compile_state *state, unsigned *equiv, int reg);
895 static int arch_select_free_register(
896 struct compile_state *state, char *used, int classes);
897 static unsigned arch_regc_size(struct compile_state *state, int class);
898 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
899 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
900 static const char *arch_reg_str(int reg);
901 static struct reg_info arch_reg_constraint(
902 struct compile_state *state, struct type *type, const char *constraint);
903 static struct reg_info arch_reg_clobber(
904 struct compile_state *state, const char *clobber);
905 static struct reg_info arch_reg_lhs(struct compile_state *state,
906 struct triple *ins, int index);
907 static struct reg_info arch_reg_rhs(struct compile_state *state,
908 struct triple *ins, int index);
909 static struct triple *transform_to_arch_instruction(
910 struct compile_state *state, struct triple *ins);
914 #define DEBUG_ABORT_ON_ERROR 0x0001
915 #define DEBUG_INTERMEDIATE_CODE 0x0002
916 #define DEBUG_CONTROL_FLOW 0x0004
917 #define DEBUG_BASIC_BLOCKS 0x0008
918 #define DEBUG_FDOMINATORS 0x0010
919 #define DEBUG_RDOMINATORS 0x0020
920 #define DEBUG_TRIPLES 0x0040
921 #define DEBUG_INTERFERENCE 0x0080
922 #define DEBUG_ARCH_CODE 0x0100
923 #define DEBUG_CODE_ELIMINATION 0x0200
924 #define DEBUG_INSERTED_COPIES 0x0400
926 #define GLOBAL_SCOPE_DEPTH 1
927 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
929 static void compile_file(struct compile_state *old_state, const char *filename, int local);
931 static void do_cleanup(struct compile_state *state)
934 fclose(state->output);
935 unlink(state->ofilename);
939 static int get_col(struct file_state *file)
943 ptr = file->line_start;
945 for(col = 0; ptr < end; ptr++) {
950 col = (col & ~7) + 8;
956 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
960 struct occurance *spot;
961 spot = triple->occurance;
962 while(spot->parent) {
965 fprintf(fp, "%s:%d.%d: ",
966 spot->filename, spot->line, spot->col);
972 col = get_col(state->file);
973 fprintf(fp, "%s:%d.%d: ",
974 state->file->report_name, state->file->report_line, col);
977 static void __internal_error(struct compile_state *state, struct triple *ptr,
982 loc(stderr, state, ptr);
984 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
986 fprintf(stderr, "Internal compiler error: ");
987 vfprintf(stderr, fmt, args);
988 fprintf(stderr, "\n");
995 static void __internal_warning(struct compile_state *state, struct triple *ptr,
1000 loc(stderr, state, ptr);
1001 fprintf(stderr, "Internal compiler warning: ");
1002 vfprintf(stderr, fmt, args);
1003 fprintf(stderr, "\n");
1009 static void __error(struct compile_state *state, struct triple *ptr,
1013 va_start(args, fmt);
1014 loc(stderr, state, ptr);
1015 vfprintf(stderr, fmt, args);
1017 fprintf(stderr, "\n");
1019 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1025 static void __warning(struct compile_state *state, struct triple *ptr,
1029 va_start(args, fmt);
1030 loc(stderr, state, ptr);
1031 fprintf(stderr, "warning: ");
1032 vfprintf(stderr, fmt, args);
1033 fprintf(stderr, "\n");
1037 #if DEBUG_ERROR_MESSAGES
1038 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1039 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1040 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1041 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1043 # define internal_error __internal_error
1044 # define internal_warning __internal_warning
1045 # define error __error
1046 # define warning __warning
1048 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1050 static void valid_op(struct compile_state *state, int op)
1052 char *fmt = "invalid op: %d";
1054 internal_error(state, 0, fmt, op);
1057 internal_error(state, 0, fmt, op);
1061 static void valid_ins(struct compile_state *state, struct triple *ptr)
1063 valid_op(state, ptr->op);
1066 static void process_trigraphs(struct compile_state *state)
1068 char *src, *dest, *end;
1069 struct file_state *file;
1071 src = dest = file->buf;
1072 end = file->buf + file->size;
1073 while((end - src) >= 3) {
1074 if ((src[0] == '?') && (src[1] == '?')) {
1077 case '=': c = '#'; break;
1078 case '/': c = '\\'; break;
1079 case '\'': c = '^'; break;
1080 case '(': c = '['; break;
1081 case ')': c = ']'; break;
1082 case '!': c = '!'; break;
1083 case '<': c = '{'; break;
1084 case '>': c = '}'; break;
1085 case '-': c = '~'; break;
1102 file->size = dest - file->buf;
1105 static void splice_lines(struct compile_state *state)
1107 char *src, *dest, *end;
1108 struct file_state *file;
1110 src = dest = file->buf;
1111 end = file->buf + file->size;
1112 while((end - src) >= 2) {
1113 if ((src[0] == '\\') && (src[1] == '\n')) {
1123 file->size = dest - file->buf;
1126 static struct type void_type;
1127 static void use_triple(struct triple *used, struct triple *user)
1129 struct triple_set **ptr, *new;
1136 if ((*ptr)->member == user) {
1139 ptr = &(*ptr)->next;
1141 /* Append new to the head of the list,
1142 * copy_func and rename_block_variables
1145 new = xcmalloc(sizeof(*new), "triple_set");
1147 new->next = used->use;
1151 static void unuse_triple(struct triple *used, struct triple *unuser)
1153 struct triple_set *use, **ptr;
1160 if (use->member == unuser) {
1170 static void push_triple(struct triple *used, struct triple *user)
1172 struct triple_set *new;
1177 /* Append new to the head of the list,
1178 * it's the only sensible behavoir for a stack.
1180 new = xcmalloc(sizeof(*new), "triple_set");
1182 new->next = used->use;
1186 static void pop_triple(struct triple *used, struct triple *unuser)
1188 struct triple_set *use, **ptr;
1192 if (use->member == unuser) {
1195 /* Only free one occurance from the stack */
1204 static void put_occurance(struct occurance *occurance)
1206 occurance->count -= 1;
1207 if (occurance->count <= 0) {
1208 if (occurance->parent) {
1209 put_occurance(occurance->parent);
1215 static void get_occurance(struct occurance *occurance)
1217 occurance->count += 1;
1221 static struct occurance *new_occurance(struct compile_state *state)
1223 struct occurance *result, *last;
1224 const char *filename;
1225 const char *function;
1233 filename = state->file->report_name;
1234 line = state->file->report_line;
1235 col = get_col(state->file);
1237 if (state->function) {
1238 function = state->function;
1240 last = state->last_occurance;
1242 (last->col == col) &&
1243 (last->line == line) &&
1244 (last->function == function) &&
1245 (strcmp(last->filename, filename) == 0)) {
1246 get_occurance(last);
1250 state->last_occurance = 0;
1251 put_occurance(last);
1253 result = xmalloc(sizeof(*result), "occurance");
1255 result->filename = filename;
1256 result->function = function;
1257 result->line = line;
1260 state->last_occurance = result;
1264 static struct occurance *inline_occurance(struct compile_state *state,
1265 struct occurance *new, struct occurance *orig)
1267 struct occurance *result, *last;
1268 last = state->last_occurance;
1270 (last->parent == orig) &&
1271 (last->col == new->col) &&
1272 (last->line == new->line) &&
1273 (last->function == new->function) &&
1274 (last->filename == new->filename)) {
1275 get_occurance(last);
1279 state->last_occurance = 0;
1280 put_occurance(last);
1282 get_occurance(orig);
1283 result = xmalloc(sizeof(*result), "occurance");
1285 result->filename = new->filename;
1286 result->function = new->function;
1287 result->line = new->line;
1288 result->col = new->col;
1289 result->parent = orig;
1290 state->last_occurance = result;
1295 static struct occurance dummy_occurance = {
1297 .filename = __FILE__,
1304 /* The zero triple is used as a place holder when we are removing pointers
1305 * from a triple. Having allows certain sanity checks to pass even
1306 * when the original triple that was pointed to is gone.
1308 static struct triple zero_triple = {
1309 .next = &zero_triple,
1310 .prev = &zero_triple,
1313 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1314 .id = -1, /* An invalid id */
1315 .u = { .cval = 0, },
1316 .occurance = &dummy_occurance,
1317 .param { [0] = 0, [1] = 0, },
1321 static unsigned short triple_sizes(struct compile_state *state,
1322 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1324 int lhs, rhs, misc, targ;
1325 valid_op(state, op);
1326 lhs = table_ops[op].lhs;
1327 rhs = table_ops[op].rhs;
1328 misc = table_ops[op].misc;
1329 targ = table_ops[op].targ;
1332 if (op == OP_CALL) {
1335 param = type->right;
1336 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1338 param = param->right;
1340 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1344 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1345 lhs = type->left->elements;
1348 else if (op == OP_VAL_VEC) {
1349 rhs = type->elements;
1351 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1354 else if (op == OP_ASM) {
1358 if ((rhs < 0) || (rhs > MAX_RHS)) {
1359 internal_error(state, 0, "bad rhs");
1361 if ((lhs < 0) || (lhs > MAX_LHS)) {
1362 internal_error(state, 0, "bad lhs");
1364 if ((misc < 0) || (misc > MAX_MISC)) {
1365 internal_error(state, 0, "bad misc");
1367 if ((targ < 0) || (targ > MAX_TARG)) {
1368 internal_error(state, 0, "bad targs");
1370 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1373 static struct triple *alloc_triple(struct compile_state *state,
1374 int op, struct type *type, int lhs, int rhs,
1375 struct occurance *occurance)
1377 size_t size, sizes, extra_count, min_count;
1379 sizes = triple_sizes(state, op, type, lhs, rhs);
1381 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1382 extra_count = TRIPLE_SIZE(sizes);
1383 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1385 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1386 ret = xcmalloc(size, "tripple");
1392 ret->occurance = occurance;
1396 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1399 int src_lhs, src_rhs, src_size;
1400 src_lhs = TRIPLE_LHS(src->sizes);
1401 src_rhs = TRIPLE_RHS(src->sizes);
1402 src_size = TRIPLE_SIZE(src->sizes);
1403 get_occurance(src->occurance);
1404 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1406 memcpy(dup, src, sizeof(*src));
1407 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1411 static struct triple *new_triple(struct compile_state *state,
1412 int op, struct type *type, int lhs, int rhs)
1415 struct occurance *occurance;
1416 occurance = new_occurance(state);
1417 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1421 static struct triple *build_triple(struct compile_state *state,
1422 int op, struct type *type, struct triple *left, struct triple *right,
1423 struct occurance *occurance)
1427 ret = alloc_triple(state, op, type, -1, -1, occurance);
1428 count = TRIPLE_SIZE(ret->sizes);
1430 ret->param[0] = left;
1433 ret->param[1] = right;
1438 static struct triple *triple(struct compile_state *state,
1439 int op, struct type *type, struct triple *left, struct triple *right)
1443 ret = new_triple(state, op, type, -1, -1);
1444 count = TRIPLE_SIZE(ret->sizes);
1446 ret->param[0] = left;
1449 ret->param[1] = right;
1454 static struct triple *branch(struct compile_state *state,
1455 struct triple *targ, struct triple *test)
1458 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1462 TARG(ret, 0) = targ;
1463 /* record the branch target was used */
1464 if (!targ || (targ->op != OP_LABEL)) {
1465 internal_error(state, 0, "branch not to label");
1466 use_triple(targ, ret);
1472 static void insert_triple(struct compile_state *state,
1473 struct triple *first, struct triple *ptr)
1476 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1477 internal_error(state, ptr, "expression already used");
1480 ptr->prev = first->prev;
1481 ptr->prev->next = ptr;
1482 ptr->next->prev = ptr;
1483 if ((ptr->prev->op == OP_BRANCH) &&
1484 TRIPLE_RHS(ptr->prev->sizes)) {
1485 unuse_triple(first, ptr->prev);
1486 use_triple(ptr, ptr->prev);
1491 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1493 /* This function is used to determine if u.block
1494 * is utilized to store the current block number.
1497 valid_ins(state, ins);
1498 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1499 return stores_block;
1502 static struct block *block_of_triple(struct compile_state *state,
1505 struct triple *first;
1506 first = RHS(state->main_function, 0);
1507 while(ins != first && !triple_stores_block(state, ins)) {
1508 if (ins == ins->prev) {
1509 internal_error(state, 0, "ins == ins->prev?");
1513 if (!triple_stores_block(state, ins)) {
1514 internal_error(state, ins, "Cannot find block");
1516 return ins->u.block;
1519 static struct triple *pre_triple(struct compile_state *state,
1520 struct triple *base,
1521 int op, struct type *type, struct triple *left, struct triple *right)
1523 struct block *block;
1525 /* If I am an OP_PIECE jump to the real instruction */
1526 if (base->op == OP_PIECE) {
1527 base = MISC(base, 0);
1529 block = block_of_triple(state, base);
1530 get_occurance(base->occurance);
1531 ret = build_triple(state, op, type, left, right, base->occurance);
1532 if (triple_stores_block(state, ret)) {
1533 ret->u.block = block;
1535 insert_triple(state, base, ret);
1536 if (block->first == base) {
1542 static struct triple *post_triple(struct compile_state *state,
1543 struct triple *base,
1544 int op, struct type *type, struct triple *left, struct triple *right)
1546 struct block *block;
1549 /* If I am an OP_PIECE jump to the real instruction */
1550 if (base->op == OP_PIECE) {
1551 base = MISC(base, 0);
1553 /* If I have a left hand side skip over it */
1554 zlhs = TRIPLE_LHS(base->sizes);
1555 if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1556 base = LHS(base, zlhs - 1);
1559 block = block_of_triple(state, base);
1560 get_occurance(base->occurance);
1561 ret = build_triple(state, op, type, left, right, base->occurance);
1562 if (triple_stores_block(state, ret)) {
1563 ret->u.block = block;
1565 insert_triple(state, base->next, ret);
1566 if (block->last == base) {
1572 static struct triple *label(struct compile_state *state)
1574 /* Labels don't get a type */
1575 struct triple *result;
1576 result = triple(state, OP_LABEL, &void_type, 0, 0);
1580 static void display_triple(FILE *fp, struct triple *ins)
1582 struct occurance *ptr;
1586 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1589 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1592 reg = arch_reg_str(ID_REG(ins->id));
1593 if (ins->op == OP_INTCONST) {
1594 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1595 ins, pre, post, reg, ins->template_id, tops(ins->op),
1598 else if (ins->op == OP_ADDRCONST) {
1599 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1600 ins, pre, post, reg, ins->template_id, tops(ins->op),
1601 MISC(ins, 0), ins->u.cval);
1605 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1606 ins, pre, post, reg, ins->template_id, tops(ins->op));
1607 count = TRIPLE_SIZE(ins->sizes);
1608 for(i = 0; i < count; i++) {
1609 fprintf(fp, " %-10p", ins->param[i]);
1616 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1617 fprintf(fp, " %s,%s:%d.%d",
1627 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1629 /* Does the triple have no side effects.
1630 * I.e. Rexecuting the triple with the same arguments
1631 * gives the same value.
1634 valid_ins(state, ins);
1635 pure = PURE_BITS(table_ops[ins->op].flags);
1636 if ((pure != PURE) && (pure != IMPURE)) {
1637 internal_error(state, 0, "Purity of %s not known\n",
1640 return pure == PURE;
1643 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1645 /* This function is used to determine which triples need
1649 valid_ins(state, ins);
1650 is_branch = (table_ops[ins->op].targ != 0);
1654 static int triple_is_def(struct compile_state *state, struct triple *ins)
1656 /* This function is used to determine which triples need
1660 valid_ins(state, ins);
1661 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1665 static struct triple **triple_iter(struct compile_state *state,
1666 size_t count, struct triple **vector,
1667 struct triple *ins, struct triple **last)
1669 struct triple **ret;
1675 else if ((last >= vector) && (last < (vector + count - 1))) {
1683 static struct triple **triple_lhs(struct compile_state *state,
1684 struct triple *ins, struct triple **last)
1686 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1690 static struct triple **triple_rhs(struct compile_state *state,
1691 struct triple *ins, struct triple **last)
1693 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1697 static struct triple **triple_misc(struct compile_state *state,
1698 struct triple *ins, struct triple **last)
1700 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1704 static struct triple **triple_targ(struct compile_state *state,
1705 struct triple *ins, struct triple **last)
1708 struct triple **ret, **vector;
1710 count = TRIPLE_TARG(ins->sizes);
1711 vector = &TARG(ins, 0);
1716 else if ((last >= vector) && (last < (vector + count - 1))) {
1719 else if ((last == (vector + count - 1)) &&
1720 TRIPLE_RHS(ins->sizes)) {
1728 static void verify_use(struct compile_state *state,
1729 struct triple *user, struct triple *used)
1732 size = TRIPLE_SIZE(user->sizes);
1733 for(i = 0; i < size; i++) {
1734 if (user->param[i] == used) {
1738 if (triple_is_branch(state, user)) {
1739 if (user->next == used) {
1744 internal_error(state, user, "%s(%p) does not use %s(%p)",
1745 tops(user->op), user, tops(used->op), used);
1749 static int find_rhs_use(struct compile_state *state,
1750 struct triple *user, struct triple *used)
1752 struct triple **param;
1754 verify_use(state, user, used);
1755 size = TRIPLE_RHS(user->sizes);
1756 param = &RHS(user, 0);
1757 for(i = 0; i < size; i++) {
1758 if (param[i] == used) {
1765 static void free_triple(struct compile_state *state, struct triple *ptr)
1768 size = sizeof(*ptr) - sizeof(ptr->param) +
1769 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1770 ptr->prev->next = ptr->next;
1771 ptr->next->prev = ptr->prev;
1773 internal_error(state, ptr, "ptr->use != 0");
1775 put_occurance(ptr->occurance);
1776 memset(ptr, -1, size);
1780 static void release_triple(struct compile_state *state, struct triple *ptr)
1782 struct triple_set *set, *next;
1783 struct triple **expr;
1784 /* Remove ptr from use chains where it is the user */
1785 expr = triple_rhs(state, ptr, 0);
1786 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1788 unuse_triple(*expr, ptr);
1791 expr = triple_lhs(state, ptr, 0);
1792 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1794 unuse_triple(*expr, ptr);
1797 expr = triple_misc(state, ptr, 0);
1798 for(; expr; expr = triple_misc(state, ptr, expr)) {
1800 unuse_triple(*expr, ptr);
1803 expr = triple_targ(state, ptr, 0);
1804 for(; expr; expr = triple_targ(state, ptr, expr)) {
1806 unuse_triple(*expr, ptr);
1809 /* Reomve ptr from use chains where it is used */
1810 for(set = ptr->use; set; set = next) {
1812 expr = triple_rhs(state, set->member, 0);
1813 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1815 *expr = &zero_triple;
1818 expr = triple_lhs(state, set->member, 0);
1819 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1821 *expr = &zero_triple;
1824 expr = triple_misc(state, set->member, 0);
1825 for(; expr; expr = triple_misc(state, set->member, expr)) {
1827 *expr = &zero_triple;
1830 expr = triple_targ(state, set->member, 0);
1831 for(; expr; expr = triple_targ(state, set->member, expr)) {
1833 *expr = &zero_triple;
1836 unuse_triple(ptr, set->member);
1838 free_triple(state, ptr);
1841 static void print_triple(struct compile_state *state, struct triple *ptr);
1843 #define TOK_UNKNOWN 0
1846 #define TOK_LBRACE 3
1847 #define TOK_RBRACE 4
1851 #define TOK_LBRACKET 8
1852 #define TOK_RBRACKET 9
1853 #define TOK_LPAREN 10
1854 #define TOK_RPAREN 11
1859 #define TOK_TIMESEQ 16
1860 #define TOK_DIVEQ 17
1861 #define TOK_MODEQ 18
1862 #define TOK_PLUSEQ 19
1863 #define TOK_MINUSEQ 20
1866 #define TOK_ANDEQ 23
1867 #define TOK_XOREQ 24
1870 #define TOK_NOTEQ 27
1871 #define TOK_QUEST 28
1872 #define TOK_LOGOR 29
1873 #define TOK_LOGAND 30
1877 #define TOK_LESSEQ 34
1878 #define TOK_MOREEQ 35
1882 #define TOK_MINUS 39
1885 #define TOK_PLUSPLUS 42
1886 #define TOK_MINUSMINUS 43
1888 #define TOK_ARROW 45
1890 #define TOK_TILDE 47
1891 #define TOK_LIT_STRING 48
1892 #define TOK_LIT_CHAR 49
1893 #define TOK_LIT_INT 50
1894 #define TOK_LIT_FLOAT 51
1895 #define TOK_MACRO 52
1896 #define TOK_CONCATENATE 53
1898 #define TOK_IDENT 54
1899 #define TOK_STRUCT_NAME 55
1900 #define TOK_ENUM_CONST 56
1901 #define TOK_TYPE_NAME 57
1904 #define TOK_BREAK 59
1907 #define TOK_CONST 62
1908 #define TOK_CONTINUE 63
1909 #define TOK_DEFAULT 64
1911 #define TOK_DOUBLE 66
1914 #define TOK_EXTERN 69
1915 #define TOK_FLOAT 70
1919 #define TOK_INLINE 74
1922 #define TOK_REGISTER 77
1923 #define TOK_RESTRICT 78
1924 #define TOK_RETURN 79
1925 #define TOK_SHORT 80
1926 #define TOK_SIGNED 81
1927 #define TOK_SIZEOF 82
1928 #define TOK_STATIC 83
1929 #define TOK_STRUCT 84
1930 #define TOK_SWITCH 85
1931 #define TOK_TYPEDEF 86
1932 #define TOK_UNION 87
1933 #define TOK_UNSIGNED 88
1935 #define TOK_VOLATILE 90
1936 #define TOK_WHILE 91
1938 #define TOK_ATTRIBUTE 93
1939 #define TOK_ALIGNOF 94
1940 #define TOK_FIRST_KEYWORD TOK_AUTO
1941 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1943 #define TOK_DEFINE 100
1944 #define TOK_UNDEF 101
1945 #define TOK_INCLUDE 102
1946 #define TOK_LINE 103
1947 #define TOK_ERROR 104
1948 #define TOK_WARNING 105
1949 #define TOK_PRAGMA 106
1950 #define TOK_IFDEF 107
1951 #define TOK_IFNDEF 108
1952 #define TOK_ELIF 109
1953 #define TOK_ENDIF 110
1955 #define TOK_FIRST_MACRO TOK_DEFINE
1956 #define TOK_LAST_MACRO TOK_ENDIF
1960 static const char *tokens[] = {
1961 [TOK_UNKNOWN ] = "unknown",
1962 [TOK_SPACE ] = ":space:",
1964 [TOK_LBRACE ] = "{",
1965 [TOK_RBRACE ] = "}",
1969 [TOK_LBRACKET ] = "[",
1970 [TOK_RBRACKET ] = "]",
1971 [TOK_LPAREN ] = "(",
1972 [TOK_RPAREN ] = ")",
1974 [TOK_DOTS ] = "...",
1977 [TOK_TIMESEQ ] = "*=",
1978 [TOK_DIVEQ ] = "/=",
1979 [TOK_MODEQ ] = "%=",
1980 [TOK_PLUSEQ ] = "+=",
1981 [TOK_MINUSEQ ] = "-=",
1982 [TOK_SLEQ ] = "<<=",
1983 [TOK_SREQ ] = ">>=",
1984 [TOK_ANDEQ ] = "&=",
1985 [TOK_XOREQ ] = "^=",
1988 [TOK_NOTEQ ] = "!=",
1990 [TOK_LOGOR ] = "||",
1991 [TOK_LOGAND ] = "&&",
1995 [TOK_LESSEQ ] = "<=",
1996 [TOK_MOREEQ ] = ">=",
2003 [TOK_PLUSPLUS ] = "++",
2004 [TOK_MINUSMINUS ] = "--",
2006 [TOK_ARROW ] = "->",
2009 [TOK_LIT_STRING ] = ":string:",
2010 [TOK_IDENT ] = ":ident:",
2011 [TOK_TYPE_NAME ] = ":typename:",
2012 [TOK_LIT_CHAR ] = ":char:",
2013 [TOK_LIT_INT ] = ":integer:",
2014 [TOK_LIT_FLOAT ] = ":float:",
2016 [TOK_CONCATENATE ] = "##",
2018 [TOK_AUTO ] = "auto",
2019 [TOK_BREAK ] = "break",
2020 [TOK_CASE ] = "case",
2021 [TOK_CHAR ] = "char",
2022 [TOK_CONST ] = "const",
2023 [TOK_CONTINUE ] = "continue",
2024 [TOK_DEFAULT ] = "default",
2026 [TOK_DOUBLE ] = "double",
2027 [TOK_ELSE ] = "else",
2028 [TOK_ENUM ] = "enum",
2029 [TOK_EXTERN ] = "extern",
2030 [TOK_FLOAT ] = "float",
2032 [TOK_GOTO ] = "goto",
2034 [TOK_INLINE ] = "inline",
2036 [TOK_LONG ] = "long",
2037 [TOK_REGISTER ] = "register",
2038 [TOK_RESTRICT ] = "restrict",
2039 [TOK_RETURN ] = "return",
2040 [TOK_SHORT ] = "short",
2041 [TOK_SIGNED ] = "signed",
2042 [TOK_SIZEOF ] = "sizeof",
2043 [TOK_STATIC ] = "static",
2044 [TOK_STRUCT ] = "struct",
2045 [TOK_SWITCH ] = "switch",
2046 [TOK_TYPEDEF ] = "typedef",
2047 [TOK_UNION ] = "union",
2048 [TOK_UNSIGNED ] = "unsigned",
2049 [TOK_VOID ] = "void",
2050 [TOK_VOLATILE ] = "volatile",
2051 [TOK_WHILE ] = "while",
2053 [TOK_ATTRIBUTE ] = "__attribute__",
2054 [TOK_ALIGNOF ] = "__alignof__",
2056 [TOK_DEFINE ] = "define",
2057 [TOK_UNDEF ] = "undef",
2058 [TOK_INCLUDE ] = "include",
2059 [TOK_LINE ] = "line",
2060 [TOK_ERROR ] = "error",
2061 [TOK_WARNING ] = "warning",
2062 [TOK_PRAGMA ] = "pragma",
2063 [TOK_IFDEF ] = "ifdef",
2064 [TOK_IFNDEF ] = "ifndef",
2065 [TOK_ELIF ] = "elif",
2066 [TOK_ENDIF ] = "endif",
2071 static unsigned int hash(const char *str, int str_len)
2075 end = str + str_len;
2077 for(; str < end; str++) {
2078 hash = (hash *263) + *str;
2080 hash = hash & (HASH_TABLE_SIZE -1);
2084 static struct hash_entry *lookup(
2085 struct compile_state *state, const char *name, int name_len)
2087 struct hash_entry *entry;
2089 index = hash(name, name_len);
2090 entry = state->hash_table[index];
2092 ((entry->name_len != name_len) ||
2093 (memcmp(entry->name, name, name_len) != 0))) {
2094 entry = entry->next;
2098 /* Get a private copy of the name */
2099 new_name = xmalloc(name_len + 1, "hash_name");
2100 memcpy(new_name, name, name_len);
2101 new_name[name_len] = '\0';
2103 /* Create a new hash entry */
2104 entry = xcmalloc(sizeof(*entry), "hash_entry");
2105 entry->next = state->hash_table[index];
2106 entry->name = new_name;
2107 entry->name_len = name_len;
2109 /* Place the new entry in the hash table */
2110 state->hash_table[index] = entry;
2115 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2117 struct hash_entry *entry;
2119 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2120 (entry->tok == TOK_ENUM_CONST) ||
2121 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2122 (entry->tok <= TOK_LAST_KEYWORD)))) {
2123 tk->tok = entry->tok;
2127 static void ident_to_macro(struct compile_state *state, struct token *tk)
2129 struct hash_entry *entry;
2132 (entry->tok >= TOK_FIRST_MACRO) &&
2133 (entry->tok <= TOK_LAST_MACRO)) {
2134 tk->tok = entry->tok;
2138 static void hash_keyword(
2139 struct compile_state *state, const char *keyword, int tok)
2141 struct hash_entry *entry;
2142 entry = lookup(state, keyword, strlen(keyword));
2143 if (entry && entry->tok != TOK_UNKNOWN) {
2144 die("keyword %s already hashed", keyword);
2150 struct compile_state *state, struct hash_entry *ident,
2151 struct symbol **chain, struct triple *def, struct type *type)
2154 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2155 error(state, 0, "%s already defined", ident->name);
2157 sym = xcmalloc(sizeof(*sym), "symbol");
2161 sym->scope_depth = state->scope_depth;
2166 static void label_symbol(struct compile_state *state,
2167 struct hash_entry *ident, struct triple *label)
2170 if (ident->sym_label) {
2171 error(state, 0, "label %s already defined", ident->name);
2173 sym = xcmalloc(sizeof(*sym), "label");
2176 sym->type = &void_type;
2177 sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2179 ident->sym_label = sym;
2182 static void start_scope(struct compile_state *state)
2184 state->scope_depth++;
2187 static void end_scope_syms(struct symbol **chain, int depth)
2189 struct symbol *sym, *next;
2191 while(sym && (sym->scope_depth == depth)) {
2199 static void end_scope(struct compile_state *state)
2203 /* Walk through the hash table and remove all symbols
2204 * in the current scope.
2206 depth = state->scope_depth;
2207 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2208 struct hash_entry *entry;
2209 entry = state->hash_table[i];
2211 end_scope_syms(&entry->sym_label, depth);
2212 end_scope_syms(&entry->sym_struct, depth);
2213 end_scope_syms(&entry->sym_ident, depth);
2214 entry = entry->next;
2217 state->scope_depth = depth - 1;
2220 static void register_keywords(struct compile_state *state)
2222 hash_keyword(state, "auto", TOK_AUTO);
2223 hash_keyword(state, "break", TOK_BREAK);
2224 hash_keyword(state, "case", TOK_CASE);
2225 hash_keyword(state, "char", TOK_CHAR);
2226 hash_keyword(state, "const", TOK_CONST);
2227 hash_keyword(state, "continue", TOK_CONTINUE);
2228 hash_keyword(state, "default", TOK_DEFAULT);
2229 hash_keyword(state, "do", TOK_DO);
2230 hash_keyword(state, "double", TOK_DOUBLE);
2231 hash_keyword(state, "else", TOK_ELSE);
2232 hash_keyword(state, "enum", TOK_ENUM);
2233 hash_keyword(state, "extern", TOK_EXTERN);
2234 hash_keyword(state, "float", TOK_FLOAT);
2235 hash_keyword(state, "for", TOK_FOR);
2236 hash_keyword(state, "goto", TOK_GOTO);
2237 hash_keyword(state, "if", TOK_IF);
2238 hash_keyword(state, "inline", TOK_INLINE);
2239 hash_keyword(state, "int", TOK_INT);
2240 hash_keyword(state, "long", TOK_LONG);
2241 hash_keyword(state, "register", TOK_REGISTER);
2242 hash_keyword(state, "restrict", TOK_RESTRICT);
2243 hash_keyword(state, "return", TOK_RETURN);
2244 hash_keyword(state, "short", TOK_SHORT);
2245 hash_keyword(state, "signed", TOK_SIGNED);
2246 hash_keyword(state, "sizeof", TOK_SIZEOF);
2247 hash_keyword(state, "static", TOK_STATIC);
2248 hash_keyword(state, "struct", TOK_STRUCT);
2249 hash_keyword(state, "switch", TOK_SWITCH);
2250 hash_keyword(state, "typedef", TOK_TYPEDEF);
2251 hash_keyword(state, "union", TOK_UNION);
2252 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2253 hash_keyword(state, "void", TOK_VOID);
2254 hash_keyword(state, "volatile", TOK_VOLATILE);
2255 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2256 hash_keyword(state, "while", TOK_WHILE);
2257 hash_keyword(state, "asm", TOK_ASM);
2258 hash_keyword(state, "__asm__", TOK_ASM);
2259 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2260 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2263 static void register_macro_keywords(struct compile_state *state)
2265 hash_keyword(state, "define", TOK_DEFINE);
2266 hash_keyword(state, "undef", TOK_UNDEF);
2267 hash_keyword(state, "include", TOK_INCLUDE);
2268 hash_keyword(state, "line", TOK_LINE);
2269 hash_keyword(state, "error", TOK_ERROR);
2270 hash_keyword(state, "warning", TOK_WARNING);
2271 hash_keyword(state, "pragma", TOK_PRAGMA);
2272 hash_keyword(state, "ifdef", TOK_IFDEF);
2273 hash_keyword(state, "ifndef", TOK_IFNDEF);
2274 hash_keyword(state, "elif", TOK_ELIF);
2275 hash_keyword(state, "endif", TOK_ENDIF);
2278 static int spacep(int c)
2294 static int digitp(int c)
2298 case '0': case '1': case '2': case '3': case '4':
2299 case '5': case '6': case '7': case '8': case '9':
2305 static int digval(int c)
2308 if ((c >= '0') && (c <= '9')) {
2314 static int hexdigitp(int c)
2318 case '0': case '1': case '2': case '3': case '4':
2319 case '5': case '6': case '7': case '8': case '9':
2320 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2321 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2327 static int hexdigval(int c)
2330 if ((c >= '0') && (c <= '9')) {
2333 else if ((c >= 'A') && (c <= 'F')) {
2334 val = 10 + (c - 'A');
2336 else if ((c >= 'a') && (c <= 'f')) {
2337 val = 10 + (c - 'a');
2342 static int octdigitp(int c)
2346 case '0': case '1': case '2': case '3':
2347 case '4': case '5': case '6': case '7':
2353 static int octdigval(int c)
2356 if ((c >= '0') && (c <= '7')) {
2362 static int letterp(int c)
2366 case 'a': case 'b': case 'c': case 'd': case 'e':
2367 case 'f': case 'g': case 'h': case 'i': case 'j':
2368 case 'k': case 'l': case 'm': case 'n': case 'o':
2369 case 'p': case 'q': case 'r': case 's': case 't':
2370 case 'u': case 'v': case 'w': case 'x': case 'y':
2372 case 'A': case 'B': case 'C': case 'D': case 'E':
2373 case 'F': case 'G': case 'H': case 'I': case 'J':
2374 case 'K': case 'L': case 'M': case 'N': case 'O':
2375 case 'P': case 'Q': case 'R': case 'S': case 'T':
2376 case 'U': case 'V': case 'W': case 'X': case 'Y':
2385 static int char_value(struct compile_state *state,
2386 const signed char **strp, const signed char *end)
2388 const signed char *str;
2392 if ((c == '\\') && (str < end)) {
2394 case 'n': c = '\n'; str++; break;
2395 case 't': c = '\t'; str++; break;
2396 case 'v': c = '\v'; str++; break;
2397 case 'b': c = '\b'; str++; break;
2398 case 'r': c = '\r'; str++; break;
2399 case 'f': c = '\f'; str++; break;
2400 case 'a': c = '\a'; str++; break;
2401 case '\\': c = '\\'; str++; break;
2402 case '?': c = '?'; str++; break;
2403 case '\'': c = '\''; str++; break;
2404 case '"': c = '"'; break;
2408 while((str < end) && hexdigitp(*str)) {
2410 c += hexdigval(*str);
2414 case '0': case '1': case '2': case '3':
2415 case '4': case '5': case '6': case '7':
2417 while((str < end) && octdigitp(*str)) {
2419 c += octdigval(*str);
2424 error(state, 0, "Invalid character constant");
2432 static char *after_digits(char *ptr, char *end)
2434 while((ptr < end) && digitp(*ptr)) {
2440 static char *after_octdigits(char *ptr, char *end)
2442 while((ptr < end) && octdigitp(*ptr)) {
2448 static char *after_hexdigits(char *ptr, char *end)
2450 while((ptr < end) && hexdigitp(*ptr)) {
2456 static void save_string(struct compile_state *state,
2457 struct token *tk, char *start, char *end, const char *id)
2461 /* Create a private copy of the string */
2462 str_len = end - start + 1;
2463 str = xmalloc(str_len + 1, id);
2464 memcpy(str, start, str_len);
2465 str[str_len] = '\0';
2467 /* Store the copy in the token */
2469 tk->str_len = str_len;
2471 static void next_token(struct compile_state *state, int index)
2473 struct file_state *file;
2481 tk = &state->token[index];
2484 token = tokp = file->pos;
2485 end = file->buf + file->size;
2492 if ((tokp + 1) < end) {
2496 if ((tokp + 2) < end) {
2500 if ((tokp + 3) < end) {
2508 else if (spacep(c)) {
2510 while ((tokp < end) && spacep(c)) {
2513 file->report_line++;
2514 file->line_start = tokp + 1;
2523 else if ((c == '/') && (c1 == '/')) {
2525 for(tokp += 2; tokp < end; tokp++) {
2529 file->report_line++;
2530 file->line_start = tokp +1;
2536 else if ((c == '/') && (c1 == '*')) {
2540 line_start = file->line_start;
2541 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2545 line_start = tokp +1;
2547 else if ((c == '*') && (tokp[1] == '/')) {
2553 if (tok == TOK_UNKNOWN) {
2554 error(state, 0, "unterminated comment");
2556 file->report_line += line - file->line;
2558 file->line_start = line_start;
2560 /* string constants */
2561 else if ((c == '"') ||
2562 ((c == 'L') && (c1 == '"'))) {
2567 line_start = file->line_start;
2573 for(tokp += 1; tokp < end; tokp++) {
2577 line_start = tokp + 1;
2579 else if ((c == '\\') && (tokp +1 < end)) {
2582 else if (c == '"') {
2583 tok = TOK_LIT_STRING;
2587 if (tok == TOK_UNKNOWN) {
2588 error(state, 0, "unterminated string constant");
2590 if (line != file->line) {
2591 warning(state, 0, "multiline string constant");
2593 file->report_line += line - file->line;
2595 file->line_start = line_start;
2597 /* Save the string value */
2598 save_string(state, tk, token, tokp, "literal string");
2600 /* character constants */
2601 else if ((c == '\'') ||
2602 ((c == 'L') && (c1 == '\''))) {
2607 line_start = file->line_start;
2613 for(tokp += 1; tokp < end; tokp++) {
2617 line_start = tokp + 1;
2619 else if ((c == '\\') && (tokp +1 < end)) {
2622 else if (c == '\'') {
2627 if (tok == TOK_UNKNOWN) {
2628 error(state, 0, "unterminated character constant");
2630 if (line != file->line) {
2631 warning(state, 0, "multiline character constant");
2633 file->report_line += line - file->line;
2635 file->line_start = line_start;
2637 /* Save the character value */
2638 save_string(state, tk, token, tokp, "literal character");
2640 /* integer and floating constants
2646 * Floating constants
2647 * {digits}.{digits}[Ee][+-]?{digits}
2649 * {digits}[Ee][+-]?{digits}
2650 * .{digits}[Ee][+-]?{digits}
2654 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2659 next = after_digits(tokp, end);
2664 if (next[0] == '.') {
2665 new = after_digits(next, end);
2666 is_float = (new != next);
2669 if ((next[0] == 'e') || (next[0] == 'E')) {
2670 if (((next + 1) < end) &&
2671 ((next[1] == '+') || (next[1] == '-'))) {
2674 new = after_digits(next, end);
2675 is_float = (new != next);
2679 tok = TOK_LIT_FLOAT;
2680 if ((next < end) && (
2689 if (!is_float && digitp(c)) {
2691 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2692 next = after_hexdigits(tokp + 2, end);
2694 else if (c == '0') {
2695 next = after_octdigits(tokp, end);
2698 next = after_digits(tokp, end);
2700 /* crazy integer suffixes */
2702 ((next[0] == 'u') || (next[0] == 'U'))) {
2705 ((next[0] == 'l') || (next[0] == 'L'))) {
2709 else if ((next < end) &&
2710 ((next[0] == 'l') || (next[0] == 'L'))) {
2713 ((next[0] == 'u') || (next[0] == 'U'))) {
2720 /* Save the integer/floating point value */
2721 save_string(state, tk, token, tokp, "literal number");
2724 else if (letterp(c)) {
2726 for(tokp += 1; tokp < end; tokp++) {
2728 if (!letterp(c) && !digitp(c)) {
2733 tk->ident = lookup(state, token, tokp +1 - token);
2735 /* C99 alternate macro characters */
2736 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2738 tok = TOK_CONCATENATE;
2740 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2741 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2742 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2743 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2744 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2745 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2746 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2747 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2748 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2749 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2750 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2751 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2752 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2753 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2754 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2755 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2756 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2757 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2758 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2759 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2760 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2761 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2762 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2763 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2764 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2765 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2766 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2767 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2768 else if (c == ';') { tok = TOK_SEMI; }
2769 else if (c == '{') { tok = TOK_LBRACE; }
2770 else if (c == '}') { tok = TOK_RBRACE; }
2771 else if (c == ',') { tok = TOK_COMMA; }
2772 else if (c == '=') { tok = TOK_EQ; }
2773 else if (c == ':') { tok = TOK_COLON; }
2774 else if (c == '[') { tok = TOK_LBRACKET; }
2775 else if (c == ']') { tok = TOK_RBRACKET; }
2776 else if (c == '(') { tok = TOK_LPAREN; }
2777 else if (c == ')') { tok = TOK_RPAREN; }
2778 else if (c == '*') { tok = TOK_STAR; }
2779 else if (c == '>') { tok = TOK_MORE; }
2780 else if (c == '<') { tok = TOK_LESS; }
2781 else if (c == '?') { tok = TOK_QUEST; }
2782 else if (c == '|') { tok = TOK_OR; }
2783 else if (c == '&') { tok = TOK_AND; }
2784 else if (c == '^') { tok = TOK_XOR; }
2785 else if (c == '+') { tok = TOK_PLUS; }
2786 else if (c == '-') { tok = TOK_MINUS; }
2787 else if (c == '/') { tok = TOK_DIV; }
2788 else if (c == '%') { tok = TOK_MOD; }
2789 else if (c == '!') { tok = TOK_BANG; }
2790 else if (c == '.') { tok = TOK_DOT; }
2791 else if (c == '~') { tok = TOK_TILDE; }
2792 else if (c == '#') { tok = TOK_MACRO; }
2793 if (tok == TOK_MACRO) {
2794 /* Only match preprocessor directives at the start of a line */
2796 for(ptr = file->line_start; spacep(*ptr); ptr++)
2802 if (tok == TOK_UNKNOWN) {
2803 error(state, 0, "unknown token");
2806 file->pos = tokp + 1;
2808 if (tok == TOK_IDENT) {
2809 ident_to_keyword(state, tk);
2811 /* Don't return space tokens. */
2812 if (tok == TOK_SPACE) {
2817 static void compile_macro(struct compile_state *state, struct token *tk)
2819 struct file_state *file;
2820 struct hash_entry *ident;
2822 file = xmalloc(sizeof(*file), "file_state");
2823 file->basename = xstrdup(tk->ident->name);
2824 file->dirname = xstrdup("");
2825 file->size = ident->sym_define->buf_len;
2826 file->buf = xmalloc(file->size +2, file->basename);
2827 memcpy(file->buf, ident->sym_define->buf, file->size);
2828 file->buf[file->size] = '\n';
2829 file->buf[file->size + 1] = '\0';
2830 file->pos = file->buf;
2831 file->line_start = file->pos;
2833 file->report_line = 1;
2834 file->report_name = file->basename;
2835 file->report_dir = file->dirname;
2836 file->prev = state->file;
2841 static int mpeek(struct compile_state *state, int index)
2845 tk = &state->token[index + 1];
2846 if (tk->tok == -1) {
2847 next_token(state, index + 1);
2851 if ((tk->tok == TOK_EOF) &&
2852 (state->file != state->macro_file) &&
2853 (state->file->prev)) {
2854 struct file_state *file = state->file;
2855 state->file = file->prev;
2856 /* file->basename is used keep it */
2857 if (file->report_dir != file->dirname) {
2858 xfree(file->report_dir);
2860 xfree(file->dirname);
2863 next_token(state, index + 1);
2866 else if (tk->ident && tk->ident->sym_define) {
2867 compile_macro(state, tk);
2868 next_token(state, index + 1);
2872 /* Don't show the token on the next line */
2873 if (state->macro_line < state->macro_file->line) {
2876 return state->token[index +1].tok;
2879 static void meat(struct compile_state *state, int index, int tok)
2883 next_tok = mpeek(state, index);
2884 if (next_tok != tok) {
2885 const char *name1, *name2;
2886 name1 = tokens[next_tok];
2888 if (next_tok == TOK_IDENT) {
2889 name2 = state->token[index + 1].ident->name;
2891 error(state, 0, "found %s %s expected %s",
2892 name1, name2, tokens[tok]);
2894 /* Free the old token value */
2895 if (state->token[index].str_len) {
2896 memset((void *)(state->token[index].val.str), -1,
2897 state->token[index].str_len);
2898 xfree(state->token[index].val.str);
2900 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2901 state->token[i] = state->token[i + 1];
2903 memset(&state->token[i], 0, sizeof(state->token[i]));
2904 state->token[i].tok = -1;
2907 static long_t mcexpr(struct compile_state *state, int index);
2909 static long_t mprimary_expr(struct compile_state *state, int index)
2913 tok = mpeek(state, index);
2914 while(state->token[index + 1].ident &&
2915 state->token[index + 1].ident->sym_define) {
2916 meat(state, index, tok);
2917 compile_macro(state, &state->token[index]);
2918 tok = mpeek(state, index);
2922 meat(state, index, TOK_LPAREN);
2923 val = mcexpr(state, index);
2924 meat(state, index, TOK_RPAREN);
2929 meat(state, index, TOK_LIT_INT);
2931 val = strtol(state->token[index].val.str, &end, 0);
2932 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2933 (errno == ERANGE)) {
2934 error(state, 0, "Integer constant to large");
2939 meat(state, index, TOK_LIT_INT);
2944 static long_t munary_expr(struct compile_state *state, int index)
2947 switch(mpeek(state, index)) {
2949 meat(state, index, TOK_PLUS);
2950 val = munary_expr(state, index);
2954 meat(state, index, TOK_MINUS);
2955 val = munary_expr(state, index);
2959 meat(state, index, TOK_BANG);
2960 val = munary_expr(state, index);
2964 meat(state, index, TOK_BANG);
2965 val = munary_expr(state, index);
2969 val = mprimary_expr(state, index);
2975 static long_t mmul_expr(struct compile_state *state, int index)
2979 val = munary_expr(state, index);
2983 switch(mpeek(state, index)) {
2985 meat(state, index, TOK_STAR);
2986 right = munary_expr(state, index);
2990 meat(state, index, TOK_DIV);
2991 right = munary_expr(state, index);
2995 meat(state, index, TOK_MOD);
2996 right = munary_expr(state, index);
3008 static long_t madd_expr(struct compile_state *state, int index)
3012 val = mmul_expr(state, index);
3016 switch(mpeek(state, index)) {
3018 meat(state, index, TOK_PLUS);
3019 right = mmul_expr(state, index);
3023 meat(state, index, TOK_MINUS);
3024 right = mmul_expr(state, index);
3036 static long_t mshift_expr(struct compile_state *state, int index)
3040 val = madd_expr(state, index);
3044 switch(mpeek(state, index)) {
3046 meat(state, index, TOK_SL);
3047 right = madd_expr(state, index);
3051 meat(state, index, TOK_SR);
3052 right = madd_expr(state, index);
3064 static long_t mrel_expr(struct compile_state *state, int index)
3068 val = mshift_expr(state, index);
3072 switch(mpeek(state, index)) {
3074 meat(state, index, TOK_LESS);
3075 right = mshift_expr(state, index);
3079 meat(state, index, TOK_MORE);
3080 right = mshift_expr(state, index);
3084 meat(state, index, TOK_LESSEQ);
3085 right = mshift_expr(state, index);
3089 meat(state, index, TOK_MOREEQ);
3090 right = mshift_expr(state, index);
3101 static long_t meq_expr(struct compile_state *state, int index)
3105 val = mrel_expr(state, index);
3109 switch(mpeek(state, index)) {
3111 meat(state, index, TOK_EQEQ);
3112 right = mrel_expr(state, index);
3116 meat(state, index, TOK_NOTEQ);
3117 right = mrel_expr(state, index);
3128 static long_t mand_expr(struct compile_state *state, int index)
3131 val = meq_expr(state, index);
3132 if (mpeek(state, index) == TOK_AND) {
3134 meat(state, index, TOK_AND);
3135 right = meq_expr(state, index);
3141 static long_t mxor_expr(struct compile_state *state, int index)
3144 val = mand_expr(state, index);
3145 if (mpeek(state, index) == TOK_XOR) {
3147 meat(state, index, TOK_XOR);
3148 right = mand_expr(state, index);
3154 static long_t mor_expr(struct compile_state *state, int index)
3157 val = mxor_expr(state, index);
3158 if (mpeek(state, index) == TOK_OR) {
3160 meat(state, index, TOK_OR);
3161 right = mxor_expr(state, index);
3167 static long_t mland_expr(struct compile_state *state, int index)
3170 val = mor_expr(state, index);
3171 if (mpeek(state, index) == TOK_LOGAND) {
3173 meat(state, index, TOK_LOGAND);
3174 right = mor_expr(state, index);
3179 static long_t mlor_expr(struct compile_state *state, int index)
3182 val = mland_expr(state, index);
3183 if (mpeek(state, index) == TOK_LOGOR) {
3185 meat(state, index, TOK_LOGOR);
3186 right = mland_expr(state, index);
3192 static long_t mcexpr(struct compile_state *state, int index)
3194 return mlor_expr(state, index);
3196 static void preprocess(struct compile_state *state, int index)
3198 /* Doing much more with the preprocessor would require
3199 * a parser and a major restructuring.
3200 * Postpone that for later.
3202 struct file_state *file;
3208 tk = &state->token[index];
3209 state->macro_line = line = file->line;
3210 state->macro_file = file;
3212 next_token(state, index);
3213 ident_to_macro(state, tk);
3214 if (tk->tok == TOK_IDENT) {
3215 error(state, 0, "undefined preprocessing directive `%s'",
3222 override_line = strtoul(tk->val.str, 0, 10);
3223 next_token(state, index);
3224 /* I have a cpp line marker parse it */
3225 if (tk->tok == TOK_LIT_STRING) {
3226 const char *token, *base;
3228 int name_len, dir_len;
3229 name = xmalloc(tk->str_len, "report_name");
3230 token = tk->val.str + 1;
3231 base = strrchr(token, '/');
3232 name_len = tk->str_len -2;
3234 dir_len = base - token;
3236 name_len -= base - token;
3241 memcpy(name, base, name_len);
3242 name[name_len] = '\0';
3243 dir = xmalloc(dir_len + 1, "report_dir");
3244 memcpy(dir, token, dir_len);
3245 dir[dir_len] = '\0';
3246 file->report_line = override_line - 1;
3247 file->report_name = name;
3248 file->report_dir = dir;
3253 meat(state, index, TOK_LINE);
3254 meat(state, index, TOK_LIT_INT);
3255 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3256 if (mpeek(state, index) == TOK_LIT_STRING) {
3257 const char *token, *base;
3259 int name_len, dir_len;
3260 meat(state, index, TOK_LIT_STRING);
3261 name = xmalloc(tk->str_len, "report_name");
3262 token = tk->val.str + 1;
3263 name_len = tk->str_len - 2;
3265 dir_len = base - token;
3267 name_len -= base - token;
3272 memcpy(name, base, name_len);
3273 name[name_len] = '\0';
3274 dir = xmalloc(dir_len + 1, "report_dir");
3275 memcpy(dir, token, dir_len);
3276 dir[dir_len] = '\0';
3277 file->report_name = name;
3278 file->report_dir = dir;
3283 if (state->if_value < 0) {
3286 warning(state, 0, "Ignoring preprocessor directive: %s",
3290 error(state, 0, "#elif not supported");
3291 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3292 if (state->if_depth == 0) {
3293 error(state, 0, "#elif without #if");
3295 /* If the #if was taken the #elif just disables the following code */
3296 if (state->if_value >= 0) {
3297 state->if_value = - state->if_value;
3299 /* If the previous #if was not taken see if the #elif enables the
3302 else if ((state->if_value < 0) &&
3303 (state->if_depth == - state->if_value))
3305 if (mcexpr(state, index) != 0) {
3306 state->if_value = state->if_depth;
3309 state->if_value = - state->if_depth;
3315 if (state->if_value < 0) {
3318 if (mcexpr(state, index) != 0) {
3319 state->if_value = state->if_depth;
3322 state->if_value = - state->if_depth;
3327 if (state->if_value < 0) {
3330 next_token(state, index);
3331 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3332 error(state, 0, "Invalid macro name");
3334 if (tk->ident->sym_define == 0) {
3335 state->if_value = state->if_depth;
3338 state->if_value = - state->if_depth;
3343 if (state->if_value < 0) {
3346 next_token(state, index);
3347 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3348 error(state, 0, "Invalid macro name");
3350 if (tk->ident->sym_define != 0) {
3351 state->if_value = state->if_depth;
3354 state->if_value = - state->if_depth;
3358 if (state->if_depth == 0) {
3359 error(state, 0, "#else without #if");
3361 if ((state->if_value >= 0) ||
3362 ((state->if_value < 0) &&
3363 (state->if_depth == -state->if_value)))
3365 state->if_value = - state->if_value;
3369 if (state->if_depth == 0) {
3370 error(state, 0, "#endif without #if");
3372 if ((state->if_value >= 0) ||
3373 ((state->if_value < 0) &&
3374 (state->if_depth == -state->if_value)))
3376 state->if_value = state->if_depth - 1;
3382 struct hash_entry *ident;
3383 struct macro *macro;
3386 if (state->if_value < 0) /* quit early when #if'd out */
3389 meat(state, index, TOK_IDENT);
3393 if (*file->pos == '(') {
3394 #warning "FIXME macros with arguments not supported"
3395 error(state, 0, "Macros with arguments not supported");
3398 /* Find the end of the line to get an estimate of
3399 * the macro's length.
3401 for(ptr = file->pos; *ptr != '\n'; ptr++)
3404 if (ident->sym_define != 0) {
3405 error(state, 0, "macro %s already defined\n", ident->name);
3407 macro = xmalloc(sizeof(*macro), "macro");
3408 macro->ident = ident;
3409 macro->buf_len = ptr - file->pos +1;
3410 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3412 memcpy(macro->buf, file->pos, macro->buf_len);
3413 macro->buf[macro->buf_len] = '\n';
3414 macro->buf[macro->buf_len +1] = '\0';
3416 ident->sym_define = macro;
3423 /* Find the end of the line */
3424 for(end = file->pos; *end != '\n'; end++)
3426 len = (end - file->pos);
3427 if (state->if_value >= 0) {
3428 error(state, 0, "%*.*s", len, len, file->pos);
3437 /* Find the end of the line */
3438 for(end = file->pos; *end != '\n'; end++)
3440 len = (end - file->pos);
3441 if (state->if_value >= 0) {
3442 warning(state, 0, "%*.*s", len, len, file->pos);
3454 next_token(state, index);
3455 if (tk->tok == TOK_LIT_STRING) {
3458 name = xmalloc(tk->str_len, "include");
3459 token = tk->val.str +1;
3460 name_len = tk->str_len -2;
3461 if (*token == '"') {
3465 memcpy(name, token, name_len);
3466 name[name_len] = '\0';
3469 else if (tk->tok == TOK_LESS) {
3472 for(end = start; *end != '\n'; end++) {
3478 error(state, 0, "Unterminated included directive");
3480 name = xmalloc(end - start + 1, "include");
3481 memcpy(name, start, end - start);
3482 name[end - start] = '\0';
3487 error(state, 0, "Invalid include directive");
3489 /* Error if there are any characters after the include */
3490 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3497 error(state, 0, "garbage after include directive");
3500 if (state->if_value >= 0) {
3501 compile_file(state, name, local);
3504 next_token(state, index);
3508 /* Ignore # without a following ident */
3509 if (tk->tok == TOK_IDENT) {
3510 error(state, 0, "Invalid preprocessor directive: %s",
3515 /* Consume the rest of the macro line */
3517 tok = mpeek(state, index);
3518 meat(state, index, tok);
3519 } while(tok != TOK_EOF);
3523 static void token(struct compile_state *state, int index)
3525 struct file_state *file;
3529 tk = &state->token[index];
3530 next_token(state, index);
3534 if (tk->tok == TOK_EOF && file->prev) {
3535 state->file = file->prev;
3536 /* file->basename is used keep it */
3537 xfree(file->dirname);
3540 next_token(state, index);
3543 else if (tk->tok == TOK_MACRO) {
3544 preprocess(state, index);
3547 else if (tk->ident && tk->ident->sym_define) {
3548 compile_macro(state, tk);
3549 next_token(state, index);
3552 else if (state->if_value < 0) {
3553 next_token(state, index);
3559 static int peek(struct compile_state *state)
3561 if (state->token[1].tok == -1) {
3564 return state->token[1].tok;
3567 static int peek2(struct compile_state *state)
3569 if (state->token[1].tok == -1) {
3572 if (state->token[2].tok == -1) {
3575 return state->token[2].tok;
3578 static void eat(struct compile_state *state, int tok)
3582 next_tok = peek(state);
3583 if (next_tok != tok) {
3584 const char *name1, *name2;
3585 name1 = tokens[next_tok];
3587 if (next_tok == TOK_IDENT) {
3588 name2 = state->token[1].ident->name;
3590 error(state, 0, "\tfound %s %s expected %s",
3591 name1, name2 ,tokens[tok]);
3593 /* Free the old token value */
3594 if (state->token[0].str_len) {
3595 xfree((void *)(state->token[0].val.str));
3597 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3598 state->token[i] = state->token[i + 1];
3600 memset(&state->token[i], 0, sizeof(state->token[i]));
3601 state->token[i].tok = -1;
3604 #warning "FIXME do not hardcode the include paths"
3605 static char *include_paths[] = {
3606 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3607 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3608 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3612 static void compile_file(struct compile_state *state, const char *filename, int local)
3615 const char *subdir, *base;
3617 struct file_state *file;
3619 file = xmalloc(sizeof(*file), "file_state");
3621 base = strrchr(filename, '/');
3624 subdir_len = base - filename;
3631 basename = xmalloc(strlen(base) +1, "basename");
3632 strcpy(basename, base);
3633 file->basename = basename;
3635 if (getcwd(cwd, sizeof(cwd)) == 0) {
3636 die("cwd buffer to small");
3639 if (subdir[0] == '/') {
3640 file->dirname = xmalloc(subdir_len + 1, "dirname");
3641 memcpy(file->dirname, subdir, subdir_len);
3642 file->dirname[subdir_len] = '\0';
3648 /* Find the appropriate directory... */
3650 if (!state->file && exists(cwd, filename)) {
3653 if (local && state->file && exists(state->file->dirname, filename)) {
3654 dir = state->file->dirname;
3656 for(path = include_paths; !dir && *path; path++) {
3657 if (exists(*path, filename)) {
3662 error(state, 0, "Cannot find `%s'\n", filename);
3664 dirlen = strlen(dir);
3665 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3666 memcpy(file->dirname, dir, dirlen);
3667 file->dirname[dirlen] = '/';
3668 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3669 file->dirname[dirlen + 1 + subdir_len] = '\0';
3671 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3674 file->pos = file->buf;
3675 file->line_start = file->pos;
3678 file->report_line = 1;
3679 file->report_name = file->basename;
3680 file->report_dir = file->dirname;
3682 file->prev = state->file;
3685 process_trigraphs(state);
3686 splice_lines(state);
3689 /* Type helper functions */
3691 static struct type *new_type(
3692 unsigned int type, struct type *left, struct type *right)
3694 struct type *result;
3695 result = xmalloc(sizeof(*result), "type");
3696 result->type = type;
3697 result->left = left;
3698 result->right = right;
3699 result->field_ident = 0;
3700 result->type_ident = 0;
3704 static struct type *clone_type(unsigned int specifiers, struct type *old)
3706 struct type *result;
3707 result = xmalloc(sizeof(*result), "type");
3708 memcpy(result, old, sizeof(*result));
3709 result->type &= TYPE_MASK;
3710 result->type |= specifiers;
3714 #define SIZEOF_SHORT 2
3715 #define SIZEOF_INT 4
3716 #define SIZEOF_LONG (sizeof(long_t))
3718 #define ALIGNOF_SHORT 2
3719 #define ALIGNOF_INT 4
3720 #define ALIGNOF_LONG (sizeof(long_t))
3722 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3723 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3724 static inline ulong_t mask_uint(ulong_t x)
3726 if (SIZEOF_INT < SIZEOF_LONG) {
3727 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3732 #define MASK_UINT(X) (mask_uint(X))
3733 #define MASK_ULONG(X) (X)
3735 static struct type void_type = { .type = TYPE_VOID };
3736 static struct type char_type = { .type = TYPE_CHAR };
3737 static struct type uchar_type = { .type = TYPE_UCHAR };
3738 static struct type short_type = { .type = TYPE_SHORT };
3739 static struct type ushort_type = { .type = TYPE_USHORT };
3740 static struct type int_type = { .type = TYPE_INT };
3741 static struct type uint_type = { .type = TYPE_UINT };
3742 static struct type long_type = { .type = TYPE_LONG };
3743 static struct type ulong_type = { .type = TYPE_ULONG };
3745 static struct triple *variable(struct compile_state *state, struct type *type)
3747 struct triple *result;
3748 if ((type->type & STOR_MASK) != STOR_PERM) {
3749 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3750 result = triple(state, OP_ADECL, type, 0, 0);
3753 struct triple **vector;
3755 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3756 vector = &result->param[0];
3760 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3761 vector[index] = variable(state, field->left);
3762 field = field->right;
3765 vector[index] = variable(state, field);
3769 result = triple(state, OP_SDECL, type, 0, 0);
3774 static void stor_of(FILE *fp, struct type *type)
3776 switch(type->type & STOR_MASK) {
3778 fprintf(fp, "auto ");
3781 fprintf(fp, "static ");
3784 fprintf(fp, "extern ");
3787 fprintf(fp, "register ");
3790 fprintf(fp, "typedef ");
3793 fprintf(fp, "inline ");
3797 static void qual_of(FILE *fp, struct type *type)
3799 if (type->type & QUAL_CONST) {
3800 fprintf(fp, " const");
3802 if (type->type & QUAL_VOLATILE) {
3803 fprintf(fp, " volatile");
3805 if (type->type & QUAL_RESTRICT) {
3806 fprintf(fp, " restrict");
3810 static void name_of(FILE *fp, struct type *type)
3813 switch(type->type & TYPE_MASK) {
3815 fprintf(fp, "void");
3819 fprintf(fp, "signed char");
3823 fprintf(fp, "unsigned char");
3827 fprintf(fp, "signed short");
3831 fprintf(fp, "unsigned short");
3835 fprintf(fp, "signed int");
3839 fprintf(fp, "unsigned int");
3843 fprintf(fp, "signed long");
3847 fprintf(fp, "unsigned long");
3851 name_of(fp, type->left);
3857 name_of(fp, type->left);
3859 name_of(fp, type->right);
3862 fprintf(fp, "enum %s", type->type_ident->name);
3866 fprintf(fp, "struct %s", type->type_ident->name);
3871 name_of(fp, type->left);
3872 fprintf(fp, " (*)(");
3873 name_of(fp, type->right);
3878 name_of(fp, type->left);
3879 fprintf(fp, " [%ld]", type->elements);
3882 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3887 static size_t align_of(struct compile_state *state, struct type *type)
3891 switch(type->type & TYPE_MASK) {
3901 align = ALIGNOF_SHORT;
3906 align = ALIGNOF_INT;
3911 align = ALIGNOF_LONG;
3916 size_t left_align, right_align;
3917 left_align = align_of(state, type->left);
3918 right_align = align_of(state, type->right);
3919 align = (left_align >= right_align) ? left_align : right_align;
3923 align = align_of(state, type->left);
3926 align = align_of(state, type->left);
3929 error(state, 0, "alignof not yet defined for type\n");
3935 static size_t size_of(struct compile_state *state, struct type *type)
3939 switch(type->type & TYPE_MASK) {
3949 size = SIZEOF_SHORT;
3964 size = size_of(state, type->left);
3965 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3967 align = align_of(state, type->left);
3968 pad = align - (size % align);
3969 size = size + pad + size_of(state, type->left);
3971 align = align_of(state, type->right);
3972 pad = align - (size % align);
3973 size = size + pad + sizeof(type->right);
3978 size_t size_left, size_right;
3979 size_left = size_of(state, type->left);
3980 size_right = size_of(state, type->right);
3981 size = (size_left >= size_right)? size_left : size_right;
3985 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3986 internal_error(state, 0, "Invalid array type");
3988 size = size_of(state, type->left) * type->elements;
3992 size = size_of(state, type->left);
3995 error(state, 0, "sizeof not yet defined for type\n");
4001 static size_t field_offset(struct compile_state *state,
4002 struct type *type, struct hash_entry *field)
4004 size_t size, align, pad;
4005 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4006 internal_error(state, 0, "field_offset only works on structures");
4010 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4011 if (type->left->field_ident == field) {
4015 size += size_of(state, type->left);
4017 align = align_of(state, type);
4018 pad = align - (size % align);
4021 if (type->field_ident != field) {
4022 internal_error(state, 0, "field_offset: member %s not present",
4028 static struct type *field_type(struct compile_state *state,
4029 struct type *type, struct hash_entry *field)
4031 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4032 internal_error(state, 0, "field_type only works on structures");
4035 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4036 if (type->left->field_ident == field) {
4042 if (type->field_ident != field) {
4043 internal_error(state, 0, "field_type: member %s not present",
4049 static struct triple *struct_field(struct compile_state *state,
4050 struct triple *decl, struct hash_entry *field)
4052 struct triple **vector;
4056 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4059 if (decl->op != OP_VAL_VEC) {
4060 internal_error(state, 0, "Invalid struct variable");
4063 internal_error(state, 0, "Missing structure field");
4066 vector = &RHS(decl, 0);
4068 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4069 if (type->left->field_ident == field) {
4076 if (type->field_ident != field) {
4077 internal_error(state, 0, "field %s not found?", field->name);
4079 return vector[index];
4082 static void arrays_complete(struct compile_state *state, struct type *type)
4084 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4085 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4086 error(state, 0, "array size not specified");
4088 arrays_complete(state, type->left);
4092 static unsigned int do_integral_promotion(unsigned int type)
4095 if (TYPE_INTEGER(type) &&
4096 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4102 static unsigned int do_arithmetic_conversion(
4103 unsigned int left, unsigned int right)
4107 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4108 return TYPE_LDOUBLE;
4110 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4113 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4116 left = do_integral_promotion(left);
4117 right = do_integral_promotion(right);
4118 /* If both operands have the same size done */
4119 if (left == right) {
4122 /* If both operands have the same signedness pick the larger */
4123 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4124 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4126 /* If the signed type can hold everything use it */
4127 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4130 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4133 /* Convert to the unsigned type with the same rank as the signed type */
4134 else if (TYPE_SIGNED(left)) {
4135 return TYPE_MKUNSIGNED(left);
4138 return TYPE_MKUNSIGNED(right);
4142 /* see if two types are the same except for qualifiers */
4143 static int equiv_types(struct type *left, struct type *right)
4146 /* Error if the basic types do not match */
4147 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4150 type = left->type & TYPE_MASK;
4151 /* if the basic types match and it is an arithmetic type we are done */
4152 if (TYPE_ARITHMETIC(type)) {
4155 /* If it is a pointer type recurse and keep testing */
4156 if (type == TYPE_POINTER) {
4157 return equiv_types(left->left, right->left);
4159 else if (type == TYPE_ARRAY) {
4160 return (left->elements == right->elements) &&
4161 equiv_types(left->left, right->left);
4163 /* test for struct/union equality */
4164 else if (type == TYPE_STRUCT) {
4165 return left->type_ident == right->type_ident;
4167 /* Test for equivalent functions */
4168 else if (type == TYPE_FUNCTION) {
4169 return equiv_types(left->left, right->left) &&
4170 equiv_types(left->right, right->right);
4172 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4173 else if (type == TYPE_PRODUCT) {
4174 return equiv_types(left->left, right->left) &&
4175 equiv_types(left->right, right->right);
4177 /* We should see TYPE_OVERLAP */
4183 static int equiv_ptrs(struct type *left, struct type *right)
4185 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4186 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4189 return equiv_types(left->left, right->left);
4192 static struct type *compatible_types(struct type *left, struct type *right)
4194 struct type *result;
4195 unsigned int type, qual_type;
4196 /* Error if the basic types do not match */
4197 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4200 type = left->type & TYPE_MASK;
4201 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4203 /* if the basic types match and it is an arithmetic type we are done */
4204 if (TYPE_ARITHMETIC(type)) {
4205 result = new_type(qual_type, 0, 0);
4207 /* If it is a pointer type recurse and keep testing */
4208 else if (type == TYPE_POINTER) {
4209 result = compatible_types(left->left, right->left);
4211 result = new_type(qual_type, result, 0);
4214 /* test for struct/union equality */
4215 else if (type == TYPE_STRUCT) {
4216 if (left->type_ident == right->type_ident) {
4220 /* Test for equivalent functions */
4221 else if (type == TYPE_FUNCTION) {
4222 struct type *lf, *rf;
4223 lf = compatible_types(left->left, right->left);
4224 rf = compatible_types(left->right, right->right);
4226 result = new_type(qual_type, lf, rf);
4229 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4230 else if (type == TYPE_PRODUCT) {
4231 struct type *lf, *rf;
4232 lf = compatible_types(left->left, right->left);
4233 rf = compatible_types(left->right, right->right);
4235 result = new_type(qual_type, lf, rf);
4239 /* Nothing else is compatible */
4244 static struct type *compatible_ptrs(struct type *left, struct type *right)
4246 struct type *result;
4247 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4248 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4251 result = compatible_types(left->left, right->left);
4253 unsigned int qual_type;
4254 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4255 result = new_type(qual_type, result, 0);
4260 static struct triple *integral_promotion(
4261 struct compile_state *state, struct triple *def)
4265 /* As all operations are carried out in registers
4266 * the values are converted on load I just convert
4267 * logical type of the operand.
4269 if (TYPE_INTEGER(type->type)) {
4270 unsigned int int_type;
4271 int_type = type->type & ~TYPE_MASK;
4272 int_type |= do_integral_promotion(type->type);
4273 if (int_type != type->type) {
4274 def->type = new_type(int_type, 0, 0);
4281 static void arithmetic(struct compile_state *state, struct triple *def)
4283 if (!TYPE_ARITHMETIC(def->type->type)) {
4284 error(state, 0, "arithmetic type expexted");
4288 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4290 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4291 error(state, def, "pointer or arithmetic type expected");
4295 static int is_integral(struct triple *ins)
4297 return TYPE_INTEGER(ins->type->type);
4300 static void integral(struct compile_state *state, struct triple *def)
4302 if (!is_integral(def)) {
4303 error(state, 0, "integral type expected");
4308 static void bool(struct compile_state *state, struct triple *def)
4310 if (!TYPE_ARITHMETIC(def->type->type) &&
4311 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4312 error(state, 0, "arithmetic or pointer type expected");
4316 static int is_signed(struct type *type)
4318 return !!TYPE_SIGNED(type->type);
4321 /* Is this value located in a register otherwise it must be in memory */
4322 static int is_in_reg(struct compile_state *state, struct triple *def)
4325 if (def->op == OP_ADECL) {
4328 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4331 else if (def->op == OP_VAL_VEC) {
4332 in_reg = is_in_reg(state, RHS(def, 0));
4334 else if (def->op == OP_DOT) {
4335 in_reg = is_in_reg(state, RHS(def, 0));
4338 internal_error(state, 0, "unknown expr storage location");
4344 /* Is this a stable variable location otherwise it must be a temporary */
4345 static int is_stable(struct compile_state *state, struct triple *def)
4352 if ((def->op == OP_ADECL) ||
4353 (def->op == OP_SDECL) ||
4354 (def->op == OP_DEREF) ||
4355 (def->op == OP_BLOBCONST)) {
4358 else if (def->op == OP_DOT) {
4359 ret = is_stable(state, RHS(def, 0));
4361 else if (def->op == OP_VAL_VEC) {
4362 struct triple **vector;
4365 vector = &RHS(def, 0);
4366 for(i = 0; i < def->type->elements; i++) {
4367 if (!is_stable(state, vector[i])) {
4376 static int is_lvalue(struct compile_state *state, struct triple *def)
4383 if (!is_stable(state, def)) {
4386 if (def->op == OP_DOT) {
4387 ret = is_lvalue(state, RHS(def, 0));
4392 static void clvalue(struct compile_state *state, struct triple *def)
4395 internal_error(state, def, "nothing where lvalue expected?");
4397 if (!is_lvalue(state, def)) {
4398 error(state, def, "lvalue expected");
4401 static void lvalue(struct compile_state *state, struct triple *def)
4403 clvalue(state, def);
4404 if (def->type->type & QUAL_CONST) {
4405 error(state, def, "modifable lvalue expected");
4409 static int is_pointer(struct triple *def)
4411 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4414 static void pointer(struct compile_state *state, struct triple *def)
4416 if (!is_pointer(def)) {
4417 error(state, def, "pointer expected");
4421 static struct triple *int_const(
4422 struct compile_state *state, struct type *type, ulong_t value)
4424 struct triple *result;
4425 switch(type->type & TYPE_MASK) {
4427 case TYPE_INT: case TYPE_UINT:
4428 case TYPE_LONG: case TYPE_ULONG:
4431 internal_error(state, 0, "constant for unkown type");
4433 result = triple(state, OP_INTCONST, type, 0, 0);
4434 result->u.cval = value;
4439 static struct triple *do_mk_addr_expr(struct compile_state *state,
4440 struct triple *expr, struct type *type, ulong_t offset)
4442 struct triple *result;
4443 clvalue(state, expr);
4446 if (expr->op == OP_ADECL) {
4447 error(state, expr, "address of auto variables not supported");
4449 else if (expr->op == OP_SDECL) {
4450 result = triple(state, OP_ADDRCONST, type, 0, 0);
4451 MISC(result, 0) = expr;
4452 result->u.cval = offset;
4454 else if (expr->op == OP_DEREF) {
4455 result = triple(state, OP_ADD, type,
4457 int_const(state, &ulong_type, offset));
4462 static struct triple *mk_addr_expr(
4463 struct compile_state *state, struct triple *expr, ulong_t offset)
4468 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4471 return do_mk_addr_expr(state, expr, type, offset);
4474 static struct triple *mk_deref_expr(
4475 struct compile_state *state, struct triple *expr)
4477 struct type *base_type;
4478 pointer(state, expr);
4479 base_type = expr->type->left;
4480 return triple(state, OP_DEREF, base_type, expr, 0);
4483 static struct triple *deref_field(
4484 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4486 struct triple *result;
4487 struct type *type, *member;
4489 internal_error(state, 0, "No field passed to deref_field");
4493 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4494 error(state, 0, "request for member %s in something not a struct or union",
4497 member = type->left;
4498 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4499 if (member->left->field_ident == field) {
4500 member = member->left;
4503 member = member->right;
4505 if (member->field_ident != field) {
4506 error(state, 0, "%s is not a member", field->name);
4508 if ((type->type & STOR_MASK) == STOR_PERM) {
4509 /* Do the pointer arithmetic to get a deref the field */
4511 offset = field_offset(state, type, field);
4512 result = do_mk_addr_expr(state, expr, member, offset);
4513 result = mk_deref_expr(state, result);
4516 /* Find the variable for the field I want. */
4517 result = triple(state, OP_DOT,
4518 field_type(state, type, field), expr, 0);
4519 result->u.field = field;
4524 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4530 if (!is_stable(state, def)) {
4533 /* Tranform an array to a pointer to the first element */
4534 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4535 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4537 struct triple *result;
4539 TYPE_POINTER | (def->type->type & QUAL_MASK),
4540 def->type->left, 0);
4541 result = triple(state, OP_ADDRCONST, type, 0, 0);
4542 MISC(result, 0) = def;
4545 if (is_in_reg(state, def)) {
4550 return triple(state, op, def->type, def, 0);
4553 static void write_compatible(struct compile_state *state,
4554 struct type *dest, struct type *rval)
4557 /* Both operands have arithmetic type */
4558 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4561 /* One operand is a pointer and the other is a pointer to void */
4562 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4563 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4564 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4565 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4568 /* If both types are the same without qualifiers we are good */
4569 else if (equiv_ptrs(dest, rval)) {
4572 /* test for struct/union equality */
4573 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4574 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4575 (dest->type_ident == rval->type_ident)) {
4579 error(state, 0, "Incompatible types in assignment");
4583 static struct triple *write_expr(
4584 struct compile_state *state, struct triple *dest, struct triple *rval)
4591 internal_error(state, 0, "missing rval");
4594 if (rval->op == OP_LIST) {
4595 internal_error(state, 0, "expression of type OP_LIST?");
4597 if (!is_lvalue(state, dest)) {
4598 internal_error(state, 0, "writing to a non lvalue?");
4600 if (dest->type->type & QUAL_CONST) {
4601 internal_error(state, 0, "modifable lvalue expexted");
4604 write_compatible(state, dest->type, rval->type);
4606 /* Now figure out which assignment operator to use */
4608 if (is_in_reg(state, dest)) {
4613 def = triple(state, op, dest->type, dest, rval);
4617 static struct triple *init_expr(
4618 struct compile_state *state, struct triple *dest, struct triple *rval)
4624 internal_error(state, 0, "missing rval");
4626 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4627 rval = read_expr(state, rval);
4628 def = write_expr(state, dest, rval);
4631 /* Fill in the array size if necessary */
4632 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4633 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4634 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4635 dest->type->elements = rval->type->elements;
4638 if (!equiv_types(dest->type, rval->type)) {
4639 error(state, 0, "Incompatible types in inializer");
4641 MISC(dest, 0) = rval;
4642 insert_triple(state, dest, rval);
4643 rval->id |= TRIPLE_FLAG_FLATTENED;
4644 use_triple(MISC(dest, 0), dest);
4649 struct type *arithmetic_result(
4650 struct compile_state *state, struct triple *left, struct triple *right)
4653 /* Sanity checks to ensure I am working with arithmetic types */
4654 arithmetic(state, left);
4655 arithmetic(state, right);
4657 do_arithmetic_conversion(
4659 right->type->type), 0, 0);
4663 struct type *ptr_arithmetic_result(
4664 struct compile_state *state, struct triple *left, struct triple *right)
4667 /* Sanity checks to ensure I am working with the proper types */
4668 ptr_arithmetic(state, left);
4669 arithmetic(state, right);
4670 if (TYPE_ARITHMETIC(left->type->type) &&
4671 TYPE_ARITHMETIC(right->type->type)) {
4672 type = arithmetic_result(state, left, right);
4674 else if (TYPE_PTR(left->type->type)) {
4678 internal_error(state, 0, "huh?");
4685 /* boolean helper function */
4687 static struct triple *ltrue_expr(struct compile_state *state,
4688 struct triple *expr)
4691 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4692 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4693 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4694 /* If the expression is already boolean do nothing */
4697 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4703 static struct triple *lfalse_expr(struct compile_state *state,
4704 struct triple *expr)
4706 return triple(state, OP_LFALSE, &int_type, expr, 0);
4709 static struct triple *cond_expr(
4710 struct compile_state *state,
4711 struct triple *test, struct triple *left, struct triple *right)
4714 struct type *result_type;
4715 unsigned int left_type, right_type;
4717 left_type = left->type->type;
4718 right_type = right->type->type;
4720 /* Both operands have arithmetic type */
4721 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4722 result_type = arithmetic_result(state, left, right);
4724 /* Both operands have void type */
4725 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4726 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4727 result_type = &void_type;
4729 /* pointers to the same type... */
4730 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4733 /* Both operands are pointers and left is a pointer to void */
4734 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4735 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4736 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4737 result_type = right->type;
4739 /* Both operands are pointers and right is a pointer to void */
4740 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4741 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4742 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4743 result_type = left->type;
4746 error(state, 0, "Incompatible types in conditional expression");
4748 /* Cleanup and invert the test */
4749 test = lfalse_expr(state, read_expr(state, test));
4750 def = new_triple(state, OP_COND, result_type, 0, 3);
4751 def->param[0] = test;
4752 def->param[1] = left;
4753 def->param[2] = right;
4758 static int expr_depth(struct compile_state *state, struct triple *ins)
4762 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4765 else if (ins->op == OP_DEREF) {
4766 count = expr_depth(state, RHS(ins, 0)) - 1;
4768 else if (ins->op == OP_VAL) {
4769 count = expr_depth(state, RHS(ins, 0)) - 1;
4771 else if (ins->op == OP_COMMA) {
4773 ldepth = expr_depth(state, RHS(ins, 0));
4774 rdepth = expr_depth(state, RHS(ins, 1));
4775 count = (ldepth >= rdepth)? ldepth : rdepth;
4777 else if (ins->op == OP_CALL) {
4778 /* Don't figure the depth of a call just guess it is huge */
4782 struct triple **expr;
4783 expr = triple_rhs(state, ins, 0);
4784 for(;expr; expr = triple_rhs(state, ins, expr)) {
4787 depth = expr_depth(state, *expr);
4788 if (depth > count) {
4797 static struct triple *flatten(
4798 struct compile_state *state, struct triple *first, struct triple *ptr);
4800 static struct triple *mk_add_expr(
4801 struct compile_state *state, struct triple *left, struct triple *right);
4803 static struct triple *flatten_generic(
4804 struct compile_state *state, struct triple *first, struct triple *ptr)
4808 struct triple **ins;
4811 /* Only operations with just a rhs should come here */
4812 rhs = TRIPLE_RHS(ptr->sizes);
4813 lhs = TRIPLE_LHS(ptr->sizes);
4814 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4815 internal_error(state, ptr, "unexpected args for: %d %s",
4816 ptr->op, tops(ptr->op));
4818 /* Find the depth of the rhs elements */
4819 for(i = 0; i < rhs; i++) {
4820 vector[i].ins = &RHS(ptr, i);
4821 vector[i].depth = expr_depth(state, *vector[i].ins);
4823 /* Selection sort the rhs */
4824 for(i = 0; i < rhs; i++) {
4826 for(j = i + 1; j < rhs; j++ ) {
4827 if (vector[j].depth > vector[max].depth) {
4832 struct rhs_vector tmp;
4834 vector[i] = vector[max];
4838 /* Now flatten the rhs elements */
4839 for(i = 0; i < rhs; i++) {
4840 *vector[i].ins = flatten(state, first, *vector[i].ins);
4841 use_triple(*vector[i].ins, ptr);
4844 /* Now flatten the lhs elements */
4845 for(i = 0; i < lhs; i++) {
4846 struct triple **ins = &LHS(ptr, i);
4847 *ins = flatten(state, first, *ins);
4848 use_triple(*ins, ptr);
4853 static struct triple *flatten_land(
4854 struct compile_state *state, struct triple *first, struct triple *ptr)
4856 struct triple *left, *right;
4857 struct triple *val, *test, *jmp, *label1, *end;
4859 /* Find the triples */
4861 right = RHS(ptr, 1);
4863 /* Generate the needed triples */
4866 /* Thread the triples together */
4867 val = flatten(state, first, variable(state, ptr->type));
4868 left = flatten(state, first, write_expr(state, val, left));
4869 test = flatten(state, first,
4870 lfalse_expr(state, read_expr(state, val)));
4871 jmp = flatten(state, first, branch(state, end, test));
4872 label1 = flatten(state, first, label(state));
4873 right = flatten(state, first, write_expr(state, val, right));
4874 TARG(jmp, 0) = flatten(state, first, end);
4876 /* Now give the caller something to chew on */
4877 return read_expr(state, val);
4880 static struct triple *flatten_lor(
4881 struct compile_state *state, struct triple *first, struct triple *ptr)
4883 struct triple *left, *right;
4884 struct triple *val, *jmp, *label1, *end;
4886 /* Find the triples */
4888 right = RHS(ptr, 1);
4890 /* Generate the needed triples */
4893 /* Thread the triples together */
4894 val = flatten(state, first, variable(state, ptr->type));
4895 left = flatten(state, first, write_expr(state, val, left));
4896 jmp = flatten(state, first, branch(state, end, left));
4897 label1 = flatten(state, first, label(state));
4898 right = flatten(state, first, write_expr(state, val, right));
4899 TARG(jmp, 0) = flatten(state, first, end);
4902 /* Now give the caller something to chew on */
4903 return read_expr(state, val);
4906 static struct triple *flatten_cond(
4907 struct compile_state *state, struct triple *first, struct triple *ptr)
4909 struct triple *test, *left, *right;
4910 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4912 /* Find the triples */
4915 right = RHS(ptr, 2);
4917 /* Generate the needed triples */
4919 middle = label(state);
4921 /* Thread the triples together */
4922 val = flatten(state, first, variable(state, ptr->type));
4923 test = flatten(state, first, test);
4924 jmp1 = flatten(state, first, branch(state, middle, test));
4925 label1 = flatten(state, first, label(state));
4926 left = flatten(state, first, left);
4927 mv1 = flatten(state, first, write_expr(state, val, left));
4928 jmp2 = flatten(state, first, branch(state, end, 0));
4929 TARG(jmp1, 0) = flatten(state, first, middle);
4930 right = flatten(state, first, right);
4931 mv2 = flatten(state, first, write_expr(state, val, right));
4932 TARG(jmp2, 0) = flatten(state, first, end);
4934 /* Now give the caller something to chew on */
4935 return read_expr(state, val);
4938 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
4939 struct occurance *base_occurance)
4941 struct triple *nfunc;
4942 struct triple *nfirst, *ofirst;
4943 struct triple *new, *old;
4946 fprintf(stdout, "\n");
4947 loc(stdout, state, 0);
4948 fprintf(stdout, "\n__________ copy_func _________\n");
4949 print_triple(state, ofunc);
4950 fprintf(stdout, "__________ copy_func _________ done\n\n");
4953 /* Make a new copy of the old function */
4954 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4956 ofirst = old = RHS(ofunc, 0);
4959 struct occurance *occurance;
4960 int old_lhs, old_rhs;
4961 old_lhs = TRIPLE_LHS(old->sizes);
4962 old_rhs = TRIPLE_RHS(old->sizes);
4963 occurance = inline_occurance(state, base_occurance, old->occurance);
4964 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4966 if (!triple_stores_block(state, new)) {
4967 memcpy(&new->u, &old->u, sizeof(new->u));
4970 RHS(nfunc, 0) = nfirst = new;
4973 insert_triple(state, nfirst, new);
4975 new->id |= TRIPLE_FLAG_FLATTENED;
4977 /* During the copy remember new as user of old */
4978 use_triple(old, new);
4980 /* Populate the return type if present */
4981 if (old == MISC(ofunc, 0)) {
4982 MISC(nfunc, 0) = new;
4985 } while(old != ofirst);
4987 /* Make a second pass to fix up any unresolved references */
4991 struct triple **oexpr, **nexpr;
4993 /* Lookup where the copy is, to join pointers */
4994 count = TRIPLE_SIZE(old->sizes);
4995 for(i = 0; i < count; i++) {
4996 oexpr = &old->param[i];
4997 nexpr = &new->param[i];
4998 if (!*nexpr && *oexpr && (*oexpr)->use) {
4999 *nexpr = (*oexpr)->use->member;
5000 if (*nexpr == old) {
5001 internal_error(state, 0, "new == old?");
5003 use_triple(*nexpr, new);
5005 if (!*nexpr && *oexpr) {
5006 internal_error(state, 0, "Could not copy %d\n", i);
5011 } while((old != ofirst) && (new != nfirst));
5013 /* Make a third pass to cleanup the extra useses */
5017 unuse_triple(old, new);
5020 } while ((old != ofirst) && (new != nfirst));
5024 static struct triple *flatten_call(
5025 struct compile_state *state, struct triple *first, struct triple *ptr)
5027 /* Inline the function call */
5029 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5030 struct triple *end, *nend;
5033 /* Find the triples */
5034 ofunc = MISC(ptr, 0);
5035 if (ofunc->op != OP_LIST) {
5036 internal_error(state, 0, "improper function");
5038 nfunc = copy_func(state, ofunc, ptr->occurance);
5039 nfirst = RHS(nfunc, 0)->next;
5040 /* Prepend the parameter reading into the new function list */
5041 ptype = nfunc->type->right;
5042 param = RHS(nfunc, 0)->next;
5043 pvals = TRIPLE_RHS(ptr->sizes);
5044 for(i = 0; i < pvals; i++) {
5048 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5049 atype = ptype->left;
5051 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5052 param = param->next;
5055 flatten(state, nfirst, write_expr(state, param, arg));
5056 ptype = ptype->right;
5057 param = param->next;
5060 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5061 result = read_expr(state, MISC(nfunc,0));
5064 fprintf(stdout, "\n");
5065 loc(stdout, state, 0);
5066 fprintf(stdout, "\n__________ flatten_call _________\n");
5067 print_triple(state, nfunc);
5068 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5071 /* Get rid of the extra triples */
5072 nfirst = RHS(nfunc, 0)->next;
5073 free_triple(state, RHS(nfunc, 0));
5075 free_triple(state, nfunc);
5077 /* Append the new function list onto the return list */
5079 nend = nfirst->prev;
5088 static struct triple *flatten(
5089 struct compile_state *state, struct triple *first, struct triple *ptr)
5091 struct triple *orig_ptr;
5096 /* Only flatten triples once */
5097 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5103 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5104 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5105 use_triple(LHS(ptr, 0), ptr);
5106 use_triple(RHS(ptr, 0), ptr);
5109 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5113 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5114 return MISC(ptr, 0);
5117 ptr = flatten_land(state, first, ptr);
5120 ptr = flatten_lor(state, first, ptr);
5123 ptr = flatten_cond(state, first, ptr);
5126 ptr = flatten_call(state, first, ptr);
5130 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5131 use_triple(RHS(ptr, 0), ptr);
5134 use_triple(TARG(ptr, 0), ptr);
5135 if (TRIPLE_RHS(ptr->sizes)) {
5136 use_triple(RHS(ptr, 0), ptr);
5137 if (ptr->next != ptr) {
5138 use_triple(ptr->next, ptr);
5143 insert_triple(state, first, ptr);
5144 ptr->id |= TRIPLE_FLAG_FLATTENED;
5145 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5146 use_triple(MISC(ptr, 0), ptr);
5149 /* Since OP_DEREF is just a marker delete it when I flatten it */
5151 RHS(orig_ptr, 0) = 0;
5152 free_triple(state, orig_ptr);
5156 struct triple *base;
5158 if (base->op == OP_DEREF) {
5160 offset = field_offset(state, base->type, ptr->u.field);
5161 ptr = mk_add_expr(state, RHS(base, 0),
5162 int_const(state, &ulong_type, offset));
5163 free_triple(state, base);
5165 else if (base->op == OP_VAL_VEC) {
5166 base = flatten(state, first, base);
5167 ptr = struct_field(state, base, ptr->u.field);
5172 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5173 use_triple(MISC(ptr, 0), ptr);
5174 use_triple(ptr, MISC(ptr, 0));
5178 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5179 use_triple(MISC(ptr, 0), ptr);
5184 /* Flatten the easy cases we don't override */
5185 ptr = flatten_generic(state, first, ptr);
5188 } while(ptr && (ptr != orig_ptr));
5190 insert_triple(state, first, ptr);
5191 ptr->id |= TRIPLE_FLAG_FLATTENED;
5196 static void release_expr(struct compile_state *state, struct triple *expr)
5198 struct triple *head;
5199 head = label(state);
5200 flatten(state, head, expr);
5201 while(head->next != head) {
5202 release_triple(state, head->next);
5204 free_triple(state, head);
5207 static int replace_rhs_use(struct compile_state *state,
5208 struct triple *orig, struct triple *new, struct triple *use)
5210 struct triple **expr;
5213 expr = triple_rhs(state, use, 0);
5214 for(;expr; expr = triple_rhs(state, use, expr)) {
5215 if (*expr == orig) {
5221 unuse_triple(orig, use);
5222 use_triple(new, use);
5227 static int replace_lhs_use(struct compile_state *state,
5228 struct triple *orig, struct triple *new, struct triple *use)
5230 struct triple **expr;
5233 expr = triple_lhs(state, use, 0);
5234 for(;expr; expr = triple_lhs(state, use, expr)) {
5235 if (*expr == orig) {
5241 unuse_triple(orig, use);
5242 use_triple(new, use);
5247 static void propogate_use(struct compile_state *state,
5248 struct triple *orig, struct triple *new)
5250 struct triple_set *user, *next;
5251 for(user = orig->use; user; user = next) {
5257 found |= replace_rhs_use(state, orig, new, use);
5258 found |= replace_lhs_use(state, orig, new, use);
5260 internal_error(state, use, "use without use");
5264 internal_error(state, orig, "used after propogate_use");
5270 * ===========================
5273 static struct triple *mk_add_expr(
5274 struct compile_state *state, struct triple *left, struct triple *right)
5276 struct type *result_type;
5277 /* Put pointer operands on the left */
5278 if (is_pointer(right)) {
5284 left = read_expr(state, left);
5285 right = read_expr(state, right);
5286 result_type = ptr_arithmetic_result(state, left, right);
5287 if (is_pointer(left)) {
5288 right = triple(state,
5289 is_signed(right->type)? OP_SMUL : OP_UMUL,
5292 int_const(state, &ulong_type,
5293 size_of(state, left->type->left)));
5295 return triple(state, OP_ADD, result_type, left, right);
5298 static struct triple *mk_sub_expr(
5299 struct compile_state *state, struct triple *left, struct triple *right)
5301 struct type *result_type;
5302 result_type = ptr_arithmetic_result(state, left, right);
5303 left = read_expr(state, left);
5304 right = read_expr(state, right);
5305 if (is_pointer(left)) {
5306 right = triple(state,
5307 is_signed(right->type)? OP_SMUL : OP_UMUL,
5310 int_const(state, &ulong_type,
5311 size_of(state, left->type->left)));
5313 return triple(state, OP_SUB, result_type, left, right);
5316 static struct triple *mk_pre_inc_expr(
5317 struct compile_state *state, struct triple *def)
5321 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5322 return triple(state, OP_VAL, def->type,
5323 write_expr(state, def, val),
5327 static struct triple *mk_pre_dec_expr(
5328 struct compile_state *state, struct triple *def)
5332 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5333 return triple(state, OP_VAL, def->type,
5334 write_expr(state, def, val),
5338 static struct triple *mk_post_inc_expr(
5339 struct compile_state *state, struct triple *def)
5343 val = read_expr(state, def);
5344 return triple(state, OP_VAL, def->type,
5345 write_expr(state, def,
5346 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5350 static struct triple *mk_post_dec_expr(
5351 struct compile_state *state, struct triple *def)
5355 val = read_expr(state, def);
5356 return triple(state, OP_VAL, def->type,
5357 write_expr(state, def,
5358 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5362 static struct triple *mk_subscript_expr(
5363 struct compile_state *state, struct triple *left, struct triple *right)
5365 left = read_expr(state, left);
5366 right = read_expr(state, right);
5367 if (!is_pointer(left) && !is_pointer(right)) {
5368 error(state, left, "subscripted value is not a pointer");
5370 return mk_deref_expr(state, mk_add_expr(state, left, right));
5374 * Compile time evaluation
5375 * ===========================
5377 static int is_const(struct triple *ins)
5379 return IS_CONST_OP(ins->op);
5382 static int constants_equal(struct compile_state *state,
5383 struct triple *left, struct triple *right)
5386 if (!is_const(left) || !is_const(right)) {
5389 else if (left->op != right->op) {
5392 else if (!equiv_types(left->type, right->type)) {
5399 if (left->u.cval == right->u.cval) {
5405 size_t lsize, rsize;
5406 lsize = size_of(state, left->type);
5407 rsize = size_of(state, right->type);
5408 if (lsize != rsize) {
5411 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5417 if ((MISC(left, 0) == MISC(right, 0)) &&
5418 (left->u.cval == right->u.cval)) {
5423 internal_error(state, left, "uknown constant type");
5430 static int is_zero(struct triple *ins)
5432 return is_const(ins) && (ins->u.cval == 0);
5435 static int is_one(struct triple *ins)
5437 return is_const(ins) && (ins->u.cval == 1);
5440 static long_t bsr(ulong_t value)
5443 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5454 static long_t bsf(ulong_t value)
5457 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5468 static long_t log2(ulong_t value)
5473 static long_t tlog2(struct triple *ins)
5475 return log2(ins->u.cval);
5478 static int is_pow2(struct triple *ins)
5480 ulong_t value, mask;
5482 if (!is_const(ins)) {
5485 value = ins->u.cval;
5492 return ((value & mask) == value);
5495 static ulong_t read_const(struct compile_state *state,
5496 struct triple *ins, struct triple **expr)
5500 switch(rhs->type->type &TYPE_MASK) {
5512 internal_error(state, rhs, "bad type to read_const\n");
5518 static long_t read_sconst(struct triple *ins, struct triple **expr)
5522 return (long_t)(rhs->u.cval);
5525 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5527 struct triple **expr;
5528 expr = triple_rhs(state, ins, 0);
5529 for(;expr;expr = triple_rhs(state, ins, expr)) {
5531 unuse_triple(*expr, ins);
5537 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5539 struct triple **expr;
5540 expr = triple_lhs(state, ins, 0);
5541 for(;expr;expr = triple_lhs(state, ins, expr)) {
5542 unuse_triple(*expr, ins);
5547 static void check_lhs(struct compile_state *state, struct triple *ins)
5549 struct triple **expr;
5550 expr = triple_lhs(state, ins, 0);
5551 for(;expr;expr = triple_lhs(state, ins, expr)) {
5552 internal_error(state, ins, "unexpected lhs");
5556 static void check_targ(struct compile_state *state, struct triple *ins)
5558 struct triple **expr;
5559 expr = triple_targ(state, ins, 0);
5560 for(;expr;expr = triple_targ(state, ins, expr)) {
5561 internal_error(state, ins, "unexpected targ");
5565 static void wipe_ins(struct compile_state *state, struct triple *ins)
5567 /* Becareful which instructions you replace the wiped
5568 * instruction with, as there are not enough slots
5569 * in all instructions to hold all others.
5571 check_targ(state, ins);
5572 unuse_rhs(state, ins);
5573 unuse_lhs(state, ins);
5576 static void mkcopy(struct compile_state *state,
5577 struct triple *ins, struct triple *rhs)
5579 wipe_ins(state, ins);
5581 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5583 use_triple(RHS(ins, 0), ins);
5586 static void mkconst(struct compile_state *state,
5587 struct triple *ins, ulong_t value)
5589 if (!is_integral(ins) && !is_pointer(ins)) {
5590 internal_error(state, ins, "unknown type to make constant\n");
5592 wipe_ins(state, ins);
5593 ins->op = OP_INTCONST;
5594 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5595 ins->u.cval = value;
5598 static void mkaddr_const(struct compile_state *state,
5599 struct triple *ins, struct triple *sdecl, ulong_t value)
5601 wipe_ins(state, ins);
5602 ins->op = OP_ADDRCONST;
5603 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5604 MISC(ins, 0) = sdecl;
5605 ins->u.cval = value;
5606 use_triple(sdecl, ins);
5609 /* Transform multicomponent variables into simple register variables */
5610 static void flatten_structures(struct compile_state *state)
5612 struct triple *ins, *first;
5613 first = RHS(state->main_function, 0);
5615 /* Pass one expand structure values into valvecs.
5619 struct triple *next;
5621 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5622 if (ins->op == OP_VAL_VEC) {
5625 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5626 struct triple *def, **vector;
5633 get_occurance(ins->occurance);
5634 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5637 vector = &RHS(next, 0);
5638 tptr = next->type->left;
5639 for(i = 0; i < next->type->elements; i++) {
5640 struct triple *sfield;
5643 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5644 mtype = mtype->left;
5646 sfield = deref_field(state, def, mtype->field_ident);
5649 state, op, mtype, sfield, 0);
5650 put_occurance(vector[i]->occurance);
5651 get_occurance(next->occurance);
5652 vector[i]->occurance = next->occurance;
5655 propogate_use(state, ins, next);
5656 flatten(state, ins, next);
5657 free_triple(state, ins);
5659 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5660 struct triple *src, *dst, **vector;
5668 get_occurance(ins->occurance);
5669 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5672 vector = &RHS(next, 0);
5673 tptr = next->type->left;
5674 for(i = 0; i < ins->type->elements; i++) {
5675 struct triple *dfield, *sfield;
5678 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5679 mtype = mtype->left;
5681 sfield = deref_field(state, src, mtype->field_ident);
5682 dfield = deref_field(state, dst, mtype->field_ident);
5684 state, op, mtype, dfield, sfield);
5685 put_occurance(vector[i]->occurance);
5686 get_occurance(next->occurance);
5687 vector[i]->occurance = next->occurance;
5690 propogate_use(state, ins, next);
5691 flatten(state, ins, next);
5692 free_triple(state, ins);
5696 } while(ins != first);
5697 /* Pass two flatten the valvecs.
5701 struct triple *next;
5703 if (ins->op == OP_VAL_VEC) {
5704 release_triple(state, ins);
5707 } while(ins != first);
5708 /* Pass three verify the state and set ->id to 0.
5712 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5713 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5714 internal_error(state, ins, "STRUCT_TYPE remains?");
5716 if (ins->op == OP_DOT) {
5717 internal_error(state, ins, "OP_DOT remains?");
5719 if (ins->op == OP_VAL_VEC) {
5720 internal_error(state, ins, "OP_VAL_VEC remains?");
5723 } while(ins != first);
5726 /* For those operations that cannot be simplified */
5727 static void simplify_noop(struct compile_state *state, struct triple *ins)
5732 static void simplify_smul(struct compile_state *state, struct triple *ins)
5734 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5737 RHS(ins, 0) = RHS(ins, 1);
5740 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5742 left = read_sconst(ins, &RHS(ins, 0));
5743 right = read_sconst(ins, &RHS(ins, 1));
5744 mkconst(state, ins, left * right);
5746 else if (is_zero(RHS(ins, 1))) {
5747 mkconst(state, ins, 0);
5749 else if (is_one(RHS(ins, 1))) {
5750 mkcopy(state, ins, RHS(ins, 0));
5752 else if (is_pow2(RHS(ins, 1))) {
5754 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5756 insert_triple(state, ins, val);
5757 unuse_triple(RHS(ins, 1), ins);
5758 use_triple(val, ins);
5763 static void simplify_umul(struct compile_state *state, struct triple *ins)
5765 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5768 RHS(ins, 0) = RHS(ins, 1);
5771 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5772 ulong_t left, right;
5773 left = read_const(state, ins, &RHS(ins, 0));
5774 right = read_const(state, ins, &RHS(ins, 1));
5775 mkconst(state, ins, left * right);
5777 else if (is_zero(RHS(ins, 1))) {
5778 mkconst(state, ins, 0);
5780 else if (is_one(RHS(ins, 1))) {
5781 mkcopy(state, ins, RHS(ins, 0));
5783 else if (is_pow2(RHS(ins, 1))) {
5785 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5787 insert_triple(state, ins, val);
5788 unuse_triple(RHS(ins, 1), ins);
5789 use_triple(val, ins);
5794 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5796 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5798 left = read_sconst(ins, &RHS(ins, 0));
5799 right = read_sconst(ins, &RHS(ins, 1));
5800 mkconst(state, ins, left / right);
5802 else if (is_zero(RHS(ins, 0))) {
5803 mkconst(state, ins, 0);
5805 else if (is_zero(RHS(ins, 1))) {
5806 error(state, ins, "division by zero");
5808 else if (is_one(RHS(ins, 1))) {
5809 mkcopy(state, ins, RHS(ins, 0));
5811 else if (is_pow2(RHS(ins, 1))) {
5813 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5815 insert_triple(state, ins, val);
5816 unuse_triple(RHS(ins, 1), ins);
5817 use_triple(val, ins);
5822 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5824 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5825 ulong_t left, right;
5826 left = read_const(state, ins, &RHS(ins, 0));
5827 right = read_const(state, ins, &RHS(ins, 1));
5828 mkconst(state, ins, left / right);
5830 else if (is_zero(RHS(ins, 0))) {
5831 mkconst(state, ins, 0);
5833 else if (is_zero(RHS(ins, 1))) {
5834 error(state, ins, "division by zero");
5836 else if (is_one(RHS(ins, 1))) {
5837 mkcopy(state, ins, RHS(ins, 0));
5839 else if (is_pow2(RHS(ins, 1))) {
5841 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5843 insert_triple(state, ins, val);
5844 unuse_triple(RHS(ins, 1), ins);
5845 use_triple(val, ins);
5850 static void simplify_smod(struct compile_state *state, struct triple *ins)
5852 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5854 left = read_const(state, ins, &RHS(ins, 0));
5855 right = read_const(state, ins, &RHS(ins, 1));
5856 mkconst(state, ins, left % right);
5858 else if (is_zero(RHS(ins, 0))) {
5859 mkconst(state, ins, 0);
5861 else if (is_zero(RHS(ins, 1))) {
5862 error(state, ins, "division by zero");
5864 else if (is_one(RHS(ins, 1))) {
5865 mkconst(state, ins, 0);
5867 else if (is_pow2(RHS(ins, 1))) {
5869 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5871 insert_triple(state, ins, val);
5872 unuse_triple(RHS(ins, 1), ins);
5873 use_triple(val, ins);
5877 static void simplify_umod(struct compile_state *state, struct triple *ins)
5879 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5880 ulong_t left, right;
5881 left = read_const(state, ins, &RHS(ins, 0));
5882 right = read_const(state, ins, &RHS(ins, 1));
5883 mkconst(state, ins, left % right);
5885 else if (is_zero(RHS(ins, 0))) {
5886 mkconst(state, ins, 0);
5888 else if (is_zero(RHS(ins, 1))) {
5889 error(state, ins, "division by zero");
5891 else if (is_one(RHS(ins, 1))) {
5892 mkconst(state, ins, 0);
5894 else if (is_pow2(RHS(ins, 1))) {
5896 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5898 insert_triple(state, ins, val);
5899 unuse_triple(RHS(ins, 1), ins);
5900 use_triple(val, ins);
5905 static void simplify_add(struct compile_state *state, struct triple *ins)
5907 /* start with the pointer on the left */
5908 if (is_pointer(RHS(ins, 1))) {
5911 RHS(ins, 0) = RHS(ins, 1);
5914 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5915 if (!is_pointer(RHS(ins, 0))) {
5916 ulong_t left, right;
5917 left = read_const(state, ins, &RHS(ins, 0));
5918 right = read_const(state, ins, &RHS(ins, 1));
5919 mkconst(state, ins, left + right);
5921 else /* op == OP_ADDRCONST */ {
5922 struct triple *sdecl;
5923 ulong_t left, right;
5924 sdecl = MISC(RHS(ins, 0), 0);
5925 left = RHS(ins, 0)->u.cval;
5926 right = RHS(ins, 1)->u.cval;
5927 mkaddr_const(state, ins, sdecl, left + right);
5930 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5933 RHS(ins, 1) = RHS(ins, 0);
5938 static void simplify_sub(struct compile_state *state, struct triple *ins)
5940 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5941 if (!is_pointer(RHS(ins, 0))) {
5942 ulong_t left, right;
5943 left = read_const(state, ins, &RHS(ins, 0));
5944 right = read_const(state, ins, &RHS(ins, 1));
5945 mkconst(state, ins, left - right);
5947 else /* op == OP_ADDRCONST */ {
5948 struct triple *sdecl;
5949 ulong_t left, right;
5950 sdecl = MISC(RHS(ins, 0), 0);
5951 left = RHS(ins, 0)->u.cval;
5952 right = RHS(ins, 1)->u.cval;
5953 mkaddr_const(state, ins, sdecl, left - right);
5958 static void simplify_sl(struct compile_state *state, struct triple *ins)
5960 if (is_const(RHS(ins, 1))) {
5962 right = read_const(state, ins, &RHS(ins, 1));
5963 if (right >= (size_of(state, ins->type)*8)) {
5964 warning(state, ins, "left shift count >= width of type");
5967 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5968 ulong_t left, right;
5969 left = read_const(state, ins, &RHS(ins, 0));
5970 right = read_const(state, ins, &RHS(ins, 1));
5971 mkconst(state, ins, left << right);
5975 static void simplify_usr(struct compile_state *state, struct triple *ins)
5977 if (is_const(RHS(ins, 1))) {
5979 right = read_const(state, ins, &RHS(ins, 1));
5980 if (right >= (size_of(state, ins->type)*8)) {
5981 warning(state, ins, "right shift count >= width of type");
5984 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5985 ulong_t left, right;
5986 left = read_const(state, ins, &RHS(ins, 0));
5987 right = read_const(state, ins, &RHS(ins, 1));
5988 mkconst(state, ins, left >> right);
5992 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5994 if (is_const(RHS(ins, 1))) {
5996 right = read_const(state, ins, &RHS(ins, 1));
5997 if (right >= (size_of(state, ins->type)*8)) {
5998 warning(state, ins, "right shift count >= width of type");
6001 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6003 left = read_sconst(ins, &RHS(ins, 0));
6004 right = read_sconst(ins, &RHS(ins, 1));
6005 mkconst(state, ins, left >> right);
6009 static void simplify_and(struct compile_state *state, struct triple *ins)
6011 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6012 ulong_t left, right;
6013 left = read_const(state, ins, &RHS(ins, 0));
6014 right = read_const(state, ins, &RHS(ins, 1));
6015 mkconst(state, ins, left & right);
6019 static void simplify_or(struct compile_state *state, struct triple *ins)
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_xor(struct compile_state *state, struct triple *ins)
6031 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6032 ulong_t left, right;
6033 left = read_const(state, ins, &RHS(ins, 0));
6034 right = read_const(state, ins, &RHS(ins, 1));
6035 mkconst(state, ins, left ^ right);
6039 static void simplify_pos(struct compile_state *state, struct triple *ins)
6041 if (is_const(RHS(ins, 0))) {
6042 mkconst(state, ins, RHS(ins, 0)->u.cval);
6045 mkcopy(state, ins, RHS(ins, 0));
6049 static void simplify_neg(struct compile_state *state, struct triple *ins)
6051 if (is_const(RHS(ins, 0))) {
6053 left = read_const(state, ins, &RHS(ins, 0));
6054 mkconst(state, ins, -left);
6056 else if (RHS(ins, 0)->op == OP_NEG) {
6057 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6061 static void simplify_invert(struct compile_state *state, struct triple *ins)
6063 if (is_const(RHS(ins, 0))) {
6065 left = read_const(state, ins, &RHS(ins, 0));
6066 mkconst(state, ins, ~left);
6070 static void simplify_eq(struct compile_state *state, struct triple *ins)
6072 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6073 ulong_t left, right;
6074 left = read_const(state, ins, &RHS(ins, 0));
6075 right = read_const(state, ins, &RHS(ins, 1));
6076 mkconst(state, ins, left == right);
6078 else if (RHS(ins, 0) == RHS(ins, 1)) {
6079 mkconst(state, ins, 1);
6083 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6085 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6086 ulong_t left, right;
6087 left = read_const(state, ins, &RHS(ins, 0));
6088 right = read_const(state, ins, &RHS(ins, 1));
6089 mkconst(state, ins, left != right);
6091 else if (RHS(ins, 0) == RHS(ins, 1)) {
6092 mkconst(state, ins, 0);
6096 static void simplify_sless(struct compile_state *state, struct triple *ins)
6098 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6100 left = read_sconst(ins, &RHS(ins, 0));
6101 right = read_sconst(ins, &RHS(ins, 1));
6102 mkconst(state, ins, left < right);
6104 else if (RHS(ins, 0) == RHS(ins, 1)) {
6105 mkconst(state, ins, 0);
6109 static void simplify_uless(struct compile_state *state, struct triple *ins)
6111 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6112 ulong_t left, right;
6113 left = read_const(state, ins, &RHS(ins, 0));
6114 right = read_const(state, ins, &RHS(ins, 1));
6115 mkconst(state, ins, left < right);
6117 else if (is_zero(RHS(ins, 0))) {
6118 mkconst(state, ins, 1);
6120 else if (RHS(ins, 0) == RHS(ins, 1)) {
6121 mkconst(state, ins, 0);
6125 static void simplify_smore(struct compile_state *state, struct triple *ins)
6127 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6129 left = read_sconst(ins, &RHS(ins, 0));
6130 right = read_sconst(ins, &RHS(ins, 1));
6131 mkconst(state, ins, left > right);
6133 else if (RHS(ins, 0) == RHS(ins, 1)) {
6134 mkconst(state, ins, 0);
6138 static void simplify_umore(struct compile_state *state, struct triple *ins)
6140 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6141 ulong_t left, right;
6142 left = read_const(state, ins, &RHS(ins, 0));
6143 right = read_const(state, ins, &RHS(ins, 1));
6144 mkconst(state, ins, left > right);
6146 else if (is_zero(RHS(ins, 1))) {
6147 mkconst(state, ins, 1);
6149 else if (RHS(ins, 0) == RHS(ins, 1)) {
6150 mkconst(state, ins, 0);
6155 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6157 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6159 left = read_sconst(ins, &RHS(ins, 0));
6160 right = read_sconst(ins, &RHS(ins, 1));
6161 mkconst(state, ins, left <= right);
6163 else if (RHS(ins, 0) == RHS(ins, 1)) {
6164 mkconst(state, ins, 1);
6168 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6170 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6171 ulong_t left, right;
6172 left = read_const(state, ins, &RHS(ins, 0));
6173 right = read_const(state, ins, &RHS(ins, 1));
6174 mkconst(state, ins, left <= right);
6176 else if (is_zero(RHS(ins, 0))) {
6177 mkconst(state, ins, 1);
6179 else if (RHS(ins, 0) == RHS(ins, 1)) {
6180 mkconst(state, ins, 1);
6184 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6186 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6188 left = read_sconst(ins, &RHS(ins, 0));
6189 right = read_sconst(ins, &RHS(ins, 1));
6190 mkconst(state, ins, left >= right);
6192 else if (RHS(ins, 0) == RHS(ins, 1)) {
6193 mkconst(state, ins, 1);
6197 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6199 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6200 ulong_t left, right;
6201 left = read_const(state, ins, &RHS(ins, 0));
6202 right = read_const(state, ins, &RHS(ins, 1));
6203 mkconst(state, ins, left >= right);
6205 else if (is_zero(RHS(ins, 1))) {
6206 mkconst(state, ins, 1);
6208 else if (RHS(ins, 0) == RHS(ins, 1)) {
6209 mkconst(state, ins, 1);
6213 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6215 if (is_const(RHS(ins, 0))) {
6217 left = read_const(state, ins, &RHS(ins, 0));
6218 mkconst(state, ins, left == 0);
6220 /* Otherwise if I am the only user... */
6221 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6223 /* Invert a boolean operation */
6224 switch(RHS(ins, 0)->op) {
6225 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6226 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6227 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6228 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6229 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6230 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6231 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6232 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6233 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6234 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6235 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6236 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6242 mkcopy(state, ins, RHS(ins, 0));
6247 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6249 if (is_const(RHS(ins, 0))) {
6251 left = read_const(state, ins, &RHS(ins, 0));
6252 mkconst(state, ins, left != 0);
6254 else switch(RHS(ins, 0)->op) {
6255 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6256 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6257 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6258 mkcopy(state, ins, RHS(ins, 0));
6263 static void simplify_copy(struct compile_state *state, struct triple *ins)
6265 if (is_const(RHS(ins, 0))) {
6266 switch(RHS(ins, 0)->op) {
6270 left = read_const(state, ins, &RHS(ins, 0));
6271 mkconst(state, ins, left);
6276 struct triple *sdecl;
6278 sdecl = MISC(RHS(ins, 0), 0);
6279 offset = RHS(ins, 0)->u.cval;
6280 mkaddr_const(state, ins, sdecl, offset);
6284 internal_error(state, ins, "uknown constant");
6290 static void simplify_branch(struct compile_state *state, struct triple *ins)
6292 struct block *block;
6293 if (ins->op != OP_BRANCH) {
6294 internal_error(state, ins, "not branch");
6296 if (ins->use != 0) {
6297 internal_error(state, ins, "branch use");
6299 #warning "FIXME implement simplify branch."
6300 /* The challenge here with simplify branch is that I need to
6301 * make modifications to the control flow graph as well
6302 * as to the branch instruction itself.
6304 block = ins->u.block;
6306 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6307 struct triple *targ;
6309 value = read_const(state, ins, &RHS(ins, 0));
6310 unuse_triple(RHS(ins, 0), ins);
6311 targ = TARG(ins, 0);
6312 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6314 unuse_triple(ins->next, ins);
6315 TARG(ins, 0) = targ;
6318 unuse_triple(targ, ins);
6319 TARG(ins, 0) = ins->next;
6321 #warning "FIXME handle the case of making a branch unconditional"
6323 if (TARG(ins, 0) == ins->next) {
6324 unuse_triple(ins->next, ins);
6325 if (TRIPLE_RHS(ins->sizes)) {
6326 unuse_triple(RHS(ins, 0), ins);
6327 unuse_triple(ins->next, ins);
6329 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6332 internal_error(state, ins, "noop use != 0");
6334 #warning "FIXME handle the case of killing a branch"
6338 static void simplify_phi(struct compile_state *state, struct triple *ins)
6340 struct triple **expr;
6342 expr = triple_rhs(state, ins, 0);
6343 if (!*expr || !is_const(*expr)) {
6346 value = read_const(state, ins, expr);
6347 for(;expr;expr = triple_rhs(state, ins, expr)) {
6348 if (!*expr || !is_const(*expr)) {
6351 if (value != read_const(state, ins, expr)) {
6355 mkconst(state, ins, value);
6359 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6361 if (is_const(RHS(ins, 0))) {
6363 left = read_const(state, ins, &RHS(ins, 0));
6364 mkconst(state, ins, bsf(left));
6368 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6370 if (is_const(RHS(ins, 0))) {
6372 left = read_const(state, ins, &RHS(ins, 0));
6373 mkconst(state, ins, bsr(left));
6378 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6379 static const simplify_t table_simplify[] = {
6381 #define simplify_smul simplify_noop
6382 #define simplify_umul simplify_noop
6383 #define simplify_sdiv simplify_noop
6384 #define simplify_udiv simplify_noop
6385 #define simplify_smod simplify_noop
6386 #define simplify_umod simplify_noop
6389 #define simplify_add simplify_noop
6390 #define simplify_sub simplify_noop
6393 #define simplify_sl simplify_noop
6394 #define simplify_usr simplify_noop
6395 #define simplify_ssr simplify_noop
6398 #define simplify_and simplify_noop
6399 #define simplify_xor simplify_noop
6400 #define simplify_or simplify_noop
6403 #define simplify_pos simplify_noop
6404 #define simplify_neg simplify_noop
6405 #define simplify_invert simplify_noop
6409 #define simplify_eq simplify_noop
6410 #define simplify_noteq simplify_noop
6413 #define simplify_sless simplify_noop
6414 #define simplify_uless simplify_noop
6415 #define simplify_smore simplify_noop
6416 #define simplify_umore simplify_noop
6419 #define simplify_slesseq simplify_noop
6420 #define simplify_ulesseq simplify_noop
6421 #define simplify_smoreeq simplify_noop
6422 #define simplify_umoreeq simplify_noop
6425 #define simplify_lfalse simplify_noop
6428 #define simplify_ltrue simplify_noop
6432 #define simplify_copy simplify_noop
6436 #define simplify_branch simplify_noop
6440 #define simplify_phi simplify_noop
6444 #define simplify_bsf simplify_noop
6445 #define simplify_bsr simplify_noop
6448 [OP_SMUL ] = simplify_smul,
6449 [OP_UMUL ] = simplify_umul,
6450 [OP_SDIV ] = simplify_sdiv,
6451 [OP_UDIV ] = simplify_udiv,
6452 [OP_SMOD ] = simplify_smod,
6453 [OP_UMOD ] = simplify_umod,
6454 [OP_ADD ] = simplify_add,
6455 [OP_SUB ] = simplify_sub,
6456 [OP_SL ] = simplify_sl,
6457 [OP_USR ] = simplify_usr,
6458 [OP_SSR ] = simplify_ssr,
6459 [OP_AND ] = simplify_and,
6460 [OP_XOR ] = simplify_xor,
6461 [OP_OR ] = simplify_or,
6462 [OP_POS ] = simplify_pos,
6463 [OP_NEG ] = simplify_neg,
6464 [OP_INVERT ] = simplify_invert,
6466 [OP_EQ ] = simplify_eq,
6467 [OP_NOTEQ ] = simplify_noteq,
6468 [OP_SLESS ] = simplify_sless,
6469 [OP_ULESS ] = simplify_uless,
6470 [OP_SMORE ] = simplify_smore,
6471 [OP_UMORE ] = simplify_umore,
6472 [OP_SLESSEQ ] = simplify_slesseq,
6473 [OP_ULESSEQ ] = simplify_ulesseq,
6474 [OP_SMOREEQ ] = simplify_smoreeq,
6475 [OP_UMOREEQ ] = simplify_umoreeq,
6476 [OP_LFALSE ] = simplify_lfalse,
6477 [OP_LTRUE ] = simplify_ltrue,
6479 [OP_LOAD ] = simplify_noop,
6480 [OP_STORE ] = simplify_noop,
6482 [OP_NOOP ] = simplify_noop,
6484 [OP_INTCONST ] = simplify_noop,
6485 [OP_BLOBCONST ] = simplify_noop,
6486 [OP_ADDRCONST ] = simplify_noop,
6488 [OP_WRITE ] = simplify_noop,
6489 [OP_READ ] = simplify_noop,
6490 [OP_COPY ] = simplify_copy,
6491 [OP_PIECE ] = simplify_noop,
6492 [OP_ASM ] = simplify_noop,
6494 [OP_DOT ] = simplify_noop,
6495 [OP_VAL_VEC ] = simplify_noop,
6497 [OP_LIST ] = simplify_noop,
6498 [OP_BRANCH ] = simplify_branch,
6499 [OP_LABEL ] = simplify_noop,
6500 [OP_ADECL ] = simplify_noop,
6501 [OP_SDECL ] = simplify_noop,
6502 [OP_PHI ] = simplify_phi,
6504 [OP_INB ] = simplify_noop,
6505 [OP_INW ] = simplify_noop,
6506 [OP_INL ] = simplify_noop,
6507 [OP_OUTB ] = simplify_noop,
6508 [OP_OUTW ] = simplify_noop,
6509 [OP_OUTL ] = simplify_noop,
6510 [OP_BSF ] = simplify_bsf,
6511 [OP_BSR ] = simplify_bsr,
6512 [OP_RDMSR ] = simplify_noop,
6513 [OP_WRMSR ] = simplify_noop,
6514 [OP_HLT ] = simplify_noop,
6517 static void simplify(struct compile_state *state, struct triple *ins)
6520 simplify_t do_simplify;
6524 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6528 do_simplify = table_simplify[op];
6531 internal_error(state, ins, "cannot simplify op: %d %s\n",
6535 do_simplify(state, ins);
6536 } while(ins->op != op);
6539 static void simplify_all(struct compile_state *state)
6541 struct triple *ins, *first;
6542 first = RHS(state->main_function, 0);
6545 simplify(state, ins);
6547 } while(ins != first);
6552 * ============================
6555 static void register_builtin_function(struct compile_state *state,
6556 const char *name, int op, struct type *rtype, ...)
6558 struct type *ftype, *atype, *param, **next;
6559 struct triple *def, *arg, *result, *work, *last, *first;
6560 struct hash_entry *ident;
6561 struct file_state file;
6567 /* Dummy file state to get debug handling right */
6568 memset(&file, 0, sizeof(file));
6569 file.basename = "<built-in>";
6571 file.report_line = 1;
6572 file.report_name = file.basename;
6573 file.prev = state->file;
6574 state->file = &file;
6575 state->function = name;
6577 /* Find the Parameter count */
6578 valid_op(state, op);
6579 parameters = table_ops[op].rhs;
6580 if (parameters < 0 ) {
6581 internal_error(state, 0, "Invalid builtin parameter count");
6584 /* Find the function type */
6585 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6586 next = &ftype->right;
6587 va_start(args, rtype);
6588 for(i = 0; i < parameters; i++) {
6589 atype = va_arg(args, struct type *);
6593 *next = new_type(TYPE_PRODUCT, *next, atype);
6594 next = &((*next)->right);
6602 /* Generate the needed triples */
6603 def = triple(state, OP_LIST, ftype, 0, 0);
6604 first = label(state);
6605 RHS(def, 0) = first;
6607 /* Now string them together */
6608 param = ftype->right;
6609 for(i = 0; i < parameters; i++) {
6610 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6611 atype = param->left;
6615 arg = flatten(state, first, variable(state, atype));
6616 param = param->right;
6619 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6620 result = flatten(state, first, variable(state, rtype));
6622 MISC(def, 0) = result;
6623 work = new_triple(state, op, rtype, -1, parameters);
6624 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6625 RHS(work, i) = read_expr(state, arg);
6627 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6629 /* Populate the LHS with the target registers */
6630 work = flatten(state, first, work);
6631 work->type = &void_type;
6632 param = rtype->left;
6633 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6634 internal_error(state, 0, "Invalid result type");
6636 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6637 for(i = 0; i < rtype->elements; i++) {
6638 struct triple *piece;
6640 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6641 atype = param->left;
6643 if (!TYPE_ARITHMETIC(atype->type) &&
6644 !TYPE_PTR(atype->type)) {
6645 internal_error(state, 0, "Invalid lhs type");
6647 piece = triple(state, OP_PIECE, atype, work, 0);
6649 LHS(work, i) = piece;
6650 RHS(val, i) = piece;
6655 work = write_expr(state, result, work);
6657 work = flatten(state, first, work);
6658 last = flatten(state, first, label(state));
6659 name_len = strlen(name);
6660 ident = lookup(state, name, name_len);
6661 symbol(state, ident, &ident->sym_ident, def, ftype);
6663 state->file = file.prev;
6664 state->function = 0;
6666 fprintf(stdout, "\n");
6667 loc(stdout, state, 0);
6668 fprintf(stdout, "\n__________ builtin_function _________\n");
6669 print_triple(state, def);
6670 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6674 static struct type *partial_struct(struct compile_state *state,
6675 const char *field_name, struct type *type, struct type *rest)
6677 struct hash_entry *field_ident;
6678 struct type *result;
6681 field_name_len = strlen(field_name);
6682 field_ident = lookup(state, field_name, field_name_len);
6684 result = clone_type(0, type);
6685 result->field_ident = field_ident;
6688 result = new_type(TYPE_PRODUCT, result, rest);
6693 static struct type *register_builtin_type(struct compile_state *state,
6694 const char *name, struct type *type)
6696 struct hash_entry *ident;
6699 name_len = strlen(name);
6700 ident = lookup(state, name, name_len);
6702 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6703 ulong_t elements = 0;
6705 type = new_type(TYPE_STRUCT, type, 0);
6707 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6709 field = field->right;
6712 symbol(state, ident, &ident->sym_struct, 0, type);
6713 type->type_ident = ident;
6714 type->elements = elements;
6716 symbol(state, ident, &ident->sym_ident, 0, type);
6717 ident->tok = TOK_TYPE_NAME;
6722 static void register_builtins(struct compile_state *state)
6724 struct type *msr_type;
6726 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6728 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6730 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6733 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6734 &uchar_type, &ushort_type);
6735 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6736 &ushort_type, &ushort_type);
6737 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6738 &uint_type, &ushort_type);
6740 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6742 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6745 msr_type = register_builtin_type(state, "__builtin_msr_t",
6746 partial_struct(state, "lo", &ulong_type,
6747 partial_struct(state, "hi", &ulong_type, 0)));
6749 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6751 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6752 &ulong_type, &ulong_type, &ulong_type);
6754 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6758 static struct type *declarator(
6759 struct compile_state *state, struct type *type,
6760 struct hash_entry **ident, int need_ident);
6761 static void decl(struct compile_state *state, struct triple *first);
6762 static struct type *specifier_qualifier_list(struct compile_state *state);
6763 static int isdecl_specifier(int tok);
6764 static struct type *decl_specifiers(struct compile_state *state);
6765 static int istype(int tok);
6766 static struct triple *expr(struct compile_state *state);
6767 static struct triple *assignment_expr(struct compile_state *state);
6768 static struct type *type_name(struct compile_state *state);
6769 static void statement(struct compile_state *state, struct triple *fist);
6771 static struct triple *call_expr(
6772 struct compile_state *state, struct triple *func)
6775 struct type *param, *type;
6776 ulong_t pvals, index;
6778 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6779 error(state, 0, "Called object is not a function");
6781 if (func->op != OP_LIST) {
6782 internal_error(state, 0, "improper function");
6784 eat(state, TOK_LPAREN);
6785 /* Find the return type without any specifiers */
6786 type = clone_type(0, func->type->left);
6787 def = new_triple(state, OP_CALL, func->type, -1, -1);
6790 pvals = TRIPLE_RHS(def->sizes);
6791 MISC(def, 0) = func;
6793 param = func->type->right;
6794 for(index = 0; index < pvals; index++) {
6796 struct type *arg_type;
6797 val = read_expr(state, assignment_expr(state));
6799 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6800 arg_type = param->left;
6802 write_compatible(state, arg_type, val->type);
6803 RHS(def, index) = val;
6804 if (index != (pvals - 1)) {
6805 eat(state, TOK_COMMA);
6806 param = param->right;
6809 eat(state, TOK_RPAREN);
6814 static struct triple *character_constant(struct compile_state *state)
6818 const signed char *str, *end;
6821 eat(state, TOK_LIT_CHAR);
6822 tk = &state->token[0];
6823 str = tk->val.str + 1;
6824 str_len = tk->str_len - 2;
6826 error(state, 0, "empty character constant");
6828 end = str + str_len;
6829 c = char_value(state, &str, end);
6831 error(state, 0, "multibyte character constant not supported");
6833 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6837 static struct triple *string_constant(struct compile_state *state)
6842 const signed char *str, *end;
6843 signed char *buf, *ptr;
6847 type = new_type(TYPE_ARRAY, &char_type, 0);
6849 /* The while loop handles string concatenation */
6851 eat(state, TOK_LIT_STRING);
6852 tk = &state->token[0];
6853 str = tk->val.str + 1;
6854 str_len = tk->str_len - 2;
6856 error(state, 0, "negative string constant length");
6858 end = str + str_len;
6860 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6861 memcpy(buf, ptr, type->elements);
6862 ptr = buf + type->elements;
6864 *ptr++ = char_value(state, &str, end);
6866 type->elements = ptr - buf;
6867 } while(peek(state) == TOK_LIT_STRING);
6869 type->elements += 1;
6870 def = triple(state, OP_BLOBCONST, type, 0, 0);
6876 static struct triple *integer_constant(struct compile_state *state)
6885 eat(state, TOK_LIT_INT);
6886 tk = &state->token[0];
6888 decimal = (tk->val.str[0] != '0');
6889 val = strtoul(tk->val.str, &end, 0);
6890 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6891 error(state, 0, "Integer constant to large");
6894 if ((*end == 'u') || (*end == 'U')) {
6898 if ((*end == 'l') || (*end == 'L')) {
6902 if ((*end == 'u') || (*end == 'U')) {
6907 error(state, 0, "Junk at end of integer constant");
6914 if (!decimal && (val > LONG_MAX)) {
6920 if (val > UINT_MAX) {
6926 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6929 else if (!decimal && (val > LONG_MAX)) {
6932 else if (val > INT_MAX) {
6936 def = int_const(state, type, val);
6940 static struct triple *primary_expr(struct compile_state *state)
6948 struct hash_entry *ident;
6949 /* Here ident is either:
6952 * an enumeration constant.
6954 eat(state, TOK_IDENT);
6955 ident = state->token[0].ident;
6956 if (!ident->sym_ident) {
6957 error(state, 0, "%s undeclared", ident->name);
6959 def = ident->sym_ident->def;
6962 case TOK_ENUM_CONST:
6963 /* Here ident is an enumeration constant */
6964 eat(state, TOK_ENUM_CONST);
6969 eat(state, TOK_LPAREN);
6971 eat(state, TOK_RPAREN);
6974 def = integer_constant(state);
6977 eat(state, TOK_LIT_FLOAT);
6978 error(state, 0, "Floating point constants not supported");
6983 def = character_constant(state);
6985 case TOK_LIT_STRING:
6986 def = string_constant(state);
6990 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6995 static struct triple *postfix_expr(struct compile_state *state)
6999 def = primary_expr(state);
7001 struct triple *left;
7005 switch((tok = peek(state))) {
7007 eat(state, TOK_LBRACKET);
7008 def = mk_subscript_expr(state, left, expr(state));
7009 eat(state, TOK_RBRACKET);
7012 def = call_expr(state, def);
7016 struct hash_entry *field;
7017 eat(state, TOK_DOT);
7018 eat(state, TOK_IDENT);
7019 field = state->token[0].ident;
7020 def = deref_field(state, def, field);
7025 struct hash_entry *field;
7026 eat(state, TOK_ARROW);
7027 eat(state, TOK_IDENT);
7028 field = state->token[0].ident;
7029 def = mk_deref_expr(state, read_expr(state, def));
7030 def = deref_field(state, def, field);
7034 eat(state, TOK_PLUSPLUS);
7035 def = mk_post_inc_expr(state, left);
7037 case TOK_MINUSMINUS:
7038 eat(state, TOK_MINUSMINUS);
7039 def = mk_post_dec_expr(state, left);
7049 static struct triple *cast_expr(struct compile_state *state);
7051 static struct triple *unary_expr(struct compile_state *state)
7053 struct triple *def, *right;
7055 switch((tok = peek(state))) {
7057 eat(state, TOK_PLUSPLUS);
7058 def = mk_pre_inc_expr(state, unary_expr(state));
7060 case TOK_MINUSMINUS:
7061 eat(state, TOK_MINUSMINUS);
7062 def = mk_pre_dec_expr(state, unary_expr(state));
7065 eat(state, TOK_AND);
7066 def = mk_addr_expr(state, cast_expr(state), 0);
7069 eat(state, TOK_STAR);
7070 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7073 eat(state, TOK_PLUS);
7074 right = read_expr(state, cast_expr(state));
7075 arithmetic(state, right);
7076 def = integral_promotion(state, right);
7079 eat(state, TOK_MINUS);
7080 right = read_expr(state, cast_expr(state));
7081 arithmetic(state, right);
7082 def = integral_promotion(state, right);
7083 def = triple(state, OP_NEG, def->type, def, 0);
7086 eat(state, TOK_TILDE);
7087 right = read_expr(state, cast_expr(state));
7088 integral(state, right);
7089 def = integral_promotion(state, right);
7090 def = triple(state, OP_INVERT, def->type, def, 0);
7093 eat(state, TOK_BANG);
7094 right = read_expr(state, cast_expr(state));
7096 def = lfalse_expr(state, right);
7102 eat(state, TOK_SIZEOF);
7104 tok2 = peek2(state);
7105 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7106 eat(state, TOK_LPAREN);
7107 type = type_name(state);
7108 eat(state, TOK_RPAREN);
7111 struct triple *expr;
7112 expr = unary_expr(state);
7114 release_expr(state, expr);
7116 def = int_const(state, &ulong_type, size_of(state, type));
7123 eat(state, TOK_ALIGNOF);
7125 tok2 = peek2(state);
7126 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7127 eat(state, TOK_LPAREN);
7128 type = type_name(state);
7129 eat(state, TOK_RPAREN);
7132 struct triple *expr;
7133 expr = unary_expr(state);
7135 release_expr(state, expr);
7137 def = int_const(state, &ulong_type, align_of(state, type));
7141 def = postfix_expr(state);
7147 static struct triple *cast_expr(struct compile_state *state)
7152 tok2 = peek2(state);
7153 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7155 eat(state, TOK_LPAREN);
7156 type = type_name(state);
7157 eat(state, TOK_RPAREN);
7158 def = read_expr(state, cast_expr(state));
7159 def = triple(state, OP_COPY, type, def, 0);
7162 def = unary_expr(state);
7167 static struct triple *mult_expr(struct compile_state *state)
7171 def = cast_expr(state);
7173 struct triple *left, *right;
7174 struct type *result_type;
7177 switch(tok = (peek(state))) {
7181 left = read_expr(state, def);
7182 arithmetic(state, left);
7186 right = read_expr(state, cast_expr(state));
7187 arithmetic(state, right);
7189 result_type = arithmetic_result(state, left, right);
7190 sign = is_signed(result_type);
7193 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7194 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7195 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7197 def = triple(state, op, result_type, left, right);
7207 static struct triple *add_expr(struct compile_state *state)
7211 def = mult_expr(state);
7214 switch( peek(state)) {
7216 eat(state, TOK_PLUS);
7217 def = mk_add_expr(state, def, mult_expr(state));
7220 eat(state, TOK_MINUS);
7221 def = mk_sub_expr(state, def, mult_expr(state));
7231 static struct triple *shift_expr(struct compile_state *state)
7235 def = add_expr(state);
7237 struct triple *left, *right;
7240 switch((tok = peek(state))) {
7243 left = read_expr(state, def);
7244 integral(state, left);
7245 left = integral_promotion(state, left);
7249 right = read_expr(state, add_expr(state));
7250 integral(state, right);
7251 right = integral_promotion(state, right);
7253 op = (tok == TOK_SL)? OP_SL :
7254 is_signed(left->type)? OP_SSR: OP_USR;
7256 def = triple(state, op, left->type, left, right);
7266 static struct triple *relational_expr(struct compile_state *state)
7268 #warning "Extend relational exprs to work on more than arithmetic types"
7271 def = shift_expr(state);
7273 struct triple *left, *right;
7274 struct type *arg_type;
7277 switch((tok = peek(state))) {
7282 left = read_expr(state, def);
7283 arithmetic(state, left);
7287 right = read_expr(state, shift_expr(state));
7288 arithmetic(state, right);
7290 arg_type = arithmetic_result(state, left, right);
7291 sign = is_signed(arg_type);
7294 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7295 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7296 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7297 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7299 def = triple(state, op, &int_type, left, right);
7309 static struct triple *equality_expr(struct compile_state *state)
7311 #warning "Extend equality exprs to work on more than arithmetic types"
7314 def = relational_expr(state);
7316 struct triple *left, *right;
7319 switch((tok = peek(state))) {
7322 left = read_expr(state, def);
7323 arithmetic(state, left);
7325 right = read_expr(state, relational_expr(state));
7326 arithmetic(state, right);
7327 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7328 def = triple(state, op, &int_type, left, right);
7338 static struct triple *and_expr(struct compile_state *state)
7341 def = equality_expr(state);
7342 while(peek(state) == TOK_AND) {
7343 struct triple *left, *right;
7344 struct type *result_type;
7345 left = read_expr(state, def);
7346 integral(state, left);
7347 eat(state, TOK_AND);
7348 right = read_expr(state, equality_expr(state));
7349 integral(state, right);
7350 result_type = arithmetic_result(state, left, right);
7351 def = triple(state, OP_AND, result_type, left, right);
7356 static struct triple *xor_expr(struct compile_state *state)
7359 def = and_expr(state);
7360 while(peek(state) == TOK_XOR) {
7361 struct triple *left, *right;
7362 struct type *result_type;
7363 left = read_expr(state, def);
7364 integral(state, left);
7365 eat(state, TOK_XOR);
7366 right = read_expr(state, and_expr(state));
7367 integral(state, right);
7368 result_type = arithmetic_result(state, left, right);
7369 def = triple(state, OP_XOR, result_type, left, right);
7374 static struct triple *or_expr(struct compile_state *state)
7377 def = xor_expr(state);
7378 while(peek(state) == TOK_OR) {
7379 struct triple *left, *right;
7380 struct type *result_type;
7381 left = read_expr(state, def);
7382 integral(state, left);
7384 right = read_expr(state, xor_expr(state));
7385 integral(state, right);
7386 result_type = arithmetic_result(state, left, right);
7387 def = triple(state, OP_OR, result_type, left, right);
7392 static struct triple *land_expr(struct compile_state *state)
7395 def = or_expr(state);
7396 while(peek(state) == TOK_LOGAND) {
7397 struct triple *left, *right;
7398 left = read_expr(state, def);
7400 eat(state, TOK_LOGAND);
7401 right = read_expr(state, or_expr(state));
7404 def = triple(state, OP_LAND, &int_type,
7405 ltrue_expr(state, left),
7406 ltrue_expr(state, right));
7411 static struct triple *lor_expr(struct compile_state *state)
7414 def = land_expr(state);
7415 while(peek(state) == TOK_LOGOR) {
7416 struct triple *left, *right;
7417 left = read_expr(state, def);
7419 eat(state, TOK_LOGOR);
7420 right = read_expr(state, land_expr(state));
7423 def = triple(state, OP_LOR, &int_type,
7424 ltrue_expr(state, left),
7425 ltrue_expr(state, right));
7430 static struct triple *conditional_expr(struct compile_state *state)
7433 def = lor_expr(state);
7434 if (peek(state) == TOK_QUEST) {
7435 struct triple *test, *left, *right;
7437 test = ltrue_expr(state, read_expr(state, def));
7438 eat(state, TOK_QUEST);
7439 left = read_expr(state, expr(state));
7440 eat(state, TOK_COLON);
7441 right = read_expr(state, conditional_expr(state));
7443 def = cond_expr(state, test, left, right);
7448 static struct triple *eval_const_expr(
7449 struct compile_state *state, struct triple *expr)
7452 if (is_const(expr)) {
7456 /* If we don't start out as a constant simplify into one */
7457 struct triple *head, *ptr;
7458 head = label(state); /* dummy initial triple */
7459 flatten(state, head, expr);
7460 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7461 simplify(state, ptr);
7463 /* Remove the constant value the tail of the list */
7465 def->prev->next = def->next;
7466 def->next->prev = def->prev;
7467 def->next = def->prev = def;
7468 if (!is_const(def)) {
7469 error(state, 0, "Not a constant expression");
7471 /* Free the intermediate expressions */
7472 while(head->next != head) {
7473 release_triple(state, head->next);
7475 free_triple(state, head);
7480 static struct triple *constant_expr(struct compile_state *state)
7482 return eval_const_expr(state, conditional_expr(state));
7485 static struct triple *assignment_expr(struct compile_state *state)
7487 struct triple *def, *left, *right;
7489 /* The C grammer in K&R shows assignment expressions
7490 * only taking unary expressions as input on their
7491 * left hand side. But specifies the precedence of
7492 * assignemnt as the lowest operator except for comma.
7494 * Allowing conditional expressions on the left hand side
7495 * of an assignement results in a grammar that accepts
7496 * a larger set of statements than standard C. As long
7497 * as the subset of the grammar that is standard C behaves
7498 * correctly this should cause no problems.
7500 * For the extra token strings accepted by the grammar
7501 * none of them should produce a valid lvalue, so they
7502 * should not produce functioning programs.
7504 * GCC has this bug as well, so surprises should be minimal.
7506 def = conditional_expr(state);
7508 switch((tok = peek(state))) {
7510 lvalue(state, left);
7512 def = write_expr(state, left,
7513 read_expr(state, assignment_expr(state)));
7518 lvalue(state, left);
7519 arithmetic(state, left);
7521 right = read_expr(state, assignment_expr(state));
7522 arithmetic(state, right);
7524 sign = is_signed(left->type);
7527 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7528 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7529 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7531 def = write_expr(state, left,
7532 triple(state, op, left->type,
7533 read_expr(state, left), right));
7536 lvalue(state, left);
7537 eat(state, TOK_PLUSEQ);
7538 def = write_expr(state, left,
7539 mk_add_expr(state, left, assignment_expr(state)));
7542 lvalue(state, left);
7543 eat(state, TOK_MINUSEQ);
7544 def = write_expr(state, left,
7545 mk_sub_expr(state, left, assignment_expr(state)));
7552 lvalue(state, left);
7553 integral(state, left);
7555 right = read_expr(state, assignment_expr(state));
7556 integral(state, right);
7557 right = integral_promotion(state, right);
7558 sign = is_signed(left->type);
7561 case TOK_SLEQ: op = OP_SL; break;
7562 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7563 case TOK_ANDEQ: op = OP_AND; break;
7564 case TOK_XOREQ: op = OP_XOR; break;
7565 case TOK_OREQ: op = OP_OR; break;
7567 def = write_expr(state, left,
7568 triple(state, op, left->type,
7569 read_expr(state, left), right));
7575 static struct triple *expr(struct compile_state *state)
7578 def = assignment_expr(state);
7579 while(peek(state) == TOK_COMMA) {
7580 struct triple *left, *right;
7582 eat(state, TOK_COMMA);
7583 right = assignment_expr(state);
7584 def = triple(state, OP_COMMA, right->type, left, right);
7589 static void expr_statement(struct compile_state *state, struct triple *first)
7591 if (peek(state) != TOK_SEMI) {
7592 flatten(state, first, expr(state));
7594 eat(state, TOK_SEMI);
7597 static void if_statement(struct compile_state *state, struct triple *first)
7599 struct triple *test, *jmp1, *jmp2, *middle, *end;
7601 jmp1 = jmp2 = middle = 0;
7603 eat(state, TOK_LPAREN);
7606 /* Cleanup and invert the test */
7607 test = lfalse_expr(state, read_expr(state, test));
7608 eat(state, TOK_RPAREN);
7609 /* Generate the needed pieces */
7610 middle = label(state);
7611 jmp1 = branch(state, middle, test);
7612 /* Thread the pieces together */
7613 flatten(state, first, test);
7614 flatten(state, first, jmp1);
7615 flatten(state, first, label(state));
7616 statement(state, first);
7617 if (peek(state) == TOK_ELSE) {
7618 eat(state, TOK_ELSE);
7619 /* Generate the rest of the pieces */
7621 jmp2 = branch(state, end, 0);
7622 /* Thread them together */
7623 flatten(state, first, jmp2);
7624 flatten(state, first, middle);
7625 statement(state, first);
7626 flatten(state, first, end);
7629 flatten(state, first, middle);
7633 static void for_statement(struct compile_state *state, struct triple *first)
7635 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7636 struct triple *label1, *label2, *label3;
7637 struct hash_entry *ident;
7639 eat(state, TOK_FOR);
7640 eat(state, TOK_LPAREN);
7641 head = test = tail = jmp1 = jmp2 = 0;
7642 if (peek(state) != TOK_SEMI) {
7645 eat(state, TOK_SEMI);
7646 if (peek(state) != TOK_SEMI) {
7649 test = ltrue_expr(state, read_expr(state, test));
7651 eat(state, TOK_SEMI);
7652 if (peek(state) != TOK_RPAREN) {
7655 eat(state, TOK_RPAREN);
7656 /* Generate the needed pieces */
7657 label1 = label(state);
7658 label2 = label(state);
7659 label3 = label(state);
7661 jmp1 = branch(state, label3, 0);
7662 jmp2 = branch(state, label1, test);
7665 jmp2 = branch(state, label1, 0);
7668 /* Remember where break and continue go */
7670 ident = state->i_break;
7671 symbol(state, ident, &ident->sym_ident, end, end->type);
7672 ident = state->i_continue;
7673 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7674 /* Now include the body */
7675 flatten(state, first, head);
7676 flatten(state, first, jmp1);
7677 flatten(state, first, label1);
7678 statement(state, first);
7679 flatten(state, first, label2);
7680 flatten(state, first, tail);
7681 flatten(state, first, label3);
7682 flatten(state, first, test);
7683 flatten(state, first, jmp2);
7684 flatten(state, first, end);
7685 /* Cleanup the break/continue scope */
7689 static void while_statement(struct compile_state *state, struct triple *first)
7691 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7692 struct hash_entry *ident;
7693 eat(state, TOK_WHILE);
7694 eat(state, TOK_LPAREN);
7697 test = ltrue_expr(state, read_expr(state, test));
7698 eat(state, TOK_RPAREN);
7699 /* Generate the needed pieces */
7700 label1 = label(state);
7701 label2 = label(state);
7702 jmp1 = branch(state, label2, 0);
7703 jmp2 = branch(state, label1, test);
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 /* Thread them together */
7712 flatten(state, first, jmp1);
7713 flatten(state, first, label1);
7714 statement(state, first);
7715 flatten(state, first, label2);
7716 flatten(state, first, test);
7717 flatten(state, first, jmp2);
7718 flatten(state, first, end);
7719 /* Cleanup the break/continue scope */
7723 static void do_statement(struct compile_state *state, struct triple *first)
7725 struct triple *label1, *label2, *test, *end;
7726 struct hash_entry *ident;
7728 /* Generate the needed pieces */
7729 label1 = label(state);
7730 label2 = label(state);
7732 /* Remember where break and continue go */
7734 ident = state->i_break;
7735 symbol(state, ident, &ident->sym_ident, end, end->type);
7736 ident = state->i_continue;
7737 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7738 /* Now include the body */
7739 flatten(state, first, label1);
7740 statement(state, first);
7741 /* Cleanup the break/continue scope */
7743 /* Eat the rest of the loop */
7744 eat(state, TOK_WHILE);
7745 eat(state, TOK_LPAREN);
7746 test = read_expr(state, expr(state));
7748 eat(state, TOK_RPAREN);
7749 eat(state, TOK_SEMI);
7750 /* Thread the pieces together */
7751 test = ltrue_expr(state, test);
7752 flatten(state, first, label2);
7753 flatten(state, first, test);
7754 flatten(state, first, branch(state, label1, test));
7755 flatten(state, first, end);
7759 static void return_statement(struct compile_state *state, struct triple *first)
7761 struct triple *jmp, *mv, *dest, *var, *val;
7763 eat(state, TOK_RETURN);
7765 #warning "FIXME implement a more general excess branch elimination"
7767 /* If we have a return value do some more work */
7768 if (peek(state) != TOK_SEMI) {
7769 val = read_expr(state, expr(state));
7771 eat(state, TOK_SEMI);
7773 /* See if this last statement in a function */
7774 last = ((peek(state) == TOK_RBRACE) &&
7775 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7777 /* Find the return variable */
7778 var = MISC(state->main_function, 0);
7779 /* Find the return destination */
7780 dest = RHS(state->main_function, 0)->prev;
7782 /* If needed generate a jump instruction */
7784 jmp = branch(state, dest, 0);
7786 /* If needed generate an assignment instruction */
7788 mv = write_expr(state, var, val);
7790 /* Now put the code together */
7792 flatten(state, first, mv);
7793 flatten(state, first, jmp);
7796 flatten(state, first, jmp);
7800 static void break_statement(struct compile_state *state, struct triple *first)
7802 struct triple *dest;
7803 eat(state, TOK_BREAK);
7804 eat(state, TOK_SEMI);
7805 if (!state->i_break->sym_ident) {
7806 error(state, 0, "break statement not within loop or switch");
7808 dest = state->i_break->sym_ident->def;
7809 flatten(state, first, branch(state, dest, 0));
7812 static void continue_statement(struct compile_state *state, struct triple *first)
7814 struct triple *dest;
7815 eat(state, TOK_CONTINUE);
7816 eat(state, TOK_SEMI);
7817 if (!state->i_continue->sym_ident) {
7818 error(state, 0, "continue statement outside of a loop");
7820 dest = state->i_continue->sym_ident->def;
7821 flatten(state, first, branch(state, dest, 0));
7824 static void goto_statement(struct compile_state *state, struct triple *first)
7826 struct hash_entry *ident;
7827 eat(state, TOK_GOTO);
7828 eat(state, TOK_IDENT);
7829 ident = state->token[0].ident;
7830 if (!ident->sym_label) {
7831 /* If this is a forward branch allocate the label now,
7832 * it will be flattend in the appropriate location later.
7836 label_symbol(state, ident, ins);
7838 eat(state, TOK_SEMI);
7840 flatten(state, first, branch(state, ident->sym_label->def, 0));
7843 static void labeled_statement(struct compile_state *state, struct triple *first)
7846 struct hash_entry *ident;
7847 eat(state, TOK_IDENT);
7849 ident = state->token[0].ident;
7850 if (ident->sym_label && ident->sym_label->def) {
7851 ins = ident->sym_label->def;
7852 put_occurance(ins->occurance);
7853 ins->occurance = new_occurance(state);
7857 label_symbol(state, ident, ins);
7859 if (ins->id & TRIPLE_FLAG_FLATTENED) {
7860 error(state, 0, "label %s already defined", ident->name);
7862 flatten(state, first, ins);
7864 eat(state, TOK_COLON);
7865 statement(state, first);
7868 static void switch_statement(struct compile_state *state, struct triple *first)
7871 eat(state, TOK_SWITCH);
7872 eat(state, TOK_LPAREN);
7874 eat(state, TOK_RPAREN);
7875 statement(state, first);
7876 error(state, 0, "switch statements are not implemented");
7880 static void case_statement(struct compile_state *state, struct triple *first)
7883 eat(state, TOK_CASE);
7884 constant_expr(state);
7885 eat(state, TOK_COLON);
7886 statement(state, first);
7887 error(state, 0, "case statements are not implemented");
7891 static void default_statement(struct compile_state *state, struct triple *first)
7894 eat(state, TOK_DEFAULT);
7895 eat(state, TOK_COLON);
7896 statement(state, first);
7897 error(state, 0, "default statements are not implemented");
7901 static void asm_statement(struct compile_state *state, struct triple *first)
7903 struct asm_info *info;
7905 struct triple *constraint;
7906 struct triple *expr;
7907 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7908 struct triple *def, *asm_str;
7909 int out, in, clobbers, more, colons, i;
7911 eat(state, TOK_ASM);
7912 /* For now ignore the qualifiers */
7913 switch(peek(state)) {
7915 eat(state, TOK_CONST);
7918 eat(state, TOK_VOLATILE);
7921 eat(state, TOK_LPAREN);
7922 asm_str = string_constant(state);
7925 out = in = clobbers = 0;
7927 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7928 eat(state, TOK_COLON);
7930 more = (peek(state) == TOK_LIT_STRING);
7933 struct triple *constraint;
7936 if (out > MAX_LHS) {
7937 error(state, 0, "Maximum output count exceeded.");
7939 constraint = string_constant(state);
7940 str = constraint->u.blob;
7941 if (str[0] != '=') {
7942 error(state, 0, "Output constraint does not start with =");
7944 constraint->u.blob = str + 1;
7945 eat(state, TOK_LPAREN);
7946 var = conditional_expr(state);
7947 eat(state, TOK_RPAREN);
7950 out_param[out].constraint = constraint;
7951 out_param[out].expr = var;
7952 if (peek(state) == TOK_COMMA) {
7953 eat(state, TOK_COMMA);
7960 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7961 eat(state, TOK_COLON);
7963 more = (peek(state) == TOK_LIT_STRING);
7966 struct triple *constraint;
7970 error(state, 0, "Maximum input count exceeded.");
7972 constraint = string_constant(state);
7973 str = constraint->u.blob;
7974 if (digitp(str[0] && str[1] == '\0')) {
7976 val = digval(str[0]);
7977 if ((val < 0) || (val >= out)) {
7978 error(state, 0, "Invalid input constraint %d", val);
7981 eat(state, TOK_LPAREN);
7982 val = conditional_expr(state);
7983 eat(state, TOK_RPAREN);
7985 in_param[in].constraint = constraint;
7986 in_param[in].expr = val;
7987 if (peek(state) == TOK_COMMA) {
7988 eat(state, TOK_COMMA);
7996 if ((colons == 2) && (peek(state) == TOK_COLON)) {
7997 eat(state, TOK_COLON);
7999 more = (peek(state) == TOK_LIT_STRING);
8001 struct triple *clobber;
8003 if ((clobbers + out) > MAX_LHS) {
8004 error(state, 0, "Maximum clobber limit exceeded.");
8006 clobber = string_constant(state);
8007 eat(state, TOK_RPAREN);
8009 clob_param[clobbers].constraint = clobber;
8010 if (peek(state) == TOK_COMMA) {
8011 eat(state, TOK_COMMA);
8017 eat(state, TOK_RPAREN);
8018 eat(state, TOK_SEMI);
8021 info = xcmalloc(sizeof(*info), "asm_info");
8022 info->str = asm_str->u.blob;
8023 free_triple(state, asm_str);
8025 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8026 def->u.ainfo = info;
8028 /* Find the register constraints */
8029 for(i = 0; i < out; i++) {
8030 struct triple *constraint;
8031 constraint = out_param[i].constraint;
8032 info->tmpl.lhs[i] = arch_reg_constraint(state,
8033 out_param[i].expr->type, constraint->u.blob);
8034 free_triple(state, constraint);
8036 for(; i - out < clobbers; i++) {
8037 struct triple *constraint;
8038 constraint = clob_param[i - out].constraint;
8039 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8040 free_triple(state, constraint);
8042 for(i = 0; i < in; i++) {
8043 struct triple *constraint;
8045 constraint = in_param[i].constraint;
8046 str = constraint->u.blob;
8047 if (digitp(str[0]) && str[1] == '\0') {
8048 struct reg_info cinfo;
8050 val = digval(str[0]);
8051 cinfo.reg = info->tmpl.lhs[val].reg;
8052 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8053 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8054 if (cinfo.reg == REG_UNSET) {
8055 cinfo.reg = REG_VIRT0 + val;
8057 if (cinfo.regcm == 0) {
8058 error(state, 0, "No registers for %d", val);
8060 info->tmpl.lhs[val] = cinfo;
8061 info->tmpl.rhs[i] = cinfo;
8064 info->tmpl.rhs[i] = arch_reg_constraint(state,
8065 in_param[i].expr->type, str);
8067 free_triple(state, constraint);
8070 /* Now build the helper expressions */
8071 for(i = 0; i < in; i++) {
8072 RHS(def, i) = read_expr(state,in_param[i].expr);
8074 flatten(state, first, def);
8075 for(i = 0; i < out; i++) {
8076 struct triple *piece;
8077 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8079 LHS(def, i) = piece;
8080 flatten(state, first,
8081 write_expr(state, out_param[i].expr, piece));
8083 for(; i - out < clobbers; i++) {
8084 struct triple *piece;
8085 piece = triple(state, OP_PIECE, &void_type, def, 0);
8087 LHS(def, i) = piece;
8088 flatten(state, first, piece);
8093 static int isdecl(int tok)
8116 case TOK_TYPE_NAME: /* typedef name */
8123 static void compound_statement(struct compile_state *state, struct triple *first)
8125 eat(state, TOK_LBRACE);
8128 /* statement-list opt */
8129 while (peek(state) != TOK_RBRACE) {
8130 statement(state, first);
8133 eat(state, TOK_RBRACE);
8136 static void statement(struct compile_state *state, struct triple *first)
8140 if (tok == TOK_LBRACE) {
8141 compound_statement(state, first);
8143 else if (tok == TOK_IF) {
8144 if_statement(state, first);
8146 else if (tok == TOK_FOR) {
8147 for_statement(state, first);
8149 else if (tok == TOK_WHILE) {
8150 while_statement(state, first);
8152 else if (tok == TOK_DO) {
8153 do_statement(state, first);
8155 else if (tok == TOK_RETURN) {
8156 return_statement(state, first);
8158 else if (tok == TOK_BREAK) {
8159 break_statement(state, first);
8161 else if (tok == TOK_CONTINUE) {
8162 continue_statement(state, first);
8164 else if (tok == TOK_GOTO) {
8165 goto_statement(state, first);
8167 else if (tok == TOK_SWITCH) {
8168 switch_statement(state, first);
8170 else if (tok == TOK_ASM) {
8171 asm_statement(state, first);
8173 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8174 labeled_statement(state, first);
8176 else if (tok == TOK_CASE) {
8177 case_statement(state, first);
8179 else if (tok == TOK_DEFAULT) {
8180 default_statement(state, first);
8182 else if (isdecl(tok)) {
8183 /* This handles C99 intermixing of statements and decls */
8187 expr_statement(state, first);
8191 static struct type *param_decl(struct compile_state *state)
8194 struct hash_entry *ident;
8195 /* Cheat so the declarator will know we are not global */
8198 type = decl_specifiers(state);
8199 type = declarator(state, type, &ident, 0);
8200 type->field_ident = ident;
8205 static struct type *param_type_list(struct compile_state *state, struct type *type)
8207 struct type *ftype, **next;
8208 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8209 next = &ftype->right;
8210 while(peek(state) == TOK_COMMA) {
8211 eat(state, TOK_COMMA);
8212 if (peek(state) == TOK_DOTS) {
8213 eat(state, TOK_DOTS);
8214 error(state, 0, "variadic functions not supported");
8217 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8218 next = &((*next)->right);
8225 static struct type *type_name(struct compile_state *state)
8228 type = specifier_qualifier_list(state);
8229 /* abstract-declarator (may consume no tokens) */
8230 type = declarator(state, type, 0, 0);
8234 static struct type *direct_declarator(
8235 struct compile_state *state, struct type *type,
8236 struct hash_entry **ident, int need_ident)
8241 arrays_complete(state, type);
8242 switch(peek(state)) {
8244 eat(state, TOK_IDENT);
8246 error(state, 0, "Unexpected identifier found");
8248 /* The name of what we are declaring */
8249 *ident = state->token[0].ident;
8252 eat(state, TOK_LPAREN);
8253 outer = declarator(state, type, ident, need_ident);
8254 eat(state, TOK_RPAREN);
8258 error(state, 0, "Identifier expected");
8264 arrays_complete(state, type);
8265 switch(peek(state)) {
8267 eat(state, TOK_LPAREN);
8268 type = param_type_list(state, type);
8269 eat(state, TOK_RPAREN);
8273 unsigned int qualifiers;
8274 struct triple *value;
8276 eat(state, TOK_LBRACKET);
8277 if (peek(state) != TOK_RBRACKET) {
8278 value = constant_expr(state);
8279 integral(state, value);
8281 eat(state, TOK_RBRACKET);
8283 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8284 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8286 type->elements = value->u.cval;
8287 free_triple(state, value);
8289 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8301 arrays_complete(state, type);
8303 for(inner = outer; inner->left; inner = inner->left)
8311 static struct type *declarator(
8312 struct compile_state *state, struct type *type,
8313 struct hash_entry **ident, int need_ident)
8315 while(peek(state) == TOK_STAR) {
8316 eat(state, TOK_STAR);
8317 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8319 type = direct_declarator(state, type, ident, need_ident);
8324 static struct type *typedef_name(
8325 struct compile_state *state, unsigned int specifiers)
8327 struct hash_entry *ident;
8329 eat(state, TOK_TYPE_NAME);
8330 ident = state->token[0].ident;
8331 type = ident->sym_ident->type;
8332 specifiers |= type->type & QUAL_MASK;
8333 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8334 (type->type & (STOR_MASK | QUAL_MASK))) {
8335 type = clone_type(specifiers, type);
8340 static struct type *enum_specifier(
8341 struct compile_state *state, unsigned int specifiers)
8347 eat(state, TOK_ENUM);
8349 if (tok == TOK_IDENT) {
8350 eat(state, TOK_IDENT);
8352 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8353 eat(state, TOK_LBRACE);
8355 eat(state, TOK_IDENT);
8356 if (peek(state) == TOK_EQ) {
8358 constant_expr(state);
8360 if (peek(state) == TOK_COMMA) {
8361 eat(state, TOK_COMMA);
8363 } while(peek(state) != TOK_RBRACE);
8364 eat(state, TOK_RBRACE);
8371 static struct type *struct_declarator(
8372 struct compile_state *state, struct type *type, struct hash_entry **ident)
8375 #warning "struct_declarator is complicated because of bitfields, kill them?"
8377 if (tok != TOK_COLON) {
8378 type = declarator(state, type, ident, 1);
8380 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8381 eat(state, TOK_COLON);
8382 constant_expr(state);
8389 static struct type *struct_or_union_specifier(
8390 struct compile_state *state, unsigned int spec)
8392 struct type *struct_type;
8393 struct hash_entry *ident;
8394 unsigned int type_join;
8398 switch(peek(state)) {
8400 eat(state, TOK_STRUCT);
8401 type_join = TYPE_PRODUCT;
8404 eat(state, TOK_UNION);
8405 type_join = TYPE_OVERLAP;
8406 error(state, 0, "unions not yet supported\n");
8409 eat(state, TOK_STRUCT);
8410 type_join = TYPE_PRODUCT;
8414 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8416 ident = state->token[0].ident;
8418 if (!ident || (peek(state) == TOK_LBRACE)) {
8421 eat(state, TOK_LBRACE);
8423 struct type *base_type;
8426 base_type = specifier_qualifier_list(state);
8427 next = &struct_type;
8430 struct hash_entry *fident;
8432 type = declarator(state, base_type, &fident, 1);
8434 if (peek(state) == TOK_COMMA) {
8436 eat(state, TOK_COMMA);
8438 type = clone_type(0, type);
8439 type->field_ident = fident;
8441 *next = new_type(type_join, *next, type);
8442 next = &((*next)->right);
8447 eat(state, TOK_SEMI);
8448 } while(peek(state) != TOK_RBRACE);
8449 eat(state, TOK_RBRACE);
8450 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8451 struct_type->type_ident = ident;
8452 struct_type->elements = elements;
8453 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8455 if (ident && ident->sym_struct) {
8456 struct_type = clone_type(spec, ident->sym_struct->type);
8458 else if (ident && !ident->sym_struct) {
8459 error(state, 0, "struct %s undeclared", ident->name);
8464 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8466 unsigned int specifiers;
8467 switch(peek(state)) {
8469 eat(state, TOK_AUTO);
8470 specifiers = STOR_AUTO;
8473 eat(state, TOK_REGISTER);
8474 specifiers = STOR_REGISTER;
8477 eat(state, TOK_STATIC);
8478 specifiers = STOR_STATIC;
8481 eat(state, TOK_EXTERN);
8482 specifiers = STOR_EXTERN;
8485 eat(state, TOK_TYPEDEF);
8486 specifiers = STOR_TYPEDEF;
8489 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8490 specifiers = STOR_STATIC;
8493 specifiers = STOR_AUTO;
8499 static unsigned int function_specifier_opt(struct compile_state *state)
8501 /* Ignore the inline keyword */
8502 unsigned int specifiers;
8504 switch(peek(state)) {
8506 eat(state, TOK_INLINE);
8507 specifiers = STOR_INLINE;
8512 static unsigned int type_qualifiers(struct compile_state *state)
8514 unsigned int specifiers;
8517 specifiers = QUAL_NONE;
8519 switch(peek(state)) {
8521 eat(state, TOK_CONST);
8522 specifiers = QUAL_CONST;
8525 eat(state, TOK_VOLATILE);
8526 specifiers = QUAL_VOLATILE;
8529 eat(state, TOK_RESTRICT);
8530 specifiers = QUAL_RESTRICT;
8540 static struct type *type_specifier(
8541 struct compile_state *state, unsigned int spec)
8545 switch(peek(state)) {
8547 eat(state, TOK_VOID);
8548 type = new_type(TYPE_VOID | spec, 0, 0);
8551 eat(state, TOK_CHAR);
8552 type = new_type(TYPE_CHAR | spec, 0, 0);
8555 eat(state, TOK_SHORT);
8556 if (peek(state) == TOK_INT) {
8557 eat(state, TOK_INT);
8559 type = new_type(TYPE_SHORT | spec, 0, 0);
8562 eat(state, TOK_INT);
8563 type = new_type(TYPE_INT | spec, 0, 0);
8566 eat(state, TOK_LONG);
8567 switch(peek(state)) {
8569 eat(state, TOK_LONG);
8570 error(state, 0, "long long not supported");
8573 eat(state, TOK_DOUBLE);
8574 error(state, 0, "long double not supported");
8577 eat(state, TOK_INT);
8578 type = new_type(TYPE_LONG | spec, 0, 0);
8581 type = new_type(TYPE_LONG | spec, 0, 0);
8586 eat(state, TOK_FLOAT);
8587 error(state, 0, "type float not supported");
8590 eat(state, TOK_DOUBLE);
8591 error(state, 0, "type double not supported");
8594 eat(state, TOK_SIGNED);
8595 switch(peek(state)) {
8597 eat(state, TOK_LONG);
8598 switch(peek(state)) {
8600 eat(state, TOK_LONG);
8601 error(state, 0, "type long long not supported");
8604 eat(state, TOK_INT);
8605 type = new_type(TYPE_LONG | spec, 0, 0);
8608 type = new_type(TYPE_LONG | spec, 0, 0);
8613 eat(state, TOK_INT);
8614 type = new_type(TYPE_INT | spec, 0, 0);
8617 eat(state, TOK_SHORT);
8618 type = new_type(TYPE_SHORT | spec, 0, 0);
8621 eat(state, TOK_CHAR);
8622 type = new_type(TYPE_CHAR | spec, 0, 0);
8625 type = new_type(TYPE_INT | spec, 0, 0);
8630 eat(state, TOK_UNSIGNED);
8631 switch(peek(state)) {
8633 eat(state, TOK_LONG);
8634 switch(peek(state)) {
8636 eat(state, TOK_LONG);
8637 error(state, 0, "unsigned long long not supported");
8640 eat(state, TOK_INT);
8641 type = new_type(TYPE_ULONG | spec, 0, 0);
8644 type = new_type(TYPE_ULONG | spec, 0, 0);
8649 eat(state, TOK_INT);
8650 type = new_type(TYPE_UINT | spec, 0, 0);
8653 eat(state, TOK_SHORT);
8654 type = new_type(TYPE_USHORT | spec, 0, 0);
8657 eat(state, TOK_CHAR);
8658 type = new_type(TYPE_UCHAR | spec, 0, 0);
8661 type = new_type(TYPE_UINT | spec, 0, 0);
8665 /* struct or union specifier */
8668 type = struct_or_union_specifier(state, spec);
8670 /* enum-spefifier */
8672 type = enum_specifier(state, spec);
8676 type = typedef_name(state, spec);
8679 error(state, 0, "bad type specifier %s",
8680 tokens[peek(state)]);
8686 static int istype(int tok)
8712 static struct type *specifier_qualifier_list(struct compile_state *state)
8715 unsigned int specifiers = 0;
8717 /* type qualifiers */
8718 specifiers |= type_qualifiers(state);
8720 /* type specifier */
8721 type = type_specifier(state, specifiers);
8726 static int isdecl_specifier(int tok)
8729 /* storage class specifier */
8735 /* type qualifier */
8739 /* type specifiers */
8749 /* struct or union specifier */
8752 /* enum-spefifier */
8756 /* function specifiers */
8764 static struct type *decl_specifiers(struct compile_state *state)
8767 unsigned int specifiers;
8768 /* I am overly restrictive in the arragement of specifiers supported.
8769 * C is overly flexible in this department it makes interpreting
8770 * the parse tree difficult.
8774 /* storage class specifier */
8775 specifiers |= storage_class_specifier_opt(state);
8777 /* function-specifier */
8778 specifiers |= function_specifier_opt(state);
8780 /* type qualifier */
8781 specifiers |= type_qualifiers(state);
8783 /* type specifier */
8784 type = type_specifier(state, specifiers);
8793 static struct field_info designator(struct compile_state *state, struct type *type)
8796 struct field_info info;
8800 switch(peek(state)) {
8803 struct triple *value;
8804 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8805 error(state, 0, "Array designator not in array initializer");
8807 eat(state, TOK_LBRACKET);
8808 value = constant_expr(state);
8809 eat(state, TOK_RBRACKET);
8811 info.type = type->left;
8812 info.offset = value->u.cval * size_of(state, info.type);
8817 struct hash_entry *field;
8818 struct type *member;
8819 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8820 error(state, 0, "Struct designator not in struct initializer");
8822 eat(state, TOK_DOT);
8823 eat(state, TOK_IDENT);
8824 field = state->token[0].ident;
8826 member = type->left;
8827 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
8828 if (member->left->field_ident == field) {
8829 member = member->left;
8832 info.offset += size_of(state, member->left);
8833 member = member->right;
8835 if (member->field_ident != field) {
8836 error(state, 0, "%s is not a member",
8843 error(state, 0, "Invalid designator");
8846 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8851 static struct triple *initializer(
8852 struct compile_state *state, struct type *type)
8854 struct triple *result;
8855 if (peek(state) != TOK_LBRACE) {
8856 result = assignment_expr(state);
8861 struct field_info info;
8863 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8864 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8865 internal_error(state, 0, "unknown initializer type");
8868 info.type = type->left;
8869 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8872 max_offset = size_of(state, type);
8874 buf = xcmalloc(max_offset, "initializer");
8875 eat(state, TOK_LBRACE);
8877 struct triple *value;
8878 struct type *value_type;
8884 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8885 info = designator(state, type);
8887 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8888 (info.offset >= max_offset)) {
8889 error(state, 0, "element beyond bounds");
8891 value_type = info.type;
8892 if ((value_type->type & TYPE_MASK) == TYPE_PRODUCT) {
8893 value_type = type->left;
8895 value = eval_const_expr(state, initializer(state, value_type));
8896 value_size = size_of(state, value_type);
8897 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8898 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8899 (max_offset <= info.offset)) {
8903 old_size = max_offset;
8904 max_offset = info.offset + value_size;
8905 buf = xmalloc(max_offset, "initializer");
8906 memcpy(buf, old_buf, old_size);
8909 dest = ((char *)buf) + info.offset;
8910 if (value->op == OP_BLOBCONST) {
8911 memcpy(dest, value->u.blob, value_size);
8913 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8914 *((uint8_t *)dest) = value->u.cval & 0xff;
8916 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8917 *((uint16_t *)dest) = value->u.cval & 0xffff;
8919 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8920 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8923 fprintf(stderr, "%d %d\n",
8924 value->op, value_size);
8925 internal_error(state, 0, "unhandled constant initializer");
8927 free_triple(state, value);
8928 if (peek(state) == TOK_COMMA) {
8929 eat(state, TOK_COMMA);
8932 info.offset += value_size;
8933 if ((info.type->type & TYPE_MASK) == TYPE_PRODUCT) {
8934 info.type = info.type->right;
8936 } while(comma && (peek(state) != TOK_RBRACE));
8937 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8938 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8939 type->elements = max_offset / size_of(state, type->left);
8941 eat(state, TOK_RBRACE);
8942 result = triple(state, OP_BLOBCONST, type, 0, 0);
8943 result->u.blob = buf;
8948 static void resolve_branches(struct compile_state *state)
8950 /* Make a second pass and finish anything outstanding
8951 * with respect to branches. The only outstanding item
8952 * is to see if there are goto to labels that have not
8953 * been defined and to error about them.
8956 for(i = 0; i < HASH_TABLE_SIZE; i++) {
8957 struct hash_entry *entry;
8958 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8960 if (!entry->sym_label) {
8963 ins = entry->sym_label->def;
8964 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8965 error(state, ins, "label `%s' used but not defined",
8972 static struct triple *function_definition(
8973 struct compile_state *state, struct type *type)
8975 struct triple *def, *tmp, *first, *end;
8976 struct hash_entry *ident;
8979 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8980 error(state, 0, "Invalid function header");
8983 /* Verify the function type */
8984 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8985 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8986 (type->right->field_ident == 0)) {
8987 error(state, 0, "Invalid function parameters");
8989 param = type->right;
8991 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8993 if (!param->left->field_ident) {
8994 error(state, 0, "No identifier for parameter %d\n", i);
8996 param = param->right;
8999 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9000 error(state, 0, "No identifier for paramter %d\n", i);
9003 /* Get a list of statements for this function. */
9004 def = triple(state, OP_LIST, type, 0, 0);
9006 /* Start a new scope for the passed parameters */
9009 /* Put a label at the very start of a function */
9010 first = label(state);
9011 RHS(def, 0) = first;
9013 /* Put a label at the very end of a function */
9015 flatten(state, first, end);
9017 /* Walk through the parameters and create symbol table entries
9020 param = type->right;
9021 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9022 ident = param->left->field_ident;
9023 tmp = variable(state, param->left);
9024 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9025 flatten(state, end, tmp);
9026 param = param->right;
9028 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9029 /* And don't forget the last parameter */
9030 ident = param->field_ident;
9031 tmp = variable(state, param);
9032 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9033 flatten(state, end, tmp);
9035 /* Add a variable for the return value */
9037 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9038 /* Remove all type qualifiers from the return type */
9039 tmp = variable(state, clone_type(0, type->left));
9040 flatten(state, end, tmp);
9041 /* Remember where the return value is */
9045 /* Remember which function I am compiling.
9046 * Also assume the last defined function is the main function.
9048 state->main_function = def;
9050 /* Now get the actual function definition */
9051 compound_statement(state, end);
9053 /* Finish anything unfinished with branches */
9054 resolve_branches(state);
9056 /* Remove the parameter scope */
9060 fprintf(stdout, "\n");
9061 loc(stdout, state, 0);
9062 fprintf(stdout, "\n__________ function_definition _________\n");
9063 print_triple(state, def);
9064 fprintf(stdout, "__________ function_definition _________ done\n\n");
9070 static struct triple *do_decl(struct compile_state *state,
9071 struct type *type, struct hash_entry *ident)
9075 /* Clean up the storage types used */
9076 switch (type->type & STOR_MASK) {
9079 /* These are the good types I am aiming for */
9082 type->type &= ~STOR_MASK;
9083 type->type |= STOR_AUTO;
9086 type->type &= ~STOR_MASK;
9087 type->type |= STOR_STATIC;
9091 error(state, 0, "typedef without name");
9093 symbol(state, ident, &ident->sym_ident, 0, type);
9094 ident->tok = TOK_TYPE_NAME;
9098 internal_error(state, 0, "Undefined storage class");
9101 ((type->type & STOR_MASK) == STOR_STATIC) &&
9102 ((type->type & QUAL_CONST) == 0)) {
9103 error(state, 0, "non const static variables not supported");
9106 def = variable(state, type);
9107 symbol(state, ident, &ident->sym_ident, def, type);
9112 static void decl(struct compile_state *state, struct triple *first)
9114 struct type *base_type, *type;
9115 struct hash_entry *ident;
9118 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9119 base_type = decl_specifiers(state);
9121 type = declarator(state, base_type, &ident, 0);
9122 if (global && ident && (peek(state) == TOK_LBRACE)) {
9124 state->function = ident->name;
9125 def = function_definition(state, type);
9126 symbol(state, ident, &ident->sym_ident, def, type);
9127 state->function = 0;
9131 flatten(state, first, do_decl(state, type, ident));
9132 /* type or variable definition */
9135 if (peek(state) == TOK_EQ) {
9137 error(state, 0, "cannot assign to a type");
9140 flatten(state, first,
9142 ident->sym_ident->def,
9143 initializer(state, type)));
9145 arrays_complete(state, type);
9146 if (peek(state) == TOK_COMMA) {
9147 eat(state, TOK_COMMA);
9149 type = declarator(state, base_type, &ident, 0);
9150 flatten(state, first, do_decl(state, type, ident));
9154 eat(state, TOK_SEMI);
9158 static void decls(struct compile_state *state)
9160 struct triple *list;
9162 list = label(state);
9165 if (tok == TOK_EOF) {
9168 if (tok == TOK_SPACE) {
9169 eat(state, TOK_SPACE);
9172 if (list->next != list) {
9173 error(state, 0, "global variables not supported");
9179 * Data structurs for optimation.
9182 static void do_use_block(
9183 struct block *used, struct block_set **head, struct block *user,
9186 struct block_set **ptr, *new;
9193 if ((*ptr)->member == user) {
9196 ptr = &(*ptr)->next;
9198 new = xcmalloc(sizeof(*new), "block_set");
9209 static void do_unuse_block(
9210 struct block *used, struct block_set **head, struct block *unuser)
9212 struct block_set *use, **ptr;
9216 if (use->member == unuser) {
9218 memset(use, -1, sizeof(*use));
9227 static void use_block(struct block *used, struct block *user)
9229 /* Append new to the head of the list, print_block
9232 do_use_block(used, &used->use, user, 1);
9235 static void unuse_block(struct block *used, struct block *unuser)
9237 do_unuse_block(used, &used->use, unuser);
9241 static void idom_block(struct block *idom, struct block *user)
9243 do_use_block(idom, &idom->idominates, user, 0);
9246 static void unidom_block(struct block *idom, struct block *unuser)
9248 do_unuse_block(idom, &idom->idominates, unuser);
9251 static void domf_block(struct block *block, struct block *domf)
9253 do_use_block(block, &block->domfrontier, domf, 0);
9256 static void undomf_block(struct block *block, struct block *undomf)
9258 do_unuse_block(block, &block->domfrontier, undomf);
9261 static void ipdom_block(struct block *ipdom, struct block *user)
9263 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9266 static void unipdom_block(struct block *ipdom, struct block *unuser)
9268 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9271 static void ipdomf_block(struct block *block, struct block *ipdomf)
9273 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9276 static void unipdomf_block(struct block *block, struct block *unipdomf)
9278 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9283 static int do_walk_triple(struct compile_state *state,
9284 struct triple *ptr, int depth,
9285 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9288 result = cb(state, ptr, depth);
9289 if ((result == 0) && (ptr->op == OP_LIST)) {
9290 struct triple *list;
9294 result = do_walk_triple(state, ptr, depth + 1, cb);
9295 if (ptr->next->prev != ptr) {
9296 internal_error(state, ptr->next, "bad prev");
9300 } while((result == 0) && (ptr != RHS(list, 0)));
9305 static int walk_triple(
9306 struct compile_state *state,
9308 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9310 return do_walk_triple(state, ptr, 0, cb);
9313 static void do_print_prefix(int depth)
9316 for(i = 0; i < depth; i++) {
9321 #define PRINT_LIST 1
9322 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9326 if (op == OP_LIST) {
9331 if ((op == OP_LABEL) && (ins->use)) {
9332 printf("\n%p:\n", ins);
9334 do_print_prefix(depth);
9335 display_triple(stdout, ins);
9337 if ((ins->op == OP_BRANCH) && ins->use) {
9338 internal_error(state, ins, "branch used?");
9342 struct triple_set *user;
9343 for(user = ins->use; user; user = user->next) {
9344 printf("use: %p\n", user->member);
9348 if (triple_is_branch(state, ins)) {
9354 static void print_triple(struct compile_state *state, struct triple *ins)
9356 walk_triple(state, ins, do_print_triple);
9359 static void print_triples(struct compile_state *state)
9361 print_triple(state, state->main_function);
9365 struct block *block;
9367 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9369 if (!block || (cf[block->vertex].block == block)) {
9372 cf[block->vertex].block = block;
9373 find_cf_blocks(cf, block->left);
9374 find_cf_blocks(cf, block->right);
9377 static void print_control_flow(struct compile_state *state)
9379 struct cf_block *cf;
9381 printf("\ncontrol flow\n");
9382 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9383 find_cf_blocks(cf, state->first_block);
9385 for(i = 1; i <= state->last_vertex; i++) {
9386 struct block *block;
9387 block = cf[i].block;
9390 printf("(%p) %d:", block, block->vertex);
9392 printf(" %d", block->left->vertex);
9394 if (block->right && (block->right != block->left)) {
9395 printf(" %d", block->right->vertex);
9404 static struct block *basic_block(struct compile_state *state,
9405 struct triple *first)
9407 struct block *block;
9410 if (first->op != OP_LABEL) {
9411 internal_error(state, 0, "block does not start with a label");
9413 /* See if this basic block has already been setup */
9414 if (first->u.block != 0) {
9415 return first->u.block;
9417 /* Allocate another basic block structure */
9418 state->last_vertex += 1;
9419 block = xcmalloc(sizeof(*block), "block");
9420 block->first = block->last = first;
9421 block->vertex = state->last_vertex;
9424 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9428 /* If ptr->u is not used remember where the baic block is */
9429 if (triple_stores_block(state, ptr)) {
9430 ptr->u.block = block;
9432 if (ptr->op == OP_BRANCH) {
9436 } while (ptr != RHS(state->main_function, 0));
9437 if (ptr == RHS(state->main_function, 0))
9440 if (op == OP_LABEL) {
9441 block->left = basic_block(state, ptr);
9443 use_block(block->left, block);
9445 else if (op == OP_BRANCH) {
9447 /* Trace the branch target */
9448 block->right = basic_block(state, TARG(ptr, 0));
9449 use_block(block->right, block);
9450 /* If there is a test trace the branch as well */
9451 if (TRIPLE_RHS(ptr->sizes)) {
9452 block->left = basic_block(state, ptr->next);
9453 use_block(block->left, block);
9457 internal_error(state, 0, "Bad basic block split");
9463 static void walk_blocks(struct compile_state *state,
9464 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9467 struct triple *ptr, *first;
9468 struct block *last_block;
9470 first = RHS(state->main_function, 0);
9473 struct block *block;
9474 if (ptr->op == OP_LABEL) {
9475 block = ptr->u.block;
9476 if (block && (block != last_block)) {
9477 cb(state, block, arg);
9482 } while(ptr != first);
9485 static void print_block(
9486 struct compile_state *state, struct block *block, void *arg)
9491 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9495 block->left && block->left->use?block->left->use->member : 0,
9497 block->right && block->right->use?block->right->use->member : 0);
9498 if (block->first->op == OP_LABEL) {
9499 fprintf(fp, "%p:\n", block->first);
9501 for(ptr = block->first; ; ptr = ptr->next) {
9502 struct triple_set *user;
9505 if (triple_stores_block(state, ptr)) {
9506 if (ptr->u.block != block) {
9507 internal_error(state, ptr,
9508 "Wrong block pointer: %p\n",
9512 if (op == OP_ADECL) {
9513 for(user = ptr->use; user; user = user->next) {
9514 if (!user->member->u.block) {
9515 internal_error(state, user->member,
9516 "Use %p not in a block?\n",
9521 display_triple(fp, ptr);
9524 for(user = ptr->use; user; user = user->next) {
9525 fprintf(fp, "use: %p\n", user->member);
9529 /* Sanity checks... */
9530 valid_ins(state, ptr);
9531 for(user = ptr->use; user; user = user->next) {
9534 valid_ins(state, use);
9535 if (triple_stores_block(state, user->member) &&
9536 !user->member->u.block) {
9537 internal_error(state, user->member,
9538 "Use %p not in a block?",
9543 if (ptr == block->last)
9550 static void print_blocks(struct compile_state *state, FILE *fp)
9552 fprintf(fp, "--------------- blocks ---------------\n");
9553 walk_blocks(state, print_block, fp);
9556 static void prune_nonblock_triples(struct compile_state *state)
9558 struct block *block;
9559 struct triple *first, *ins, *next;
9560 /* Delete the triples not in a basic block */
9561 first = RHS(state->main_function, 0);
9566 if (ins->op == OP_LABEL) {
9567 block = ins->u.block;
9570 release_triple(state, ins);
9573 } while(ins != first);
9576 static void setup_basic_blocks(struct compile_state *state)
9578 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9579 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9580 internal_error(state, 0, "ins will not store block?");
9582 /* Find the basic blocks */
9583 state->last_vertex = 0;
9584 state->first_block = basic_block(state, RHS(state->main_function,0));
9585 /* Delete the triples not in a basic block */
9586 prune_nonblock_triples(state);
9587 /* Find the last basic block */
9588 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9589 if (!state->last_block) {
9590 internal_error(state, 0, "end not used?");
9592 /* Insert an extra unused edge from start to the end
9593 * This helps with reverse control flow calculations.
9595 use_block(state->first_block, state->last_block);
9596 /* If we are debugging print what I have just done */
9597 if (state->debug & DEBUG_BASIC_BLOCKS) {
9598 print_blocks(state, stdout);
9599 print_control_flow(state);
9603 static void free_basic_block(struct compile_state *state, struct block *block)
9605 struct block_set *entry, *next;
9606 struct block *child;
9610 if (block->vertex == -1) {
9615 unuse_block(block->left, block);
9618 unuse_block(block->right, block);
9621 unidom_block(block->idom, block);
9625 unipdom_block(block->ipdom, block);
9628 for(entry = block->use; entry; entry = next) {
9630 child = entry->member;
9631 unuse_block(block, child);
9632 if (child->left == block) {
9635 if (child->right == block) {
9639 for(entry = block->idominates; entry; entry = next) {
9641 child = entry->member;
9642 unidom_block(block, child);
9645 for(entry = block->domfrontier; entry; entry = next) {
9647 child = entry->member;
9648 undomf_block(block, child);
9650 for(entry = block->ipdominates; entry; entry = next) {
9652 child = entry->member;
9653 unipdom_block(block, child);
9656 for(entry = block->ipdomfrontier; entry; entry = next) {
9658 child = entry->member;
9659 unipdomf_block(block, child);
9661 if (block->users != 0) {
9662 internal_error(state, 0, "block still has users");
9664 free_basic_block(state, block->left);
9666 free_basic_block(state, block->right);
9668 memset(block, -1, sizeof(*block));
9672 static void free_basic_blocks(struct compile_state *state)
9674 struct triple *first, *ins;
9675 free_basic_block(state, state->first_block);
9676 state->last_vertex = 0;
9677 state->first_block = state->last_block = 0;
9678 first = RHS(state->main_function, 0);
9681 if (triple_stores_block(state, ins)) {
9685 } while(ins != first);
9690 struct block *block;
9691 struct sdom_block *sdominates;
9692 struct sdom_block *sdom_next;
9693 struct sdom_block *sdom;
9694 struct sdom_block *label;
9695 struct sdom_block *parent;
9696 struct sdom_block *ancestor;
9701 static void unsdom_block(struct sdom_block *block)
9703 struct sdom_block **ptr;
9704 if (!block->sdom_next) {
9707 ptr = &block->sdom->sdominates;
9709 if ((*ptr) == block) {
9710 *ptr = block->sdom_next;
9713 ptr = &(*ptr)->sdom_next;
9717 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9719 unsdom_block(block);
9721 block->sdom_next = sdom->sdominates;
9722 sdom->sdominates = block;
9727 static int initialize_sdblock(struct sdom_block *sd,
9728 struct block *parent, struct block *block, int vertex)
9730 if (!block || (sd[block->vertex].block == block)) {
9734 /* Renumber the blocks in a convinient fashion */
9735 block->vertex = vertex;
9736 sd[vertex].block = block;
9737 sd[vertex].sdom = &sd[vertex];
9738 sd[vertex].label = &sd[vertex];
9739 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9740 sd[vertex].ancestor = 0;
9741 sd[vertex].vertex = vertex;
9742 vertex = initialize_sdblock(sd, block, block->left, vertex);
9743 vertex = initialize_sdblock(sd, block, block->right, vertex);
9747 static int initialize_sdpblock(struct sdom_block *sd,
9748 struct block *parent, struct block *block, int vertex)
9750 struct block_set *user;
9751 if (!block || (sd[block->vertex].block == block)) {
9755 /* Renumber the blocks in a convinient fashion */
9756 block->vertex = vertex;
9757 sd[vertex].block = block;
9758 sd[vertex].sdom = &sd[vertex];
9759 sd[vertex].label = &sd[vertex];
9760 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9761 sd[vertex].ancestor = 0;
9762 sd[vertex].vertex = vertex;
9763 for(user = block->use; user; user = user->next) {
9764 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9769 static void compress_ancestors(struct sdom_block *v)
9771 /* This procedure assumes ancestor(v) != 0 */
9772 /* if (ancestor(ancestor(v)) != 0) {
9773 * compress(ancestor(ancestor(v)));
9774 * if (semi(label(ancestor(v))) < semi(label(v))) {
9775 * label(v) = label(ancestor(v));
9777 * ancestor(v) = ancestor(ancestor(v));
9783 if (v->ancestor->ancestor) {
9784 compress_ancestors(v->ancestor->ancestor);
9785 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9786 v->label = v->ancestor->label;
9788 v->ancestor = v->ancestor->ancestor;
9792 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9796 * for each v <= pred(w) {
9798 * if (semi[u] < semi[w] {
9799 * semi[w] = semi[u];
9802 * add w to bucket(vertex(semi[w]));
9803 * LINK(parent(w), w);
9806 * for each v <= bucket(parent(w)) {
9807 * delete v from bucket(parent(w));
9809 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9812 for(i = state->last_vertex; i >= 2; i--) {
9813 struct sdom_block *v, *parent, *next;
9814 struct block_set *user;
9815 struct block *block;
9816 block = sd[i].block;
9817 parent = sd[i].parent;
9819 for(user = block->use; user; user = user->next) {
9820 struct sdom_block *v, *u;
9821 v = &sd[user->member->vertex];
9822 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9823 if (u->sdom->vertex < sd[i].sdom->vertex) {
9824 sd[i].sdom = u->sdom;
9827 sdom_block(sd[i].sdom, &sd[i]);
9828 sd[i].ancestor = parent;
9830 for(v = parent->sdominates; v; v = next) {
9831 struct sdom_block *u;
9832 next = v->sdom_next;
9834 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9835 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9836 u->block : parent->block;
9841 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9845 * for each v <= pred(w) {
9847 * if (semi[u] < semi[w] {
9848 * semi[w] = semi[u];
9851 * add w to bucket(vertex(semi[w]));
9852 * LINK(parent(w), w);
9855 * for each v <= bucket(parent(w)) {
9856 * delete v from bucket(parent(w));
9858 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9861 for(i = state->last_vertex; i >= 2; i--) {
9862 struct sdom_block *u, *v, *parent, *next;
9863 struct block *block;
9864 block = sd[i].block;
9865 parent = sd[i].parent;
9868 v = &sd[block->left->vertex];
9869 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9870 if (u->sdom->vertex < sd[i].sdom->vertex) {
9871 sd[i].sdom = u->sdom;
9874 if (block->right && (block->right != block->left)) {
9875 v = &sd[block->right->vertex];
9876 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9877 if (u->sdom->vertex < sd[i].sdom->vertex) {
9878 sd[i].sdom = u->sdom;
9881 sdom_block(sd[i].sdom, &sd[i]);
9882 sd[i].ancestor = parent;
9884 for(v = parent->sdominates; v; v = next) {
9885 struct sdom_block *u;
9886 next = v->sdom_next;
9888 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9889 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9890 u->block : parent->block;
9895 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9898 for(i = 2; i <= state->last_vertex; i++) {
9899 struct block *block;
9900 block = sd[i].block;
9901 if (block->idom->vertex != sd[i].sdom->vertex) {
9902 block->idom = block->idom->idom;
9904 idom_block(block->idom, block);
9906 sd[1].block->idom = 0;
9909 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9912 for(i = 2; i <= state->last_vertex; i++) {
9913 struct block *block;
9914 block = sd[i].block;
9915 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9916 block->ipdom = block->ipdom->ipdom;
9918 ipdom_block(block->ipdom, block);
9920 sd[1].block->ipdom = 0;
9924 * Every vertex of a flowgraph G = (V, E, r) except r has
9925 * a unique immediate dominator.
9926 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9927 * rooted at r, called the dominator tree of G, such that
9928 * v dominates w if and only if v is a proper ancestor of w in
9929 * the dominator tree.
9932 * If v and w are vertices of G such that v <= w,
9933 * than any path from v to w must contain a common ancestor
9936 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9937 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9938 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9940 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9941 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9944 * Let w != r and let u be a vertex for which sdom(u) is
9945 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9946 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9948 /* Lemma 5: Let vertices v,w satisfy v -> w.
9949 * Then v -> idom(w) or idom(w) -> idom(v)
9952 static void find_immediate_dominators(struct compile_state *state)
9954 struct sdom_block *sd;
9955 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9956 * vi > w for (1 <= i <= k - 1}
9959 * For any vertex w != r.
9961 * {v|(v,w) <= E and v < w } U
9962 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9965 * Let w != r and let u be a vertex for which sdom(u) is
9966 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9968 * { sdom(w) if sdom(w) = sdom(u),
9970 * { idom(u) otherwise
9972 /* The algorithm consists of the following 4 steps.
9973 * Step 1. Carry out a depth-first search of the problem graph.
9974 * Number the vertices from 1 to N as they are reached during
9975 * the search. Initialize the variables used in succeeding steps.
9976 * Step 2. Compute the semidominators of all vertices by applying
9977 * theorem 4. Carry out the computation vertex by vertex in
9978 * decreasing order by number.
9979 * Step 3. Implicitly define the immediate dominator of each vertex
9980 * by applying Corollary 1.
9981 * Step 4. Explicitly define the immediate dominator of each vertex,
9982 * carrying out the computation vertex by vertex in increasing order
9985 /* Step 1 initialize the basic block information */
9986 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9987 initialize_sdblock(sd, 0, state->first_block, 0);
9993 /* Step 2 compute the semidominators */
9994 /* Step 3 implicitly define the immediate dominator of each vertex */
9995 compute_sdom(state, sd);
9996 /* Step 4 explicitly define the immediate dominator of each vertex */
9997 compute_idom(state, sd);
10001 static void find_post_dominators(struct compile_state *state)
10003 struct sdom_block *sd;
10004 /* Step 1 initialize the basic block information */
10005 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10007 initialize_sdpblock(sd, 0, state->last_block, 0);
10009 /* Step 2 compute the semidominators */
10010 /* Step 3 implicitly define the immediate dominator of each vertex */
10011 compute_spdom(state, sd);
10012 /* Step 4 explicitly define the immediate dominator of each vertex */
10013 compute_ipdom(state, sd);
10019 static void find_block_domf(struct compile_state *state, struct block *block)
10021 struct block *child;
10022 struct block_set *user;
10023 if (block->domfrontier != 0) {
10024 internal_error(state, block->first, "domfrontier present?");
10026 for(user = block->idominates; user; user = user->next) {
10027 child = user->member;
10028 if (child->idom != block) {
10029 internal_error(state, block->first, "bad idom");
10031 find_block_domf(state, child);
10033 if (block->left && block->left->idom != block) {
10034 domf_block(block, block->left);
10036 if (block->right && block->right->idom != block) {
10037 domf_block(block, block->right);
10039 for(user = block->idominates; user; user = user->next) {
10040 struct block_set *frontier;
10041 child = user->member;
10042 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10043 if (frontier->member->idom != block) {
10044 domf_block(block, frontier->member);
10050 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10052 struct block *child;
10053 struct block_set *user;
10054 if (block->ipdomfrontier != 0) {
10055 internal_error(state, block->first, "ipdomfrontier present?");
10057 for(user = block->ipdominates; user; user = user->next) {
10058 child = user->member;
10059 if (child->ipdom != block) {
10060 internal_error(state, block->first, "bad ipdom");
10062 find_block_ipdomf(state, child);
10064 if (block->left && block->left->ipdom != block) {
10065 ipdomf_block(block, block->left);
10067 if (block->right && block->right->ipdom != block) {
10068 ipdomf_block(block, block->right);
10070 for(user = block->idominates; user; user = user->next) {
10071 struct block_set *frontier;
10072 child = user->member;
10073 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10074 if (frontier->member->ipdom != block) {
10075 ipdomf_block(block, frontier->member);
10081 static void print_dominated(
10082 struct compile_state *state, struct block *block, void *arg)
10084 struct block_set *user;
10087 fprintf(fp, "%d:", block->vertex);
10088 for(user = block->idominates; user; user = user->next) {
10089 fprintf(fp, " %d", user->member->vertex);
10090 if (user->member->idom != block) {
10091 internal_error(state, user->member->first, "bad idom");
10097 static void print_dominators(struct compile_state *state, FILE *fp)
10099 fprintf(fp, "\ndominates\n");
10100 walk_blocks(state, print_dominated, fp);
10104 static int print_frontiers(
10105 struct compile_state *state, struct block *block, int vertex)
10107 struct block_set *user;
10109 if (!block || (block->vertex != vertex + 1)) {
10114 printf("%d:", block->vertex);
10115 for(user = block->domfrontier; user; user = user->next) {
10116 printf(" %d", user->member->vertex);
10120 vertex = print_frontiers(state, block->left, vertex);
10121 vertex = print_frontiers(state, block->right, vertex);
10124 static void print_dominance_frontiers(struct compile_state *state)
10126 printf("\ndominance frontiers\n");
10127 print_frontiers(state, state->first_block, 0);
10131 static void analyze_idominators(struct compile_state *state)
10133 /* Find the immediate dominators */
10134 find_immediate_dominators(state);
10135 /* Find the dominance frontiers */
10136 find_block_domf(state, state->first_block);
10137 /* If debuging print the print what I have just found */
10138 if (state->debug & DEBUG_FDOMINATORS) {
10139 print_dominators(state, stdout);
10140 print_dominance_frontiers(state);
10141 print_control_flow(state);
10147 static void print_ipdominated(
10148 struct compile_state *state, struct block *block, void *arg)
10150 struct block_set *user;
10153 fprintf(fp, "%d:", block->vertex);
10154 for(user = block->ipdominates; user; user = user->next) {
10155 fprintf(fp, " %d", user->member->vertex);
10156 if (user->member->ipdom != block) {
10157 internal_error(state, user->member->first, "bad ipdom");
10163 static void print_ipdominators(struct compile_state *state, FILE *fp)
10165 fprintf(fp, "\nipdominates\n");
10166 walk_blocks(state, print_ipdominated, fp);
10169 static int print_pfrontiers(
10170 struct compile_state *state, struct block *block, int vertex)
10172 struct block_set *user;
10174 if (!block || (block->vertex != vertex + 1)) {
10179 printf("%d:", block->vertex);
10180 for(user = block->ipdomfrontier; user; user = user->next) {
10181 printf(" %d", user->member->vertex);
10184 for(user = block->use; user; user = user->next) {
10185 vertex = print_pfrontiers(state, user->member, vertex);
10189 static void print_ipdominance_frontiers(struct compile_state *state)
10191 printf("\nipdominance frontiers\n");
10192 print_pfrontiers(state, state->last_block, 0);
10196 static void analyze_ipdominators(struct compile_state *state)
10198 /* Find the post dominators */
10199 find_post_dominators(state);
10200 /* Find the control dependencies (post dominance frontiers) */
10201 find_block_ipdomf(state, state->last_block);
10202 /* If debuging print the print what I have just found */
10203 if (state->debug & DEBUG_RDOMINATORS) {
10204 print_ipdominators(state, stdout);
10205 print_ipdominance_frontiers(state);
10206 print_control_flow(state);
10210 static int bdominates(struct compile_state *state,
10211 struct block *dom, struct block *sub)
10213 while(sub && (sub != dom)) {
10219 static int tdominates(struct compile_state *state,
10220 struct triple *dom, struct triple *sub)
10222 struct block *bdom, *bsub;
10224 bdom = block_of_triple(state, dom);
10225 bsub = block_of_triple(state, sub);
10226 if (bdom != bsub) {
10227 result = bdominates(state, bdom, bsub);
10230 struct triple *ins;
10232 while((ins != bsub->first) && (ins != dom)) {
10235 result = (ins == dom);
10240 static void insert_phi_operations(struct compile_state *state)
10243 struct triple *first;
10244 int *has_already, *work;
10245 struct block *work_list, **work_list_tail;
10247 struct triple *var;
10249 size = sizeof(int) * (state->last_vertex + 1);
10250 has_already = xcmalloc(size, "has_already");
10251 work = xcmalloc(size, "work");
10254 first = RHS(state->main_function, 0);
10255 for(var = first->next; var != first ; var = var->next) {
10256 struct block *block;
10257 struct triple_set *user;
10258 if ((var->op != OP_ADECL) || !var->use) {
10263 work_list_tail = &work_list;
10264 for(user = var->use; user; user = user->next) {
10265 if (user->member->op == OP_READ) {
10268 if (user->member->op != OP_WRITE) {
10269 internal_error(state, user->member,
10270 "bad variable access");
10272 block = user->member->u.block;
10274 warning(state, user->member, "dead code");
10276 if (work[block->vertex] >= iter) {
10279 work[block->vertex] = iter;
10280 *work_list_tail = block;
10281 block->work_next = 0;
10282 work_list_tail = &block->work_next;
10284 for(block = work_list; block; block = block->work_next) {
10285 struct block_set *df;
10286 for(df = block->domfrontier; df; df = df->next) {
10287 struct triple *phi;
10288 struct block *front;
10290 front = df->member;
10292 if (has_already[front->vertex] >= iter) {
10295 /* Count how many edges flow into this block */
10296 in_edges = front->users;
10297 /* Insert a phi function for this variable */
10298 get_occurance(front->first->occurance);
10299 phi = alloc_triple(
10300 state, OP_PHI, var->type, -1, in_edges,
10301 front->first->occurance);
10302 phi->u.block = front;
10303 MISC(phi, 0) = var;
10304 use_triple(var, phi);
10305 /* Insert the phi functions immediately after the label */
10306 insert_triple(state, front->first->next, phi);
10307 if (front->first == front->last) {
10308 front->last = front->first->next;
10310 has_already[front->vertex] = iter;
10312 /* If necessary plan to visit the basic block */
10313 if (work[front->vertex] >= iter) {
10316 work[front->vertex] = iter;
10317 *work_list_tail = front;
10318 front->work_next = 0;
10319 work_list_tail = &front->work_next;
10323 xfree(has_already);
10331 static void fixup_block_phi_variables(
10332 struct compile_state *state, struct block *parent, struct block *block)
10334 struct block_set *set;
10335 struct triple *ptr;
10337 if (!parent || !block)
10339 /* Find the edge I am coming in on */
10341 for(set = block->use; set; set = set->next, edge++) {
10342 if (set->member == parent) {
10347 internal_error(state, 0, "phi input is not on a control predecessor");
10349 for(ptr = block->first; ; ptr = ptr->next) {
10350 if (ptr->op == OP_PHI) {
10351 struct triple *var, *val, **slot;
10352 var = MISC(ptr, 0);
10354 internal_error(state, ptr, "no var???");
10356 /* Find the current value of the variable */
10357 val = var->use->member;
10358 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10359 internal_error(state, val, "bad value in phi");
10361 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10362 internal_error(state, ptr, "edges > phi rhs");
10364 slot = &RHS(ptr, edge);
10365 if ((*slot != 0) && (*slot != val)) {
10366 internal_error(state, ptr, "phi already bound on this edge");
10369 use_triple(val, ptr);
10371 if (ptr == block->last) {
10378 static void rename_block_variables(
10379 struct compile_state *state, struct block *block)
10381 struct block_set *user;
10382 struct triple *ptr, *next, *last;
10386 last = block->first;
10388 for(ptr = block->first; !done; ptr = next) {
10390 if (ptr == block->last) {
10394 if (ptr->op == OP_READ) {
10395 struct triple *var, *val;
10397 unuse_triple(var, ptr);
10399 error(state, ptr, "variable used without being set");
10401 /* Find the current value of the variable */
10402 val = var->use->member;
10403 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10404 internal_error(state, val, "bad value in read");
10406 propogate_use(state, ptr, val);
10407 release_triple(state, ptr);
10411 if (ptr->op == OP_WRITE) {
10412 struct triple *var, *val;
10415 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10416 internal_error(state, val, "bad value in write");
10418 propogate_use(state, ptr, val);
10419 unuse_triple(var, ptr);
10420 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10421 push_triple(var, val);
10423 if (ptr->op == OP_PHI) {
10424 struct triple *var;
10425 var = MISC(ptr, 0);
10426 /* Push OP_PHI onto a stack of variable uses */
10427 push_triple(var, ptr);
10431 block->last = last;
10433 /* Fixup PHI functions in the cf successors */
10434 fixup_block_phi_variables(state, block, block->left);
10435 fixup_block_phi_variables(state, block, block->right);
10436 /* rename variables in the dominated nodes */
10437 for(user = block->idominates; user; user = user->next) {
10438 rename_block_variables(state, user->member);
10440 /* pop the renamed variable stack */
10441 last = block->first;
10443 for(ptr = block->first; !done ; ptr = next) {
10445 if (ptr == block->last) {
10448 if (ptr->op == OP_WRITE) {
10449 struct triple *var;
10451 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10452 pop_triple(var, RHS(ptr, 0));
10453 release_triple(state, ptr);
10456 if (ptr->op == OP_PHI) {
10457 struct triple *var;
10458 var = MISC(ptr, 0);
10459 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10460 pop_triple(var, ptr);
10464 block->last = last;
10467 static void prune_block_variables(struct compile_state *state,
10468 struct block *block)
10470 struct block_set *user;
10471 struct triple *next, *last, *ptr;
10473 last = block->first;
10475 for(ptr = block->first; !done; ptr = next) {
10477 if (ptr == block->last) {
10480 if (ptr->op == OP_ADECL) {
10481 struct triple_set *user, *next;
10482 for(user = ptr->use; user; user = next) {
10483 struct triple *use;
10485 use = user->member;
10486 if (use->op != OP_PHI) {
10487 internal_error(state, use, "decl still used");
10489 if (MISC(use, 0) != ptr) {
10490 internal_error(state, use, "bad phi use of decl");
10492 unuse_triple(ptr, use);
10495 release_triple(state, ptr);
10500 block->last = last;
10501 for(user = block->idominates; user; user = user->next) {
10502 prune_block_variables(state, user->member);
10506 static void transform_to_ssa_form(struct compile_state *state)
10508 insert_phi_operations(state);
10510 printf("@%s:%d\n", __FILE__, __LINE__);
10511 print_blocks(state, stdout);
10513 rename_block_variables(state, state->first_block);
10514 prune_block_variables(state, state->first_block);
10518 static void clear_vertex(
10519 struct compile_state *state, struct block *block, void *arg)
10524 static void mark_live_block(
10525 struct compile_state *state, struct block *block, int *next_vertex)
10527 /* See if this is a block that has not been marked */
10528 if (block->vertex != 0) {
10531 block->vertex = *next_vertex;
10533 if (triple_is_branch(state, block->last)) {
10534 struct triple **targ;
10535 targ = triple_targ(state, block->last, 0);
10536 for(; targ; targ = triple_targ(state, block->last, targ)) {
10540 if (!triple_stores_block(state, *targ)) {
10541 internal_error(state, 0, "bad targ");
10543 mark_live_block(state, (*targ)->u.block, next_vertex);
10546 else if (block->last->next != RHS(state->main_function, 0)) {
10547 struct triple *ins;
10548 ins = block->last->next;
10549 if (!triple_stores_block(state, ins)) {
10550 internal_error(state, 0, "bad block start");
10552 mark_live_block(state, ins->u.block, next_vertex);
10556 static void transform_from_ssa_form(struct compile_state *state)
10558 /* To get out of ssa form we insert moves on the incoming
10559 * edges to blocks containting phi functions.
10561 struct triple *first;
10562 struct triple *phi, *next;
10565 /* Walk the control flow to see which blocks remain alive */
10566 walk_blocks(state, clear_vertex, 0);
10568 mark_live_block(state, state->first_block, &next_vertex);
10570 /* Walk all of the operations to find the phi functions */
10571 first = RHS(state->main_function, 0);
10572 for(phi = first->next; phi != first ; phi = next) {
10573 struct block_set *set;
10574 struct block *block;
10575 struct triple **slot;
10576 struct triple *var, *read;
10577 struct triple_set *use, *use_next;
10580 if (phi->op != OP_PHI) {
10583 block = phi->u.block;
10584 slot = &RHS(phi, 0);
10586 /* Forget uses from code in dead blocks */
10587 for(use = phi->use; use; use = use_next) {
10588 struct block *ublock;
10589 struct triple **expr;
10590 use_next = use->next;
10591 ublock = block_of_triple(state, use->member);
10592 if ((use->member == phi) || (ublock->vertex != 0)) {
10595 expr = triple_rhs(state, use->member, 0);
10596 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10597 if (*expr == phi) {
10601 unuse_triple(phi, use->member);
10604 /* A variable to replace the phi function */
10605 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10606 /* A read of the single value that is set into the variable */
10607 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10608 use_triple(var, read);
10610 /* Replaces uses of the phi with variable reads */
10611 propogate_use(state, phi, read);
10613 /* Walk all of the incoming edges/blocks and insert moves.
10615 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10616 struct block *eblock;
10617 struct triple *move;
10618 struct triple *val;
10619 eblock = set->member;
10622 unuse_triple(val, phi);
10624 if (!val || (val == &zero_triple) ||
10625 (block->vertex == 0) || (eblock->vertex == 0) ||
10626 (val == phi) || (val == read)) {
10630 move = post_triple(state,
10631 val, OP_WRITE, phi->type, var, val);
10632 use_triple(val, move);
10633 use_triple(var, move);
10635 /* See if there are any writers of var */
10637 for(use = var->use; use; use = use->next) {
10638 struct triple **expr;
10639 expr = triple_lhs(state, use->member, 0);
10640 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10641 if (*expr == var) {
10646 /* If var is not used free it */
10648 unuse_triple(var, read);
10649 free_triple(state, read);
10650 free_triple(state, var);
10653 /* Release the phi function */
10654 release_triple(state, phi);
10661 * Register conflict resolution
10662 * =========================================================
10665 static struct reg_info find_def_color(
10666 struct compile_state *state, struct triple *def)
10668 struct triple_set *set;
10669 struct reg_info info;
10670 info.reg = REG_UNSET;
10672 if (!triple_is_def(state, def)) {
10675 info = arch_reg_lhs(state, def, 0);
10676 if (info.reg >= MAX_REGISTERS) {
10677 info.reg = REG_UNSET;
10679 for(set = def->use; set; set = set->next) {
10680 struct reg_info tinfo;
10682 i = find_rhs_use(state, set->member, def);
10686 tinfo = arch_reg_rhs(state, set->member, i);
10687 if (tinfo.reg >= MAX_REGISTERS) {
10688 tinfo.reg = REG_UNSET;
10690 if ((tinfo.reg != REG_UNSET) &&
10691 (info.reg != REG_UNSET) &&
10692 (tinfo.reg != info.reg)) {
10693 internal_error(state, def, "register conflict");
10695 if ((info.regcm & tinfo.regcm) == 0) {
10696 internal_error(state, def, "regcm conflict %x & %x == 0",
10697 info.regcm, tinfo.regcm);
10699 if (info.reg == REG_UNSET) {
10700 info.reg = tinfo.reg;
10702 info.regcm &= tinfo.regcm;
10704 if (info.reg >= MAX_REGISTERS) {
10705 internal_error(state, def, "register out of range");
10710 static struct reg_info find_lhs_pre_color(
10711 struct compile_state *state, struct triple *ins, int index)
10713 struct reg_info info;
10715 zrhs = TRIPLE_RHS(ins->sizes);
10716 zlhs = TRIPLE_LHS(ins->sizes);
10717 if (!zlhs && triple_is_def(state, ins)) {
10720 if (index >= zlhs) {
10721 internal_error(state, ins, "Bad lhs %d", index);
10723 info = arch_reg_lhs(state, ins, index);
10724 for(i = 0; i < zrhs; i++) {
10725 struct reg_info rinfo;
10726 rinfo = arch_reg_rhs(state, ins, i);
10727 if ((info.reg == rinfo.reg) &&
10728 (rinfo.reg >= MAX_REGISTERS)) {
10729 struct reg_info tinfo;
10730 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10731 info.reg = tinfo.reg;
10732 info.regcm &= tinfo.regcm;
10736 if (info.reg >= MAX_REGISTERS) {
10737 info.reg = REG_UNSET;
10742 static struct reg_info find_rhs_post_color(
10743 struct compile_state *state, struct triple *ins, int index);
10745 static struct reg_info find_lhs_post_color(
10746 struct compile_state *state, struct triple *ins, int index)
10748 struct triple_set *set;
10749 struct reg_info info;
10750 struct triple *lhs;
10752 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10755 if ((index == 0) && triple_is_def(state, ins)) {
10758 else if (index < TRIPLE_LHS(ins->sizes)) {
10759 lhs = LHS(ins, index);
10762 internal_error(state, ins, "Bad lhs %d", index);
10765 info = arch_reg_lhs(state, ins, index);
10766 if (info.reg >= MAX_REGISTERS) {
10767 info.reg = REG_UNSET;
10769 for(set = lhs->use; set; set = set->next) {
10770 struct reg_info rinfo;
10771 struct triple *user;
10773 user = set->member;
10774 zrhs = TRIPLE_RHS(user->sizes);
10775 for(i = 0; i < zrhs; i++) {
10776 if (RHS(user, i) != lhs) {
10779 rinfo = find_rhs_post_color(state, user, i);
10780 if ((info.reg != REG_UNSET) &&
10781 (rinfo.reg != REG_UNSET) &&
10782 (info.reg != rinfo.reg)) {
10783 internal_error(state, ins, "register conflict");
10785 if ((info.regcm & rinfo.regcm) == 0) {
10786 internal_error(state, ins, "regcm conflict %x & %x == 0",
10787 info.regcm, rinfo.regcm);
10789 if (info.reg == REG_UNSET) {
10790 info.reg = rinfo.reg;
10792 info.regcm &= rinfo.regcm;
10796 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10797 ins, index, info.reg, info.regcm);
10802 static struct reg_info find_rhs_post_color(
10803 struct compile_state *state, struct triple *ins, int index)
10805 struct reg_info info, rinfo;
10808 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10811 rinfo = arch_reg_rhs(state, ins, index);
10812 zlhs = TRIPLE_LHS(ins->sizes);
10813 if (!zlhs && triple_is_def(state, ins)) {
10817 if (info.reg >= MAX_REGISTERS) {
10818 info.reg = REG_UNSET;
10820 for(i = 0; i < zlhs; i++) {
10821 struct reg_info linfo;
10822 linfo = arch_reg_lhs(state, ins, i);
10823 if ((linfo.reg == rinfo.reg) &&
10824 (linfo.reg >= MAX_REGISTERS)) {
10825 struct reg_info tinfo;
10826 tinfo = find_lhs_post_color(state, ins, i);
10827 if (tinfo.reg >= MAX_REGISTERS) {
10828 tinfo.reg = REG_UNSET;
10830 info.regcm &= linfo.reg;
10831 info.regcm &= tinfo.regcm;
10832 if (info.reg != REG_UNSET) {
10833 internal_error(state, ins, "register conflict");
10835 if (info.regcm == 0) {
10836 internal_error(state, ins, "regcm conflict");
10838 info.reg = tinfo.reg;
10842 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10843 ins, index, info.reg, info.regcm);
10848 static struct reg_info find_lhs_color(
10849 struct compile_state *state, struct triple *ins, int index)
10851 struct reg_info pre, post, info;
10853 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10856 pre = find_lhs_pre_color(state, ins, index);
10857 post = find_lhs_post_color(state, ins, index);
10858 if ((pre.reg != post.reg) &&
10859 (pre.reg != REG_UNSET) &&
10860 (post.reg != REG_UNSET)) {
10861 internal_error(state, ins, "register conflict");
10863 info.regcm = pre.regcm & post.regcm;
10864 info.reg = pre.reg;
10865 if (info.reg == REG_UNSET) {
10866 info.reg = post.reg;
10869 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10870 ins, index, info.reg, info.regcm);
10875 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10877 struct triple_set *entry, *next;
10878 struct triple *out;
10879 struct reg_info info, rinfo;
10881 info = arch_reg_lhs(state, ins, 0);
10882 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10883 use_triple(RHS(out, 0), out);
10884 /* Get the users of ins to use out instead */
10885 for(entry = ins->use; entry; entry = next) {
10887 next = entry->next;
10888 if (entry->member == out) {
10891 i = find_rhs_use(state, entry->member, ins);
10895 rinfo = arch_reg_rhs(state, entry->member, i);
10896 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10899 replace_rhs_use(state, ins, out, entry->member);
10901 transform_to_arch_instruction(state, out);
10905 static struct triple *pre_copy(
10906 struct compile_state *state, struct triple *ins, int index)
10908 /* Carefully insert enough operations so that I can
10909 * enter any operation with a GPR32.
10912 struct triple **expr;
10913 if (ins->op == OP_PHI) {
10914 internal_error(state, ins, "pre_copy on a phi?");
10916 expr = &RHS(ins, index);
10917 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10918 unuse_triple(*expr, ins);
10920 use_triple(RHS(in, 0), in);
10921 use_triple(in, ins);
10922 transform_to_arch_instruction(state, in);
10927 static void insert_copies_to_phi(struct compile_state *state)
10929 /* To get out of ssa form we insert moves on the incoming
10930 * edges to blocks containting phi functions.
10932 struct triple *first;
10933 struct triple *phi;
10935 /* Walk all of the operations to find the phi functions */
10936 first = RHS(state->main_function, 0);
10937 for(phi = first->next; phi != first ; phi = phi->next) {
10938 struct block_set *set;
10939 struct block *block;
10940 struct triple **slot;
10942 if (phi->op != OP_PHI) {
10945 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10946 block = phi->u.block;
10947 slot = &RHS(phi, 0);
10948 /* Walk all of the incoming edges/blocks and insert moves.
10950 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10951 struct block *eblock;
10952 struct triple *move;
10953 struct triple *val;
10954 struct triple *ptr;
10955 eblock = set->member;
10962 get_occurance(val->occurance);
10963 move = build_triple(state, OP_COPY, phi->type, val, 0,
10965 move->u.block = eblock;
10966 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10967 use_triple(val, move);
10970 unuse_triple(val, phi);
10971 use_triple(move, phi);
10973 /* Walk through the block backwards to find
10974 * an appropriate location for the OP_COPY.
10976 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10977 struct triple **expr;
10978 if ((ptr == phi) || (ptr == val)) {
10981 expr = triple_rhs(state, ptr, 0);
10982 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10983 if ((*expr) == phi) {
10989 if (triple_is_branch(state, ptr)) {
10990 internal_error(state, ptr,
10991 "Could not insert write to phi");
10993 insert_triple(state, ptr->next, move);
10994 if (eblock->last == ptr) {
10995 eblock->last = move;
10997 transform_to_arch_instruction(state, move);
11002 struct triple_reg_set {
11003 struct triple_reg_set *next;
11004 struct triple *member;
11005 struct triple *new;
11009 struct block *block;
11010 struct triple_reg_set *in;
11011 struct triple_reg_set *out;
11015 static int do_triple_set(struct triple_reg_set **head,
11016 struct triple *member, struct triple *new_member)
11018 struct triple_reg_set **ptr, *new;
11023 if ((*ptr)->member == member) {
11026 ptr = &(*ptr)->next;
11028 new = xcmalloc(sizeof(*new), "triple_set");
11029 new->member = member;
11030 new->new = new_member;
11036 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11038 struct triple_reg_set *entry, **ptr;
11042 if (entry->member == member) {
11043 *ptr = entry->next;
11048 ptr = &entry->next;
11053 static int in_triple(struct reg_block *rb, struct triple *in)
11055 return do_triple_set(&rb->in, in, 0);
11057 static void unin_triple(struct reg_block *rb, struct triple *unin)
11059 do_triple_unset(&rb->in, unin);
11062 static int out_triple(struct reg_block *rb, struct triple *out)
11064 return do_triple_set(&rb->out, out, 0);
11066 static void unout_triple(struct reg_block *rb, struct triple *unout)
11068 do_triple_unset(&rb->out, unout);
11071 static int initialize_regblock(struct reg_block *blocks,
11072 struct block *block, int vertex)
11074 struct block_set *user;
11075 if (!block || (blocks[block->vertex].block == block)) {
11079 /* Renumber the blocks in a convinient fashion */
11080 block->vertex = vertex;
11081 blocks[vertex].block = block;
11082 blocks[vertex].vertex = vertex;
11083 for(user = block->use; user; user = user->next) {
11084 vertex = initialize_regblock(blocks, user->member, vertex);
11089 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11090 struct reg_block *rb, struct block *suc)
11092 /* Read the conditional input set of a successor block
11093 * (i.e. the input to the phi nodes) and place it in the
11094 * current blocks output set.
11096 struct block_set *set;
11097 struct triple *ptr;
11101 /* Find the edge I am coming in on */
11102 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11103 if (set->member == rb->block) {
11108 internal_error(state, 0, "Not coming on a control edge?");
11110 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11111 struct triple **slot, *expr, *ptr2;
11112 int out_change, done2;
11113 done = (ptr == suc->last);
11114 if (ptr->op != OP_PHI) {
11117 slot = &RHS(ptr, 0);
11119 out_change = out_triple(rb, expr);
11123 /* If we don't define the variable also plast it
11124 * in the current blocks input set.
11126 ptr2 = rb->block->first;
11127 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11128 if (ptr2 == expr) {
11131 done2 = (ptr2 == rb->block->last);
11136 change |= in_triple(rb, expr);
11141 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11142 struct reg_block *rb, struct block *suc)
11144 struct triple_reg_set *in_set;
11147 /* Read the input set of a successor block
11148 * and place it in the current blocks output set.
11150 in_set = blocks[suc->vertex].in;
11151 for(; in_set; in_set = in_set->next) {
11152 int out_change, done;
11153 struct triple *first, *last, *ptr;
11154 out_change = out_triple(rb, in_set->member);
11158 /* If we don't define the variable also place it
11159 * in the current blocks input set.
11161 first = rb->block->first;
11162 last = rb->block->last;
11164 for(ptr = first; !done; ptr = ptr->next) {
11165 if (ptr == in_set->member) {
11168 done = (ptr == last);
11173 change |= in_triple(rb, in_set->member);
11175 change |= phi_in(state, blocks, rb, suc);
11180 static int use_in(struct compile_state *state, struct reg_block *rb)
11182 /* Find the variables we use but don't define and add
11183 * it to the current blocks input set.
11185 #warning "FIXME is this O(N^2) algorithm bad?"
11186 struct block *block;
11187 struct triple *ptr;
11192 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11193 struct triple **expr;
11194 done = (ptr == block->first);
11195 /* The variable a phi function uses depends on the
11196 * control flow, and is handled in phi_in, not
11199 if (ptr->op == OP_PHI) {
11202 expr = triple_rhs(state, ptr, 0);
11203 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11204 struct triple *rhs, *test;
11210 /* See if rhs is defined in this block */
11211 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11212 tdone = (test == block->first);
11218 /* If I still have a valid rhs add it to in */
11219 change |= in_triple(rb, rhs);
11225 static struct reg_block *compute_variable_lifetimes(
11226 struct compile_state *state)
11228 struct reg_block *blocks;
11231 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11232 initialize_regblock(blocks, state->last_block, 0);
11236 for(i = 1; i <= state->last_vertex; i++) {
11237 struct reg_block *rb;
11239 /* Add the left successor's input set to in */
11240 if (rb->block->left) {
11241 change |= reg_in(state, blocks, rb, rb->block->left);
11243 /* Add the right successor's input set to in */
11244 if ((rb->block->right) &&
11245 (rb->block->right != rb->block->left)) {
11246 change |= reg_in(state, blocks, rb, rb->block->right);
11248 /* Add use to in... */
11249 change |= use_in(state, rb);
11255 static void free_variable_lifetimes(
11256 struct compile_state *state, struct reg_block *blocks)
11259 /* free in_set && out_set on each block */
11260 for(i = 1; i <= state->last_vertex; i++) {
11261 struct triple_reg_set *entry, *next;
11262 struct reg_block *rb;
11264 for(entry = rb->in; entry ; entry = next) {
11265 next = entry->next;
11266 do_triple_unset(&rb->in, entry->member);
11268 for(entry = rb->out; entry; entry = next) {
11269 next = entry->next;
11270 do_triple_unset(&rb->out, entry->member);
11277 typedef void (*wvl_cb_t)(
11278 struct compile_state *state,
11279 struct reg_block *blocks, struct triple_reg_set *live,
11280 struct reg_block *rb, struct triple *ins, void *arg);
11282 static void walk_variable_lifetimes(struct compile_state *state,
11283 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11287 for(i = 1; i <= state->last_vertex; i++) {
11288 struct triple_reg_set *live;
11289 struct triple_reg_set *entry, *next;
11290 struct triple *ptr, *prev;
11291 struct reg_block *rb;
11292 struct block *block;
11295 /* Get the blocks */
11299 /* Copy out into live */
11301 for(entry = rb->out; entry; entry = next) {
11302 next = entry->next;
11303 do_triple_set(&live, entry->member, entry->new);
11305 /* Walk through the basic block calculating live */
11306 for(done = 0, ptr = block->last; !done; ptr = prev) {
11307 struct triple **expr;
11310 done = (ptr == block->first);
11312 /* Ensure the current definition is in live */
11313 if (triple_is_def(state, ptr)) {
11314 do_triple_set(&live, ptr, 0);
11317 /* Inform the callback function of what is
11320 cb(state, blocks, live, rb, ptr, arg);
11322 /* Remove the current definition from live */
11323 do_triple_unset(&live, ptr);
11325 /* Add the current uses to live.
11327 * It is safe to skip phi functions because they do
11328 * not have any block local uses, and the block
11329 * output sets already properly account for what
11330 * control flow depedent uses phi functions do have.
11332 if (ptr->op == OP_PHI) {
11335 expr = triple_rhs(state, ptr, 0);
11336 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11337 /* If the triple is not a definition skip it. */
11338 if (!*expr || !triple_is_def(state, *expr)) {
11341 do_triple_set(&live, *expr, 0);
11345 for(entry = live; entry; entry = next) {
11346 next = entry->next;
11347 do_triple_unset(&live, entry->member);
11352 static int count_triples(struct compile_state *state)
11354 struct triple *first, *ins;
11356 first = RHS(state->main_function, 0);
11361 } while (ins != first);
11364 struct dead_triple {
11365 struct triple *triple;
11366 struct dead_triple *work_next;
11367 struct block *block;
11370 #define TRIPLE_FLAG_ALIVE 1
11374 static void awaken(
11375 struct compile_state *state,
11376 struct dead_triple *dtriple, struct triple **expr,
11377 struct dead_triple ***work_list_tail)
11379 struct triple *triple;
11380 struct dead_triple *dt;
11388 if (triple->id <= 0) {
11389 internal_error(state, triple, "bad triple id: %d",
11392 if (triple->op == OP_NOOP) {
11393 internal_warning(state, triple, "awakening noop?");
11396 dt = &dtriple[triple->id];
11397 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11398 dt->flags |= TRIPLE_FLAG_ALIVE;
11399 if (!dt->work_next) {
11400 **work_list_tail = dt;
11401 *work_list_tail = &dt->work_next;
11406 static void eliminate_inefectual_code(struct compile_state *state)
11408 struct block *block;
11409 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11411 struct triple *first, *ins;
11413 /* Setup the work list */
11415 work_list_tail = &work_list;
11417 first = RHS(state->main_function, 0);
11419 /* Count how many triples I have */
11420 triples = count_triples(state);
11422 /* Now put then in an array and mark all of the triples dead */
11423 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11429 if (ins->op == OP_LABEL) {
11430 block = ins->u.block;
11432 dtriple[i].triple = ins;
11433 dtriple[i].block = block;
11434 dtriple[i].flags = 0;
11435 dtriple[i].color = ins->id;
11437 /* See if it is an operation we always keep */
11438 #warning "FIXME handle the case of killing a branch instruction"
11439 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11440 awaken(state, dtriple, &ins, &work_list_tail);
11444 } while(ins != first);
11446 struct dead_triple *dt;
11447 struct block_set *user;
11448 struct triple **expr;
11450 work_list = dt->work_next;
11452 work_list_tail = &work_list;
11454 /* Wake up the data depencencies of this triple */
11457 expr = triple_rhs(state, dt->triple, expr);
11458 awaken(state, dtriple, expr, &work_list_tail);
11461 expr = triple_lhs(state, dt->triple, expr);
11462 awaken(state, dtriple, expr, &work_list_tail);
11465 expr = triple_misc(state, dt->triple, expr);
11466 awaken(state, dtriple, expr, &work_list_tail);
11468 /* Wake up the forward control dependencies */
11470 expr = triple_targ(state, dt->triple, expr);
11471 awaken(state, dtriple, expr, &work_list_tail);
11473 /* Wake up the reverse control dependencies of this triple */
11474 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11475 awaken(state, dtriple, &user->member->last, &work_list_tail);
11478 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11479 if ((dt->triple->op == OP_NOOP) &&
11480 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11481 internal_error(state, dt->triple, "noop effective?");
11483 dt->triple->id = dt->color; /* Restore the color */
11484 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11485 #warning "FIXME handle the case of killing a basic block"
11486 if (dt->block->first == dt->triple) {
11489 if (dt->block->last == dt->triple) {
11490 dt->block->last = dt->triple->prev;
11492 release_triple(state, dt->triple);
11499 static void insert_mandatory_copies(struct compile_state *state)
11501 struct triple *ins, *first;
11503 /* The object is with a minimum of inserted copies,
11504 * to resolve in fundamental register conflicts between
11505 * register value producers and consumers.
11506 * Theoretically we may be greater than minimal when we
11507 * are inserting copies before instructions but that
11508 * case should be rare.
11510 first = RHS(state->main_function, 0);
11513 struct triple_set *entry, *next;
11514 struct triple *tmp;
11515 struct reg_info info;
11516 unsigned reg, regcm;
11517 int do_post_copy, do_pre_copy;
11519 if (!triple_is_def(state, ins)) {
11522 /* Find the architecture specific color information */
11523 info = arch_reg_lhs(state, ins, 0);
11524 if (info.reg >= MAX_REGISTERS) {
11525 info.reg = REG_UNSET;
11529 regcm = arch_type_to_regcm(state, ins->type);
11530 do_post_copy = do_pre_copy = 0;
11532 /* Walk through the uses of ins and check for conflicts */
11533 for(entry = ins->use; entry; entry = next) {
11534 struct reg_info rinfo;
11536 next = entry->next;
11537 i = find_rhs_use(state, entry->member, ins);
11542 /* Find the users color requirements */
11543 rinfo = arch_reg_rhs(state, entry->member, i);
11544 if (rinfo.reg >= MAX_REGISTERS) {
11545 rinfo.reg = REG_UNSET;
11548 /* See if I need a pre_copy */
11549 if (rinfo.reg != REG_UNSET) {
11550 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11555 regcm &= rinfo.regcm;
11556 regcm = arch_regcm_normalize(state, regcm);
11563 (((info.reg != REG_UNSET) &&
11564 (reg != REG_UNSET) &&
11565 (info.reg != reg)) ||
11566 ((info.regcm & regcm) == 0));
11569 regcm = info.regcm;
11570 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11571 for(entry = ins->use; entry; entry = next) {
11572 struct reg_info rinfo;
11574 next = entry->next;
11575 i = find_rhs_use(state, entry->member, ins);
11580 /* Find the users color requirements */
11581 rinfo = arch_reg_rhs(state, entry->member, i);
11582 if (rinfo.reg >= MAX_REGISTERS) {
11583 rinfo.reg = REG_UNSET;
11586 /* Now see if it is time to do the pre_copy */
11587 if (rinfo.reg != REG_UNSET) {
11588 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11589 ((regcm & rinfo.regcm) == 0) ||
11590 /* Don't let a mandatory coalesce sneak
11591 * into a operation that is marked to prevent
11594 ((reg != REG_UNNEEDED) &&
11595 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11596 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11599 struct triple *user;
11600 user = entry->member;
11601 if (RHS(user, i) != ins) {
11602 internal_error(state, user, "bad rhs");
11604 tmp = pre_copy(state, user, i);
11605 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11613 if ((regcm & rinfo.regcm) == 0) {
11615 struct triple *user;
11616 user = entry->member;
11617 if (RHS(user, i) != ins) {
11618 internal_error(state, user, "bad rhs");
11620 tmp = pre_copy(state, user, i);
11621 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11627 regcm &= rinfo.regcm;
11630 if (do_post_copy) {
11631 struct reg_info pre, post;
11632 tmp = post_copy(state, ins);
11633 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11634 pre = arch_reg_lhs(state, ins, 0);
11635 post = arch_reg_lhs(state, tmp, 0);
11636 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11637 internal_error(state, tmp, "useless copy");
11642 } while(ins != first);
11646 struct live_range_edge;
11647 struct live_range_def;
11648 struct live_range {
11649 struct live_range_edge *edges;
11650 struct live_range_def *defs;
11651 /* Note. The list pointed to by defs is kept in order.
11652 * That is baring splits in the flow control
11653 * defs dominates defs->next wich dominates defs->next->next
11660 struct live_range *group_next, **group_prev;
11663 struct live_range_edge {
11664 struct live_range_edge *next;
11665 struct live_range *node;
11668 struct live_range_def {
11669 struct live_range_def *next;
11670 struct live_range_def *prev;
11671 struct live_range *lr;
11672 struct triple *def;
11676 #define LRE_HASH_SIZE 2048
11678 struct lre_hash *next;
11679 struct live_range *left;
11680 struct live_range *right;
11685 struct lre_hash *hash[LRE_HASH_SIZE];
11686 struct reg_block *blocks;
11687 struct live_range_def *lrd;
11688 struct live_range *lr;
11689 struct live_range *low, **low_tail;
11690 struct live_range *high, **high_tail;
11693 int passes, max_passes;
11694 #define MAX_ALLOCATION_PASSES 100
11698 static unsigned regc_max_size(struct compile_state *state, int classes)
11703 for(i = 0; i < MAX_REGC; i++) {
11704 if (classes & (1 << i)) {
11706 size = arch_regc_size(state, i);
11707 if (size > max_size) {
11715 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11717 unsigned equivs[MAX_REG_EQUIVS];
11719 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11720 internal_error(state, 0, "invalid register");
11722 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11723 internal_error(state, 0, "invalid register");
11725 arch_reg_equivs(state, equivs, reg1);
11726 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11727 if (equivs[i] == reg2) {
11734 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11736 unsigned equivs[MAX_REG_EQUIVS];
11738 if (reg == REG_UNNEEDED) {
11741 arch_reg_equivs(state, equivs, reg);
11742 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11743 used[equivs[i]] = 1;
11748 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11750 unsigned equivs[MAX_REG_EQUIVS];
11752 if (reg == REG_UNNEEDED) {
11755 arch_reg_equivs(state, equivs, reg);
11756 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11757 used[equivs[i]] += 1;
11762 static unsigned int hash_live_edge(
11763 struct live_range *left, struct live_range *right)
11765 unsigned int hash, val;
11766 unsigned long lval, rval;
11767 lval = ((unsigned long)left)/sizeof(struct live_range);
11768 rval = ((unsigned long)right)/sizeof(struct live_range);
11773 hash = (hash *263) + val;
11778 hash = (hash *263) + val;
11780 hash = hash & (LRE_HASH_SIZE - 1);
11784 static struct lre_hash **lre_probe(struct reg_state *rstate,
11785 struct live_range *left, struct live_range *right)
11787 struct lre_hash **ptr;
11788 unsigned int index;
11789 /* Ensure left <= right */
11790 if (left > right) {
11791 struct live_range *tmp;
11796 index = hash_live_edge(left, right);
11798 ptr = &rstate->hash[index];
11800 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
11803 ptr = &(*ptr)->next;
11808 static int interfere(struct reg_state *rstate,
11809 struct live_range *left, struct live_range *right)
11811 struct lre_hash **ptr;
11812 ptr = lre_probe(rstate, left, right);
11813 return ptr && *ptr;
11816 static void add_live_edge(struct reg_state *rstate,
11817 struct live_range *left, struct live_range *right)
11819 /* FIXME the memory allocation overhead is noticeable here... */
11820 struct lre_hash **ptr, *new_hash;
11821 struct live_range_edge *edge;
11823 if (left == right) {
11826 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11829 /* Ensure left <= right */
11830 if (left > right) {
11831 struct live_range *tmp;
11836 ptr = lre_probe(rstate, left, right);
11841 fprintf(stderr, "new_live_edge(%p, %p)\n",
11844 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11845 new_hash->next = *ptr;
11846 new_hash->left = left;
11847 new_hash->right = right;
11850 edge = xmalloc(sizeof(*edge), "live_range_edge");
11851 edge->next = left->edges;
11852 edge->node = right;
11853 left->edges = edge;
11856 edge = xmalloc(sizeof(*edge), "live_range_edge");
11857 edge->next = right->edges;
11859 right->edges = edge;
11860 right->degree += 1;
11863 static void remove_live_edge(struct reg_state *rstate,
11864 struct live_range *left, struct live_range *right)
11866 struct live_range_edge *edge, **ptr;
11867 struct lre_hash **hptr, *entry;
11868 hptr = lre_probe(rstate, left, right);
11869 if (!hptr || !*hptr) {
11873 *hptr = entry->next;
11876 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11878 if (edge->node == right) {
11880 memset(edge, 0, sizeof(*edge));
11886 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11888 if (edge->node == left) {
11890 memset(edge, 0, sizeof(*edge));
11898 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11900 struct live_range_edge *edge, *next;
11901 for(edge = range->edges; edge; edge = next) {
11903 remove_live_edge(rstate, range, edge->node);
11907 static void transfer_live_edges(struct reg_state *rstate,
11908 struct live_range *dest, struct live_range *src)
11910 struct live_range_edge *edge, *next;
11911 for(edge = src->edges; edge; edge = next) {
11912 struct live_range *other;
11914 other = edge->node;
11915 remove_live_edge(rstate, src, other);
11916 add_live_edge(rstate, dest, other);
11921 /* Interference graph...
11923 * new(n) --- Return a graph with n nodes but no edges.
11924 * add(g,x,y) --- Return a graph including g with an between x and y
11925 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11926 * x and y in the graph g
11927 * degree(g, x) --- Return the degree of the node x in the graph g
11928 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11930 * Implement with a hash table && a set of adjcency vectors.
11931 * The hash table supports constant time implementations of add and interfere.
11932 * The adjacency vectors support an efficient implementation of neighbors.
11936 * +---------------------------------------------------+
11937 * | +--------------+ |
11939 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11941 * -- In simplify implment optimistic coloring... (No backtracking)
11942 * -- Implement Rematerialization it is the only form of spilling we can perform
11943 * Essentially this means dropping a constant from a register because
11944 * we can regenerate it later.
11946 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11947 * coalesce at phi points...
11948 * --- Bias coloring if at all possible do the coalesing a compile time.
11953 static void different_colored(
11954 struct compile_state *state, struct reg_state *rstate,
11955 struct triple *parent, struct triple *ins)
11957 struct live_range *lr;
11958 struct triple **expr;
11959 lr = rstate->lrd[ins->id].lr;
11960 expr = triple_rhs(state, ins, 0);
11961 for(;expr; expr = triple_rhs(state, ins, expr)) {
11962 struct live_range *lr2;
11963 if (!*expr || (*expr == parent) || (*expr == ins)) {
11966 lr2 = rstate->lrd[(*expr)->id].lr;
11967 if (lr->color == lr2->color) {
11968 internal_error(state, ins, "live range too big");
11974 static struct live_range *coalesce_ranges(
11975 struct compile_state *state, struct reg_state *rstate,
11976 struct live_range *lr1, struct live_range *lr2)
11978 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11984 if (!lr1->defs || !lr2->defs) {
11985 internal_error(state, 0,
11986 "cannot coalese dead live ranges");
11988 if ((lr1->color == REG_UNNEEDED) ||
11989 (lr2->color == REG_UNNEEDED)) {
11990 internal_error(state, 0,
11991 "cannot coalesce live ranges without a possible color");
11993 if ((lr1->color != lr2->color) &&
11994 (lr1->color != REG_UNSET) &&
11995 (lr2->color != REG_UNSET)) {
11996 internal_error(state, lr1->defs->def,
11997 "cannot coalesce live ranges of different colors");
11999 color = lr1->color;
12000 if (color == REG_UNSET) {
12001 color = lr2->color;
12003 classes = lr1->classes & lr2->classes;
12005 internal_error(state, lr1->defs->def,
12006 "cannot coalesce live ranges with dissimilar register classes");
12008 /* If there is a clear dominate live range put it in lr1,
12009 * For purposes of this test phi functions are
12010 * considered dominated by the definitions that feed into
12013 if ((lr1->defs->prev->def->op == OP_PHI) ||
12014 ((lr2->defs->prev->def->op != OP_PHI) &&
12015 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12016 struct live_range *tmp;
12022 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12023 fprintf(stderr, "lr1 post\n");
12025 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12026 fprintf(stderr, "lr1 pre\n");
12028 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12029 fprintf(stderr, "lr2 post\n");
12031 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12032 fprintf(stderr, "lr2 pre\n");
12036 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12043 lr1->classes = classes;
12044 /* Append lr2 onto lr1 */
12045 #warning "FIXME should this be a merge instead of a splice?"
12046 /* This FIXME item applies to the correctness of live_range_end
12047 * and to the necessity of making multiple passes of coalesce_live_ranges.
12048 * A failure to find some coalesce opportunities in coaleace_live_ranges
12049 * does not impact the correct of the compiler just the efficiency with
12050 * which registers are allocated.
12053 mid1 = lr1->defs->prev;
12055 end = lr2->defs->prev;
12063 /* Fixup the live range in the added live range defs */
12068 } while(lrd != head);
12070 /* Mark lr2 as free. */
12072 lr2->color = REG_UNNEEDED;
12076 internal_error(state, 0, "lr1->defs == 0 ?");
12079 lr1->color = color;
12080 lr1->classes = classes;
12082 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12083 transfer_live_edges(rstate, lr1, lr2);
12088 static struct live_range_def *live_range_head(
12089 struct compile_state *state, struct live_range *lr,
12090 struct live_range_def *last)
12092 struct live_range_def *result;
12097 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12098 result = last->next;
12103 static struct live_range_def *live_range_end(
12104 struct compile_state *state, struct live_range *lr,
12105 struct live_range_def *last)
12107 struct live_range_def *result;
12110 result = lr->defs->prev;
12112 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12113 result = last->prev;
12119 static void initialize_live_ranges(
12120 struct compile_state *state, struct reg_state *rstate)
12122 struct triple *ins, *first;
12123 size_t count, size;
12126 first = RHS(state->main_function, 0);
12127 /* First count how many instructions I have.
12129 count = count_triples(state);
12130 /* Potentially I need one live range definitions for each
12131 * instruction, plus an extra for the split routines.
12133 rstate->defs = count + 1;
12134 /* Potentially I need one live range for each instruction
12135 * plus an extra for the dummy live range.
12137 rstate->ranges = count + 1;
12138 size = sizeof(rstate->lrd[0]) * rstate->defs;
12139 rstate->lrd = xcmalloc(size, "live_range_def");
12140 size = sizeof(rstate->lr[0]) * rstate->ranges;
12141 rstate->lr = xcmalloc(size, "live_range");
12143 /* Setup the dummy live range */
12144 rstate->lr[0].classes = 0;
12145 rstate->lr[0].color = REG_UNSET;
12146 rstate->lr[0].defs = 0;
12150 /* If the triple is a variable give it a live range */
12151 if (triple_is_def(state, ins)) {
12152 struct reg_info info;
12153 /* Find the architecture specific color information */
12154 info = find_def_color(state, ins);
12157 rstate->lr[i].defs = &rstate->lrd[j];
12158 rstate->lr[i].color = info.reg;
12159 rstate->lr[i].classes = info.regcm;
12160 rstate->lr[i].degree = 0;
12161 rstate->lrd[j].lr = &rstate->lr[i];
12163 /* Otherwise give the triple the dummy live range. */
12165 rstate->lrd[j].lr = &rstate->lr[0];
12168 /* Initalize the live_range_def */
12169 rstate->lrd[j].next = &rstate->lrd[j];
12170 rstate->lrd[j].prev = &rstate->lrd[j];
12171 rstate->lrd[j].def = ins;
12172 rstate->lrd[j].orig_id = ins->id;
12177 } while(ins != first);
12178 rstate->ranges = i;
12181 /* Make a second pass to handle achitecture specific register
12186 int zlhs, zrhs, i, j;
12187 if (ins->id > rstate->defs) {
12188 internal_error(state, ins, "bad id");
12191 /* Walk through the template of ins and coalesce live ranges */
12192 zlhs = TRIPLE_LHS(ins->sizes);
12193 if ((zlhs == 0) && triple_is_def(state, ins)) {
12196 zrhs = TRIPLE_RHS(ins->sizes);
12198 for(i = 0; i < zlhs; i++) {
12199 struct reg_info linfo;
12200 struct live_range_def *lhs;
12201 linfo = arch_reg_lhs(state, ins, i);
12202 if (linfo.reg < MAX_REGISTERS) {
12205 if (triple_is_def(state, ins)) {
12206 lhs = &rstate->lrd[ins->id];
12208 lhs = &rstate->lrd[LHS(ins, i)->id];
12210 for(j = 0; j < zrhs; j++) {
12211 struct reg_info rinfo;
12212 struct live_range_def *rhs;
12213 rinfo = arch_reg_rhs(state, ins, j);
12214 if (rinfo.reg < MAX_REGISTERS) {
12217 rhs = &rstate->lrd[RHS(ins, i)->id];
12218 if (rinfo.reg == linfo.reg) {
12219 coalesce_ranges(state, rstate,
12225 } while(ins != first);
12228 static void graph_ins(
12229 struct compile_state *state,
12230 struct reg_block *blocks, struct triple_reg_set *live,
12231 struct reg_block *rb, struct triple *ins, void *arg)
12233 struct reg_state *rstate = arg;
12234 struct live_range *def;
12235 struct triple_reg_set *entry;
12237 /* If the triple is not a definition
12238 * we do not have a definition to add to
12239 * the interference graph.
12241 if (!triple_is_def(state, ins)) {
12244 def = rstate->lrd[ins->id].lr;
12246 /* Create an edge between ins and everything that is
12247 * alive, unless the live_range cannot share
12248 * a physical register with ins.
12250 for(entry = live; entry; entry = entry->next) {
12251 struct live_range *lr;
12252 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12253 internal_error(state, 0, "bad entry?");
12255 lr = rstate->lrd[entry->member->id].lr;
12259 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12262 add_live_edge(rstate, def, lr);
12267 static struct live_range *get_verify_live_range(
12268 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12270 struct live_range *lr;
12271 struct live_range_def *lrd;
12273 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12274 internal_error(state, ins, "bad ins?");
12276 lr = rstate->lrd[ins->id].lr;
12280 if (lrd->def == ins) {
12284 } while(lrd != lr->defs);
12286 internal_error(state, ins, "ins not in live range");
12291 static void verify_graph_ins(
12292 struct compile_state *state,
12293 struct reg_block *blocks, struct triple_reg_set *live,
12294 struct reg_block *rb, struct triple *ins, void *arg)
12296 struct reg_state *rstate = arg;
12297 struct triple_reg_set *entry1, *entry2;
12300 /* Compare live against edges and make certain the code is working */
12301 for(entry1 = live; entry1; entry1 = entry1->next) {
12302 struct live_range *lr1;
12303 lr1 = get_verify_live_range(state, rstate, entry1->member);
12304 for(entry2 = live; entry2; entry2 = entry2->next) {
12305 struct live_range *lr2;
12306 struct live_range_edge *edge2;
12309 if (entry2 == entry1) {
12312 lr2 = get_verify_live_range(state, rstate, entry2->member);
12314 internal_error(state, entry2->member,
12315 "live range with 2 values simultaneously alive");
12317 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12320 if (!interfere(rstate, lr1, lr2)) {
12321 internal_error(state, entry2->member,
12322 "edges don't interfere?");
12327 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12329 if (edge2->node == lr1) {
12333 if (lr2_degree != lr2->degree) {
12334 internal_error(state, entry2->member,
12335 "computed degree: %d does not match reported degree: %d\n",
12336 lr2_degree, lr2->degree);
12339 internal_error(state, entry2->member, "missing edge");
12347 static void print_interference_ins(
12348 struct compile_state *state,
12349 struct reg_block *blocks, struct triple_reg_set *live,
12350 struct reg_block *rb, struct triple *ins, void *arg)
12352 struct reg_state *rstate = arg;
12353 struct live_range *lr;
12356 lr = rstate->lrd[ins->id].lr;
12358 ins->id = rstate->lrd[id].orig_id;
12359 SET_REG(ins->id, lr->color);
12360 display_triple(stdout, ins);
12364 struct live_range_def *lrd;
12368 printf(" %-10p", lrd->def);
12370 } while(lrd != lr->defs);
12374 struct triple_reg_set *entry;
12376 for(entry = live; entry; entry = entry->next) {
12377 printf(" %-10p", entry->member);
12382 struct live_range_edge *entry;
12384 for(entry = lr->edges; entry; entry = entry->next) {
12385 struct live_range_def *lrd;
12386 lrd = entry->node->defs;
12388 printf(" %-10p", lrd->def);
12390 } while(lrd != entry->node->defs);
12395 if (triple_is_branch(state, ins)) {
12401 static int coalesce_live_ranges(
12402 struct compile_state *state, struct reg_state *rstate)
12404 /* At the point where a value is moved from one
12405 * register to another that value requires two
12406 * registers, thus increasing register pressure.
12407 * Live range coaleescing reduces the register
12408 * pressure by keeping a value in one register
12411 * In the case of a phi function all paths leading
12412 * into it must be allocated to the same register
12413 * otherwise the phi function may not be removed.
12415 * Forcing a value to stay in a single register
12416 * for an extended period of time does have
12417 * limitations when applied to non homogenous
12420 * The two cases I have identified are:
12421 * 1) Two forced register assignments may
12423 * 2) Registers may go unused because they
12424 * are only good for storing the value
12425 * and not manipulating it.
12427 * Because of this I need to split live ranges,
12428 * even outside of the context of coalesced live
12429 * ranges. The need to split live ranges does
12430 * impose some constraints on live range coalescing.
12432 * - Live ranges may not be coalesced across phi
12433 * functions. This creates a 2 headed live
12434 * range that cannot be sanely split.
12436 * - phi functions (coalesced in initialize_live_ranges)
12437 * are handled as pre split live ranges so we will
12438 * never attempt to split them.
12444 for(i = 0; i <= rstate->ranges; i++) {
12445 struct live_range *lr1;
12446 struct live_range_def *lrd1;
12447 lr1 = &rstate->lr[i];
12451 lrd1 = live_range_end(state, lr1, 0);
12452 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12453 struct triple_set *set;
12454 if (lrd1->def->op != OP_COPY) {
12457 /* Skip copies that are the result of a live range split. */
12458 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12461 for(set = lrd1->def->use; set; set = set->next) {
12462 struct live_range_def *lrd2;
12463 struct live_range *lr2, *res;
12465 lrd2 = &rstate->lrd[set->member->id];
12467 /* Don't coalesce with instructions
12468 * that are the result of a live range
12471 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12474 lr2 = rstate->lrd[set->member->id].lr;
12478 if ((lr1->color != lr2->color) &&
12479 (lr1->color != REG_UNSET) &&
12480 (lr2->color != REG_UNSET)) {
12483 if ((lr1->classes & lr2->classes) == 0) {
12487 if (interfere(rstate, lr1, lr2)) {
12491 res = coalesce_ranges(state, rstate, lr1, lr2);
12505 static void fix_coalesce_conflicts(struct compile_state *state,
12506 struct reg_block *blocks, struct triple_reg_set *live,
12507 struct reg_block *rb, struct triple *ins, void *arg)
12509 int zlhs, zrhs, i, j;
12511 /* See if we have a mandatory coalesce operation between
12512 * a lhs and a rhs value. If so and the rhs value is also
12513 * alive then this triple needs to be pre copied. Otherwise
12514 * we would have two definitions in the same live range simultaneously
12517 zlhs = TRIPLE_LHS(ins->sizes);
12518 if ((zlhs == 0) && triple_is_def(state, ins)) {
12521 zrhs = TRIPLE_RHS(ins->sizes);
12522 for(i = 0; i < zlhs; i++) {
12523 struct reg_info linfo;
12524 linfo = arch_reg_lhs(state, ins, i);
12525 if (linfo.reg < MAX_REGISTERS) {
12528 for(j = 0; j < zrhs; j++) {
12529 struct reg_info rinfo;
12530 struct triple *rhs;
12531 struct triple_reg_set *set;
12534 rinfo = arch_reg_rhs(state, ins, j);
12535 if (rinfo.reg != linfo.reg) {
12539 for(set = live; set && !found; set = set->next) {
12540 if (set->member == rhs) {
12545 struct triple *copy;
12546 copy = pre_copy(state, ins, j);
12547 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12554 static void replace_set_use(struct compile_state *state,
12555 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12557 struct triple_reg_set *set;
12558 for(set = head; set; set = set->next) {
12559 if (set->member == orig) {
12565 static void replace_block_use(struct compile_state *state,
12566 struct reg_block *blocks, struct triple *orig, struct triple *new)
12569 #warning "WISHLIST visit just those blocks that need it *"
12570 for(i = 1; i <= state->last_vertex; i++) {
12571 struct reg_block *rb;
12573 replace_set_use(state, rb->in, orig, new);
12574 replace_set_use(state, rb->out, orig, new);
12578 static void color_instructions(struct compile_state *state)
12580 struct triple *ins, *first;
12581 first = RHS(state->main_function, 0);
12584 if (triple_is_def(state, ins)) {
12585 struct reg_info info;
12586 info = find_lhs_color(state, ins, 0);
12587 if (info.reg >= MAX_REGISTERS) {
12588 info.reg = REG_UNSET;
12590 SET_INFO(ins->id, info);
12593 } while(ins != first);
12596 static struct reg_info read_lhs_color(
12597 struct compile_state *state, struct triple *ins, int index)
12599 struct reg_info info;
12600 if ((index == 0) && triple_is_def(state, ins)) {
12601 info.reg = ID_REG(ins->id);
12602 info.regcm = ID_REGCM(ins->id);
12604 else if (index < TRIPLE_LHS(ins->sizes)) {
12605 info = read_lhs_color(state, LHS(ins, index), 0);
12608 internal_error(state, ins, "Bad lhs %d", index);
12609 info.reg = REG_UNSET;
12615 static struct triple *resolve_tangle(
12616 struct compile_state *state, struct triple *tangle)
12618 struct reg_info info, uinfo;
12619 struct triple_set *set, *next;
12620 struct triple *copy;
12622 #warning "WISHLIST recalculate all affected instructions colors"
12623 info = find_lhs_color(state, tangle, 0);
12624 for(set = tangle->use; set; set = next) {
12625 struct triple *user;
12628 user = set->member;
12629 zrhs = TRIPLE_RHS(user->sizes);
12630 for(i = 0; i < zrhs; i++) {
12631 if (RHS(user, i) != tangle) {
12634 uinfo = find_rhs_post_color(state, user, i);
12635 if (uinfo.reg == info.reg) {
12636 copy = pre_copy(state, user, i);
12637 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12638 SET_INFO(copy->id, uinfo);
12643 uinfo = find_lhs_pre_color(state, tangle, 0);
12644 if (uinfo.reg == info.reg) {
12645 struct reg_info linfo;
12646 copy = post_copy(state, tangle);
12647 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12648 linfo = find_lhs_color(state, copy, 0);
12649 SET_INFO(copy->id, linfo);
12651 info = find_lhs_color(state, tangle, 0);
12652 SET_INFO(tangle->id, info);
12658 static void fix_tangles(struct compile_state *state,
12659 struct reg_block *blocks, struct triple_reg_set *live,
12660 struct reg_block *rb, struct triple *ins, void *arg)
12662 int *tangles = arg;
12663 struct triple *tangle;
12665 char used[MAX_REGISTERS];
12666 struct triple_reg_set *set;
12669 /* Find out which registers have multiple uses at this point */
12670 memset(used, 0, sizeof(used));
12671 for(set = live; set; set = set->next) {
12672 struct reg_info info;
12673 info = read_lhs_color(state, set->member, 0);
12674 if (info.reg == REG_UNSET) {
12677 reg_inc_used(state, used, info.reg);
12680 /* Now find the least dominated definition of a register in
12681 * conflict I have seen so far.
12683 for(set = live; set; set = set->next) {
12684 struct reg_info info;
12685 info = read_lhs_color(state, set->member, 0);
12686 if (used[info.reg] < 2) {
12689 /* Changing copies that feed into phi functions
12692 if (set->member->use &&
12693 (set->member->use->member->op == OP_PHI)) {
12696 if (!tangle || tdominates(state, set->member, tangle)) {
12697 tangle = set->member;
12700 /* If I have found a tangle resolve it */
12702 struct triple *post_copy;
12704 post_copy = resolve_tangle(state, tangle);
12706 replace_block_use(state, blocks, tangle, post_copy);
12708 if (post_copy && (tangle != ins)) {
12709 replace_set_use(state, live, tangle, post_copy);
12716 static int correct_tangles(
12717 struct compile_state *state, struct reg_block *blocks)
12721 color_instructions(state);
12722 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
12726 struct least_conflict {
12727 struct reg_state *rstate;
12728 struct live_range *ref_range;
12729 struct triple *ins;
12730 struct triple_reg_set *live;
12734 static void least_conflict(struct compile_state *state,
12735 struct reg_block *blocks, struct triple_reg_set *live,
12736 struct reg_block *rb, struct triple *ins, void *arg)
12738 struct least_conflict *conflict = arg;
12739 struct live_range_edge *edge;
12740 struct triple_reg_set *set;
12744 #warning "FIXME handle instructions with left hand sides..."
12745 /* Only instructions that introduce a new definition
12746 * can be the conflict instruction.
12748 if (!triple_is_def(state, ins)) {
12752 /* See if live ranges at this instruction are a
12753 * strict subset of the live ranges that are in conflict.
12756 for(set = live; set; set = set->next) {
12757 struct live_range *lr;
12758 lr = conflict->rstate->lrd[set->member->id].lr;
12759 /* Ignore it if there cannot be an edge between these two nodes */
12760 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12763 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12764 if (edge->node == lr) {
12768 if (!edge && (lr != conflict->ref_range)) {
12778 /* See if there is an uncolored member in this subset.
12780 for(set = live; set; set = set->next) {
12781 struct live_range *lr;
12782 lr = conflict->rstate->lrd[set->member->id].lr;
12783 if (lr->color == REG_UNSET) {
12787 if (!set && (conflict->ref_range != REG_UNSET)) {
12792 /* See if any of the live registers are constrained,
12793 * if not it won't be productive to pick this as
12794 * a conflict instruction.
12797 for(set = live; set; set = set->next) {
12798 struct triple_set *uset;
12799 struct reg_info info;
12801 unsigned cur_size, size;
12802 /* Skip this instruction */
12803 if (set->member == ins) {
12806 /* Find how many registers this value can potentially
12809 classes = arch_type_to_regcm(state, set->member->type);
12810 size = regc_max_size(state, classes);
12812 /* Find how many registers we allow this value to
12815 info = arch_reg_lhs(state, set->member, 0);
12817 /* If the value does not live in a register it
12818 * isn't constrained.
12820 if (info.reg == REG_UNNEEDED) {
12824 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12825 cur_size = regc_max_size(state, info.regcm);
12830 /* If there is no difference between potential and
12831 * actual register count there is not a constraint
12833 if (cur_size >= size) {
12837 /* If this live_range feeds into conflict->inds
12838 * it isn't a constraint we can relieve.
12840 for(uset = set->member->use; uset; uset = uset->next) {
12841 if (uset->member == ins) {
12851 /* Don't drop canidates with constraints */
12852 if (conflict->constraints && !constraints) {
12858 fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12859 ins, tops(ins->op), count, constraints);
12861 /* Find the instruction with the largest possible subset of
12862 * conflict ranges and that dominates any other instruction
12863 * with an equal sized set of conflicting ranges.
12865 if ((count > conflict->count) ||
12866 ((count == conflict->count) &&
12867 tdominates(state, ins, conflict->ins))) {
12868 struct triple_reg_set *next;
12869 /* Remember the canidate instruction */
12870 conflict->ins = ins;
12871 conflict->count = count;
12872 conflict->constraints = constraints;
12873 /* Free the old collection of live registers */
12874 for(set = conflict->live; set; set = next) {
12876 do_triple_unset(&conflict->live, set->member);
12878 conflict->live = 0;
12879 /* Rember the registers that are alive but do not feed
12880 * into or out of conflict->ins.
12882 for(set = live; set; set = set->next) {
12883 struct triple **expr;
12884 if (set->member == ins) {
12887 expr = triple_rhs(state, ins, 0);
12888 for(;expr; expr = triple_rhs(state, ins, expr)) {
12889 if (*expr == set->member) {
12893 expr = triple_lhs(state, ins, 0);
12894 for(; expr; expr = triple_lhs(state, ins, expr)) {
12895 if (*expr == set->member) {
12899 do_triple_set(&conflict->live, set->member, set->new);
12907 static void find_range_conflict(struct compile_state *state,
12908 struct reg_state *rstate, char *used, struct live_range *ref_range,
12909 struct least_conflict *conflict)
12912 /* there are 3 kinds ways conflicts can occure.
12913 * 1) the life time of 2 values simply overlap.
12914 * 2) the 2 values feed into the same instruction.
12915 * 3) the 2 values feed into a phi function.
12918 /* find the instruction where the problematic conflict comes
12919 * into existance. that the instruction where all of
12920 * the values are alive, and among such instructions it is
12921 * the least dominated one.
12923 * a value is alive an an instruction if either;
12924 * 1) the value defintion dominates the instruction and there
12925 * is a use at or after that instrction
12926 * 2) the value definition feeds into a phi function in the
12927 * same block as the instruction. and the phi function
12928 * is at or after the instruction.
12930 memset(conflict, 0, sizeof(*conflict));
12931 conflict->rstate = rstate;
12932 conflict->ref_range = ref_range;
12934 conflict->live = 0;
12935 conflict->count = 0;
12936 conflict->constraints = 0;
12937 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12939 if (!conflict->ins) {
12940 internal_error(state, ref_range->defs->def, "No conflict ins?");
12942 if (!conflict->live) {
12943 internal_error(state, ref_range->defs->def, "No conflict live?");
12946 fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n",
12947 conflict->ins, tops(conflict->ins->op),
12948 conflict->count, conflict->constraints);
12953 static struct triple *split_constrained_range(struct compile_state *state,
12954 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12956 unsigned constrained_size;
12957 struct triple *new, *constrained;
12958 struct triple_reg_set *cset;
12959 /* Find a range that is having problems because it is
12960 * artificially constrained.
12962 constrained_size = ~0;
12965 for(cset = conflict->live; cset; cset = cset->next) {
12966 struct triple_set *set;
12967 struct reg_info info;
12969 unsigned cur_size, size;
12970 /* Skip the live range that starts with conflict->ins */
12971 if (cset->member == conflict->ins) {
12974 /* Find how many registers this value can potentially
12977 classes = arch_type_to_regcm(state, cset->member->type);
12978 size = regc_max_size(state, classes);
12980 /* Find how many registers we allow this value to
12983 info = arch_reg_lhs(state, cset->member, 0);
12985 /* If the register doesn't need a register
12986 * splitting it can't help.
12988 if (info.reg == REG_UNNEEDED) {
12991 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12992 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12993 cur_size = regc_max_size(state, info.regcm);
12997 /* If this live_range feeds into conflict->ins
12998 * splitting it is unlikely to help.
13000 for(set = cset->member->use; set; set = set->next) {
13001 if (set->member == conflict->ins) {
13006 /* If there is no difference between potential and
13007 * actual register count there is nothing to do.
13009 if (cur_size >= size) {
13012 /* Of the constrained registers deal with the
13013 * most constrained one first.
13015 if (!constrained ||
13016 (size < constrained_size)) {
13017 constrained = cset->member;
13018 constrained_size = size;
13024 new = post_copy(state, constrained);
13025 new->id |= TRIPLE_FLAG_POST_SPLIT;
13030 static int split_ranges(
13031 struct compile_state *state, struct reg_state *rstate,
13032 char *used, struct live_range *range)
13034 struct triple *new;
13037 fprintf(stderr, "split_ranges %d %s %p\n",
13038 rstate->passes, tops(range->defs->def->op), range->defs->def);
13040 if ((range->color == REG_UNNEEDED) ||
13041 (rstate->passes >= rstate->max_passes)) {
13045 /* If I can't allocate a register something needs to be split */
13046 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
13047 struct least_conflict conflict;
13050 fprintf(stderr, "find_range_conflict\n");
13052 /* Find where in the set of registers the conflict
13055 find_range_conflict(state, rstate, used, range, &conflict);
13057 /* If a range has been artifically constrained split it */
13058 new = split_constrained_range(state, rstate, used, &conflict);
13061 /* Ideally I would split the live range that will not be used
13062 * for the longest period of time in hopes that this will
13063 * (a) allow me to spill a register or
13064 * (b) allow me to place a value in another register.
13066 * So far I don't have a test case for this, the resolving
13067 * of mandatory constraints has solved all of my
13068 * know issues. So I have choosen not to write any
13069 * code until I cat get a better feel for cases where
13070 * it would be useful to have.
13073 #warning "WISHLIST implement live range splitting..."
13075 print_blocks(state, stderr);
13076 print_dominators(state, stderr);
13083 rstate->lrd[rstate->defs].orig_id = new->id;
13084 new->id = rstate->defs;
13087 fprintf(stderr, "new: %p old: %s %p\n",
13088 new, tops(RHS(new, 0)->op), RHS(new, 0));
13091 print_blocks(state, stderr);
13092 print_dominators(state, stderr);
13100 #if DEBUG_COLOR_GRAPH > 1
13101 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13102 #define cgdebug_flush() fflush(stdout)
13103 #elif DEBUG_COLOR_GRAPH == 1
13104 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13105 #define cgdebug_flush() fflush(stderr)
13107 #define cgdebug_printf(...)
13108 #define cgdebug_flush()
13112 static int select_free_color(struct compile_state *state,
13113 struct reg_state *rstate, struct live_range *range)
13115 struct triple_set *entry;
13116 struct live_range_def *lrd;
13117 struct live_range_def *phi;
13118 struct live_range_edge *edge;
13119 char used[MAX_REGISTERS];
13120 struct triple **expr;
13122 /* Instead of doing just the trivial color select here I try
13123 * a few extra things because a good color selection will help reduce
13127 /* Find the registers currently in use */
13128 memset(used, 0, sizeof(used));
13129 for(edge = range->edges; edge; edge = edge->next) {
13130 if (edge->node->color == REG_UNSET) {
13133 reg_fill_used(state, used, edge->node->color);
13135 #if DEBUG_COLOR_GRAPH > 1
13139 for(edge = range->edges; edge; edge = edge->next) {
13142 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13143 tops(range->def->op), i,
13144 range->def->filename, range->def->line, range->def->col);
13145 for(i = 0; i < MAX_REGISTERS; i++) {
13147 cgdebug_printf("used: %s\n",
13154 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13156 /* If a color is already assigned see if it will work */
13157 if (range->color != REG_UNSET) {
13158 struct live_range_def *lrd;
13159 if (!used[range->color]) {
13162 for(edge = range->edges; edge; edge = edge->next) {
13163 if (edge->node->color != range->color) {
13166 warning(state, edge->node->defs->def, "edge: ");
13167 lrd = edge->node->defs;
13169 warning(state, lrd->def, " %p %s",
13170 lrd->def, tops(lrd->def->op));
13172 } while(lrd != edge->node->defs);
13175 warning(state, range->defs->def, "def: ");
13177 warning(state, lrd->def, " %p %s",
13178 lrd->def, tops(lrd->def->op));
13180 } while(lrd != range->defs);
13181 internal_error(state, range->defs->def,
13182 "live range with already used color %s",
13183 arch_reg_str(range->color));
13186 /* If I feed into an expression reuse it's color.
13187 * This should help remove copies in the case of 2 register instructions
13188 * and phi functions.
13191 lrd = live_range_end(state, range, 0);
13192 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13193 entry = lrd->def->use;
13194 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13195 struct live_range_def *insd;
13196 insd = &rstate->lrd[entry->member->id];
13197 if (insd->lr->defs == 0) {
13200 if (!phi && (insd->def->op == OP_PHI) &&
13201 !interfere(rstate, range, insd->lr)) {
13204 if ((insd->lr->color == REG_UNSET) ||
13205 ((insd->lr->classes & range->classes) == 0) ||
13206 (used[insd->lr->color])) {
13209 if (interfere(rstate, range, insd->lr)) {
13212 range->color = insd->lr->color;
13215 /* If I feed into a phi function reuse it's color or the color
13216 * of something else that feeds into the phi function.
13219 if (phi->lr->color != REG_UNSET) {
13220 if (used[phi->lr->color]) {
13221 range->color = phi->lr->color;
13225 expr = triple_rhs(state, phi->def, 0);
13226 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13227 struct live_range *lr;
13231 lr = rstate->lrd[(*expr)->id].lr;
13232 if ((lr->color == REG_UNSET) ||
13233 ((lr->classes & range->classes) == 0) ||
13234 (used[lr->color])) {
13237 if (interfere(rstate, range, lr)) {
13240 range->color = lr->color;
13244 /* If I don't interfere with a rhs node reuse it's color */
13245 lrd = live_range_head(state, range, 0);
13246 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13247 expr = triple_rhs(state, lrd->def, 0);
13248 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13249 struct live_range *lr;
13253 lr = rstate->lrd[(*expr)->id].lr;
13254 if ((lr->color == -1) ||
13255 ((lr->classes & range->classes) == 0) ||
13256 (used[lr->color])) {
13259 if (interfere(rstate, range, lr)) {
13262 range->color = lr->color;
13266 /* If I have not opportunitically picked a useful color
13267 * pick the first color that is free.
13269 if (range->color == REG_UNSET) {
13271 arch_select_free_register(state, used, range->classes);
13273 if (range->color == REG_UNSET) {
13274 struct live_range_def *lrd;
13276 if (split_ranges(state, rstate, used, range)) {
13279 for(edge = range->edges; edge; edge = edge->next) {
13280 warning(state, edge->node->defs->def, "edge reg %s",
13281 arch_reg_str(edge->node->color));
13282 lrd = edge->node->defs;
13284 warning(state, lrd->def, " %s",
13285 tops(lrd->def->op));
13287 } while(lrd != edge->node->defs);
13289 warning(state, range->defs->def, "range: ");
13292 warning(state, lrd->def, " %s",
13293 tops(lrd->def->op));
13295 } while(lrd != range->defs);
13297 warning(state, range->defs->def, "classes: %x",
13299 for(i = 0; i < MAX_REGISTERS; i++) {
13301 warning(state, range->defs->def, "used: %s",
13305 #if DEBUG_COLOR_GRAPH < 2
13306 error(state, range->defs->def, "too few registers");
13308 internal_error(state, range->defs->def, "too few registers");
13311 range->classes = arch_reg_regcm(state, range->color);
13312 if (range->color == -1) {
13313 internal_error(state, range->defs->def, "select_free_color did not?");
13318 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13321 struct live_range_edge *edge;
13322 struct live_range *range;
13324 cgdebug_printf("Lo: ");
13325 range = rstate->low;
13326 if (*range->group_prev != range) {
13327 internal_error(state, 0, "lo: *prev != range?");
13329 *range->group_prev = range->group_next;
13330 if (range->group_next) {
13331 range->group_next->group_prev = range->group_prev;
13333 if (&range->group_next == rstate->low_tail) {
13334 rstate->low_tail = range->group_prev;
13336 if (rstate->low == range) {
13337 internal_error(state, 0, "low: next != prev?");
13340 else if (rstate->high) {
13341 cgdebug_printf("Hi: ");
13342 range = rstate->high;
13343 if (*range->group_prev != range) {
13344 internal_error(state, 0, "hi: *prev != range?");
13346 *range->group_prev = range->group_next;
13347 if (range->group_next) {
13348 range->group_next->group_prev = range->group_prev;
13350 if (&range->group_next == rstate->high_tail) {
13351 rstate->high_tail = range->group_prev;
13353 if (rstate->high == range) {
13354 internal_error(state, 0, "high: next != prev?");
13360 cgdebug_printf(" %d\n", range - rstate->lr);
13361 range->group_prev = 0;
13362 for(edge = range->edges; edge; edge = edge->next) {
13363 struct live_range *node;
13365 /* Move nodes from the high to the low list */
13366 if (node->group_prev && (node->color == REG_UNSET) &&
13367 (node->degree == regc_max_size(state, node->classes))) {
13368 if (*node->group_prev != node) {
13369 internal_error(state, 0, "move: *prev != node?");
13371 *node->group_prev = node->group_next;
13372 if (node->group_next) {
13373 node->group_next->group_prev = node->group_prev;
13375 if (&node->group_next == rstate->high_tail) {
13376 rstate->high_tail = node->group_prev;
13378 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13379 node->group_prev = rstate->low_tail;
13380 node->group_next = 0;
13381 *rstate->low_tail = node;
13382 rstate->low_tail = &node->group_next;
13383 if (*node->group_prev != node) {
13384 internal_error(state, 0, "move2: *prev != node?");
13389 colored = color_graph(state, rstate);
13391 cgdebug_printf("Coloring %d @%s:%d.%d:",
13392 range - rstate->lr,
13393 range->def->filename, range->def->line, range->def->col);
13395 colored = select_free_color(state, rstate, range);
13396 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13401 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13403 struct live_range *lr;
13404 struct live_range_edge *edge;
13405 struct triple *ins, *first;
13406 char used[MAX_REGISTERS];
13407 first = RHS(state->main_function, 0);
13410 if (triple_is_def(state, ins)) {
13411 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13412 internal_error(state, ins,
13413 "triple without a live range def");
13415 lr = rstate->lrd[ins->id].lr;
13416 if (lr->color == REG_UNSET) {
13417 internal_error(state, ins,
13418 "triple without a color");
13420 /* Find the registers used by the edges */
13421 memset(used, 0, sizeof(used));
13422 for(edge = lr->edges; edge; edge = edge->next) {
13423 if (edge->node->color == REG_UNSET) {
13424 internal_error(state, 0,
13425 "live range without a color");
13427 reg_fill_used(state, used, edge->node->color);
13429 if (used[lr->color]) {
13430 internal_error(state, ins,
13431 "triple with already used color");
13435 } while(ins != first);
13438 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13440 struct live_range *lr;
13441 struct triple *first, *ins;
13442 first = RHS(state->main_function, 0);
13445 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13446 internal_error(state, ins,
13447 "triple without a live range");
13449 lr = rstate->lrd[ins->id].lr;
13450 SET_REG(ins->id, lr->color);
13452 } while (ins != first);
13455 static void print_interference_block(
13456 struct compile_state *state, struct block *block, void *arg)
13459 struct reg_state *rstate = arg;
13460 struct reg_block *rb;
13461 struct triple *ptr;
13464 rb = &rstate->blocks[block->vertex];
13466 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
13470 block->left && block->left->use?block->left->use->member : 0,
13472 block->right && block->right->use?block->right->use->member : 0);
13474 struct triple_reg_set *in_set;
13476 for(in_set = rb->in; in_set; in_set = in_set->next) {
13477 printf(" %-10p", in_set->member);
13482 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13483 done = (ptr == block->last);
13484 if (ptr->op == OP_PHI) {
13491 for(edge = 0; edge < block->users; edge++) {
13492 printf(" in(%d):", edge);
13493 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13494 struct triple **slot;
13495 done = (ptr == block->last);
13496 if (ptr->op != OP_PHI) {
13499 slot = &RHS(ptr, 0);
13500 printf(" %-10p", slot[edge]);
13505 if (block->first->op == OP_LABEL) {
13506 printf("%p:\n", block->first);
13508 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13509 struct triple_set *user;
13510 struct live_range *lr;
13514 done = (ptr == block->last);
13515 lr = rstate->lrd[ptr->id].lr;
13517 if (triple_stores_block(state, ptr)) {
13518 if (ptr->u.block != block) {
13519 internal_error(state, ptr,
13520 "Wrong block pointer: %p",
13524 if (op == OP_ADECL) {
13525 for(user = ptr->use; user; user = user->next) {
13526 if (!user->member->u.block) {
13527 internal_error(state, user->member,
13528 "Use %p not in a block?",
13535 ptr->id = rstate->lrd[id].orig_id;
13536 SET_REG(ptr->id, lr->color);
13537 display_triple(stdout, ptr);
13540 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13541 internal_error(state, ptr, "lr has no defs!");
13545 struct live_range_def *lrd;
13549 printf(" %-10p", lrd->def);
13551 } while(lrd != lr->defs);
13554 if (lr->edges > 0) {
13555 struct live_range_edge *edge;
13557 for(edge = lr->edges; edge; edge = edge->next) {
13558 struct live_range_def *lrd;
13559 lrd = edge->node->defs;
13561 printf(" %-10p", lrd->def);
13563 } while(lrd != edge->node->defs);
13568 /* Do a bunch of sanity checks */
13569 valid_ins(state, ptr);
13570 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13571 internal_error(state, ptr, "Invalid triple id: %d",
13574 for(user = ptr->use; user; user = user->next) {
13575 struct triple *use;
13576 struct live_range *ulr;
13577 use = user->member;
13578 valid_ins(state, use);
13579 if ((use->id < 0) || (use->id > rstate->defs)) {
13580 internal_error(state, use, "Invalid triple id: %d",
13583 ulr = rstate->lrd[user->member->id].lr;
13584 if (triple_stores_block(state, user->member) &&
13585 !user->member->u.block) {
13586 internal_error(state, user->member,
13587 "Use %p not in a block?",
13593 struct triple_reg_set *out_set;
13595 for(out_set = rb->out; out_set; out_set = out_set->next) {
13596 printf(" %-10p", out_set->member);
13603 static struct live_range *merge_sort_lr(
13604 struct live_range *first, struct live_range *last)
13606 struct live_range *mid, *join, **join_tail, *pick;
13608 size = (last - first) + 1;
13610 mid = first + size/2;
13611 first = merge_sort_lr(first, mid -1);
13612 mid = merge_sort_lr(mid, last);
13616 /* merge the two lists */
13617 while(first && mid) {
13618 if ((first->degree < mid->degree) ||
13619 ((first->degree == mid->degree) &&
13620 (first->length < mid->length))) {
13622 first = first->group_next;
13624 first->group_prev = 0;
13629 mid = mid->group_next;
13631 mid->group_prev = 0;
13634 pick->group_next = 0;
13635 pick->group_prev = join_tail;
13637 join_tail = &pick->group_next;
13639 /* Splice the remaining list */
13640 pick = (first)? first : mid;
13643 pick->group_prev = join_tail;
13647 if (!first->defs) {
13655 static void ids_from_rstate(struct compile_state *state,
13656 struct reg_state *rstate)
13658 struct triple *ins, *first;
13659 if (!rstate->defs) {
13662 /* Display the graph if desired */
13663 if (state->debug & DEBUG_INTERFERENCE) {
13664 print_blocks(state, stdout);
13665 print_control_flow(state);
13667 first = RHS(state->main_function, 0);
13671 struct live_range_def *lrd;
13672 lrd = &rstate->lrd[ins->id];
13673 ins->id = lrd->orig_id;
13676 } while(ins != first);
13679 static void cleanup_live_edges(struct reg_state *rstate)
13682 /* Free the edges on each node */
13683 for(i = 1; i <= rstate->ranges; i++) {
13684 remove_live_edges(rstate, &rstate->lr[i]);
13688 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13690 cleanup_live_edges(rstate);
13691 xfree(rstate->lrd);
13694 /* Free the variable lifetime information */
13695 if (rstate->blocks) {
13696 free_variable_lifetimes(state, rstate->blocks);
13699 rstate->ranges = 0;
13702 rstate->blocks = 0;
13705 static void verify_consistency(struct compile_state *state);
13706 static void allocate_registers(struct compile_state *state)
13708 struct reg_state rstate;
13711 /* Clear out the reg_state */
13712 memset(&rstate, 0, sizeof(rstate));
13713 rstate.max_passes = MAX_ALLOCATION_PASSES;
13716 struct live_range **point, **next;
13721 fprintf(stderr, "pass: %d\n", rstate.passes);
13725 ids_from_rstate(state, &rstate);
13727 /* Cleanup the temporary data structures */
13728 cleanup_rstate(state, &rstate);
13730 /* Compute the variable lifetimes */
13731 rstate.blocks = compute_variable_lifetimes(state);
13733 /* Fix invalid mandatory live range coalesce conflicts */
13734 walk_variable_lifetimes(
13735 state, rstate.blocks, fix_coalesce_conflicts, 0);
13737 /* Fix two simultaneous uses of the same register.
13738 * In a few pathlogical cases a partial untangle moves
13739 * the tangle to a part of the graph we won't revisit.
13740 * So we keep looping until we have no more tangle fixes
13744 tangles = correct_tangles(state, rstate.blocks);
13747 if (state->debug & DEBUG_INSERTED_COPIES) {
13748 printf("After resolve_tangles\n");
13749 print_blocks(state, stdout);
13750 print_control_flow(state);
13752 verify_consistency(state);
13754 /* Allocate and initialize the live ranges */
13755 initialize_live_ranges(state, &rstate);
13757 /* Note current doing coalescing in a loop appears to
13758 * buys me nothing. The code is left this way in case
13759 * there is some value in it. Or if a future bugfix
13760 * yields some benefit.
13764 fprintf(stderr, "coalescing\n");
13766 /* Remove any previous live edge calculations */
13767 cleanup_live_edges(&rstate);
13769 /* Compute the interference graph */
13770 walk_variable_lifetimes(
13771 state, rstate.blocks, graph_ins, &rstate);
13773 /* Display the interference graph if desired */
13774 if (state->debug & DEBUG_INTERFERENCE) {
13775 printf("\nlive variables by block\n");
13776 walk_blocks(state, print_interference_block, &rstate);
13777 printf("\nlive variables by instruction\n");
13778 walk_variable_lifetimes(
13779 state, rstate.blocks,
13780 print_interference_ins, &rstate);
13783 coalesced = coalesce_live_ranges(state, &rstate);
13786 fprintf(stderr, "coalesced: %d\n", coalesced);
13788 } while(coalesced);
13790 #if DEBUG_CONSISTENCY > 1
13792 fprintf(stderr, "verify_graph_ins...\n");
13794 /* Verify the interference graph */
13795 walk_variable_lifetimes(
13796 state, rstate.blocks, verify_graph_ins, &rstate);
13798 fprintf(stderr, "verify_graph_ins done\n");
13802 /* Build the groups low and high. But with the nodes
13803 * first sorted by degree order.
13805 rstate.low_tail = &rstate.low;
13806 rstate.high_tail = &rstate.high;
13807 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13809 rstate.high->group_prev = &rstate.high;
13811 for(point = &rstate.high; *point; point = &(*point)->group_next)
13813 rstate.high_tail = point;
13814 /* Walk through the high list and move everything that needs
13817 for(point = &rstate.high; *point; point = next) {
13818 struct live_range *range;
13819 next = &(*point)->group_next;
13822 /* If it has a low degree or it already has a color
13823 * place the node in low.
13825 if ((range->degree < regc_max_size(state, range->classes)) ||
13826 (range->color != REG_UNSET)) {
13827 cgdebug_printf("Lo: %5d degree %5d%s\n",
13828 range - rstate.lr, range->degree,
13829 (range->color != REG_UNSET) ? " (colored)": "");
13830 *range->group_prev = range->group_next;
13831 if (range->group_next) {
13832 range->group_next->group_prev = range->group_prev;
13834 if (&range->group_next == rstate.high_tail) {
13835 rstate.high_tail = range->group_prev;
13837 range->group_prev = rstate.low_tail;
13838 range->group_next = 0;
13839 *rstate.low_tail = range;
13840 rstate.low_tail = &range->group_next;
13844 cgdebug_printf("hi: %5d degree %5d%s\n",
13845 range - rstate.lr, range->degree,
13846 (range->color != REG_UNSET) ? " (colored)": "");
13849 /* Color the live_ranges */
13850 colored = color_graph(state, &rstate);
13852 } while (!colored);
13854 /* Verify the graph was properly colored */
13855 verify_colors(state, &rstate);
13857 /* Move the colors from the graph to the triples */
13858 color_triples(state, &rstate);
13860 /* Cleanup the temporary data structures */
13861 cleanup_rstate(state, &rstate);
13864 /* Sparce Conditional Constant Propogation
13865 * =========================================
13869 struct lattice_node {
13871 struct triple *def;
13872 struct ssa_edge *out;
13873 struct flow_block *fblock;
13874 struct triple *val;
13875 /* lattice high val && !is_const(val)
13876 * lattice const is_const(val)
13877 * lattice low val == 0
13881 struct lattice_node *src;
13882 struct lattice_node *dst;
13883 struct ssa_edge *work_next;
13884 struct ssa_edge *work_prev;
13885 struct ssa_edge *out_next;
13888 struct flow_block *src;
13889 struct flow_block *dst;
13890 struct flow_edge *work_next;
13891 struct flow_edge *work_prev;
13892 struct flow_edge *in_next;
13893 struct flow_edge *out_next;
13896 struct flow_block {
13897 struct block *block;
13898 struct flow_edge *in;
13899 struct flow_edge *out;
13900 struct flow_edge left, right;
13905 struct lattice_node *lattice;
13906 struct ssa_edge *ssa_edges;
13907 struct flow_block *flow_blocks;
13908 struct flow_edge *flow_work_list;
13909 struct ssa_edge *ssa_work_list;
13913 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13914 struct flow_edge *fedge)
13916 if (!scc->flow_work_list) {
13917 scc->flow_work_list = fedge;
13918 fedge->work_next = fedge->work_prev = fedge;
13921 struct flow_edge *ftail;
13922 ftail = scc->flow_work_list->work_prev;
13923 fedge->work_next = ftail->work_next;
13924 fedge->work_prev = ftail;
13925 fedge->work_next->work_prev = fedge;
13926 fedge->work_prev->work_next = fedge;
13930 static struct flow_edge *scc_next_fedge(
13931 struct compile_state *state, struct scc_state *scc)
13933 struct flow_edge *fedge;
13934 fedge = scc->flow_work_list;
13936 fedge->work_next->work_prev = fedge->work_prev;
13937 fedge->work_prev->work_next = fedge->work_next;
13938 if (fedge->work_next != fedge) {
13939 scc->flow_work_list = fedge->work_next;
13941 scc->flow_work_list = 0;
13947 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13948 struct ssa_edge *sedge)
13950 if (!scc->ssa_work_list) {
13951 scc->ssa_work_list = sedge;
13952 sedge->work_next = sedge->work_prev = sedge;
13955 struct ssa_edge *stail;
13956 stail = scc->ssa_work_list->work_prev;
13957 sedge->work_next = stail->work_next;
13958 sedge->work_prev = stail;
13959 sedge->work_next->work_prev = sedge;
13960 sedge->work_prev->work_next = sedge;
13964 static struct ssa_edge *scc_next_sedge(
13965 struct compile_state *state, struct scc_state *scc)
13967 struct ssa_edge *sedge;
13968 sedge = scc->ssa_work_list;
13970 sedge->work_next->work_prev = sedge->work_prev;
13971 sedge->work_prev->work_next = sedge->work_next;
13972 if (sedge->work_next != sedge) {
13973 scc->ssa_work_list = sedge->work_next;
13975 scc->ssa_work_list = 0;
13981 static void initialize_scc_state(
13982 struct compile_state *state, struct scc_state *scc)
13984 int ins_count, ssa_edge_count;
13985 int ins_index, ssa_edge_index, fblock_index;
13986 struct triple *first, *ins;
13987 struct block *block;
13988 struct flow_block *fblock;
13990 memset(scc, 0, sizeof(*scc));
13992 /* Inialize pass zero find out how much memory we need */
13993 first = RHS(state->main_function, 0);
13995 ins_count = ssa_edge_count = 0;
13997 struct triple_set *edge;
13999 for(edge = ins->use; edge; edge = edge->next) {
14003 } while(ins != first);
14005 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14006 ins_count, ssa_edge_count, state->last_vertex);
14008 scc->ins_count = ins_count;
14010 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14012 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14014 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
14017 /* Initialize pass one collect up the nodes */
14020 ins_index = ssa_edge_index = fblock_index = 0;
14023 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14024 block = ins->u.block;
14026 internal_error(state, ins, "label without block");
14029 block->vertex = fblock_index;
14030 fblock = &scc->flow_blocks[fblock_index];
14031 fblock->block = block;
14034 struct lattice_node *lnode;
14036 lnode = &scc->lattice[ins_index];
14039 lnode->fblock = fblock;
14040 lnode->val = ins; /* LATTICE HIGH */
14041 lnode->old_id = ins->id;
14042 ins->id = ins_index;
14045 } while(ins != first);
14046 /* Initialize pass two collect up the edges */
14051 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14052 struct flow_edge *fedge, **ftail;
14053 struct block_set *bedge;
14054 block = ins->u.block;
14055 fblock = &scc->flow_blocks[block->vertex];
14058 ftail = &fblock->out;
14060 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14061 if (fblock->left.dst->block != block->left) {
14062 internal_error(state, 0, "block mismatch");
14064 fblock->left.out_next = 0;
14065 *ftail = &fblock->left;
14066 ftail = &fblock->left.out_next;
14068 if (block->right) {
14069 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14070 if (fblock->right.dst->block != block->right) {
14071 internal_error(state, 0, "block mismatch");
14073 fblock->right.out_next = 0;
14074 *ftail = &fblock->right;
14075 ftail = &fblock->right.out_next;
14077 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14078 fedge->src = fblock;
14079 fedge->work_next = fedge->work_prev = fedge;
14080 fedge->executable = 0;
14082 ftail = &fblock->in;
14083 for(bedge = block->use; bedge; bedge = bedge->next) {
14084 struct block *src_block;
14085 struct flow_block *sfblock;
14086 struct flow_edge *sfedge;
14087 src_block = bedge->member;
14088 sfblock = &scc->flow_blocks[src_block->vertex];
14090 if (src_block->left == block) {
14091 sfedge = &sfblock->left;
14093 sfedge = &sfblock->right;
14096 ftail = &sfedge->in_next;
14097 sfedge->in_next = 0;
14101 struct triple_set *edge;
14102 struct ssa_edge **stail;
14103 struct lattice_node *lnode;
14104 lnode = &scc->lattice[ins->id];
14106 stail = &lnode->out;
14107 for(edge = ins->use; edge; edge = edge->next) {
14108 struct ssa_edge *sedge;
14109 ssa_edge_index += 1;
14110 sedge = &scc->ssa_edges[ssa_edge_index];
14112 stail = &sedge->out_next;
14113 sedge->src = lnode;
14114 sedge->dst = &scc->lattice[edge->member->id];
14115 sedge->work_next = sedge->work_prev = sedge;
14116 sedge->out_next = 0;
14120 } while(ins != first);
14121 /* Setup a dummy block 0 as a node above the start node */
14123 struct flow_block *fblock, *dst;
14124 struct flow_edge *fedge;
14125 fblock = &scc->flow_blocks[0];
14128 fblock->out = &fblock->left;
14129 dst = &scc->flow_blocks[state->first_block->vertex];
14130 fedge = &fblock->left;
14131 fedge->src = fblock;
14133 fedge->work_next = fedge;
14134 fedge->work_prev = fedge;
14135 fedge->in_next = fedge->dst->in;
14136 fedge->out_next = 0;
14137 fedge->executable = 0;
14138 fedge->dst->in = fedge;
14140 /* Initialize the work lists */
14141 scc->flow_work_list = 0;
14142 scc->ssa_work_list = 0;
14143 scc_add_fedge(state, scc, fedge);
14146 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14147 ins_index, ssa_edge_index, fblock_index);
14152 static void free_scc_state(
14153 struct compile_state *state, struct scc_state *scc)
14155 xfree(scc->flow_blocks);
14156 xfree(scc->ssa_edges);
14157 xfree(scc->lattice);
14161 static struct lattice_node *triple_to_lattice(
14162 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14164 if (ins->id <= 0) {
14165 internal_error(state, ins, "bad id");
14167 return &scc->lattice[ins->id];
14170 static struct triple *preserve_lval(
14171 struct compile_state *state, struct lattice_node *lnode)
14173 struct triple *old;
14174 /* Preserve the original value */
14176 old = dup_triple(state, lnode->val);
14177 if (lnode->val != lnode->def) {
14187 static int lval_changed(struct compile_state *state,
14188 struct triple *old, struct lattice_node *lnode)
14191 /* See if the lattice value has changed */
14193 if (!old && !lnode->val) {
14196 if (changed && lnode->val && !is_const(lnode->val)) {
14200 lnode->val && old &&
14201 (memcmp(lnode->val->param, old->param,
14202 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14203 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14213 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14214 struct lattice_node *lnode)
14216 struct lattice_node *tmp;
14217 struct triple **slot, *old;
14218 struct flow_edge *fedge;
14220 if (lnode->def->op != OP_PHI) {
14221 internal_error(state, lnode->def, "not phi");
14223 /* Store the original value */
14224 old = preserve_lval(state, lnode);
14226 /* default to lattice high */
14227 lnode->val = lnode->def;
14228 slot = &RHS(lnode->def, 0);
14230 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14231 if (!fedge->executable) {
14234 if (!slot[index]) {
14235 internal_error(state, lnode->def, "no phi value");
14237 tmp = triple_to_lattice(state, scc, slot[index]);
14238 /* meet(X, lattice low) = lattice low */
14242 /* meet(X, lattice high) = X */
14243 else if (!tmp->val) {
14244 lnode->val = lnode->val;
14246 /* meet(lattice high, X) = X */
14247 else if (!is_const(lnode->val)) {
14248 lnode->val = dup_triple(state, tmp->val);
14249 lnode->val->type = lnode->def->type;
14251 /* meet(const, const) = const or lattice low */
14252 else if (!constants_equal(state, lnode->val, tmp->val)) {
14260 fprintf(stderr, "phi: %d -> %s\n",
14262 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14264 /* If the lattice value has changed update the work lists. */
14265 if (lval_changed(state, old, lnode)) {
14266 struct ssa_edge *sedge;
14267 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14268 scc_add_sedge(state, scc, sedge);
14273 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14274 struct lattice_node *lnode)
14277 struct triple *old, *scratch;
14278 struct triple **dexpr, **vexpr;
14281 /* Store the original value */
14282 old = preserve_lval(state, lnode);
14284 /* Reinitialize the value */
14285 lnode->val = scratch = dup_triple(state, lnode->def);
14286 scratch->id = lnode->old_id;
14287 scratch->next = scratch;
14288 scratch->prev = scratch;
14291 count = TRIPLE_SIZE(scratch->sizes);
14292 for(i = 0; i < count; i++) {
14293 dexpr = &lnode->def->param[i];
14294 vexpr = &scratch->param[i];
14296 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14297 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14299 struct lattice_node *tmp;
14300 tmp = triple_to_lattice(state, scc, *dexpr);
14301 *vexpr = (tmp->val)? tmp->val : tmp->def;
14304 if (scratch->op == OP_BRANCH) {
14305 scratch->next = lnode->def->next;
14307 /* Recompute the value */
14308 #warning "FIXME see if simplify does anything bad"
14309 /* So far it looks like only the strength reduction
14310 * optimization are things I need to worry about.
14312 simplify(state, scratch);
14313 /* Cleanup my value */
14314 if (scratch->use) {
14315 internal_error(state, lnode->def, "scratch used?");
14317 if ((scratch->prev != scratch) ||
14318 ((scratch->next != scratch) &&
14319 ((lnode->def->op != OP_BRANCH) ||
14320 (scratch->next != lnode->def->next)))) {
14321 internal_error(state, lnode->def, "scratch in list?");
14323 /* undo any uses... */
14324 count = TRIPLE_SIZE(scratch->sizes);
14325 for(i = 0; i < count; i++) {
14326 vexpr = &scratch->param[i];
14328 unuse_triple(*vexpr, scratch);
14331 if (!is_const(scratch)) {
14332 for(i = 0; i < count; i++) {
14333 dexpr = &lnode->def->param[i];
14334 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14335 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14337 struct lattice_node *tmp;
14338 tmp = triple_to_lattice(state, scc, *dexpr);
14346 (lnode->val->op == lnode->def->op) &&
14347 (memcmp(lnode->val->param, lnode->def->param,
14348 count * sizeof(lnode->val->param[0])) == 0) &&
14349 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14350 lnode->val = lnode->def;
14352 /* Find the cases that are always lattice lo */
14354 triple_is_def(state, lnode->val) &&
14355 !triple_is_pure(state, lnode->val)) {
14359 (lnode->val->op == OP_SDECL) &&
14360 (lnode->val != lnode->def)) {
14361 internal_error(state, lnode->def, "bad sdecl");
14363 /* See if the lattice value has changed */
14364 changed = lval_changed(state, old, lnode);
14365 if (lnode->val != scratch) {
14371 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14372 struct lattice_node *lnode)
14374 struct lattice_node *cond;
14377 struct flow_edge *fedge;
14378 fprintf(stderr, "branch: %d (",
14381 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14382 fprintf(stderr, " %d", fedge->dst->block->vertex);
14384 fprintf(stderr, " )");
14385 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14386 fprintf(stderr, " <- %d",
14387 RHS(lnode->def, 0)->id);
14389 fprintf(stderr, "\n");
14392 if (lnode->def->op != OP_BRANCH) {
14393 internal_error(state, lnode->def, "not branch");
14395 /* This only applies to conditional branches */
14396 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14399 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14400 if (cond->val && !is_const(cond->val)) {
14401 #warning "FIXME do I need to do something here?"
14402 warning(state, cond->def, "condition not constant?");
14405 if (cond->val == 0) {
14406 scc_add_fedge(state, scc, cond->fblock->out);
14407 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14409 else if (cond->val->u.cval) {
14410 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14413 scc_add_fedge(state, scc, cond->fblock->out);
14418 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14419 struct lattice_node *lnode)
14423 changed = compute_lnode_val(state, scc, lnode);
14426 struct triple **expr;
14427 fprintf(stderr, "expr: %3d %10s (",
14428 lnode->def->id, tops(lnode->def->op));
14429 expr = triple_rhs(state, lnode->def, 0);
14430 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14432 fprintf(stderr, " %d", (*expr)->id);
14435 fprintf(stderr, " ) -> %s\n",
14436 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14439 if (lnode->def->op == OP_BRANCH) {
14440 scc_visit_branch(state, scc, lnode);
14443 else if (changed) {
14444 struct ssa_edge *sedge;
14445 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14446 scc_add_sedge(state, scc, sedge);
14451 static void scc_writeback_values(
14452 struct compile_state *state, struct scc_state *scc)
14454 struct triple *first, *ins;
14455 first = RHS(state->main_function, 0);
14458 struct lattice_node *lnode;
14459 lnode = triple_to_lattice(state, scc, ins);
14461 ins->id = lnode->old_id;
14463 if (lnode->val && !is_const(lnode->val)) {
14464 warning(state, lnode->def,
14465 "lattice node still high?");
14468 if (lnode->val && (lnode->val != ins)) {
14469 /* See if it something I know how to write back */
14470 switch(lnode->val->op) {
14472 mkconst(state, ins, lnode->val->u.cval);
14475 mkaddr_const(state, ins,
14476 MISC(lnode->val, 0), lnode->val->u.cval);
14479 /* By default don't copy the changes,
14480 * recompute them in place instead.
14482 simplify(state, ins);
14485 if (is_const(lnode->val) &&
14486 !constants_equal(state, lnode->val, ins)) {
14487 internal_error(state, 0, "constants not equal");
14489 /* Free the lattice nodes */
14494 } while(ins != first);
14497 static void scc_transform(struct compile_state *state)
14499 struct scc_state scc;
14501 initialize_scc_state(state, &scc);
14503 while(scc.flow_work_list || scc.ssa_work_list) {
14504 struct flow_edge *fedge;
14505 struct ssa_edge *sedge;
14506 struct flow_edge *fptr;
14507 while((fedge = scc_next_fedge(state, &scc))) {
14508 struct block *block;
14509 struct triple *ptr;
14510 struct flow_block *fblock;
14513 if (fedge->executable) {
14517 internal_error(state, 0, "fedge without dst");
14520 internal_error(state, 0, "fedge without src");
14522 fedge->executable = 1;
14523 fblock = fedge->dst;
14524 block = fblock->block;
14526 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14527 if (fptr->executable) {
14532 fprintf(stderr, "vertex: %d time: %d\n",
14533 block->vertex, time);
14537 for(ptr = block->first; !done; ptr = ptr->next) {
14538 struct lattice_node *lnode;
14539 done = (ptr == block->last);
14540 lnode = &scc.lattice[ptr->id];
14541 if (ptr->op == OP_PHI) {
14542 scc_visit_phi(state, &scc, lnode);
14544 else if (time == 1) {
14545 scc_visit_expr(state, &scc, lnode);
14548 if (fblock->out && !fblock->out->out_next) {
14549 scc_add_fedge(state, &scc, fblock->out);
14552 while((sedge = scc_next_sedge(state, &scc))) {
14553 struct lattice_node *lnode;
14554 struct flow_block *fblock;
14555 lnode = sedge->dst;
14556 fblock = lnode->fblock;
14558 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14559 sedge - scc.ssa_edges,
14560 sedge->src->def->id,
14561 sedge->dst->def->id);
14563 if (lnode->def->op == OP_PHI) {
14564 scc_visit_phi(state, &scc, lnode);
14567 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14568 if (fptr->executable) {
14573 scc_visit_expr(state, &scc, lnode);
14579 scc_writeback_values(state, &scc);
14580 free_scc_state(state, &scc);
14584 static void transform_to_arch_instructions(struct compile_state *state)
14586 struct triple *ins, *first;
14587 first = RHS(state->main_function, 0);
14590 ins = transform_to_arch_instruction(state, ins);
14591 } while(ins != first);
14594 #if DEBUG_CONSISTENCY
14595 static void verify_uses(struct compile_state *state)
14597 struct triple *first, *ins;
14598 struct triple_set *set;
14599 first = RHS(state->main_function, 0);
14602 struct triple **expr;
14603 expr = triple_rhs(state, ins, 0);
14604 for(; expr; expr = triple_rhs(state, ins, expr)) {
14605 struct triple *rhs;
14607 for(set = rhs?rhs->use:0; set; set = set->next) {
14608 if (set->member == ins) {
14613 internal_error(state, ins, "rhs not used");
14616 expr = triple_lhs(state, ins, 0);
14617 for(; expr; expr = triple_lhs(state, ins, expr)) {
14618 struct triple *lhs;
14620 for(set = lhs?lhs->use:0; set; set = set->next) {
14621 if (set->member == ins) {
14626 internal_error(state, ins, "lhs not used");
14630 } while(ins != first);
14633 static void verify_blocks(struct compile_state *state)
14635 struct triple *ins;
14636 struct block *block;
14637 block = state->first_block;
14642 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14643 if (!triple_stores_block(state, ins)) {
14646 if (ins->u.block != block) {
14647 internal_error(state, ins, "inconsitent block specified");
14650 if (!triple_stores_block(state, block->last->next)) {
14651 internal_error(state, block->last->next,
14652 "cannot find next block");
14654 block = block->last->next->u.block;
14656 internal_error(state, block->last->next,
14659 } while(block != state->first_block);
14662 static void verify_domination(struct compile_state *state)
14664 struct triple *first, *ins;
14665 struct triple_set *set;
14666 if (!state->first_block) {
14670 first = RHS(state->main_function, 0);
14673 for(set = ins->use; set; set = set->next) {
14674 struct triple **expr;
14675 if (set->member->op == OP_PHI) {
14678 /* See if the use is on the righ hand side */
14679 expr = triple_rhs(state, set->member, 0);
14680 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14681 if (*expr == ins) {
14686 !tdominates(state, ins, set->member)) {
14687 internal_error(state, set->member,
14688 "non dominated rhs use?");
14692 } while(ins != first);
14695 static void verify_piece(struct compile_state *state)
14697 struct triple *first, *ins;
14698 first = RHS(state->main_function, 0);
14701 struct triple *ptr;
14703 lhs = TRIPLE_LHS(ins->sizes);
14704 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14707 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14708 if (ptr != LHS(ins, i)) {
14709 internal_error(state, ins, "malformed lhs on %s",
14712 if (ptr->op != OP_PIECE) {
14713 internal_error(state, ins, "bad lhs op %s at %d on %s",
14714 tops(ptr->op), i, tops(ins->op));
14716 if (ptr->u.cval != i) {
14717 internal_error(state, ins, "bad u.cval of %d %d expected",
14722 } while(ins != first);
14724 static void verify_ins_colors(struct compile_state *state)
14726 struct triple *first, *ins;
14728 first = RHS(state->main_function, 0);
14732 } while(ins != first);
14734 static void verify_consistency(struct compile_state *state)
14736 verify_uses(state);
14737 verify_blocks(state);
14738 verify_domination(state);
14739 verify_piece(state);
14740 verify_ins_colors(state);
14743 static void verify_consistency(struct compile_state *state) {}
14744 #endif /* DEBUG_USES */
14746 static void optimize(struct compile_state *state)
14748 if (state->debug & DEBUG_TRIPLES) {
14749 print_triples(state);
14751 /* Replace structures with simpler data types */
14752 flatten_structures(state);
14753 if (state->debug & DEBUG_TRIPLES) {
14754 print_triples(state);
14756 verify_consistency(state);
14757 /* Analize the intermediate code */
14758 setup_basic_blocks(state);
14759 analyze_idominators(state);
14760 analyze_ipdominators(state);
14761 /* Transform the code to ssa form */
14762 transform_to_ssa_form(state);
14763 verify_consistency(state);
14764 if (state->debug & DEBUG_CODE_ELIMINATION) {
14765 fprintf(stdout, "After transform_to_ssa_form\n");
14766 print_blocks(state, stdout);
14768 /* Do strength reduction and simple constant optimizations */
14769 if (state->optimize >= 1) {
14770 simplify_all(state);
14772 verify_consistency(state);
14773 /* Propogate constants throughout the code */
14774 if (state->optimize >= 2) {
14775 #warning "FIXME fix scc_transform"
14776 scc_transform(state);
14777 transform_from_ssa_form(state);
14778 free_basic_blocks(state);
14779 setup_basic_blocks(state);
14780 analyze_idominators(state);
14781 analyze_ipdominators(state);
14782 transform_to_ssa_form(state);
14784 verify_consistency(state);
14785 #warning "WISHLIST implement single use constants (least possible register pressure)"
14786 #warning "WISHLIST implement induction variable elimination"
14787 /* Select architecture instructions and an initial partial
14788 * coloring based on architecture constraints.
14790 transform_to_arch_instructions(state);
14791 verify_consistency(state);
14792 if (state->debug & DEBUG_ARCH_CODE) {
14793 printf("After transform_to_arch_instructions\n");
14794 print_blocks(state, stdout);
14795 print_control_flow(state);
14797 eliminate_inefectual_code(state);
14798 verify_consistency(state);
14799 if (state->debug & DEBUG_CODE_ELIMINATION) {
14800 printf("After eliminate_inefectual_code\n");
14801 print_blocks(state, stdout);
14802 print_control_flow(state);
14804 verify_consistency(state);
14805 /* Color all of the variables to see if they will fit in registers */
14806 insert_copies_to_phi(state);
14807 if (state->debug & DEBUG_INSERTED_COPIES) {
14808 printf("After insert_copies_to_phi\n");
14809 print_blocks(state, stdout);
14810 print_control_flow(state);
14812 verify_consistency(state);
14813 insert_mandatory_copies(state);
14814 if (state->debug & DEBUG_INSERTED_COPIES) {
14815 printf("After insert_mandatory_copies\n");
14816 print_blocks(state, stdout);
14817 print_control_flow(state);
14819 verify_consistency(state);
14820 allocate_registers(state);
14821 verify_consistency(state);
14822 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14823 print_blocks(state, stdout);
14825 if (state->debug & DEBUG_CONTROL_FLOW) {
14826 print_control_flow(state);
14828 /* Remove the optimization information.
14829 * This is more to check for memory consistency than to free memory.
14831 free_basic_blocks(state);
14834 static void print_op_asm(struct compile_state *state,
14835 struct triple *ins, FILE *fp)
14837 struct asm_info *info;
14839 unsigned lhs, rhs, i;
14840 info = ins->u.ainfo;
14841 lhs = TRIPLE_LHS(ins->sizes);
14842 rhs = TRIPLE_RHS(ins->sizes);
14843 /* Don't count the clobbers in lhs */
14844 for(i = 0; i < lhs; i++) {
14845 if (LHS(ins, i)->type == &void_type) {
14850 fprintf(fp, "#ASM\n");
14852 for(ptr = info->str; *ptr; ptr++) {
14854 unsigned long param;
14855 struct triple *piece;
14865 param = strtoul(ptr, &next, 10);
14867 error(state, ins, "Invalid asm template");
14869 if (param >= (lhs + rhs)) {
14870 error(state, ins, "Invalid param %%%u in asm template",
14873 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14875 arch_reg_str(ID_REG(piece->id)));
14878 fprintf(fp, "\n#NOT ASM\n");
14882 /* Only use the low x86 byte registers. This allows me
14883 * allocate the entire register when a byte register is used.
14885 #define X86_4_8BIT_GPRS 1
14887 /* Recognized x86 cpu variants */
14895 #define CPU_DEFAULT CPU_I386
14897 /* The x86 register classes */
14898 #define REGC_FLAGS 0
14899 #define REGC_GPR8 1
14900 #define REGC_GPR16 2
14901 #define REGC_GPR32 3
14902 #define REGC_GPR64 4
14905 #define REGC_GPR32_8 7
14906 #define REGC_GPR16_8 8
14907 #define REGC_IMM32 9
14908 #define REGC_IMM16 10
14909 #define REGC_IMM8 11
14910 #define LAST_REGC REGC_IMM8
14911 #if LAST_REGC >= MAX_REGC
14912 #error "MAX_REGC is to low"
14915 /* Register class masks */
14916 #define REGCM_FLAGS (1 << REGC_FLAGS)
14917 #define REGCM_GPR8 (1 << REGC_GPR8)
14918 #define REGCM_GPR16 (1 << REGC_GPR16)
14919 #define REGCM_GPR32 (1 << REGC_GPR32)
14920 #define REGCM_GPR64 (1 << REGC_GPR64)
14921 #define REGCM_MMX (1 << REGC_MMX)
14922 #define REGCM_XMM (1 << REGC_XMM)
14923 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14924 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14925 #define REGCM_IMM32 (1 << REGC_IMM32)
14926 #define REGCM_IMM16 (1 << REGC_IMM16)
14927 #define REGCM_IMM8 (1 << REGC_IMM8)
14928 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14930 /* The x86 registers */
14931 #define REG_EFLAGS 2
14932 #define REGC_FLAGS_FIRST REG_EFLAGS
14933 #define REGC_FLAGS_LAST REG_EFLAGS
14942 #define REGC_GPR8_FIRST REG_AL
14943 #if X86_4_8BIT_GPRS
14944 #define REGC_GPR8_LAST REG_DL
14946 #define REGC_GPR8_LAST REG_DH
14956 #define REGC_GPR16_FIRST REG_AX
14957 #define REGC_GPR16_LAST REG_SP
14966 #define REGC_GPR32_FIRST REG_EAX
14967 #define REGC_GPR32_LAST REG_ESP
14968 #define REG_EDXEAX 27
14969 #define REGC_GPR64_FIRST REG_EDXEAX
14970 #define REGC_GPR64_LAST REG_EDXEAX
14971 #define REG_MMX0 28
14972 #define REG_MMX1 29
14973 #define REG_MMX2 30
14974 #define REG_MMX3 31
14975 #define REG_MMX4 32
14976 #define REG_MMX5 33
14977 #define REG_MMX6 34
14978 #define REG_MMX7 35
14979 #define REGC_MMX_FIRST REG_MMX0
14980 #define REGC_MMX_LAST REG_MMX7
14981 #define REG_XMM0 36
14982 #define REG_XMM1 37
14983 #define REG_XMM2 38
14984 #define REG_XMM3 39
14985 #define REG_XMM4 40
14986 #define REG_XMM5 41
14987 #define REG_XMM6 42
14988 #define REG_XMM7 43
14989 #define REGC_XMM_FIRST REG_XMM0
14990 #define REGC_XMM_LAST REG_XMM7
14991 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14992 #define LAST_REG REG_XMM7
14994 #define REGC_GPR32_8_FIRST REG_EAX
14995 #define REGC_GPR32_8_LAST REG_EDX
14996 #define REGC_GPR16_8_FIRST REG_AX
14997 #define REGC_GPR16_8_LAST REG_DX
14999 #define REGC_IMM8_FIRST -1
15000 #define REGC_IMM8_LAST -1
15001 #define REGC_IMM16_FIRST -2
15002 #define REGC_IMM16_LAST -1
15003 #define REGC_IMM32_FIRST -4
15004 #define REGC_IMM32_LAST -1
15006 #if LAST_REG >= MAX_REGISTERS
15007 #error "MAX_REGISTERS to low"
15011 static unsigned regc_size[LAST_REGC +1] = {
15012 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
15013 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
15014 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
15015 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
15016 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
15017 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
15018 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
15019 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15020 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15026 static const struct {
15028 } regcm_bound[LAST_REGC + 1] = {
15029 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
15030 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
15031 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
15032 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
15033 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
15034 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
15035 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
15036 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15037 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15038 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
15039 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
15040 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
15043 static int arch_encode_cpu(const char *cpu)
15049 { "i386", CPU_I386 },
15057 for(ptr = cpus; ptr->name; ptr++) {
15058 if (strcmp(ptr->name, cpu) == 0) {
15065 static unsigned arch_regc_size(struct compile_state *state, int class)
15067 if ((class < 0) || (class > LAST_REGC)) {
15070 return regc_size[class];
15072 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15074 /* See if two register classes may have overlapping registers */
15075 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15076 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
15078 /* Special case for the immediates */
15079 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15080 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15081 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15082 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
15085 return (regcm1 & regcm2) ||
15086 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15089 static void arch_reg_equivs(
15090 struct compile_state *state, unsigned *equiv, int reg)
15092 if ((reg < 0) || (reg > LAST_REG)) {
15093 internal_error(state, 0, "invalid register");
15098 #if X86_4_8BIT_GPRS
15102 *equiv++ = REG_EAX;
15103 *equiv++ = REG_EDXEAX;
15106 #if X86_4_8BIT_GPRS
15110 *equiv++ = REG_EAX;
15111 *equiv++ = REG_EDXEAX;
15114 #if X86_4_8BIT_GPRS
15118 *equiv++ = REG_EBX;
15122 #if X86_4_8BIT_GPRS
15126 *equiv++ = REG_EBX;
15129 #if X86_4_8BIT_GPRS
15133 *equiv++ = REG_ECX;
15137 #if X86_4_8BIT_GPRS
15141 *equiv++ = REG_ECX;
15144 #if X86_4_8BIT_GPRS
15148 *equiv++ = REG_EDX;
15149 *equiv++ = REG_EDXEAX;
15152 #if X86_4_8BIT_GPRS
15156 *equiv++ = REG_EDX;
15157 *equiv++ = REG_EDXEAX;
15162 *equiv++ = REG_EAX;
15163 *equiv++ = REG_EDXEAX;
15168 *equiv++ = REG_EBX;
15173 *equiv++ = REG_ECX;
15178 *equiv++ = REG_EDX;
15179 *equiv++ = REG_EDXEAX;
15182 *equiv++ = REG_ESI;
15185 *equiv++ = REG_EDI;
15188 *equiv++ = REG_EBP;
15191 *equiv++ = REG_ESP;
15197 *equiv++ = REG_EDXEAX;
15213 *equiv++ = REG_EDXEAX;
15234 *equiv++ = REG_EAX;
15235 *equiv++ = REG_EDX;
15238 *equiv++ = REG_UNSET;
15241 static unsigned arch_avail_mask(struct compile_state *state)
15243 unsigned avail_mask;
15244 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15245 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15246 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15247 switch(state->cpu) {
15250 avail_mask |= REGCM_MMX;
15254 avail_mask |= REGCM_MMX | REGCM_XMM;
15258 /* Don't enable 8 bit values until I can force both operands
15259 * to be 8bits simultaneously.
15261 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15266 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15268 unsigned mask, result;
15271 result &= arch_avail_mask(state);
15273 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15274 if ((result & mask) == 0) {
15277 if (class > LAST_REGC) {
15280 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15281 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15282 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15283 result |= (1 << class2);
15290 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15295 for(class = 0; class <= LAST_REGC; class++) {
15296 if ((reg >= regcm_bound[class].first) &&
15297 (reg <= regcm_bound[class].last)) {
15298 mask |= (1 << class);
15302 internal_error(state, 0, "reg %d not in any class", reg);
15307 static struct reg_info arch_reg_constraint(
15308 struct compile_state *state, struct type *type, const char *constraint)
15310 static const struct {
15314 } constraints[] = {
15315 { 'r', REGCM_GPR32, REG_UNSET },
15316 { 'g', REGCM_GPR32, REG_UNSET },
15317 { 'p', REGCM_GPR32, REG_UNSET },
15318 { 'q', REGCM_GPR8, REG_UNSET },
15319 { 'Q', REGCM_GPR32_8, REG_UNSET },
15320 { 'x', REGCM_XMM, REG_UNSET },
15321 { 'y', REGCM_MMX, REG_UNSET },
15322 { 'a', REGCM_GPR32, REG_EAX },
15323 { 'b', REGCM_GPR32, REG_EBX },
15324 { 'c', REGCM_GPR32, REG_ECX },
15325 { 'd', REGCM_GPR32, REG_EDX },
15326 { 'D', REGCM_GPR32, REG_EDI },
15327 { 'S', REGCM_GPR32, REG_ESI },
15328 { '\0', 0, REG_UNSET },
15330 unsigned int regcm;
15331 unsigned int mask, reg;
15332 struct reg_info result;
15334 regcm = arch_type_to_regcm(state, type);
15337 for(ptr = constraint; *ptr; ptr++) {
15342 for(i = 0; constraints[i].class != '\0'; i++) {
15343 if (constraints[i].class == *ptr) {
15347 if (constraints[i].class == '\0') {
15348 error(state, 0, "invalid register constraint ``%c''", *ptr);
15351 if ((constraints[i].mask & regcm) == 0) {
15352 error(state, 0, "invalid register class %c specified",
15355 mask |= constraints[i].mask;
15356 if (constraints[i].reg != REG_UNSET) {
15357 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15358 error(state, 0, "Only one register may be specified");
15360 reg = constraints[i].reg;
15364 result.regcm = mask;
15368 static struct reg_info arch_reg_clobber(
15369 struct compile_state *state, const char *clobber)
15371 struct reg_info result;
15372 if (strcmp(clobber, "memory") == 0) {
15373 result.reg = REG_UNSET;
15376 else if (strcmp(clobber, "%eax") == 0) {
15377 result.reg = REG_EAX;
15378 result.regcm = REGCM_GPR32;
15380 else if (strcmp(clobber, "%ebx") == 0) {
15381 result.reg = REG_EBX;
15382 result.regcm = REGCM_GPR32;
15384 else if (strcmp(clobber, "%ecx") == 0) {
15385 result.reg = REG_ECX;
15386 result.regcm = REGCM_GPR32;
15388 else if (strcmp(clobber, "%edx") == 0) {
15389 result.reg = REG_EDX;
15390 result.regcm = REGCM_GPR32;
15392 else if (strcmp(clobber, "%esi") == 0) {
15393 result.reg = REG_ESI;
15394 result.regcm = REGCM_GPR32;
15396 else if (strcmp(clobber, "%edi") == 0) {
15397 result.reg = REG_EDI;
15398 result.regcm = REGCM_GPR32;
15400 else if (strcmp(clobber, "%ebp") == 0) {
15401 result.reg = REG_EBP;
15402 result.regcm = REGCM_GPR32;
15404 else if (strcmp(clobber, "%esp") == 0) {
15405 result.reg = REG_ESP;
15406 result.regcm = REGCM_GPR32;
15408 else if (strcmp(clobber, "cc") == 0) {
15409 result.reg = REG_EFLAGS;
15410 result.regcm = REGCM_FLAGS;
15412 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15413 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15414 result.reg = REG_XMM0 + octdigval(clobber[3]);
15415 result.regcm = REGCM_XMM;
15417 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15418 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15419 result.reg = REG_MMX0 + octdigval(clobber[3]);
15420 result.regcm = REGCM_MMX;
15423 error(state, 0, "Invalid register clobber");
15424 result.reg = REG_UNSET;
15430 static int do_select_reg(struct compile_state *state,
15431 char *used, int reg, unsigned classes)
15437 mask = arch_reg_regcm(state, reg);
15438 return (classes & mask) ? reg : REG_UNSET;
15441 static int arch_select_free_register(
15442 struct compile_state *state, char *used, int classes)
15444 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
15445 * other types of registers.
15449 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15450 reg = do_select_reg(state, used, i, classes);
15452 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
15453 reg = do_select_reg(state, used, i, classes);
15455 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15456 reg = do_select_reg(state, used, i, classes);
15458 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15459 reg = do_select_reg(state, used, i, classes);
15461 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15462 reg = do_select_reg(state, used, i, classes);
15464 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15465 reg = do_select_reg(state, used, i, classes);
15467 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15468 reg = do_select_reg(state, used, i, classes);
15474 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15476 #warning "FIXME force types smaller (if legal) before I get here"
15477 unsigned avail_mask;
15480 avail_mask = arch_avail_mask(state);
15481 switch(type->type & TYPE_MASK) {
15488 mask = REGCM_GPR8 |
15489 REGCM_GPR16 | REGCM_GPR16_8 |
15490 REGCM_GPR32 | REGCM_GPR32_8 |
15492 REGCM_MMX | REGCM_XMM |
15493 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15497 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15498 REGCM_GPR32 | REGCM_GPR32_8 |
15500 REGCM_MMX | REGCM_XMM |
15501 REGCM_IMM32 | REGCM_IMM16;
15508 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15509 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15513 internal_error(state, 0, "no register class for type");
15516 mask &= avail_mask;
15520 static int is_imm32(struct triple *imm)
15522 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15523 (imm->op == OP_ADDRCONST);
15526 static int is_imm16(struct triple *imm)
15528 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15530 static int is_imm8(struct triple *imm)
15532 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15535 static int get_imm32(struct triple *ins, struct triple **expr)
15537 struct triple *imm;
15539 while(imm->op == OP_COPY) {
15542 if (!is_imm32(imm)) {
15545 unuse_triple(*expr, ins);
15546 use_triple(imm, ins);
15551 static int get_imm8(struct triple *ins, struct triple **expr)
15553 struct triple *imm;
15555 while(imm->op == OP_COPY) {
15558 if (!is_imm8(imm)) {
15561 unuse_triple(*expr, ins);
15562 use_triple(imm, ins);
15567 #define TEMPLATE_NOP 0
15568 #define TEMPLATE_INTCONST8 1
15569 #define TEMPLATE_INTCONST32 2
15570 #define TEMPLATE_COPY_REG 3
15571 #define TEMPLATE_COPY_IMM32 4
15572 #define TEMPLATE_COPY_IMM16 5
15573 #define TEMPLATE_COPY_IMM8 6
15574 #define TEMPLATE_PHI 7
15575 #define TEMPLATE_STORE8 8
15576 #define TEMPLATE_STORE16 9
15577 #define TEMPLATE_STORE32 10
15578 #define TEMPLATE_LOAD8 11
15579 #define TEMPLATE_LOAD16 12
15580 #define TEMPLATE_LOAD32 13
15581 #define TEMPLATE_BINARY_REG 14
15582 #define TEMPLATE_BINARY_IMM 15
15583 #define TEMPLATE_SL_CL 16
15584 #define TEMPLATE_SL_IMM 17
15585 #define TEMPLATE_UNARY 18
15586 #define TEMPLATE_CMP_REG 19
15587 #define TEMPLATE_CMP_IMM 20
15588 #define TEMPLATE_TEST 21
15589 #define TEMPLATE_SET 22
15590 #define TEMPLATE_JMP 23
15591 #define TEMPLATE_INB_DX 24
15592 #define TEMPLATE_INB_IMM 25
15593 #define TEMPLATE_INW_DX 26
15594 #define TEMPLATE_INW_IMM 27
15595 #define TEMPLATE_INL_DX 28
15596 #define TEMPLATE_INL_IMM 29
15597 #define TEMPLATE_OUTB_DX 30
15598 #define TEMPLATE_OUTB_IMM 31
15599 #define TEMPLATE_OUTW_DX 32
15600 #define TEMPLATE_OUTW_IMM 33
15601 #define TEMPLATE_OUTL_DX 34
15602 #define TEMPLATE_OUTL_IMM 35
15603 #define TEMPLATE_BSF 36
15604 #define TEMPLATE_RDMSR 37
15605 #define TEMPLATE_WRMSR 38
15606 #define LAST_TEMPLATE TEMPLATE_WRMSR
15607 #if LAST_TEMPLATE >= MAX_TEMPLATES
15608 #error "MAX_TEMPLATES to low"
15611 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15612 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15614 static struct ins_template templates[] = {
15615 [TEMPLATE_NOP] = {},
15616 [TEMPLATE_INTCONST8] = {
15617 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15619 [TEMPLATE_INTCONST32] = {
15620 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15622 [TEMPLATE_COPY_REG] = {
15623 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15624 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
15626 [TEMPLATE_COPY_IMM32] = {
15627 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15628 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15630 [TEMPLATE_COPY_IMM16] = {
15631 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15632 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15634 [TEMPLATE_COPY_IMM8] = {
15635 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15636 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15639 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15641 [ 0] = { REG_VIRT0, COPY_REGCM },
15642 [ 1] = { REG_VIRT0, COPY_REGCM },
15643 [ 2] = { REG_VIRT0, COPY_REGCM },
15644 [ 3] = { REG_VIRT0, COPY_REGCM },
15645 [ 4] = { REG_VIRT0, COPY_REGCM },
15646 [ 5] = { REG_VIRT0, COPY_REGCM },
15647 [ 6] = { REG_VIRT0, COPY_REGCM },
15648 [ 7] = { REG_VIRT0, COPY_REGCM },
15649 [ 8] = { REG_VIRT0, COPY_REGCM },
15650 [ 9] = { REG_VIRT0, COPY_REGCM },
15651 [10] = { REG_VIRT0, COPY_REGCM },
15652 [11] = { REG_VIRT0, COPY_REGCM },
15653 [12] = { REG_VIRT0, COPY_REGCM },
15654 [13] = { REG_VIRT0, COPY_REGCM },
15655 [14] = { REG_VIRT0, COPY_REGCM },
15656 [15] = { REG_VIRT0, COPY_REGCM },
15658 [TEMPLATE_STORE8] = {
15659 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15660 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15662 [TEMPLATE_STORE16] = {
15663 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15664 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15666 [TEMPLATE_STORE32] = {
15667 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15668 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15670 [TEMPLATE_LOAD8] = {
15671 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15672 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15674 [TEMPLATE_LOAD16] = {
15675 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15676 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15678 [TEMPLATE_LOAD32] = {
15679 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15680 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15682 [TEMPLATE_BINARY_REG] = {
15683 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15685 [0] = { REG_VIRT0, REGCM_GPR32 },
15686 [1] = { REG_UNSET, REGCM_GPR32 },
15689 [TEMPLATE_BINARY_IMM] = {
15690 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15692 [0] = { REG_VIRT0, REGCM_GPR32 },
15693 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15696 [TEMPLATE_SL_CL] = {
15697 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15699 [0] = { REG_VIRT0, REGCM_GPR32 },
15700 [1] = { REG_CL, REGCM_GPR8 },
15703 [TEMPLATE_SL_IMM] = {
15704 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15706 [0] = { REG_VIRT0, REGCM_GPR32 },
15707 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15710 [TEMPLATE_UNARY] = {
15711 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15712 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15714 [TEMPLATE_CMP_REG] = {
15715 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15717 [0] = { REG_UNSET, REGCM_GPR32 },
15718 [1] = { REG_UNSET, REGCM_GPR32 },
15721 [TEMPLATE_CMP_IMM] = {
15722 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15724 [0] = { REG_UNSET, REGCM_GPR32 },
15725 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15728 [TEMPLATE_TEST] = {
15729 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15730 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15733 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15734 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15737 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15739 [TEMPLATE_INB_DX] = {
15740 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15741 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15743 [TEMPLATE_INB_IMM] = {
15744 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15745 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15747 [TEMPLATE_INW_DX] = {
15748 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15749 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15751 [TEMPLATE_INW_IMM] = {
15752 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15753 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15755 [TEMPLATE_INL_DX] = {
15756 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15757 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15759 [TEMPLATE_INL_IMM] = {
15760 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15761 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15763 [TEMPLATE_OUTB_DX] = {
15765 [0] = { REG_AL, REGCM_GPR8 },
15766 [1] = { REG_DX, REGCM_GPR16 },
15769 [TEMPLATE_OUTB_IMM] = {
15771 [0] = { REG_AL, REGCM_GPR8 },
15772 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15775 [TEMPLATE_OUTW_DX] = {
15777 [0] = { REG_AX, REGCM_GPR16 },
15778 [1] = { REG_DX, REGCM_GPR16 },
15781 [TEMPLATE_OUTW_IMM] = {
15783 [0] = { REG_AX, REGCM_GPR16 },
15784 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15787 [TEMPLATE_OUTL_DX] = {
15789 [0] = { REG_EAX, REGCM_GPR32 },
15790 [1] = { REG_DX, REGCM_GPR16 },
15793 [TEMPLATE_OUTL_IMM] = {
15795 [0] = { REG_EAX, REGCM_GPR32 },
15796 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15800 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15801 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15803 [TEMPLATE_RDMSR] = {
15805 [0] = { REG_EAX, REGCM_GPR32 },
15806 [1] = { REG_EDX, REGCM_GPR32 },
15808 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15810 [TEMPLATE_WRMSR] = {
15812 [0] = { REG_ECX, REGCM_GPR32 },
15813 [1] = { REG_EAX, REGCM_GPR32 },
15814 [2] = { REG_EDX, REGCM_GPR32 },
15819 static void fixup_branches(struct compile_state *state,
15820 struct triple *cmp, struct triple *use, int jmp_op)
15822 struct triple_set *entry, *next;
15823 for(entry = use->use; entry; entry = next) {
15824 next = entry->next;
15825 if (entry->member->op == OP_COPY) {
15826 fixup_branches(state, cmp, entry->member, jmp_op);
15828 else if (entry->member->op == OP_BRANCH) {
15829 struct triple *branch, *test;
15830 struct triple *left, *right;
15832 left = RHS(cmp, 0);
15833 if (TRIPLE_RHS(cmp->sizes) > 1) {
15834 right = RHS(cmp, 1);
15836 branch = entry->member;
15837 test = pre_triple(state, branch,
15838 cmp->op, cmp->type, left, right);
15839 test->template_id = TEMPLATE_TEST;
15840 if (cmp->op == OP_CMP) {
15841 test->template_id = TEMPLATE_CMP_REG;
15842 if (get_imm32(test, &RHS(test, 1))) {
15843 test->template_id = TEMPLATE_CMP_IMM;
15846 use_triple(RHS(test, 0), test);
15847 use_triple(RHS(test, 1), test);
15848 unuse_triple(RHS(branch, 0), branch);
15849 RHS(branch, 0) = test;
15850 branch->op = jmp_op;
15851 branch->template_id = TEMPLATE_JMP;
15852 use_triple(RHS(branch, 0), branch);
15857 static void bool_cmp(struct compile_state *state,
15858 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15860 struct triple_set *entry, *next;
15861 struct triple *set;
15863 /* Put a barrier up before the cmp which preceeds the
15864 * copy instruction. If a set actually occurs this gives
15865 * us a chance to move variables in registers out of the way.
15868 /* Modify the comparison operator */
15870 ins->template_id = TEMPLATE_TEST;
15871 if (cmp_op == OP_CMP) {
15872 ins->template_id = TEMPLATE_CMP_REG;
15873 if (get_imm32(ins, &RHS(ins, 1))) {
15874 ins->template_id = TEMPLATE_CMP_IMM;
15877 /* Generate the instruction sequence that will transform the
15878 * result of the comparison into a logical value.
15880 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15881 use_triple(ins, set);
15882 set->template_id = TEMPLATE_SET;
15884 for(entry = ins->use; entry; entry = next) {
15885 next = entry->next;
15886 if (entry->member == set) {
15889 replace_rhs_use(state, ins, set, entry->member);
15891 fixup_branches(state, ins, set, jmp_op);
15894 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15896 struct triple *next;
15898 lhs = TRIPLE_LHS(ins->sizes);
15899 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15900 if (next != LHS(ins, i)) {
15901 internal_error(state, ins, "malformed lhs on %s",
15904 if (next->op != OP_PIECE) {
15905 internal_error(state, ins, "bad lhs op %s at %d on %s",
15906 tops(next->op), i, tops(ins->op));
15908 if (next->u.cval != i) {
15909 internal_error(state, ins, "bad u.cval of %d %d expected",
15916 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15918 struct ins_template *template;
15919 struct reg_info result;
15921 if (ins->op == OP_PIECE) {
15922 index = ins->u.cval;
15923 ins = MISC(ins, 0);
15925 zlhs = TRIPLE_LHS(ins->sizes);
15926 if (triple_is_def(state, ins)) {
15929 if (index >= zlhs) {
15930 internal_error(state, ins, "index %d out of range for %s\n",
15931 index, tops(ins->op));
15935 template = &ins->u.ainfo->tmpl;
15938 if (ins->template_id > LAST_TEMPLATE) {
15939 internal_error(state, ins, "bad template number %d",
15942 template = &templates[ins->template_id];
15945 result = template->lhs[index];
15946 result.regcm = arch_regcm_normalize(state, result.regcm);
15947 if (result.reg != REG_UNNEEDED) {
15948 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15950 if (result.regcm == 0) {
15951 internal_error(state, ins, "lhs %d regcm == 0", index);
15956 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15958 struct reg_info result;
15959 struct ins_template *template;
15960 if ((index > TRIPLE_RHS(ins->sizes)) ||
15961 (ins->op == OP_PIECE)) {
15962 internal_error(state, ins, "index %d out of range for %s\n",
15963 index, tops(ins->op));
15967 template = &ins->u.ainfo->tmpl;
15970 if (ins->template_id > LAST_TEMPLATE) {
15971 internal_error(state, ins, "bad template number %d",
15974 template = &templates[ins->template_id];
15977 result = template->rhs[index];
15978 result.regcm = arch_regcm_normalize(state, result.regcm);
15979 if (result.regcm == 0) {
15980 internal_error(state, ins, "rhs %d regcm == 0", index);
15985 static struct triple *transform_to_arch_instruction(
15986 struct compile_state *state, struct triple *ins)
15988 /* Transform from generic 3 address instructions
15989 * to archtecture specific instructions.
15990 * And apply architecture specific constrains to instructions.
15991 * Copies are inserted to preserve the register flexibility
15992 * of 3 address instructions.
15994 struct triple *next;
15998 ins->template_id = TEMPLATE_INTCONST32;
15999 if (ins->u.cval < 256) {
16000 ins->template_id = TEMPLATE_INTCONST8;
16004 ins->template_id = TEMPLATE_INTCONST32;
16010 ins->template_id = TEMPLATE_NOP;
16013 ins->template_id = TEMPLATE_COPY_REG;
16014 if (is_imm8(RHS(ins, 0))) {
16015 ins->template_id = TEMPLATE_COPY_IMM8;
16017 else if (is_imm16(RHS(ins, 0))) {
16018 ins->template_id = TEMPLATE_COPY_IMM16;
16020 else if (is_imm32(RHS(ins, 0))) {
16021 ins->template_id = TEMPLATE_COPY_IMM32;
16023 else if (is_const(RHS(ins, 0))) {
16024 internal_error(state, ins, "bad constant passed to copy");
16028 ins->template_id = TEMPLATE_PHI;
16031 switch(ins->type->type & TYPE_MASK) {
16032 case TYPE_CHAR: case TYPE_UCHAR:
16033 ins->template_id = TEMPLATE_STORE8;
16035 case TYPE_SHORT: case TYPE_USHORT:
16036 ins->template_id = TEMPLATE_STORE16;
16038 case TYPE_INT: case TYPE_UINT:
16039 case TYPE_LONG: case TYPE_ULONG:
16041 ins->template_id = TEMPLATE_STORE32;
16044 internal_error(state, ins, "unknown type in store");
16049 switch(ins->type->type & TYPE_MASK) {
16050 case TYPE_CHAR: case TYPE_UCHAR:
16051 ins->template_id = TEMPLATE_LOAD8;
16055 ins->template_id = TEMPLATE_LOAD16;
16062 ins->template_id = TEMPLATE_LOAD32;
16065 internal_error(state, ins, "unknown type in load");
16075 ins->template_id = TEMPLATE_BINARY_REG;
16076 if (get_imm32(ins, &RHS(ins, 1))) {
16077 ins->template_id = TEMPLATE_BINARY_IMM;
16083 ins->template_id = TEMPLATE_SL_CL;
16084 if (get_imm8(ins, &RHS(ins, 1))) {
16085 ins->template_id = TEMPLATE_SL_IMM;
16090 ins->template_id = TEMPLATE_UNARY;
16093 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16096 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16099 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16102 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16105 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16108 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16111 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16114 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16117 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16120 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16123 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16126 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16129 if (TRIPLE_RHS(ins->sizes) > 0) {
16130 internal_error(state, ins, "bad branch test");
16133 ins->template_id = TEMPLATE_NOP;
16139 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16140 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16141 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16143 if (get_imm8(ins, &RHS(ins, 0))) {
16144 ins->template_id += 1;
16151 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16152 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16153 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16155 if (get_imm8(ins, &RHS(ins, 1))) {
16156 ins->template_id += 1;
16161 ins->template_id = TEMPLATE_BSF;
16164 ins->template_id = TEMPLATE_RDMSR;
16165 next = after_lhs(state, ins);
16168 ins->template_id = TEMPLATE_WRMSR;
16171 ins->template_id = TEMPLATE_NOP;
16174 ins->template_id = TEMPLATE_NOP;
16175 next = after_lhs(state, ins);
16177 /* Already transformed instructions */
16179 ins->template_id = TEMPLATE_TEST;
16182 ins->template_id = TEMPLATE_CMP_REG;
16183 if (get_imm32(ins, &RHS(ins, 1))) {
16184 ins->template_id = TEMPLATE_CMP_IMM;
16187 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16188 case OP_JMP_SLESS: case OP_JMP_ULESS:
16189 case OP_JMP_SMORE: case OP_JMP_UMORE:
16190 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16191 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16192 ins->template_id = TEMPLATE_JMP;
16194 case OP_SET_EQ: case OP_SET_NOTEQ:
16195 case OP_SET_SLESS: case OP_SET_ULESS:
16196 case OP_SET_SMORE: case OP_SET_UMORE:
16197 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16198 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16199 ins->template_id = TEMPLATE_SET;
16201 /* Unhandled instructions */
16204 internal_error(state, ins, "unhandled ins: %d %s\n",
16205 ins->op, tops(ins->op));
16211 static void generate_local_labels(struct compile_state *state)
16213 struct triple *first, *label;
16216 first = RHS(state->main_function, 0);
16219 if ((label->op == OP_LABEL) ||
16220 (label->op == OP_SDECL)) {
16222 label->u.cval = ++label_counter;
16228 label = label->next;
16229 } while(label != first);
16232 static int check_reg(struct compile_state *state,
16233 struct triple *triple, int classes)
16237 reg = ID_REG(triple->id);
16238 if (reg == REG_UNSET) {
16239 internal_error(state, triple, "register not set");
16241 mask = arch_reg_regcm(state, reg);
16242 if (!(classes & mask)) {
16243 internal_error(state, triple, "reg %d in wrong class",
16249 static const char *arch_reg_str(int reg)
16251 static const char *regs[] = {
16255 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16256 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16257 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16259 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16260 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16261 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16263 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16270 static const char *reg(struct compile_state *state, struct triple *triple,
16274 reg = check_reg(state, triple, classes);
16275 return arch_reg_str(reg);
16278 const char *type_suffix(struct compile_state *state, struct type *type)
16280 const char *suffix;
16281 switch(size_of(state, type)) {
16282 case 1: suffix = "b"; break;
16283 case 2: suffix = "w"; break;
16284 case 4: suffix = "l"; break;
16286 internal_error(state, 0, "unknown suffix");
16293 static void print_const_val(
16294 struct compile_state *state, struct triple *ins, FILE *fp)
16298 fprintf(fp, " $%ld ",
16299 (long_t)(ins->u.cval));
16302 fprintf(fp, " $L%s%lu+%lu ",
16303 state->label_prefix,
16304 MISC(ins, 0)->u.cval,
16308 internal_error(state, ins, "unknown constant type");
16313 static void print_binary_op(struct compile_state *state,
16314 const char *op, struct triple *ins, FILE *fp)
16317 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16318 if (RHS(ins, 0)->id != ins->id) {
16319 internal_error(state, ins, "invalid register assignment");
16321 if (is_const(RHS(ins, 1))) {
16322 fprintf(fp, "\t%s ", op);
16323 print_const_val(state, RHS(ins, 1), fp);
16324 fprintf(fp, ", %s\n",
16325 reg(state, RHS(ins, 0), mask));
16328 unsigned lmask, rmask;
16330 lreg = check_reg(state, RHS(ins, 0), mask);
16331 rreg = check_reg(state, RHS(ins, 1), mask);
16332 lmask = arch_reg_regcm(state, lreg);
16333 rmask = arch_reg_regcm(state, rreg);
16334 mask = lmask & rmask;
16335 fprintf(fp, "\t%s %s, %s\n",
16337 reg(state, RHS(ins, 1), mask),
16338 reg(state, RHS(ins, 0), mask));
16341 static void print_unary_op(struct compile_state *state,
16342 const char *op, struct triple *ins, FILE *fp)
16345 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16346 fprintf(fp, "\t%s %s\n",
16348 reg(state, RHS(ins, 0), mask));
16351 static void print_op_shift(struct compile_state *state,
16352 const char *op, struct triple *ins, FILE *fp)
16355 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16356 if (RHS(ins, 0)->id != ins->id) {
16357 internal_error(state, ins, "invalid register assignment");
16359 if (is_const(RHS(ins, 1))) {
16360 fprintf(fp, "\t%s ", op);
16361 print_const_val(state, RHS(ins, 1), fp);
16362 fprintf(fp, ", %s\n",
16363 reg(state, RHS(ins, 0), mask));
16366 fprintf(fp, "\t%s %s, %s\n",
16368 reg(state, RHS(ins, 1), REGCM_GPR8),
16369 reg(state, RHS(ins, 0), mask));
16373 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16380 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16381 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16382 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16384 internal_error(state, ins, "not an in operation");
16388 dreg = check_reg(state, ins, mask);
16389 if (!reg_is_reg(state, dreg, REG_EAX)) {
16390 internal_error(state, ins, "dst != %%eax");
16392 if (is_const(RHS(ins, 0))) {
16393 fprintf(fp, "\t%s ", op);
16394 print_const_val(state, RHS(ins, 0), fp);
16395 fprintf(fp, ", %s\n",
16396 reg(state, ins, mask));
16400 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16401 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16402 internal_error(state, ins, "src != %%dx");
16404 fprintf(fp, "\t%s %s, %s\n",
16406 reg(state, RHS(ins, 0), REGCM_GPR16),
16407 reg(state, ins, mask));
16411 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16418 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16419 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16420 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16422 internal_error(state, ins, "not an out operation");
16426 lreg = check_reg(state, RHS(ins, 0), mask);
16427 if (!reg_is_reg(state, lreg, REG_EAX)) {
16428 internal_error(state, ins, "src != %%eax");
16430 if (is_const(RHS(ins, 1))) {
16431 fprintf(fp, "\t%s %s,",
16432 op, reg(state, RHS(ins, 0), mask));
16433 print_const_val(state, RHS(ins, 1), fp);
16438 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16439 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16440 internal_error(state, ins, "dst != %%dx");
16442 fprintf(fp, "\t%s %s, %s\n",
16444 reg(state, RHS(ins, 0), mask),
16445 reg(state, RHS(ins, 1), REGCM_GPR16));
16449 static void print_op_move(struct compile_state *state,
16450 struct triple *ins, FILE *fp)
16452 /* op_move is complex because there are many types
16453 * of registers we can move between.
16454 * Because OP_COPY will be introduced in arbitrary locations
16455 * OP_COPY must not affect flags.
16457 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16458 struct triple *dst, *src;
16459 if (ins->op == OP_COPY) {
16463 else if (ins->op == OP_WRITE) {
16468 internal_error(state, ins, "unknown move operation");
16471 if (!is_const(src)) {
16472 int src_reg, dst_reg;
16473 int src_regcm, dst_regcm;
16474 src_reg = ID_REG(src->id);
16475 dst_reg = ID_REG(dst->id);
16476 src_regcm = arch_reg_regcm(state, src_reg);
16477 dst_regcm = arch_reg_regcm(state, dst_reg);
16478 /* If the class is the same just move the register */
16479 if (src_regcm & dst_regcm &
16480 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16481 if ((src_reg != dst_reg) || !omit_copy) {
16482 fprintf(fp, "\tmov %s, %s\n",
16483 reg(state, src, src_regcm),
16484 reg(state, dst, dst_regcm));
16487 /* Move 32bit to 16bit */
16488 else if ((src_regcm & REGCM_GPR32) &&
16489 (dst_regcm & REGCM_GPR16)) {
16490 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16491 if ((src_reg != dst_reg) || !omit_copy) {
16492 fprintf(fp, "\tmovw %s, %s\n",
16493 arch_reg_str(src_reg),
16494 arch_reg_str(dst_reg));
16497 /* Move 32bit to 8bit */
16498 else if ((src_regcm & REGCM_GPR32_8) &&
16499 (dst_regcm & REGCM_GPR8))
16501 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16502 if ((src_reg != dst_reg) || !omit_copy) {
16503 fprintf(fp, "\tmovb %s, %s\n",
16504 arch_reg_str(src_reg),
16505 arch_reg_str(dst_reg));
16508 /* Move 16bit to 8bit */
16509 else if ((src_regcm & REGCM_GPR16_8) &&
16510 (dst_regcm & REGCM_GPR8))
16512 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16513 if ((src_reg != dst_reg) || !omit_copy) {
16514 fprintf(fp, "\tmovb %s, %s\n",
16515 arch_reg_str(src_reg),
16516 arch_reg_str(dst_reg));
16519 /* Move 8/16bit to 16/32bit */
16520 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
16521 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16523 op = is_signed(src->type)? "movsx": "movzx";
16524 fprintf(fp, "\t%s %s, %s\n",
16526 reg(state, src, src_regcm),
16527 reg(state, dst, dst_regcm));
16529 /* Move between sse registers */
16530 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16531 if ((src_reg != dst_reg) || !omit_copy) {
16532 fprintf(fp, "\tmovdqa %s, %s\n",
16533 reg(state, src, src_regcm),
16534 reg(state, dst, dst_regcm));
16537 /* Move between mmx registers or mmx & sse registers */
16538 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16539 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16540 if ((src_reg != dst_reg) || !omit_copy) {
16541 fprintf(fp, "\tmovq %s, %s\n",
16542 reg(state, src, src_regcm),
16543 reg(state, dst, dst_regcm));
16546 /* Move between 32bit gprs & mmx/sse registers */
16547 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16548 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16549 fprintf(fp, "\tmovd %s, %s\n",
16550 reg(state, src, src_regcm),
16551 reg(state, dst, dst_regcm));
16553 #if X86_4_8BIT_GPRS
16554 /* Move from 8bit gprs to mmx/sse registers */
16555 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16556 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16559 op = is_signed(src->type)? "movsx":"movzx";
16560 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16561 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16563 reg(state, src, src_regcm),
16564 arch_reg_str(mid_reg),
16565 arch_reg_str(mid_reg),
16566 reg(state, dst, dst_regcm));
16568 /* Move from mmx/sse registers and 8bit gprs */
16569 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16570 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16572 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16573 fprintf(fp, "\tmovd %s, %s\n",
16574 reg(state, src, src_regcm),
16575 arch_reg_str(mid_reg));
16577 /* Move from 32bit gprs to 16bit gprs */
16578 else if ((src_regcm & REGCM_GPR32) &&
16579 (dst_regcm & REGCM_GPR16)) {
16580 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16581 if ((src_reg != dst_reg) || !omit_copy) {
16582 fprintf(fp, "\tmov %s, %s\n",
16583 arch_reg_str(src_reg),
16584 arch_reg_str(dst_reg));
16587 /* Move from 32bit gprs to 8bit gprs */
16588 else if ((src_regcm & REGCM_GPR32) &&
16589 (dst_regcm & REGCM_GPR8)) {
16590 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16591 if ((src_reg != dst_reg) || !omit_copy) {
16592 fprintf(fp, "\tmov %s, %s\n",
16593 arch_reg_str(src_reg),
16594 arch_reg_str(dst_reg));
16597 /* Move from 16bit gprs to 8bit gprs */
16598 else if ((src_regcm & REGCM_GPR16) &&
16599 (dst_regcm & REGCM_GPR8)) {
16600 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16601 if ((src_reg != dst_reg) || !omit_copy) {
16602 fprintf(fp, "\tmov %s, %s\n",
16603 arch_reg_str(src_reg),
16604 arch_reg_str(dst_reg));
16607 #endif /* X86_4_8BIT_GPRS */
16609 internal_error(state, ins, "unknown copy type");
16613 fprintf(fp, "\tmov ");
16614 print_const_val(state, src, fp);
16615 fprintf(fp, ", %s\n",
16616 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16620 static void print_op_load(struct compile_state *state,
16621 struct triple *ins, FILE *fp)
16623 struct triple *dst, *src;
16626 if (is_const(src) || is_const(dst)) {
16627 internal_error(state, ins, "unknown load operation");
16629 fprintf(fp, "\tmov (%s), %s\n",
16630 reg(state, src, REGCM_GPR32),
16631 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16635 static void print_op_store(struct compile_state *state,
16636 struct triple *ins, FILE *fp)
16638 struct triple *dst, *src;
16641 if (is_const(src) && (src->op == OP_INTCONST)) {
16643 value = (long_t)(src->u.cval);
16644 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16645 type_suffix(state, src->type),
16647 reg(state, dst, REGCM_GPR32));
16649 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16650 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16651 type_suffix(state, src->type),
16652 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16656 if (is_const(src) || is_const(dst)) {
16657 internal_error(state, ins, "unknown store operation");
16659 fprintf(fp, "\tmov%s %s, (%s)\n",
16660 type_suffix(state, src->type),
16661 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16662 reg(state, dst, REGCM_GPR32));
16668 static void print_op_smul(struct compile_state *state,
16669 struct triple *ins, FILE *fp)
16671 if (!is_const(RHS(ins, 1))) {
16672 fprintf(fp, "\timul %s, %s\n",
16673 reg(state, RHS(ins, 1), REGCM_GPR32),
16674 reg(state, RHS(ins, 0), REGCM_GPR32));
16677 fprintf(fp, "\timul ");
16678 print_const_val(state, RHS(ins, 1), fp);
16679 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16683 static void print_op_cmp(struct compile_state *state,
16684 struct triple *ins, FILE *fp)
16688 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16689 dreg = check_reg(state, ins, REGCM_FLAGS);
16690 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16691 internal_error(state, ins, "bad dest register for cmp");
16693 if (is_const(RHS(ins, 1))) {
16694 fprintf(fp, "\tcmp ");
16695 print_const_val(state, RHS(ins, 1), fp);
16696 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16699 unsigned lmask, rmask;
16701 lreg = check_reg(state, RHS(ins, 0), mask);
16702 rreg = check_reg(state, RHS(ins, 1), mask);
16703 lmask = arch_reg_regcm(state, lreg);
16704 rmask = arch_reg_regcm(state, rreg);
16705 mask = lmask & rmask;
16706 fprintf(fp, "\tcmp %s, %s\n",
16707 reg(state, RHS(ins, 1), mask),
16708 reg(state, RHS(ins, 0), mask));
16712 static void print_op_test(struct compile_state *state,
16713 struct triple *ins, FILE *fp)
16716 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16717 fprintf(fp, "\ttest %s, %s\n",
16718 reg(state, RHS(ins, 0), mask),
16719 reg(state, RHS(ins, 0), mask));
16722 static void print_op_branch(struct compile_state *state,
16723 struct triple *branch, FILE *fp)
16725 const char *bop = "j";
16726 if (branch->op == OP_JMP) {
16727 if (TRIPLE_RHS(branch->sizes) != 0) {
16728 internal_error(state, branch, "jmp with condition?");
16733 struct triple *ptr;
16734 if (TRIPLE_RHS(branch->sizes) != 1) {
16735 internal_error(state, branch, "jmpcc without condition?");
16737 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16738 if ((RHS(branch, 0)->op != OP_CMP) &&
16739 (RHS(branch, 0)->op != OP_TEST)) {
16740 internal_error(state, branch, "bad branch test");
16742 #warning "FIXME I have observed instructions between the test and branch instructions"
16743 ptr = RHS(branch, 0);
16744 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16745 if (ptr->op != OP_COPY) {
16746 internal_error(state, branch, "branch does not follow test");
16749 switch(branch->op) {
16750 case OP_JMP_EQ: bop = "jz"; break;
16751 case OP_JMP_NOTEQ: bop = "jnz"; break;
16752 case OP_JMP_SLESS: bop = "jl"; break;
16753 case OP_JMP_ULESS: bop = "jb"; break;
16754 case OP_JMP_SMORE: bop = "jg"; break;
16755 case OP_JMP_UMORE: bop = "ja"; break;
16756 case OP_JMP_SLESSEQ: bop = "jle"; break;
16757 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16758 case OP_JMP_SMOREEQ: bop = "jge"; break;
16759 case OP_JMP_UMOREEQ: bop = "jae"; break;
16761 internal_error(state, branch, "Invalid branch op");
16766 fprintf(fp, "\t%s L%s%lu\n",
16768 state->label_prefix,
16769 TARG(branch, 0)->u.cval);
16772 static void print_op_set(struct compile_state *state,
16773 struct triple *set, FILE *fp)
16775 const char *sop = "set";
16776 if (TRIPLE_RHS(set->sizes) != 1) {
16777 internal_error(state, set, "setcc without condition?");
16779 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16780 if ((RHS(set, 0)->op != OP_CMP) &&
16781 (RHS(set, 0)->op != OP_TEST)) {
16782 internal_error(state, set, "bad set test");
16784 if (RHS(set, 0)->next != set) {
16785 internal_error(state, set, "set does not follow test");
16788 case OP_SET_EQ: sop = "setz"; break;
16789 case OP_SET_NOTEQ: sop = "setnz"; break;
16790 case OP_SET_SLESS: sop = "setl"; break;
16791 case OP_SET_ULESS: sop = "setb"; break;
16792 case OP_SET_SMORE: sop = "setg"; break;
16793 case OP_SET_UMORE: sop = "seta"; break;
16794 case OP_SET_SLESSEQ: sop = "setle"; break;
16795 case OP_SET_ULESSEQ: sop = "setbe"; break;
16796 case OP_SET_SMOREEQ: sop = "setge"; break;
16797 case OP_SET_UMOREEQ: sop = "setae"; break;
16799 internal_error(state, set, "Invalid set op");
16802 fprintf(fp, "\t%s %s\n",
16803 sop, reg(state, set, REGCM_GPR8));
16806 static void print_op_bit_scan(struct compile_state *state,
16807 struct triple *ins, FILE *fp)
16811 case OP_BSF: op = "bsf"; break;
16812 case OP_BSR: op = "bsr"; break;
16814 internal_error(state, ins, "unknown bit scan");
16824 reg(state, RHS(ins, 0), REGCM_GPR32),
16825 reg(state, ins, REGCM_GPR32),
16826 reg(state, ins, REGCM_GPR32));
16829 static void print_const(struct compile_state *state,
16830 struct triple *ins, FILE *fp)
16834 switch(ins->type->type & TYPE_MASK) {
16837 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16841 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16847 fprintf(fp, ".int %lu\n", ins->u.cval);
16850 internal_error(state, ins, "Unknown constant type");
16855 unsigned char *blob;
16857 size = size_of(state, ins->type);
16858 blob = ins->u.blob;
16859 for(i = 0; i < size; i++) {
16860 fprintf(fp, ".byte 0x%02x\n",
16866 internal_error(state, ins, "Unknown constant type");
16871 #define TEXT_SECTION ".rom.text"
16872 #define DATA_SECTION ".rom.data"
16874 static void print_sdecl(struct compile_state *state,
16875 struct triple *ins, FILE *fp)
16877 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16878 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16879 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16880 print_const(state, MISC(ins, 0), fp);
16881 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16885 static void print_instruction(struct compile_state *state,
16886 struct triple *ins, FILE *fp)
16888 /* Assumption: after I have exted the register allocator
16889 * everything is in a valid register.
16893 print_op_asm(state, ins, fp);
16895 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16896 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16897 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16898 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16899 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16900 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16901 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16902 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16903 case OP_POS: break;
16904 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16905 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16909 /* Don't generate anything here for constants */
16911 /* Don't generate anything for variable declarations. */
16914 print_sdecl(state, ins, fp);
16918 print_op_move(state, ins, fp);
16921 print_op_load(state, ins, fp);
16924 print_op_store(state, ins, fp);
16927 print_op_smul(state, ins, fp);
16929 case OP_CMP: print_op_cmp(state, ins, fp); break;
16930 case OP_TEST: print_op_test(state, ins, fp); break;
16932 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16933 case OP_JMP_SLESS: case OP_JMP_ULESS:
16934 case OP_JMP_SMORE: case OP_JMP_UMORE:
16935 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16936 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16937 print_op_branch(state, ins, fp);
16939 case OP_SET_EQ: case OP_SET_NOTEQ:
16940 case OP_SET_SLESS: case OP_SET_ULESS:
16941 case OP_SET_SMORE: case OP_SET_UMORE:
16942 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16943 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16944 print_op_set(state, ins, fp);
16946 case OP_INB: case OP_INW: case OP_INL:
16947 print_op_in(state, ins, fp);
16949 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16950 print_op_out(state, ins, fp);
16954 print_op_bit_scan(state, ins, fp);
16957 after_lhs(state, ins);
16958 fprintf(fp, "\trdmsr\n");
16961 fprintf(fp, "\twrmsr\n");
16964 fprintf(fp, "\thlt\n");
16970 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16972 /* Ignore OP_PIECE */
16975 /* Operations I am not yet certain how to handle */
16977 case OP_SDIV: case OP_UDIV:
16978 case OP_SMOD: case OP_UMOD:
16979 /* Operations that should never get here */
16980 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16981 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16982 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16984 internal_error(state, ins, "unknown op: %d %s",
16985 ins->op, tops(ins->op));
16990 static void print_instructions(struct compile_state *state)
16992 struct triple *first, *ins;
16993 int print_location;
16994 struct occurance *last_occurance;
16996 print_location = 1;
16997 last_occurance = 0;
16998 fp = state->output;
16999 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17000 first = RHS(state->main_function, 0);
17003 if (print_location &&
17004 last_occurance != ins->occurance) {
17005 if (!ins->occurance->parent) {
17006 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17007 ins->occurance->function,
17008 ins->occurance->filename,
17009 ins->occurance->line,
17010 ins->occurance->col);
17013 struct occurance *ptr;
17014 fprintf(fp, "\t/*\n");
17015 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17016 fprintf(fp, "\t * %s,%s:%d.%d\n",
17022 fprintf(fp, "\t */\n");
17025 if (last_occurance) {
17026 put_occurance(last_occurance);
17028 get_occurance(ins->occurance);
17029 last_occurance = ins->occurance;
17032 print_instruction(state, ins, fp);
17034 } while(ins != first);
17037 static void generate_code(struct compile_state *state)
17039 generate_local_labels(state);
17040 print_instructions(state);
17044 static void print_tokens(struct compile_state *state)
17047 tk = &state->token[0];
17052 next_token(state, 0);
17054 loc(stdout, state, 0);
17055 printf("%s <- `%s'\n",
17057 tk->ident ? tk->ident->name :
17058 tk->str_len ? tk->val.str : "");
17060 } while(tk->tok != TOK_EOF);
17063 static void compile(const char *filename, const char *ofilename,
17064 int cpu, int debug, int opt, const char *label_prefix)
17067 struct compile_state state;
17068 memset(&state, 0, sizeof(state));
17070 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17071 memset(&state.token[i], 0, sizeof(state.token[i]));
17072 state.token[i].tok = -1;
17074 /* Remember the debug settings */
17076 state.debug = debug;
17077 state.optimize = opt;
17078 /* Remember the output filename */
17079 state.ofilename = ofilename;
17080 state.output = fopen(state.ofilename, "w");
17081 if (!state.output) {
17082 error(&state, 0, "Cannot open output file %s\n",
17085 /* Remember the label prefix */
17086 state.label_prefix = label_prefix;
17087 /* Prep the preprocessor */
17088 state.if_depth = 0;
17089 state.if_value = 0;
17090 /* register the C keywords */
17091 register_keywords(&state);
17092 /* register the keywords the macro preprocessor knows */
17093 register_macro_keywords(&state);
17094 /* Memorize where some special keywords are. */
17095 state.i_continue = lookup(&state, "continue", 8);
17096 state.i_break = lookup(&state, "break", 5);
17097 /* Enter the globl definition scope */
17098 start_scope(&state);
17099 register_builtins(&state);
17100 compile_file(&state, filename, 1);
17102 print_tokens(&state);
17105 /* Exit the global definition scope */
17108 /* Now that basic compilation has happened
17109 * optimize the intermediate code
17113 generate_code(&state);
17115 fprintf(stderr, "done\n");
17119 static void version(void)
17121 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17124 static void usage(void)
17128 "Usage: romcc <source>.c\n"
17129 "Compile a C source file without using ram\n"
17133 static void arg_error(char *fmt, ...)
17136 va_start(args, fmt);
17137 vfprintf(stderr, fmt, args);
17143 int main(int argc, char **argv)
17145 const char *filename;
17146 const char *ofilename;
17147 const char *label_prefix;
17154 ofilename = "auto.inc";
17158 while((argc > 1) && (argc != last_argc)) {
17160 if (strncmp(argv[1], "--debug=", 8) == 0) {
17161 debug = atoi(argv[1] + 8);
17165 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17166 label_prefix= argv[1] + 15;
17170 else if ((strcmp(argv[1],"-O") == 0) ||
17171 (strcmp(argv[1], "-O1") == 0)) {
17176 else if (strcmp(argv[1],"-O2") == 0) {
17181 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17182 ofilename = argv[2];
17186 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17187 cpu = arch_encode_cpu(argv[1] + 6);
17188 if (cpu == BAD_CPU) {
17189 arg_error("Invalid cpu specified: %s\n",
17197 arg_error("Wrong argument count %d\n", argc);
17199 filename = argv[1];
17200 compile(filename, ofilename, cpu, debug, optimize, label_prefix);