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 needed_padding(size_t offset, size_t align)
3939 if (offset % align) {
3940 padding = align - (offset % align);
3944 static size_t size_of(struct compile_state *state, struct type *type)
3948 switch(type->type & TYPE_MASK) {
3958 size = SIZEOF_SHORT;
3974 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3975 align = align_of(state, type->left);
3976 pad = needed_padding(size, align);
3977 size = size + pad + size_of(state, type->left);
3980 align = align_of(state, type);
3981 pad = needed_padding(size, align);
3982 size = size + pad + sizeof(type);
3987 size_t size_left, size_right;
3988 size_left = size_of(state, type->left);
3989 size_right = size_of(state, type->right);
3990 size = (size_left >= size_right)? size_left : size_right;
3994 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3995 internal_error(state, 0, "Invalid array type");
3997 size = size_of(state, type->left) * type->elements;
4001 size = size_of(state, type->left);
4004 error(state, 0, "sizeof not yet defined for type\n");
4010 static size_t field_offset(struct compile_state *state,
4011 struct type *type, struct hash_entry *field)
4014 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4015 internal_error(state, 0, "field_offset only works on structures");
4019 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4020 align = align_of(state, type->left);
4021 size += needed_padding(size, align);
4022 if (type->left->field_ident == field) {
4026 size += size_of(state, type->left);
4029 align = align_of(state, type);
4030 size += needed_padding(size, align);
4031 if (type->field_ident != field) {
4032 error(state, 0, "member %s not present", field->name);
4037 static struct type *field_type(struct compile_state *state,
4038 struct type *type, struct hash_entry *field)
4040 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4041 internal_error(state, 0, "field_type only works on structures");
4044 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4045 if (type->left->field_ident == field) {
4051 if (type->field_ident != field) {
4052 error(state, 0, "member %s not present", field->name);
4057 static struct type *next_field(struct compile_state *state,
4058 struct type *type, struct type *prev_member)
4060 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4061 internal_error(state, 0, "next_field only works on structures");
4064 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4069 if (type->left == prev_member) {
4074 if (type == prev_member) {
4078 internal_error(state, 0, "prev_member %s not present",
4079 prev_member->field_ident->name);
4084 static struct triple *struct_field(struct compile_state *state,
4085 struct triple *decl, struct hash_entry *field)
4087 struct triple **vector;
4091 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4094 if (decl->op != OP_VAL_VEC) {
4095 internal_error(state, 0, "Invalid struct variable");
4098 internal_error(state, 0, "Missing structure field");
4101 vector = &RHS(decl, 0);
4103 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4104 if (type->left->field_ident == field) {
4111 if (type->field_ident != field) {
4112 internal_error(state, 0, "field %s not found?", field->name);
4114 return vector[index];
4117 static void arrays_complete(struct compile_state *state, struct type *type)
4119 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4120 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4121 error(state, 0, "array size not specified");
4123 arrays_complete(state, type->left);
4127 static unsigned int do_integral_promotion(unsigned int type)
4130 if (TYPE_INTEGER(type) &&
4131 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4137 static unsigned int do_arithmetic_conversion(
4138 unsigned int left, unsigned int right)
4142 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4143 return TYPE_LDOUBLE;
4145 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4148 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4151 left = do_integral_promotion(left);
4152 right = do_integral_promotion(right);
4153 /* If both operands have the same size done */
4154 if (left == right) {
4157 /* If both operands have the same signedness pick the larger */
4158 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4159 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4161 /* If the signed type can hold everything use it */
4162 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4165 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4168 /* Convert to the unsigned type with the same rank as the signed type */
4169 else if (TYPE_SIGNED(left)) {
4170 return TYPE_MKUNSIGNED(left);
4173 return TYPE_MKUNSIGNED(right);
4177 /* see if two types are the same except for qualifiers */
4178 static int equiv_types(struct type *left, struct type *right)
4181 /* Error if the basic types do not match */
4182 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4185 type = left->type & TYPE_MASK;
4186 /* if the basic types match and it is an arithmetic type we are done */
4187 if (TYPE_ARITHMETIC(type)) {
4190 /* If it is a pointer type recurse and keep testing */
4191 if (type == TYPE_POINTER) {
4192 return equiv_types(left->left, right->left);
4194 else if (type == TYPE_ARRAY) {
4195 return (left->elements == right->elements) &&
4196 equiv_types(left->left, right->left);
4198 /* test for struct/union equality */
4199 else if (type == TYPE_STRUCT) {
4200 return left->type_ident == right->type_ident;
4202 /* Test for equivalent functions */
4203 else if (type == TYPE_FUNCTION) {
4204 return equiv_types(left->left, right->left) &&
4205 equiv_types(left->right, right->right);
4207 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4208 else if (type == TYPE_PRODUCT) {
4209 return equiv_types(left->left, right->left) &&
4210 equiv_types(left->right, right->right);
4212 /* We should see TYPE_OVERLAP */
4218 static int equiv_ptrs(struct type *left, struct type *right)
4220 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4221 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4224 return equiv_types(left->left, right->left);
4227 static struct type *compatible_types(struct type *left, struct type *right)
4229 struct type *result;
4230 unsigned int type, qual_type;
4231 /* Error if the basic types do not match */
4232 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4235 type = left->type & TYPE_MASK;
4236 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4238 /* if the basic types match and it is an arithmetic type we are done */
4239 if (TYPE_ARITHMETIC(type)) {
4240 result = new_type(qual_type, 0, 0);
4242 /* If it is a pointer type recurse and keep testing */
4243 else if (type == TYPE_POINTER) {
4244 result = compatible_types(left->left, right->left);
4246 result = new_type(qual_type, result, 0);
4249 /* test for struct/union equality */
4250 else if (type == TYPE_STRUCT) {
4251 if (left->type_ident == right->type_ident) {
4255 /* Test for equivalent functions */
4256 else if (type == TYPE_FUNCTION) {
4257 struct type *lf, *rf;
4258 lf = compatible_types(left->left, right->left);
4259 rf = compatible_types(left->right, right->right);
4261 result = new_type(qual_type, lf, rf);
4264 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4265 else if (type == TYPE_PRODUCT) {
4266 struct type *lf, *rf;
4267 lf = compatible_types(left->left, right->left);
4268 rf = compatible_types(left->right, right->right);
4270 result = new_type(qual_type, lf, rf);
4274 /* Nothing else is compatible */
4279 static struct type *compatible_ptrs(struct type *left, struct type *right)
4281 struct type *result;
4282 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4283 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4286 result = compatible_types(left->left, right->left);
4288 unsigned int qual_type;
4289 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4290 result = new_type(qual_type, result, 0);
4295 static struct triple *integral_promotion(
4296 struct compile_state *state, struct triple *def)
4300 /* As all operations are carried out in registers
4301 * the values are converted on load I just convert
4302 * logical type of the operand.
4304 if (TYPE_INTEGER(type->type)) {
4305 unsigned int int_type;
4306 int_type = type->type & ~TYPE_MASK;
4307 int_type |= do_integral_promotion(type->type);
4308 if (int_type != type->type) {
4309 def->type = new_type(int_type, 0, 0);
4316 static void arithmetic(struct compile_state *state, struct triple *def)
4318 if (!TYPE_ARITHMETIC(def->type->type)) {
4319 error(state, 0, "arithmetic type expexted");
4323 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4325 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4326 error(state, def, "pointer or arithmetic type expected");
4330 static int is_integral(struct triple *ins)
4332 return TYPE_INTEGER(ins->type->type);
4335 static void integral(struct compile_state *state, struct triple *def)
4337 if (!is_integral(def)) {
4338 error(state, 0, "integral type expected");
4343 static void bool(struct compile_state *state, struct triple *def)
4345 if (!TYPE_ARITHMETIC(def->type->type) &&
4346 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4347 error(state, 0, "arithmetic or pointer type expected");
4351 static int is_signed(struct type *type)
4353 return !!TYPE_SIGNED(type->type);
4356 /* Is this value located in a register otherwise it must be in memory */
4357 static int is_in_reg(struct compile_state *state, struct triple *def)
4360 if (def->op == OP_ADECL) {
4363 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4366 else if (def->op == OP_VAL_VEC) {
4367 in_reg = is_in_reg(state, RHS(def, 0));
4369 else if (def->op == OP_DOT) {
4370 in_reg = is_in_reg(state, RHS(def, 0));
4373 internal_error(state, 0, "unknown expr storage location");
4379 /* Is this a stable variable location otherwise it must be a temporary */
4380 static int is_stable(struct compile_state *state, struct triple *def)
4387 if ((def->op == OP_ADECL) ||
4388 (def->op == OP_SDECL) ||
4389 (def->op == OP_DEREF) ||
4390 (def->op == OP_BLOBCONST)) {
4393 else if (def->op == OP_DOT) {
4394 ret = is_stable(state, RHS(def, 0));
4396 else if (def->op == OP_VAL_VEC) {
4397 struct triple **vector;
4400 vector = &RHS(def, 0);
4401 for(i = 0; i < def->type->elements; i++) {
4402 if (!is_stable(state, vector[i])) {
4411 static int is_lvalue(struct compile_state *state, struct triple *def)
4418 if (!is_stable(state, def)) {
4421 if (def->op == OP_DOT) {
4422 ret = is_lvalue(state, RHS(def, 0));
4427 static void clvalue(struct compile_state *state, struct triple *def)
4430 internal_error(state, def, "nothing where lvalue expected?");
4432 if (!is_lvalue(state, def)) {
4433 error(state, def, "lvalue expected");
4436 static void lvalue(struct compile_state *state, struct triple *def)
4438 clvalue(state, def);
4439 if (def->type->type & QUAL_CONST) {
4440 error(state, def, "modifable lvalue expected");
4444 static int is_pointer(struct triple *def)
4446 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4449 static void pointer(struct compile_state *state, struct triple *def)
4451 if (!is_pointer(def)) {
4452 error(state, def, "pointer expected");
4456 static struct triple *int_const(
4457 struct compile_state *state, struct type *type, ulong_t value)
4459 struct triple *result;
4460 switch(type->type & TYPE_MASK) {
4462 case TYPE_INT: case TYPE_UINT:
4463 case TYPE_LONG: case TYPE_ULONG:
4466 internal_error(state, 0, "constant for unkown type");
4468 result = triple(state, OP_INTCONST, type, 0, 0);
4469 result->u.cval = value;
4474 static struct triple *do_mk_addr_expr(struct compile_state *state,
4475 struct triple *expr, struct type *type, ulong_t offset)
4477 struct triple *result;
4478 clvalue(state, expr);
4481 if (expr->op == OP_ADECL) {
4482 error(state, expr, "address of auto variables not supported");
4484 else if (expr->op == OP_SDECL) {
4485 result = triple(state, OP_ADDRCONST, type, 0, 0);
4486 MISC(result, 0) = expr;
4487 result->u.cval = offset;
4489 else if (expr->op == OP_DEREF) {
4490 result = triple(state, OP_ADD, type,
4492 int_const(state, &ulong_type, offset));
4497 static struct triple *mk_addr_expr(
4498 struct compile_state *state, struct triple *expr, ulong_t offset)
4503 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4506 return do_mk_addr_expr(state, expr, type, offset);
4509 static struct triple *mk_deref_expr(
4510 struct compile_state *state, struct triple *expr)
4512 struct type *base_type;
4513 pointer(state, expr);
4514 base_type = expr->type->left;
4515 return triple(state, OP_DEREF, base_type, expr, 0);
4518 static struct triple *deref_field(
4519 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4521 struct triple *result;
4522 struct type *type, *member;
4524 internal_error(state, 0, "No field passed to deref_field");
4528 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4529 error(state, 0, "request for member %s in something not a struct or union",
4532 member = field_type(state, type, field);
4533 if ((type->type & STOR_MASK) == STOR_PERM) {
4534 /* Do the pointer arithmetic to get a deref the field */
4536 offset = field_offset(state, type, field);
4537 result = do_mk_addr_expr(state, expr, member, offset);
4538 result = mk_deref_expr(state, result);
4541 /* Find the variable for the field I want. */
4542 result = triple(state, OP_DOT, member, expr, 0);
4543 result->u.field = field;
4548 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4554 if (!is_stable(state, def)) {
4557 /* Tranform an array to a pointer to the first element */
4558 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4559 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4561 struct triple *result;
4563 TYPE_POINTER | (def->type->type & QUAL_MASK),
4564 def->type->left, 0);
4565 result = triple(state, OP_ADDRCONST, type, 0, 0);
4566 MISC(result, 0) = def;
4569 if (is_in_reg(state, def)) {
4574 return triple(state, op, def->type, def, 0);
4577 static void write_compatible(struct compile_state *state,
4578 struct type *dest, struct type *rval)
4581 /* Both operands have arithmetic type */
4582 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4585 /* One operand is a pointer and the other is a pointer to void */
4586 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4587 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4588 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4589 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4592 /* If both types are the same without qualifiers we are good */
4593 else if (equiv_ptrs(dest, rval)) {
4596 /* test for struct/union equality */
4597 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4598 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4599 (dest->type_ident == rval->type_ident)) {
4603 error(state, 0, "Incompatible types in assignment");
4607 static struct triple *write_expr(
4608 struct compile_state *state, struct triple *dest, struct triple *rval)
4615 internal_error(state, 0, "missing rval");
4618 if (rval->op == OP_LIST) {
4619 internal_error(state, 0, "expression of type OP_LIST?");
4621 if (!is_lvalue(state, dest)) {
4622 internal_error(state, 0, "writing to a non lvalue?");
4624 if (dest->type->type & QUAL_CONST) {
4625 internal_error(state, 0, "modifable lvalue expexted");
4628 write_compatible(state, dest->type, rval->type);
4630 /* Now figure out which assignment operator to use */
4632 if (is_in_reg(state, dest)) {
4637 def = triple(state, op, dest->type, dest, rval);
4641 static struct triple *init_expr(
4642 struct compile_state *state, struct triple *dest, struct triple *rval)
4648 internal_error(state, 0, "missing rval");
4650 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4651 rval = read_expr(state, rval);
4652 def = write_expr(state, dest, rval);
4655 /* Fill in the array size if necessary */
4656 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4657 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4658 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4659 dest->type->elements = rval->type->elements;
4662 if (!equiv_types(dest->type, rval->type)) {
4663 error(state, 0, "Incompatible types in inializer");
4665 MISC(dest, 0) = rval;
4666 insert_triple(state, dest, rval);
4667 rval->id |= TRIPLE_FLAG_FLATTENED;
4668 use_triple(MISC(dest, 0), dest);
4673 struct type *arithmetic_result(
4674 struct compile_state *state, struct triple *left, struct triple *right)
4677 /* Sanity checks to ensure I am working with arithmetic types */
4678 arithmetic(state, left);
4679 arithmetic(state, right);
4681 do_arithmetic_conversion(
4683 right->type->type), 0, 0);
4687 struct type *ptr_arithmetic_result(
4688 struct compile_state *state, struct triple *left, struct triple *right)
4691 /* Sanity checks to ensure I am working with the proper types */
4692 ptr_arithmetic(state, left);
4693 arithmetic(state, right);
4694 if (TYPE_ARITHMETIC(left->type->type) &&
4695 TYPE_ARITHMETIC(right->type->type)) {
4696 type = arithmetic_result(state, left, right);
4698 else if (TYPE_PTR(left->type->type)) {
4702 internal_error(state, 0, "huh?");
4709 /* boolean helper function */
4711 static struct triple *ltrue_expr(struct compile_state *state,
4712 struct triple *expr)
4715 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4716 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4717 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4718 /* If the expression is already boolean do nothing */
4721 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4727 static struct triple *lfalse_expr(struct compile_state *state,
4728 struct triple *expr)
4730 return triple(state, OP_LFALSE, &int_type, expr, 0);
4733 static struct triple *cond_expr(
4734 struct compile_state *state,
4735 struct triple *test, struct triple *left, struct triple *right)
4738 struct type *result_type;
4739 unsigned int left_type, right_type;
4741 left_type = left->type->type;
4742 right_type = right->type->type;
4744 /* Both operands have arithmetic type */
4745 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4746 result_type = arithmetic_result(state, left, right);
4748 /* Both operands have void type */
4749 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4750 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4751 result_type = &void_type;
4753 /* pointers to the same type... */
4754 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4757 /* Both operands are pointers and left is a pointer to void */
4758 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4759 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4760 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4761 result_type = right->type;
4763 /* Both operands are pointers and right is a pointer to void */
4764 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4765 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4766 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4767 result_type = left->type;
4770 error(state, 0, "Incompatible types in conditional expression");
4772 /* Cleanup and invert the test */
4773 test = lfalse_expr(state, read_expr(state, test));
4774 def = new_triple(state, OP_COND, result_type, 0, 3);
4775 def->param[0] = test;
4776 def->param[1] = left;
4777 def->param[2] = right;
4782 static int expr_depth(struct compile_state *state, struct triple *ins)
4786 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4789 else if (ins->op == OP_DEREF) {
4790 count = expr_depth(state, RHS(ins, 0)) - 1;
4792 else if (ins->op == OP_VAL) {
4793 count = expr_depth(state, RHS(ins, 0)) - 1;
4795 else if (ins->op == OP_COMMA) {
4797 ldepth = expr_depth(state, RHS(ins, 0));
4798 rdepth = expr_depth(state, RHS(ins, 1));
4799 count = (ldepth >= rdepth)? ldepth : rdepth;
4801 else if (ins->op == OP_CALL) {
4802 /* Don't figure the depth of a call just guess it is huge */
4806 struct triple **expr;
4807 expr = triple_rhs(state, ins, 0);
4808 for(;expr; expr = triple_rhs(state, ins, expr)) {
4811 depth = expr_depth(state, *expr);
4812 if (depth > count) {
4821 static struct triple *flatten(
4822 struct compile_state *state, struct triple *first, struct triple *ptr);
4824 static struct triple *flatten_generic(
4825 struct compile_state *state, struct triple *first, struct triple *ptr)
4829 struct triple **ins;
4832 /* Only operations with just a rhs should come here */
4833 rhs = TRIPLE_RHS(ptr->sizes);
4834 lhs = TRIPLE_LHS(ptr->sizes);
4835 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4836 internal_error(state, ptr, "unexpected args for: %d %s",
4837 ptr->op, tops(ptr->op));
4839 /* Find the depth of the rhs elements */
4840 for(i = 0; i < rhs; i++) {
4841 vector[i].ins = &RHS(ptr, i);
4842 vector[i].depth = expr_depth(state, *vector[i].ins);
4844 /* Selection sort the rhs */
4845 for(i = 0; i < rhs; i++) {
4847 for(j = i + 1; j < rhs; j++ ) {
4848 if (vector[j].depth > vector[max].depth) {
4853 struct rhs_vector tmp;
4855 vector[i] = vector[max];
4859 /* Now flatten the rhs elements */
4860 for(i = 0; i < rhs; i++) {
4861 *vector[i].ins = flatten(state, first, *vector[i].ins);
4862 use_triple(*vector[i].ins, ptr);
4865 /* Now flatten the lhs elements */
4866 for(i = 0; i < lhs; i++) {
4867 struct triple **ins = &LHS(ptr, i);
4868 *ins = flatten(state, first, *ins);
4869 use_triple(*ins, ptr);
4874 static struct triple *flatten_land(
4875 struct compile_state *state, struct triple *first, struct triple *ptr)
4877 struct triple *left, *right;
4878 struct triple *val, *test, *jmp, *label1, *end;
4880 /* Find the triples */
4882 right = RHS(ptr, 1);
4884 /* Generate the needed triples */
4887 /* Thread the triples together */
4888 val = flatten(state, first, variable(state, ptr->type));
4889 left = flatten(state, first, write_expr(state, val, left));
4890 test = flatten(state, first,
4891 lfalse_expr(state, read_expr(state, val)));
4892 jmp = flatten(state, first, branch(state, end, test));
4893 label1 = flatten(state, first, label(state));
4894 right = flatten(state, first, write_expr(state, val, right));
4895 TARG(jmp, 0) = flatten(state, first, end);
4897 /* Now give the caller something to chew on */
4898 return read_expr(state, val);
4901 static struct triple *flatten_lor(
4902 struct compile_state *state, struct triple *first, struct triple *ptr)
4904 struct triple *left, *right;
4905 struct triple *val, *jmp, *label1, *end;
4907 /* Find the triples */
4909 right = RHS(ptr, 1);
4911 /* Generate the needed triples */
4914 /* Thread the triples together */
4915 val = flatten(state, first, variable(state, ptr->type));
4916 left = flatten(state, first, write_expr(state, val, left));
4917 jmp = flatten(state, first, branch(state, end, left));
4918 label1 = flatten(state, first, label(state));
4919 right = flatten(state, first, write_expr(state, val, right));
4920 TARG(jmp, 0) = flatten(state, first, end);
4923 /* Now give the caller something to chew on */
4924 return read_expr(state, val);
4927 static struct triple *flatten_cond(
4928 struct compile_state *state, struct triple *first, struct triple *ptr)
4930 struct triple *test, *left, *right;
4931 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4933 /* Find the triples */
4936 right = RHS(ptr, 2);
4938 /* Generate the needed triples */
4940 middle = label(state);
4942 /* Thread the triples together */
4943 val = flatten(state, first, variable(state, ptr->type));
4944 test = flatten(state, first, test);
4945 jmp1 = flatten(state, first, branch(state, middle, test));
4946 label1 = flatten(state, first, label(state));
4947 left = flatten(state, first, left);
4948 mv1 = flatten(state, first, write_expr(state, val, left));
4949 jmp2 = flatten(state, first, branch(state, end, 0));
4950 TARG(jmp1, 0) = flatten(state, first, middle);
4951 right = flatten(state, first, right);
4952 mv2 = flatten(state, first, write_expr(state, val, right));
4953 TARG(jmp2, 0) = flatten(state, first, end);
4955 /* Now give the caller something to chew on */
4956 return read_expr(state, val);
4959 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
4960 struct occurance *base_occurance)
4962 struct triple *nfunc;
4963 struct triple *nfirst, *ofirst;
4964 struct triple *new, *old;
4967 fprintf(stdout, "\n");
4968 loc(stdout, state, 0);
4969 fprintf(stdout, "\n__________ copy_func _________\n");
4970 print_triple(state, ofunc);
4971 fprintf(stdout, "__________ copy_func _________ done\n\n");
4974 /* Make a new copy of the old function */
4975 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4977 ofirst = old = RHS(ofunc, 0);
4980 struct occurance *occurance;
4981 int old_lhs, old_rhs;
4982 old_lhs = TRIPLE_LHS(old->sizes);
4983 old_rhs = TRIPLE_RHS(old->sizes);
4984 occurance = inline_occurance(state, base_occurance, old->occurance);
4985 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4987 if (!triple_stores_block(state, new)) {
4988 memcpy(&new->u, &old->u, sizeof(new->u));
4991 RHS(nfunc, 0) = nfirst = new;
4994 insert_triple(state, nfirst, new);
4996 new->id |= TRIPLE_FLAG_FLATTENED;
4998 /* During the copy remember new as user of old */
4999 use_triple(old, new);
5001 /* Populate the return type if present */
5002 if (old == MISC(ofunc, 0)) {
5003 MISC(nfunc, 0) = new;
5006 } while(old != ofirst);
5008 /* Make a second pass to fix up any unresolved references */
5012 struct triple **oexpr, **nexpr;
5014 /* Lookup where the copy is, to join pointers */
5015 count = TRIPLE_SIZE(old->sizes);
5016 for(i = 0; i < count; i++) {
5017 oexpr = &old->param[i];
5018 nexpr = &new->param[i];
5019 if (!*nexpr && *oexpr && (*oexpr)->use) {
5020 *nexpr = (*oexpr)->use->member;
5021 if (*nexpr == old) {
5022 internal_error(state, 0, "new == old?");
5024 use_triple(*nexpr, new);
5026 if (!*nexpr && *oexpr) {
5027 internal_error(state, 0, "Could not copy %d\n", i);
5032 } while((old != ofirst) && (new != nfirst));
5034 /* Make a third pass to cleanup the extra useses */
5038 unuse_triple(old, new);
5041 } while ((old != ofirst) && (new != nfirst));
5045 static struct triple *flatten_call(
5046 struct compile_state *state, struct triple *first, struct triple *ptr)
5048 /* Inline the function call */
5050 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5051 struct triple *end, *nend;
5054 /* Find the triples */
5055 ofunc = MISC(ptr, 0);
5056 if (ofunc->op != OP_LIST) {
5057 internal_error(state, 0, "improper function");
5059 nfunc = copy_func(state, ofunc, ptr->occurance);
5060 nfirst = RHS(nfunc, 0)->next;
5061 /* Prepend the parameter reading into the new function list */
5062 ptype = nfunc->type->right;
5063 param = RHS(nfunc, 0)->next;
5064 pvals = TRIPLE_RHS(ptr->sizes);
5065 for(i = 0; i < pvals; i++) {
5069 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5070 atype = ptype->left;
5072 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5073 param = param->next;
5076 flatten(state, nfirst, write_expr(state, param, arg));
5077 ptype = ptype->right;
5078 param = param->next;
5081 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5082 result = read_expr(state, MISC(nfunc,0));
5085 fprintf(stdout, "\n");
5086 loc(stdout, state, 0);
5087 fprintf(stdout, "\n__________ flatten_call _________\n");
5088 print_triple(state, nfunc);
5089 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5092 /* Get rid of the extra triples */
5093 nfirst = RHS(nfunc, 0)->next;
5094 free_triple(state, RHS(nfunc, 0));
5096 free_triple(state, nfunc);
5098 /* Append the new function list onto the return list */
5100 nend = nfirst->prev;
5109 static struct triple *flatten(
5110 struct compile_state *state, struct triple *first, struct triple *ptr)
5112 struct triple *orig_ptr;
5117 /* Only flatten triples once */
5118 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5124 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5125 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5126 use_triple(LHS(ptr, 0), ptr);
5127 use_triple(RHS(ptr, 0), ptr);
5130 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5134 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5135 return MISC(ptr, 0);
5138 ptr = flatten_land(state, first, ptr);
5141 ptr = flatten_lor(state, first, ptr);
5144 ptr = flatten_cond(state, first, ptr);
5147 ptr = flatten_call(state, first, ptr);
5151 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5152 use_triple(RHS(ptr, 0), ptr);
5155 use_triple(TARG(ptr, 0), ptr);
5156 if (TRIPLE_RHS(ptr->sizes)) {
5157 use_triple(RHS(ptr, 0), ptr);
5158 if (ptr->next != ptr) {
5159 use_triple(ptr->next, ptr);
5164 insert_triple(state, first, ptr);
5165 ptr->id |= TRIPLE_FLAG_FLATTENED;
5166 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5167 use_triple(MISC(ptr, 0), ptr);
5170 /* Since OP_DEREF is just a marker delete it when I flatten it */
5172 RHS(orig_ptr, 0) = 0;
5173 free_triple(state, orig_ptr);
5177 struct triple *base;
5179 if (base->op == OP_DEREF) {
5180 struct triple *left;
5182 offset = field_offset(state, base->type, ptr->u.field);
5183 left = RHS(base, 0);
5184 ptr = triple(state, OP_ADD, left->type,
5185 read_expr(state, left),
5186 int_const(state, &ulong_type, offset));
5187 free_triple(state, base);
5189 else if (base->op == OP_VAL_VEC) {
5190 base = flatten(state, first, base);
5191 ptr = struct_field(state, base, ptr->u.field);
5196 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5197 use_triple(MISC(ptr, 0), ptr);
5198 use_triple(ptr, MISC(ptr, 0));
5202 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5203 use_triple(MISC(ptr, 0), ptr);
5208 /* Flatten the easy cases we don't override */
5209 ptr = flatten_generic(state, first, ptr);
5212 } while(ptr && (ptr != orig_ptr));
5214 insert_triple(state, first, ptr);
5215 ptr->id |= TRIPLE_FLAG_FLATTENED;
5220 static void release_expr(struct compile_state *state, struct triple *expr)
5222 struct triple *head;
5223 head = label(state);
5224 flatten(state, head, expr);
5225 while(head->next != head) {
5226 release_triple(state, head->next);
5228 free_triple(state, head);
5231 static int replace_rhs_use(struct compile_state *state,
5232 struct triple *orig, struct triple *new, struct triple *use)
5234 struct triple **expr;
5237 expr = triple_rhs(state, use, 0);
5238 for(;expr; expr = triple_rhs(state, use, expr)) {
5239 if (*expr == orig) {
5245 unuse_triple(orig, use);
5246 use_triple(new, use);
5251 static int replace_lhs_use(struct compile_state *state,
5252 struct triple *orig, struct triple *new, struct triple *use)
5254 struct triple **expr;
5257 expr = triple_lhs(state, use, 0);
5258 for(;expr; expr = triple_lhs(state, use, expr)) {
5259 if (*expr == orig) {
5265 unuse_triple(orig, use);
5266 use_triple(new, use);
5271 static void propogate_use(struct compile_state *state,
5272 struct triple *orig, struct triple *new)
5274 struct triple_set *user, *next;
5275 for(user = orig->use; user; user = next) {
5281 found |= replace_rhs_use(state, orig, new, use);
5282 found |= replace_lhs_use(state, orig, new, use);
5284 internal_error(state, use, "use without use");
5288 internal_error(state, orig, "used after propogate_use");
5294 * ===========================
5297 static struct triple *mk_add_expr(
5298 struct compile_state *state, struct triple *left, struct triple *right)
5300 struct type *result_type;
5301 /* Put pointer operands on the left */
5302 if (is_pointer(right)) {
5308 left = read_expr(state, left);
5309 right = read_expr(state, right);
5310 result_type = ptr_arithmetic_result(state, left, right);
5311 if (is_pointer(left)) {
5312 right = triple(state,
5313 is_signed(right->type)? OP_SMUL : OP_UMUL,
5316 int_const(state, &ulong_type,
5317 size_of(state, left->type->left)));
5319 return triple(state, OP_ADD, result_type, left, right);
5322 static struct triple *mk_sub_expr(
5323 struct compile_state *state, struct triple *left, struct triple *right)
5325 struct type *result_type;
5326 result_type = ptr_arithmetic_result(state, left, right);
5327 left = read_expr(state, left);
5328 right = read_expr(state, right);
5329 if (is_pointer(left)) {
5330 right = triple(state,
5331 is_signed(right->type)? OP_SMUL : OP_UMUL,
5334 int_const(state, &ulong_type,
5335 size_of(state, left->type->left)));
5337 return triple(state, OP_SUB, result_type, left, right);
5340 static struct triple *mk_pre_inc_expr(
5341 struct compile_state *state, struct triple *def)
5345 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5346 return triple(state, OP_VAL, def->type,
5347 write_expr(state, def, val),
5351 static struct triple *mk_pre_dec_expr(
5352 struct compile_state *state, struct triple *def)
5356 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5357 return triple(state, OP_VAL, def->type,
5358 write_expr(state, def, val),
5362 static struct triple *mk_post_inc_expr(
5363 struct compile_state *state, struct triple *def)
5367 val = read_expr(state, def);
5368 return triple(state, OP_VAL, def->type,
5369 write_expr(state, def,
5370 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5374 static struct triple *mk_post_dec_expr(
5375 struct compile_state *state, struct triple *def)
5379 val = read_expr(state, def);
5380 return triple(state, OP_VAL, def->type,
5381 write_expr(state, def,
5382 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5386 static struct triple *mk_subscript_expr(
5387 struct compile_state *state, struct triple *left, struct triple *right)
5389 left = read_expr(state, left);
5390 right = read_expr(state, right);
5391 if (!is_pointer(left) && !is_pointer(right)) {
5392 error(state, left, "subscripted value is not a pointer");
5394 return mk_deref_expr(state, mk_add_expr(state, left, right));
5398 * Compile time evaluation
5399 * ===========================
5401 static int is_const(struct triple *ins)
5403 return IS_CONST_OP(ins->op);
5406 static int constants_equal(struct compile_state *state,
5407 struct triple *left, struct triple *right)
5410 if (!is_const(left) || !is_const(right)) {
5413 else if (left->op != right->op) {
5416 else if (!equiv_types(left->type, right->type)) {
5423 if (left->u.cval == right->u.cval) {
5429 size_t lsize, rsize;
5430 lsize = size_of(state, left->type);
5431 rsize = size_of(state, right->type);
5432 if (lsize != rsize) {
5435 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5441 if ((MISC(left, 0) == MISC(right, 0)) &&
5442 (left->u.cval == right->u.cval)) {
5447 internal_error(state, left, "uknown constant type");
5454 static int is_zero(struct triple *ins)
5456 return is_const(ins) && (ins->u.cval == 0);
5459 static int is_one(struct triple *ins)
5461 return is_const(ins) && (ins->u.cval == 1);
5464 static long_t bsr(ulong_t value)
5467 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5478 static long_t bsf(ulong_t value)
5481 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5492 static long_t log2(ulong_t value)
5497 static long_t tlog2(struct triple *ins)
5499 return log2(ins->u.cval);
5502 static int is_pow2(struct triple *ins)
5504 ulong_t value, mask;
5506 if (!is_const(ins)) {
5509 value = ins->u.cval;
5516 return ((value & mask) == value);
5519 static ulong_t read_const(struct compile_state *state,
5520 struct triple *ins, struct triple **expr)
5524 switch(rhs->type->type &TYPE_MASK) {
5536 internal_error(state, rhs, "bad type to read_const\n");
5542 static long_t read_sconst(struct triple *ins, struct triple **expr)
5546 return (long_t)(rhs->u.cval);
5549 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5551 struct triple **expr;
5552 expr = triple_rhs(state, ins, 0);
5553 for(;expr;expr = triple_rhs(state, ins, expr)) {
5555 unuse_triple(*expr, ins);
5561 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5563 struct triple **expr;
5564 expr = triple_lhs(state, ins, 0);
5565 for(;expr;expr = triple_lhs(state, ins, expr)) {
5566 unuse_triple(*expr, ins);
5571 static void check_lhs(struct compile_state *state, struct triple *ins)
5573 struct triple **expr;
5574 expr = triple_lhs(state, ins, 0);
5575 for(;expr;expr = triple_lhs(state, ins, expr)) {
5576 internal_error(state, ins, "unexpected lhs");
5580 static void check_targ(struct compile_state *state, struct triple *ins)
5582 struct triple **expr;
5583 expr = triple_targ(state, ins, 0);
5584 for(;expr;expr = triple_targ(state, ins, expr)) {
5585 internal_error(state, ins, "unexpected targ");
5589 static void wipe_ins(struct compile_state *state, struct triple *ins)
5591 /* Becareful which instructions you replace the wiped
5592 * instruction with, as there are not enough slots
5593 * in all instructions to hold all others.
5595 check_targ(state, ins);
5596 unuse_rhs(state, ins);
5597 unuse_lhs(state, ins);
5600 static void mkcopy(struct compile_state *state,
5601 struct triple *ins, struct triple *rhs)
5603 wipe_ins(state, ins);
5605 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5607 use_triple(RHS(ins, 0), ins);
5610 static void mkconst(struct compile_state *state,
5611 struct triple *ins, ulong_t value)
5613 if (!is_integral(ins) && !is_pointer(ins)) {
5614 internal_error(state, ins, "unknown type to make constant\n");
5616 wipe_ins(state, ins);
5617 ins->op = OP_INTCONST;
5618 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5619 ins->u.cval = value;
5622 static void mkaddr_const(struct compile_state *state,
5623 struct triple *ins, struct triple *sdecl, ulong_t value)
5625 wipe_ins(state, ins);
5626 ins->op = OP_ADDRCONST;
5627 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5628 MISC(ins, 0) = sdecl;
5629 ins->u.cval = value;
5630 use_triple(sdecl, ins);
5633 /* Transform multicomponent variables into simple register variables */
5634 static void flatten_structures(struct compile_state *state)
5636 struct triple *ins, *first;
5637 first = RHS(state->main_function, 0);
5639 /* Pass one expand structure values into valvecs.
5643 struct triple *next;
5645 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5646 if (ins->op == OP_VAL_VEC) {
5649 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5650 struct triple *def, **vector;
5657 get_occurance(ins->occurance);
5658 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5661 vector = &RHS(next, 0);
5662 tptr = next->type->left;
5663 for(i = 0; i < next->type->elements; i++) {
5664 struct triple *sfield;
5667 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5668 mtype = mtype->left;
5670 sfield = deref_field(state, def, mtype->field_ident);
5673 state, op, mtype, sfield, 0);
5674 put_occurance(vector[i]->occurance);
5675 get_occurance(next->occurance);
5676 vector[i]->occurance = next->occurance;
5679 propogate_use(state, ins, next);
5680 flatten(state, ins, next);
5681 free_triple(state, ins);
5683 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5684 struct triple *src, *dst, **vector;
5692 get_occurance(ins->occurance);
5693 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5696 vector = &RHS(next, 0);
5697 tptr = next->type->left;
5698 for(i = 0; i < ins->type->elements; i++) {
5699 struct triple *dfield, *sfield;
5702 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5703 mtype = mtype->left;
5705 sfield = deref_field(state, src, mtype->field_ident);
5706 dfield = deref_field(state, dst, mtype->field_ident);
5708 state, op, mtype, dfield, sfield);
5709 put_occurance(vector[i]->occurance);
5710 get_occurance(next->occurance);
5711 vector[i]->occurance = next->occurance;
5714 propogate_use(state, ins, next);
5715 flatten(state, ins, next);
5716 free_triple(state, ins);
5720 } while(ins != first);
5721 /* Pass two flatten the valvecs.
5725 struct triple *next;
5727 if (ins->op == OP_VAL_VEC) {
5728 release_triple(state, ins);
5731 } while(ins != first);
5732 /* Pass three verify the state and set ->id to 0.
5736 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5737 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5738 internal_error(state, ins, "STRUCT_TYPE remains?");
5740 if (ins->op == OP_DOT) {
5741 internal_error(state, ins, "OP_DOT remains?");
5743 if (ins->op == OP_VAL_VEC) {
5744 internal_error(state, ins, "OP_VAL_VEC remains?");
5747 } while(ins != first);
5750 /* For those operations that cannot be simplified */
5751 static void simplify_noop(struct compile_state *state, struct triple *ins)
5756 static void simplify_smul(struct compile_state *state, struct triple *ins)
5758 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5761 RHS(ins, 0) = RHS(ins, 1);
5764 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5766 left = read_sconst(ins, &RHS(ins, 0));
5767 right = read_sconst(ins, &RHS(ins, 1));
5768 mkconst(state, ins, left * right);
5770 else if (is_zero(RHS(ins, 1))) {
5771 mkconst(state, ins, 0);
5773 else if (is_one(RHS(ins, 1))) {
5774 mkcopy(state, ins, RHS(ins, 0));
5776 else if (is_pow2(RHS(ins, 1))) {
5778 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5780 insert_triple(state, ins, val);
5781 unuse_triple(RHS(ins, 1), ins);
5782 use_triple(val, ins);
5787 static void simplify_umul(struct compile_state *state, struct triple *ins)
5789 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5792 RHS(ins, 0) = RHS(ins, 1);
5795 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5796 ulong_t left, right;
5797 left = read_const(state, ins, &RHS(ins, 0));
5798 right = read_const(state, ins, &RHS(ins, 1));
5799 mkconst(state, ins, left * right);
5801 else if (is_zero(RHS(ins, 1))) {
5802 mkconst(state, ins, 0);
5804 else if (is_one(RHS(ins, 1))) {
5805 mkcopy(state, ins, RHS(ins, 0));
5807 else if (is_pow2(RHS(ins, 1))) {
5809 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5811 insert_triple(state, ins, val);
5812 unuse_triple(RHS(ins, 1), ins);
5813 use_triple(val, ins);
5818 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5820 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5822 left = read_sconst(ins, &RHS(ins, 0));
5823 right = read_sconst(ins, &RHS(ins, 1));
5824 mkconst(state, ins, left / right);
5826 else if (is_zero(RHS(ins, 0))) {
5827 mkconst(state, ins, 0);
5829 else if (is_zero(RHS(ins, 1))) {
5830 error(state, ins, "division by zero");
5832 else if (is_one(RHS(ins, 1))) {
5833 mkcopy(state, ins, RHS(ins, 0));
5835 else if (is_pow2(RHS(ins, 1))) {
5837 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5839 insert_triple(state, ins, val);
5840 unuse_triple(RHS(ins, 1), ins);
5841 use_triple(val, ins);
5846 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5848 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5849 ulong_t left, right;
5850 left = read_const(state, ins, &RHS(ins, 0));
5851 right = read_const(state, ins, &RHS(ins, 1));
5852 mkconst(state, ins, left / right);
5854 else if (is_zero(RHS(ins, 0))) {
5855 mkconst(state, ins, 0);
5857 else if (is_zero(RHS(ins, 1))) {
5858 error(state, ins, "division by zero");
5860 else if (is_one(RHS(ins, 1))) {
5861 mkcopy(state, ins, RHS(ins, 0));
5863 else if (is_pow2(RHS(ins, 1))) {
5865 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5867 insert_triple(state, ins, val);
5868 unuse_triple(RHS(ins, 1), ins);
5869 use_triple(val, ins);
5874 static void simplify_smod(struct compile_state *state, struct triple *ins)
5876 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5878 left = read_const(state, ins, &RHS(ins, 0));
5879 right = read_const(state, ins, &RHS(ins, 1));
5880 mkconst(state, ins, left % right);
5882 else if (is_zero(RHS(ins, 0))) {
5883 mkconst(state, ins, 0);
5885 else if (is_zero(RHS(ins, 1))) {
5886 error(state, ins, "division by zero");
5888 else if (is_one(RHS(ins, 1))) {
5889 mkconst(state, ins, 0);
5891 else if (is_pow2(RHS(ins, 1))) {
5893 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5895 insert_triple(state, ins, val);
5896 unuse_triple(RHS(ins, 1), ins);
5897 use_triple(val, ins);
5901 static void simplify_umod(struct compile_state *state, struct triple *ins)
5903 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5904 ulong_t left, right;
5905 left = read_const(state, ins, &RHS(ins, 0));
5906 right = read_const(state, ins, &RHS(ins, 1));
5907 mkconst(state, ins, left % right);
5909 else if (is_zero(RHS(ins, 0))) {
5910 mkconst(state, ins, 0);
5912 else if (is_zero(RHS(ins, 1))) {
5913 error(state, ins, "division by zero");
5915 else if (is_one(RHS(ins, 1))) {
5916 mkconst(state, ins, 0);
5918 else if (is_pow2(RHS(ins, 1))) {
5920 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5922 insert_triple(state, ins, val);
5923 unuse_triple(RHS(ins, 1), ins);
5924 use_triple(val, ins);
5929 static void simplify_add(struct compile_state *state, struct triple *ins)
5931 /* start with the pointer on the left */
5932 if (is_pointer(RHS(ins, 1))) {
5935 RHS(ins, 0) = RHS(ins, 1);
5938 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5939 if (!is_pointer(RHS(ins, 0))) {
5940 ulong_t left, right;
5941 left = read_const(state, ins, &RHS(ins, 0));
5942 right = read_const(state, ins, &RHS(ins, 1));
5943 mkconst(state, ins, left + right);
5945 else /* op == OP_ADDRCONST */ {
5946 struct triple *sdecl;
5947 ulong_t left, right;
5948 sdecl = MISC(RHS(ins, 0), 0);
5949 left = RHS(ins, 0)->u.cval;
5950 right = RHS(ins, 1)->u.cval;
5951 mkaddr_const(state, ins, sdecl, left + right);
5954 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5957 RHS(ins, 1) = RHS(ins, 0);
5962 static void simplify_sub(struct compile_state *state, struct triple *ins)
5964 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5965 if (!is_pointer(RHS(ins, 0))) {
5966 ulong_t left, right;
5967 left = read_const(state, ins, &RHS(ins, 0));
5968 right = read_const(state, ins, &RHS(ins, 1));
5969 mkconst(state, ins, left - right);
5971 else /* op == OP_ADDRCONST */ {
5972 struct triple *sdecl;
5973 ulong_t left, right;
5974 sdecl = MISC(RHS(ins, 0), 0);
5975 left = RHS(ins, 0)->u.cval;
5976 right = RHS(ins, 1)->u.cval;
5977 mkaddr_const(state, ins, sdecl, left - right);
5982 static void simplify_sl(struct compile_state *state, struct triple *ins)
5984 if (is_const(RHS(ins, 1))) {
5986 right = read_const(state, ins, &RHS(ins, 1));
5987 if (right >= (size_of(state, ins->type)*8)) {
5988 warning(state, ins, "left shift count >= width of type");
5991 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5992 ulong_t left, right;
5993 left = read_const(state, ins, &RHS(ins, 0));
5994 right = read_const(state, ins, &RHS(ins, 1));
5995 mkconst(state, ins, left << right);
5999 static void simplify_usr(struct compile_state *state, struct triple *ins)
6001 if (is_const(RHS(ins, 1))) {
6003 right = read_const(state, ins, &RHS(ins, 1));
6004 if (right >= (size_of(state, ins->type)*8)) {
6005 warning(state, ins, "right shift count >= width of type");
6008 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6009 ulong_t left, right;
6010 left = read_const(state, ins, &RHS(ins, 0));
6011 right = read_const(state, ins, &RHS(ins, 1));
6012 mkconst(state, ins, left >> right);
6016 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6018 if (is_const(RHS(ins, 1))) {
6020 right = read_const(state, ins, &RHS(ins, 1));
6021 if (right >= (size_of(state, ins->type)*8)) {
6022 warning(state, ins, "right shift count >= width of type");
6025 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6027 left = read_sconst(ins, &RHS(ins, 0));
6028 right = read_sconst(ins, &RHS(ins, 1));
6029 mkconst(state, ins, left >> right);
6033 static void simplify_and(struct compile_state *state, struct triple *ins)
6035 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6036 ulong_t left, right;
6037 left = read_const(state, ins, &RHS(ins, 0));
6038 right = read_const(state, ins, &RHS(ins, 1));
6039 mkconst(state, ins, left & right);
6043 static void simplify_or(struct compile_state *state, struct triple *ins)
6045 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6046 ulong_t left, right;
6047 left = read_const(state, ins, &RHS(ins, 0));
6048 right = read_const(state, ins, &RHS(ins, 1));
6049 mkconst(state, ins, left | right);
6053 static void simplify_xor(struct compile_state *state, struct triple *ins)
6055 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6056 ulong_t left, right;
6057 left = read_const(state, ins, &RHS(ins, 0));
6058 right = read_const(state, ins, &RHS(ins, 1));
6059 mkconst(state, ins, left ^ right);
6063 static void simplify_pos(struct compile_state *state, struct triple *ins)
6065 if (is_const(RHS(ins, 0))) {
6066 mkconst(state, ins, RHS(ins, 0)->u.cval);
6069 mkcopy(state, ins, RHS(ins, 0));
6073 static void simplify_neg(struct compile_state *state, struct triple *ins)
6075 if (is_const(RHS(ins, 0))) {
6077 left = read_const(state, ins, &RHS(ins, 0));
6078 mkconst(state, ins, -left);
6080 else if (RHS(ins, 0)->op == OP_NEG) {
6081 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6085 static void simplify_invert(struct compile_state *state, struct triple *ins)
6087 if (is_const(RHS(ins, 0))) {
6089 left = read_const(state, ins, &RHS(ins, 0));
6090 mkconst(state, ins, ~left);
6094 static void simplify_eq(struct compile_state *state, struct triple *ins)
6096 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6097 ulong_t left, right;
6098 left = read_const(state, ins, &RHS(ins, 0));
6099 right = read_const(state, ins, &RHS(ins, 1));
6100 mkconst(state, ins, left == right);
6102 else if (RHS(ins, 0) == RHS(ins, 1)) {
6103 mkconst(state, ins, 1);
6107 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6109 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6110 ulong_t left, right;
6111 left = read_const(state, ins, &RHS(ins, 0));
6112 right = read_const(state, ins, &RHS(ins, 1));
6113 mkconst(state, ins, left != right);
6115 else if (RHS(ins, 0) == RHS(ins, 1)) {
6116 mkconst(state, ins, 0);
6120 static void simplify_sless(struct compile_state *state, struct triple *ins)
6122 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6124 left = read_sconst(ins, &RHS(ins, 0));
6125 right = read_sconst(ins, &RHS(ins, 1));
6126 mkconst(state, ins, left < right);
6128 else if (RHS(ins, 0) == RHS(ins, 1)) {
6129 mkconst(state, ins, 0);
6133 static void simplify_uless(struct compile_state *state, struct triple *ins)
6135 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6136 ulong_t left, right;
6137 left = read_const(state, ins, &RHS(ins, 0));
6138 right = read_const(state, ins, &RHS(ins, 1));
6139 mkconst(state, ins, left < right);
6141 else if (is_zero(RHS(ins, 0))) {
6142 mkconst(state, ins, 1);
6144 else if (RHS(ins, 0) == RHS(ins, 1)) {
6145 mkconst(state, ins, 0);
6149 static void simplify_smore(struct compile_state *state, struct triple *ins)
6151 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6153 left = read_sconst(ins, &RHS(ins, 0));
6154 right = read_sconst(ins, &RHS(ins, 1));
6155 mkconst(state, ins, left > right);
6157 else if (RHS(ins, 0) == RHS(ins, 1)) {
6158 mkconst(state, ins, 0);
6162 static void simplify_umore(struct compile_state *state, struct triple *ins)
6164 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6165 ulong_t left, right;
6166 left = read_const(state, ins, &RHS(ins, 0));
6167 right = read_const(state, ins, &RHS(ins, 1));
6168 mkconst(state, ins, left > right);
6170 else if (is_zero(RHS(ins, 1))) {
6171 mkconst(state, ins, 1);
6173 else if (RHS(ins, 0) == RHS(ins, 1)) {
6174 mkconst(state, ins, 0);
6179 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6181 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6183 left = read_sconst(ins, &RHS(ins, 0));
6184 right = read_sconst(ins, &RHS(ins, 1));
6185 mkconst(state, ins, left <= right);
6187 else if (RHS(ins, 0) == RHS(ins, 1)) {
6188 mkconst(state, ins, 1);
6192 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6194 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6195 ulong_t left, right;
6196 left = read_const(state, ins, &RHS(ins, 0));
6197 right = read_const(state, ins, &RHS(ins, 1));
6198 mkconst(state, ins, left <= right);
6200 else if (is_zero(RHS(ins, 0))) {
6201 mkconst(state, ins, 1);
6203 else if (RHS(ins, 0) == RHS(ins, 1)) {
6204 mkconst(state, ins, 1);
6208 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6210 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6212 left = read_sconst(ins, &RHS(ins, 0));
6213 right = read_sconst(ins, &RHS(ins, 1));
6214 mkconst(state, ins, left >= right);
6216 else if (RHS(ins, 0) == RHS(ins, 1)) {
6217 mkconst(state, ins, 1);
6221 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6223 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6224 ulong_t left, right;
6225 left = read_const(state, ins, &RHS(ins, 0));
6226 right = read_const(state, ins, &RHS(ins, 1));
6227 mkconst(state, ins, left >= right);
6229 else if (is_zero(RHS(ins, 1))) {
6230 mkconst(state, ins, 1);
6232 else if (RHS(ins, 0) == RHS(ins, 1)) {
6233 mkconst(state, ins, 1);
6237 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6239 if (is_const(RHS(ins, 0))) {
6241 left = read_const(state, ins, &RHS(ins, 0));
6242 mkconst(state, ins, left == 0);
6244 /* Otherwise if I am the only user... */
6245 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6247 /* Invert a boolean operation */
6248 switch(RHS(ins, 0)->op) {
6249 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6250 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6251 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6252 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6253 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6254 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6255 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6256 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6257 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6258 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6259 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6260 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6266 mkcopy(state, ins, RHS(ins, 0));
6271 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6273 if (is_const(RHS(ins, 0))) {
6275 left = read_const(state, ins, &RHS(ins, 0));
6276 mkconst(state, ins, left != 0);
6278 else switch(RHS(ins, 0)->op) {
6279 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6280 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6281 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6282 mkcopy(state, ins, RHS(ins, 0));
6287 static void simplify_copy(struct compile_state *state, struct triple *ins)
6289 if (is_const(RHS(ins, 0))) {
6290 switch(RHS(ins, 0)->op) {
6294 left = read_const(state, ins, &RHS(ins, 0));
6295 mkconst(state, ins, left);
6300 struct triple *sdecl;
6302 sdecl = MISC(RHS(ins, 0), 0);
6303 offset = RHS(ins, 0)->u.cval;
6304 mkaddr_const(state, ins, sdecl, offset);
6308 internal_error(state, ins, "uknown constant");
6314 static void simplify_branch(struct compile_state *state, struct triple *ins)
6316 struct block *block;
6317 if (ins->op != OP_BRANCH) {
6318 internal_error(state, ins, "not branch");
6320 if (ins->use != 0) {
6321 internal_error(state, ins, "branch use");
6323 #warning "FIXME implement simplify branch."
6324 /* The challenge here with simplify branch is that I need to
6325 * make modifications to the control flow graph as well
6326 * as to the branch instruction itself.
6328 block = ins->u.block;
6330 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6331 struct triple *targ;
6333 value = read_const(state, ins, &RHS(ins, 0));
6334 unuse_triple(RHS(ins, 0), ins);
6335 targ = TARG(ins, 0);
6336 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6338 unuse_triple(ins->next, ins);
6339 TARG(ins, 0) = targ;
6342 unuse_triple(targ, ins);
6343 TARG(ins, 0) = ins->next;
6345 #warning "FIXME handle the case of making a branch unconditional"
6347 if (TARG(ins, 0) == ins->next) {
6348 unuse_triple(ins->next, ins);
6349 if (TRIPLE_RHS(ins->sizes)) {
6350 unuse_triple(RHS(ins, 0), ins);
6351 unuse_triple(ins->next, ins);
6353 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6356 internal_error(state, ins, "noop use != 0");
6358 #warning "FIXME handle the case of killing a branch"
6362 static void simplify_phi(struct compile_state *state, struct triple *ins)
6364 struct triple **expr;
6366 expr = triple_rhs(state, ins, 0);
6367 if (!*expr || !is_const(*expr)) {
6370 value = read_const(state, ins, expr);
6371 for(;expr;expr = triple_rhs(state, ins, expr)) {
6372 if (!*expr || !is_const(*expr)) {
6375 if (value != read_const(state, ins, expr)) {
6379 mkconst(state, ins, value);
6383 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6385 if (is_const(RHS(ins, 0))) {
6387 left = read_const(state, ins, &RHS(ins, 0));
6388 mkconst(state, ins, bsf(left));
6392 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6394 if (is_const(RHS(ins, 0))) {
6396 left = read_const(state, ins, &RHS(ins, 0));
6397 mkconst(state, ins, bsr(left));
6402 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6403 static const simplify_t table_simplify[] = {
6405 #define simplify_smul simplify_noop
6406 #define simplify_umul simplify_noop
6407 #define simplify_sdiv simplify_noop
6408 #define simplify_udiv simplify_noop
6409 #define simplify_smod simplify_noop
6410 #define simplify_umod simplify_noop
6413 #define simplify_add simplify_noop
6414 #define simplify_sub simplify_noop
6417 #define simplify_sl simplify_noop
6418 #define simplify_usr simplify_noop
6419 #define simplify_ssr simplify_noop
6422 #define simplify_and simplify_noop
6423 #define simplify_xor simplify_noop
6424 #define simplify_or simplify_noop
6427 #define simplify_pos simplify_noop
6428 #define simplify_neg simplify_noop
6429 #define simplify_invert simplify_noop
6433 #define simplify_eq simplify_noop
6434 #define simplify_noteq simplify_noop
6437 #define simplify_sless simplify_noop
6438 #define simplify_uless simplify_noop
6439 #define simplify_smore simplify_noop
6440 #define simplify_umore simplify_noop
6443 #define simplify_slesseq simplify_noop
6444 #define simplify_ulesseq simplify_noop
6445 #define simplify_smoreeq simplify_noop
6446 #define simplify_umoreeq simplify_noop
6449 #define simplify_lfalse simplify_noop
6452 #define simplify_ltrue simplify_noop
6456 #define simplify_copy simplify_noop
6460 #define simplify_branch simplify_noop
6464 #define simplify_phi simplify_noop
6468 #define simplify_bsf simplify_noop
6469 #define simplify_bsr simplify_noop
6472 [OP_SMUL ] = simplify_smul,
6473 [OP_UMUL ] = simplify_umul,
6474 [OP_SDIV ] = simplify_sdiv,
6475 [OP_UDIV ] = simplify_udiv,
6476 [OP_SMOD ] = simplify_smod,
6477 [OP_UMOD ] = simplify_umod,
6478 [OP_ADD ] = simplify_add,
6479 [OP_SUB ] = simplify_sub,
6480 [OP_SL ] = simplify_sl,
6481 [OP_USR ] = simplify_usr,
6482 [OP_SSR ] = simplify_ssr,
6483 [OP_AND ] = simplify_and,
6484 [OP_XOR ] = simplify_xor,
6485 [OP_OR ] = simplify_or,
6486 [OP_POS ] = simplify_pos,
6487 [OP_NEG ] = simplify_neg,
6488 [OP_INVERT ] = simplify_invert,
6490 [OP_EQ ] = simplify_eq,
6491 [OP_NOTEQ ] = simplify_noteq,
6492 [OP_SLESS ] = simplify_sless,
6493 [OP_ULESS ] = simplify_uless,
6494 [OP_SMORE ] = simplify_smore,
6495 [OP_UMORE ] = simplify_umore,
6496 [OP_SLESSEQ ] = simplify_slesseq,
6497 [OP_ULESSEQ ] = simplify_ulesseq,
6498 [OP_SMOREEQ ] = simplify_smoreeq,
6499 [OP_UMOREEQ ] = simplify_umoreeq,
6500 [OP_LFALSE ] = simplify_lfalse,
6501 [OP_LTRUE ] = simplify_ltrue,
6503 [OP_LOAD ] = simplify_noop,
6504 [OP_STORE ] = simplify_noop,
6506 [OP_NOOP ] = simplify_noop,
6508 [OP_INTCONST ] = simplify_noop,
6509 [OP_BLOBCONST ] = simplify_noop,
6510 [OP_ADDRCONST ] = simplify_noop,
6512 [OP_WRITE ] = simplify_noop,
6513 [OP_READ ] = simplify_noop,
6514 [OP_COPY ] = simplify_copy,
6515 [OP_PIECE ] = simplify_noop,
6516 [OP_ASM ] = simplify_noop,
6518 [OP_DOT ] = simplify_noop,
6519 [OP_VAL_VEC ] = simplify_noop,
6521 [OP_LIST ] = simplify_noop,
6522 [OP_BRANCH ] = simplify_branch,
6523 [OP_LABEL ] = simplify_noop,
6524 [OP_ADECL ] = simplify_noop,
6525 [OP_SDECL ] = simplify_noop,
6526 [OP_PHI ] = simplify_phi,
6528 [OP_INB ] = simplify_noop,
6529 [OP_INW ] = simplify_noop,
6530 [OP_INL ] = simplify_noop,
6531 [OP_OUTB ] = simplify_noop,
6532 [OP_OUTW ] = simplify_noop,
6533 [OP_OUTL ] = simplify_noop,
6534 [OP_BSF ] = simplify_bsf,
6535 [OP_BSR ] = simplify_bsr,
6536 [OP_RDMSR ] = simplify_noop,
6537 [OP_WRMSR ] = simplify_noop,
6538 [OP_HLT ] = simplify_noop,
6541 static void simplify(struct compile_state *state, struct triple *ins)
6544 simplify_t do_simplify;
6548 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6552 do_simplify = table_simplify[op];
6555 internal_error(state, ins, "cannot simplify op: %d %s\n",
6559 do_simplify(state, ins);
6560 } while(ins->op != op);
6563 static void simplify_all(struct compile_state *state)
6565 struct triple *ins, *first;
6566 first = RHS(state->main_function, 0);
6569 simplify(state, ins);
6571 } while(ins != first);
6576 * ============================
6579 static void register_builtin_function(struct compile_state *state,
6580 const char *name, int op, struct type *rtype, ...)
6582 struct type *ftype, *atype, *param, **next;
6583 struct triple *def, *arg, *result, *work, *last, *first;
6584 struct hash_entry *ident;
6585 struct file_state file;
6591 /* Dummy file state to get debug handling right */
6592 memset(&file, 0, sizeof(file));
6593 file.basename = "<built-in>";
6595 file.report_line = 1;
6596 file.report_name = file.basename;
6597 file.prev = state->file;
6598 state->file = &file;
6599 state->function = name;
6601 /* Find the Parameter count */
6602 valid_op(state, op);
6603 parameters = table_ops[op].rhs;
6604 if (parameters < 0 ) {
6605 internal_error(state, 0, "Invalid builtin parameter count");
6608 /* Find the function type */
6609 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6610 next = &ftype->right;
6611 va_start(args, rtype);
6612 for(i = 0; i < parameters; i++) {
6613 atype = va_arg(args, struct type *);
6617 *next = new_type(TYPE_PRODUCT, *next, atype);
6618 next = &((*next)->right);
6626 /* Generate the needed triples */
6627 def = triple(state, OP_LIST, ftype, 0, 0);
6628 first = label(state);
6629 RHS(def, 0) = first;
6631 /* Now string them together */
6632 param = ftype->right;
6633 for(i = 0; i < parameters; i++) {
6634 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6635 atype = param->left;
6639 arg = flatten(state, first, variable(state, atype));
6640 param = param->right;
6643 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6644 result = flatten(state, first, variable(state, rtype));
6646 MISC(def, 0) = result;
6647 work = new_triple(state, op, rtype, -1, parameters);
6648 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6649 RHS(work, i) = read_expr(state, arg);
6651 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6653 /* Populate the LHS with the target registers */
6654 work = flatten(state, first, work);
6655 work->type = &void_type;
6656 param = rtype->left;
6657 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6658 internal_error(state, 0, "Invalid result type");
6660 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6661 for(i = 0; i < rtype->elements; i++) {
6662 struct triple *piece;
6664 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6665 atype = param->left;
6667 if (!TYPE_ARITHMETIC(atype->type) &&
6668 !TYPE_PTR(atype->type)) {
6669 internal_error(state, 0, "Invalid lhs type");
6671 piece = triple(state, OP_PIECE, atype, work, 0);
6673 LHS(work, i) = piece;
6674 RHS(val, i) = piece;
6679 work = write_expr(state, result, work);
6681 work = flatten(state, first, work);
6682 last = flatten(state, first, label(state));
6683 name_len = strlen(name);
6684 ident = lookup(state, name, name_len);
6685 symbol(state, ident, &ident->sym_ident, def, ftype);
6687 state->file = file.prev;
6688 state->function = 0;
6690 fprintf(stdout, "\n");
6691 loc(stdout, state, 0);
6692 fprintf(stdout, "\n__________ builtin_function _________\n");
6693 print_triple(state, def);
6694 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6698 static struct type *partial_struct(struct compile_state *state,
6699 const char *field_name, struct type *type, struct type *rest)
6701 struct hash_entry *field_ident;
6702 struct type *result;
6705 field_name_len = strlen(field_name);
6706 field_ident = lookup(state, field_name, field_name_len);
6708 result = clone_type(0, type);
6709 result->field_ident = field_ident;
6712 result = new_type(TYPE_PRODUCT, result, rest);
6717 static struct type *register_builtin_type(struct compile_state *state,
6718 const char *name, struct type *type)
6720 struct hash_entry *ident;
6723 name_len = strlen(name);
6724 ident = lookup(state, name, name_len);
6726 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6727 ulong_t elements = 0;
6729 type = new_type(TYPE_STRUCT, type, 0);
6731 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6733 field = field->right;
6736 symbol(state, ident, &ident->sym_struct, 0, type);
6737 type->type_ident = ident;
6738 type->elements = elements;
6740 symbol(state, ident, &ident->sym_ident, 0, type);
6741 ident->tok = TOK_TYPE_NAME;
6746 static void register_builtins(struct compile_state *state)
6748 struct type *msr_type;
6750 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6752 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6754 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6757 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6758 &uchar_type, &ushort_type);
6759 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6760 &ushort_type, &ushort_type);
6761 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6762 &uint_type, &ushort_type);
6764 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6766 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6769 msr_type = register_builtin_type(state, "__builtin_msr_t",
6770 partial_struct(state, "lo", &ulong_type,
6771 partial_struct(state, "hi", &ulong_type, 0)));
6773 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6775 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6776 &ulong_type, &ulong_type, &ulong_type);
6778 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6782 static struct type *declarator(
6783 struct compile_state *state, struct type *type,
6784 struct hash_entry **ident, int need_ident);
6785 static void decl(struct compile_state *state, struct triple *first);
6786 static struct type *specifier_qualifier_list(struct compile_state *state);
6787 static int isdecl_specifier(int tok);
6788 static struct type *decl_specifiers(struct compile_state *state);
6789 static int istype(int tok);
6790 static struct triple *expr(struct compile_state *state);
6791 static struct triple *assignment_expr(struct compile_state *state);
6792 static struct type *type_name(struct compile_state *state);
6793 static void statement(struct compile_state *state, struct triple *fist);
6795 static struct triple *call_expr(
6796 struct compile_state *state, struct triple *func)
6799 struct type *param, *type;
6800 ulong_t pvals, index;
6802 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6803 error(state, 0, "Called object is not a function");
6805 if (func->op != OP_LIST) {
6806 internal_error(state, 0, "improper function");
6808 eat(state, TOK_LPAREN);
6809 /* Find the return type without any specifiers */
6810 type = clone_type(0, func->type->left);
6811 def = new_triple(state, OP_CALL, func->type, -1, -1);
6814 pvals = TRIPLE_RHS(def->sizes);
6815 MISC(def, 0) = func;
6817 param = func->type->right;
6818 for(index = 0; index < pvals; index++) {
6820 struct type *arg_type;
6821 val = read_expr(state, assignment_expr(state));
6823 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6824 arg_type = param->left;
6826 write_compatible(state, arg_type, val->type);
6827 RHS(def, index) = val;
6828 if (index != (pvals - 1)) {
6829 eat(state, TOK_COMMA);
6830 param = param->right;
6833 eat(state, TOK_RPAREN);
6838 static struct triple *character_constant(struct compile_state *state)
6842 const signed char *str, *end;
6845 eat(state, TOK_LIT_CHAR);
6846 tk = &state->token[0];
6847 str = tk->val.str + 1;
6848 str_len = tk->str_len - 2;
6850 error(state, 0, "empty character constant");
6852 end = str + str_len;
6853 c = char_value(state, &str, end);
6855 error(state, 0, "multibyte character constant not supported");
6857 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6861 static struct triple *string_constant(struct compile_state *state)
6866 const signed char *str, *end;
6867 signed char *buf, *ptr;
6871 type = new_type(TYPE_ARRAY, &char_type, 0);
6873 /* The while loop handles string concatenation */
6875 eat(state, TOK_LIT_STRING);
6876 tk = &state->token[0];
6877 str = tk->val.str + 1;
6878 str_len = tk->str_len - 2;
6880 error(state, 0, "negative string constant length");
6882 end = str + str_len;
6884 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6885 memcpy(buf, ptr, type->elements);
6886 ptr = buf + type->elements;
6888 *ptr++ = char_value(state, &str, end);
6890 type->elements = ptr - buf;
6891 } while(peek(state) == TOK_LIT_STRING);
6893 type->elements += 1;
6894 def = triple(state, OP_BLOBCONST, type, 0, 0);
6900 static struct triple *integer_constant(struct compile_state *state)
6909 eat(state, TOK_LIT_INT);
6910 tk = &state->token[0];
6912 decimal = (tk->val.str[0] != '0');
6913 val = strtoul(tk->val.str, &end, 0);
6914 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6915 error(state, 0, "Integer constant to large");
6918 if ((*end == 'u') || (*end == 'U')) {
6922 if ((*end == 'l') || (*end == 'L')) {
6926 if ((*end == 'u') || (*end == 'U')) {
6931 error(state, 0, "Junk at end of integer constant");
6938 if (!decimal && (val > LONG_MAX)) {
6944 if (val > UINT_MAX) {
6950 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6953 else if (!decimal && (val > LONG_MAX)) {
6956 else if (val > INT_MAX) {
6960 def = int_const(state, type, val);
6964 static struct triple *primary_expr(struct compile_state *state)
6972 struct hash_entry *ident;
6973 /* Here ident is either:
6976 * an enumeration constant.
6978 eat(state, TOK_IDENT);
6979 ident = state->token[0].ident;
6980 if (!ident->sym_ident) {
6981 error(state, 0, "%s undeclared", ident->name);
6983 def = ident->sym_ident->def;
6986 case TOK_ENUM_CONST:
6987 /* Here ident is an enumeration constant */
6988 eat(state, TOK_ENUM_CONST);
6993 eat(state, TOK_LPAREN);
6995 eat(state, TOK_RPAREN);
6998 def = integer_constant(state);
7001 eat(state, TOK_LIT_FLOAT);
7002 error(state, 0, "Floating point constants not supported");
7007 def = character_constant(state);
7009 case TOK_LIT_STRING:
7010 def = string_constant(state);
7014 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7019 static struct triple *postfix_expr(struct compile_state *state)
7023 def = primary_expr(state);
7025 struct triple *left;
7029 switch((tok = peek(state))) {
7031 eat(state, TOK_LBRACKET);
7032 def = mk_subscript_expr(state, left, expr(state));
7033 eat(state, TOK_RBRACKET);
7036 def = call_expr(state, def);
7040 struct hash_entry *field;
7041 eat(state, TOK_DOT);
7042 eat(state, TOK_IDENT);
7043 field = state->token[0].ident;
7044 def = deref_field(state, def, field);
7049 struct hash_entry *field;
7050 eat(state, TOK_ARROW);
7051 eat(state, TOK_IDENT);
7052 field = state->token[0].ident;
7053 def = mk_deref_expr(state, read_expr(state, def));
7054 def = deref_field(state, def, field);
7058 eat(state, TOK_PLUSPLUS);
7059 def = mk_post_inc_expr(state, left);
7061 case TOK_MINUSMINUS:
7062 eat(state, TOK_MINUSMINUS);
7063 def = mk_post_dec_expr(state, left);
7073 static struct triple *cast_expr(struct compile_state *state);
7075 static struct triple *unary_expr(struct compile_state *state)
7077 struct triple *def, *right;
7079 switch((tok = peek(state))) {
7081 eat(state, TOK_PLUSPLUS);
7082 def = mk_pre_inc_expr(state, unary_expr(state));
7084 case TOK_MINUSMINUS:
7085 eat(state, TOK_MINUSMINUS);
7086 def = mk_pre_dec_expr(state, unary_expr(state));
7089 eat(state, TOK_AND);
7090 def = mk_addr_expr(state, cast_expr(state), 0);
7093 eat(state, TOK_STAR);
7094 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7097 eat(state, TOK_PLUS);
7098 right = read_expr(state, cast_expr(state));
7099 arithmetic(state, right);
7100 def = integral_promotion(state, right);
7103 eat(state, TOK_MINUS);
7104 right = read_expr(state, cast_expr(state));
7105 arithmetic(state, right);
7106 def = integral_promotion(state, right);
7107 def = triple(state, OP_NEG, def->type, def, 0);
7110 eat(state, TOK_TILDE);
7111 right = read_expr(state, cast_expr(state));
7112 integral(state, right);
7113 def = integral_promotion(state, right);
7114 def = triple(state, OP_INVERT, def->type, def, 0);
7117 eat(state, TOK_BANG);
7118 right = read_expr(state, cast_expr(state));
7120 def = lfalse_expr(state, right);
7126 eat(state, TOK_SIZEOF);
7128 tok2 = peek2(state);
7129 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7130 eat(state, TOK_LPAREN);
7131 type = type_name(state);
7132 eat(state, TOK_RPAREN);
7135 struct triple *expr;
7136 expr = unary_expr(state);
7138 release_expr(state, expr);
7140 def = int_const(state, &ulong_type, size_of(state, type));
7147 eat(state, TOK_ALIGNOF);
7149 tok2 = peek2(state);
7150 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7151 eat(state, TOK_LPAREN);
7152 type = type_name(state);
7153 eat(state, TOK_RPAREN);
7156 struct triple *expr;
7157 expr = unary_expr(state);
7159 release_expr(state, expr);
7161 def = int_const(state, &ulong_type, align_of(state, type));
7165 def = postfix_expr(state);
7171 static struct triple *cast_expr(struct compile_state *state)
7176 tok2 = peek2(state);
7177 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7179 eat(state, TOK_LPAREN);
7180 type = type_name(state);
7181 eat(state, TOK_RPAREN);
7182 def = read_expr(state, cast_expr(state));
7183 def = triple(state, OP_COPY, type, def, 0);
7186 def = unary_expr(state);
7191 static struct triple *mult_expr(struct compile_state *state)
7195 def = cast_expr(state);
7197 struct triple *left, *right;
7198 struct type *result_type;
7201 switch(tok = (peek(state))) {
7205 left = read_expr(state, def);
7206 arithmetic(state, left);
7210 right = read_expr(state, cast_expr(state));
7211 arithmetic(state, right);
7213 result_type = arithmetic_result(state, left, right);
7214 sign = is_signed(result_type);
7217 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7218 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7219 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7221 def = triple(state, op, result_type, left, right);
7231 static struct triple *add_expr(struct compile_state *state)
7235 def = mult_expr(state);
7238 switch( peek(state)) {
7240 eat(state, TOK_PLUS);
7241 def = mk_add_expr(state, def, mult_expr(state));
7244 eat(state, TOK_MINUS);
7245 def = mk_sub_expr(state, def, mult_expr(state));
7255 static struct triple *shift_expr(struct compile_state *state)
7259 def = add_expr(state);
7261 struct triple *left, *right;
7264 switch((tok = peek(state))) {
7267 left = read_expr(state, def);
7268 integral(state, left);
7269 left = integral_promotion(state, left);
7273 right = read_expr(state, add_expr(state));
7274 integral(state, right);
7275 right = integral_promotion(state, right);
7277 op = (tok == TOK_SL)? OP_SL :
7278 is_signed(left->type)? OP_SSR: OP_USR;
7280 def = triple(state, op, left->type, left, right);
7290 static struct triple *relational_expr(struct compile_state *state)
7292 #warning "Extend relational exprs to work on more than arithmetic types"
7295 def = shift_expr(state);
7297 struct triple *left, *right;
7298 struct type *arg_type;
7301 switch((tok = peek(state))) {
7306 left = read_expr(state, def);
7307 arithmetic(state, left);
7311 right = read_expr(state, shift_expr(state));
7312 arithmetic(state, right);
7314 arg_type = arithmetic_result(state, left, right);
7315 sign = is_signed(arg_type);
7318 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7319 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7320 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7321 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7323 def = triple(state, op, &int_type, left, right);
7333 static struct triple *equality_expr(struct compile_state *state)
7335 #warning "Extend equality exprs to work on more than arithmetic types"
7338 def = relational_expr(state);
7340 struct triple *left, *right;
7343 switch((tok = peek(state))) {
7346 left = read_expr(state, def);
7347 arithmetic(state, left);
7349 right = read_expr(state, relational_expr(state));
7350 arithmetic(state, right);
7351 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7352 def = triple(state, op, &int_type, left, right);
7362 static struct triple *and_expr(struct compile_state *state)
7365 def = equality_expr(state);
7366 while(peek(state) == TOK_AND) {
7367 struct triple *left, *right;
7368 struct type *result_type;
7369 left = read_expr(state, def);
7370 integral(state, left);
7371 eat(state, TOK_AND);
7372 right = read_expr(state, equality_expr(state));
7373 integral(state, right);
7374 result_type = arithmetic_result(state, left, right);
7375 def = triple(state, OP_AND, result_type, left, right);
7380 static struct triple *xor_expr(struct compile_state *state)
7383 def = and_expr(state);
7384 while(peek(state) == TOK_XOR) {
7385 struct triple *left, *right;
7386 struct type *result_type;
7387 left = read_expr(state, def);
7388 integral(state, left);
7389 eat(state, TOK_XOR);
7390 right = read_expr(state, and_expr(state));
7391 integral(state, right);
7392 result_type = arithmetic_result(state, left, right);
7393 def = triple(state, OP_XOR, result_type, left, right);
7398 static struct triple *or_expr(struct compile_state *state)
7401 def = xor_expr(state);
7402 while(peek(state) == TOK_OR) {
7403 struct triple *left, *right;
7404 struct type *result_type;
7405 left = read_expr(state, def);
7406 integral(state, left);
7408 right = read_expr(state, xor_expr(state));
7409 integral(state, right);
7410 result_type = arithmetic_result(state, left, right);
7411 def = triple(state, OP_OR, result_type, left, right);
7416 static struct triple *land_expr(struct compile_state *state)
7419 def = or_expr(state);
7420 while(peek(state) == TOK_LOGAND) {
7421 struct triple *left, *right;
7422 left = read_expr(state, def);
7424 eat(state, TOK_LOGAND);
7425 right = read_expr(state, or_expr(state));
7428 def = triple(state, OP_LAND, &int_type,
7429 ltrue_expr(state, left),
7430 ltrue_expr(state, right));
7435 static struct triple *lor_expr(struct compile_state *state)
7438 def = land_expr(state);
7439 while(peek(state) == TOK_LOGOR) {
7440 struct triple *left, *right;
7441 left = read_expr(state, def);
7443 eat(state, TOK_LOGOR);
7444 right = read_expr(state, land_expr(state));
7447 def = triple(state, OP_LOR, &int_type,
7448 ltrue_expr(state, left),
7449 ltrue_expr(state, right));
7454 static struct triple *conditional_expr(struct compile_state *state)
7457 def = lor_expr(state);
7458 if (peek(state) == TOK_QUEST) {
7459 struct triple *test, *left, *right;
7461 test = ltrue_expr(state, read_expr(state, def));
7462 eat(state, TOK_QUEST);
7463 left = read_expr(state, expr(state));
7464 eat(state, TOK_COLON);
7465 right = read_expr(state, conditional_expr(state));
7467 def = cond_expr(state, test, left, right);
7472 static struct triple *eval_const_expr(
7473 struct compile_state *state, struct triple *expr)
7476 if (is_const(expr)) {
7480 /* If we don't start out as a constant simplify into one */
7481 struct triple *head, *ptr;
7482 head = label(state); /* dummy initial triple */
7483 flatten(state, head, expr);
7484 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7485 simplify(state, ptr);
7487 /* Remove the constant value the tail of the list */
7489 def->prev->next = def->next;
7490 def->next->prev = def->prev;
7491 def->next = def->prev = def;
7492 if (!is_const(def)) {
7493 error(state, 0, "Not a constant expression");
7495 /* Free the intermediate expressions */
7496 while(head->next != head) {
7497 release_triple(state, head->next);
7499 free_triple(state, head);
7504 static struct triple *constant_expr(struct compile_state *state)
7506 return eval_const_expr(state, conditional_expr(state));
7509 static struct triple *assignment_expr(struct compile_state *state)
7511 struct triple *def, *left, *right;
7513 /* The C grammer in K&R shows assignment expressions
7514 * only taking unary expressions as input on their
7515 * left hand side. But specifies the precedence of
7516 * assignemnt as the lowest operator except for comma.
7518 * Allowing conditional expressions on the left hand side
7519 * of an assignement results in a grammar that accepts
7520 * a larger set of statements than standard C. As long
7521 * as the subset of the grammar that is standard C behaves
7522 * correctly this should cause no problems.
7524 * For the extra token strings accepted by the grammar
7525 * none of them should produce a valid lvalue, so they
7526 * should not produce functioning programs.
7528 * GCC has this bug as well, so surprises should be minimal.
7530 def = conditional_expr(state);
7532 switch((tok = peek(state))) {
7534 lvalue(state, left);
7536 def = write_expr(state, left,
7537 read_expr(state, assignment_expr(state)));
7542 lvalue(state, left);
7543 arithmetic(state, left);
7545 right = read_expr(state, assignment_expr(state));
7546 arithmetic(state, right);
7548 sign = is_signed(left->type);
7551 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7552 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7553 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7555 def = write_expr(state, left,
7556 triple(state, op, left->type,
7557 read_expr(state, left), right));
7560 lvalue(state, left);
7561 eat(state, TOK_PLUSEQ);
7562 def = write_expr(state, left,
7563 mk_add_expr(state, left, assignment_expr(state)));
7566 lvalue(state, left);
7567 eat(state, TOK_MINUSEQ);
7568 def = write_expr(state, left,
7569 mk_sub_expr(state, left, assignment_expr(state)));
7576 lvalue(state, left);
7577 integral(state, left);
7579 right = read_expr(state, assignment_expr(state));
7580 integral(state, right);
7581 right = integral_promotion(state, right);
7582 sign = is_signed(left->type);
7585 case TOK_SLEQ: op = OP_SL; break;
7586 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7587 case TOK_ANDEQ: op = OP_AND; break;
7588 case TOK_XOREQ: op = OP_XOR; break;
7589 case TOK_OREQ: op = OP_OR; break;
7591 def = write_expr(state, left,
7592 triple(state, op, left->type,
7593 read_expr(state, left), right));
7599 static struct triple *expr(struct compile_state *state)
7602 def = assignment_expr(state);
7603 while(peek(state) == TOK_COMMA) {
7604 struct triple *left, *right;
7606 eat(state, TOK_COMMA);
7607 right = assignment_expr(state);
7608 def = triple(state, OP_COMMA, right->type, left, right);
7613 static void expr_statement(struct compile_state *state, struct triple *first)
7615 if (peek(state) != TOK_SEMI) {
7616 flatten(state, first, expr(state));
7618 eat(state, TOK_SEMI);
7621 static void if_statement(struct compile_state *state, struct triple *first)
7623 struct triple *test, *jmp1, *jmp2, *middle, *end;
7625 jmp1 = jmp2 = middle = 0;
7627 eat(state, TOK_LPAREN);
7630 /* Cleanup and invert the test */
7631 test = lfalse_expr(state, read_expr(state, test));
7632 eat(state, TOK_RPAREN);
7633 /* Generate the needed pieces */
7634 middle = label(state);
7635 jmp1 = branch(state, middle, test);
7636 /* Thread the pieces together */
7637 flatten(state, first, test);
7638 flatten(state, first, jmp1);
7639 flatten(state, first, label(state));
7640 statement(state, first);
7641 if (peek(state) == TOK_ELSE) {
7642 eat(state, TOK_ELSE);
7643 /* Generate the rest of the pieces */
7645 jmp2 = branch(state, end, 0);
7646 /* Thread them together */
7647 flatten(state, first, jmp2);
7648 flatten(state, first, middle);
7649 statement(state, first);
7650 flatten(state, first, end);
7653 flatten(state, first, middle);
7657 static void for_statement(struct compile_state *state, struct triple *first)
7659 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7660 struct triple *label1, *label2, *label3;
7661 struct hash_entry *ident;
7663 eat(state, TOK_FOR);
7664 eat(state, TOK_LPAREN);
7665 head = test = tail = jmp1 = jmp2 = 0;
7666 if (peek(state) != TOK_SEMI) {
7669 eat(state, TOK_SEMI);
7670 if (peek(state) != TOK_SEMI) {
7673 test = ltrue_expr(state, read_expr(state, test));
7675 eat(state, TOK_SEMI);
7676 if (peek(state) != TOK_RPAREN) {
7679 eat(state, TOK_RPAREN);
7680 /* Generate the needed pieces */
7681 label1 = label(state);
7682 label2 = label(state);
7683 label3 = label(state);
7685 jmp1 = branch(state, label3, 0);
7686 jmp2 = branch(state, label1, test);
7689 jmp2 = branch(state, label1, 0);
7692 /* Remember where break and continue go */
7694 ident = state->i_break;
7695 symbol(state, ident, &ident->sym_ident, end, end->type);
7696 ident = state->i_continue;
7697 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7698 /* Now include the body */
7699 flatten(state, first, head);
7700 flatten(state, first, jmp1);
7701 flatten(state, first, label1);
7702 statement(state, first);
7703 flatten(state, first, label2);
7704 flatten(state, first, tail);
7705 flatten(state, first, label3);
7706 flatten(state, first, test);
7707 flatten(state, first, jmp2);
7708 flatten(state, first, end);
7709 /* Cleanup the break/continue scope */
7713 static void while_statement(struct compile_state *state, struct triple *first)
7715 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7716 struct hash_entry *ident;
7717 eat(state, TOK_WHILE);
7718 eat(state, TOK_LPAREN);
7721 test = ltrue_expr(state, read_expr(state, test));
7722 eat(state, TOK_RPAREN);
7723 /* Generate the needed pieces */
7724 label1 = label(state);
7725 label2 = label(state);
7726 jmp1 = branch(state, label2, 0);
7727 jmp2 = branch(state, label1, test);
7729 /* Remember where break and continue go */
7731 ident = state->i_break;
7732 symbol(state, ident, &ident->sym_ident, end, end->type);
7733 ident = state->i_continue;
7734 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7735 /* Thread them together */
7736 flatten(state, first, jmp1);
7737 flatten(state, first, label1);
7738 statement(state, first);
7739 flatten(state, first, label2);
7740 flatten(state, first, test);
7741 flatten(state, first, jmp2);
7742 flatten(state, first, end);
7743 /* Cleanup the break/continue scope */
7747 static void do_statement(struct compile_state *state, struct triple *first)
7749 struct triple *label1, *label2, *test, *end;
7750 struct hash_entry *ident;
7752 /* Generate the needed pieces */
7753 label1 = label(state);
7754 label2 = label(state);
7756 /* Remember where break and continue go */
7758 ident = state->i_break;
7759 symbol(state, ident, &ident->sym_ident, end, end->type);
7760 ident = state->i_continue;
7761 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7762 /* Now include the body */
7763 flatten(state, first, label1);
7764 statement(state, first);
7765 /* Cleanup the break/continue scope */
7767 /* Eat the rest of the loop */
7768 eat(state, TOK_WHILE);
7769 eat(state, TOK_LPAREN);
7770 test = read_expr(state, expr(state));
7772 eat(state, TOK_RPAREN);
7773 eat(state, TOK_SEMI);
7774 /* Thread the pieces together */
7775 test = ltrue_expr(state, test);
7776 flatten(state, first, label2);
7777 flatten(state, first, test);
7778 flatten(state, first, branch(state, label1, test));
7779 flatten(state, first, end);
7783 static void return_statement(struct compile_state *state, struct triple *first)
7785 struct triple *jmp, *mv, *dest, *var, *val;
7787 eat(state, TOK_RETURN);
7789 #warning "FIXME implement a more general excess branch elimination"
7791 /* If we have a return value do some more work */
7792 if (peek(state) != TOK_SEMI) {
7793 val = read_expr(state, expr(state));
7795 eat(state, TOK_SEMI);
7797 /* See if this last statement in a function */
7798 last = ((peek(state) == TOK_RBRACE) &&
7799 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7801 /* Find the return variable */
7802 var = MISC(state->main_function, 0);
7803 /* Find the return destination */
7804 dest = RHS(state->main_function, 0)->prev;
7806 /* If needed generate a jump instruction */
7808 jmp = branch(state, dest, 0);
7810 /* If needed generate an assignment instruction */
7812 mv = write_expr(state, var, val);
7814 /* Now put the code together */
7816 flatten(state, first, mv);
7817 flatten(state, first, jmp);
7820 flatten(state, first, jmp);
7824 static void break_statement(struct compile_state *state, struct triple *first)
7826 struct triple *dest;
7827 eat(state, TOK_BREAK);
7828 eat(state, TOK_SEMI);
7829 if (!state->i_break->sym_ident) {
7830 error(state, 0, "break statement not within loop or switch");
7832 dest = state->i_break->sym_ident->def;
7833 flatten(state, first, branch(state, dest, 0));
7836 static void continue_statement(struct compile_state *state, struct triple *first)
7838 struct triple *dest;
7839 eat(state, TOK_CONTINUE);
7840 eat(state, TOK_SEMI);
7841 if (!state->i_continue->sym_ident) {
7842 error(state, 0, "continue statement outside of a loop");
7844 dest = state->i_continue->sym_ident->def;
7845 flatten(state, first, branch(state, dest, 0));
7848 static void goto_statement(struct compile_state *state, struct triple *first)
7850 struct hash_entry *ident;
7851 eat(state, TOK_GOTO);
7852 eat(state, TOK_IDENT);
7853 ident = state->token[0].ident;
7854 if (!ident->sym_label) {
7855 /* If this is a forward branch allocate the label now,
7856 * it will be flattend in the appropriate location later.
7860 label_symbol(state, ident, ins);
7862 eat(state, TOK_SEMI);
7864 flatten(state, first, branch(state, ident->sym_label->def, 0));
7867 static void labeled_statement(struct compile_state *state, struct triple *first)
7870 struct hash_entry *ident;
7871 eat(state, TOK_IDENT);
7873 ident = state->token[0].ident;
7874 if (ident->sym_label && ident->sym_label->def) {
7875 ins = ident->sym_label->def;
7876 put_occurance(ins->occurance);
7877 ins->occurance = new_occurance(state);
7881 label_symbol(state, ident, ins);
7883 if (ins->id & TRIPLE_FLAG_FLATTENED) {
7884 error(state, 0, "label %s already defined", ident->name);
7886 flatten(state, first, ins);
7888 eat(state, TOK_COLON);
7889 statement(state, first);
7892 static void switch_statement(struct compile_state *state, struct triple *first)
7895 eat(state, TOK_SWITCH);
7896 eat(state, TOK_LPAREN);
7898 eat(state, TOK_RPAREN);
7899 statement(state, first);
7900 error(state, 0, "switch statements are not implemented");
7904 static void case_statement(struct compile_state *state, struct triple *first)
7907 eat(state, TOK_CASE);
7908 constant_expr(state);
7909 eat(state, TOK_COLON);
7910 statement(state, first);
7911 error(state, 0, "case statements are not implemented");
7915 static void default_statement(struct compile_state *state, struct triple *first)
7918 eat(state, TOK_DEFAULT);
7919 eat(state, TOK_COLON);
7920 statement(state, first);
7921 error(state, 0, "default statements are not implemented");
7925 static void asm_statement(struct compile_state *state, struct triple *first)
7927 struct asm_info *info;
7929 struct triple *constraint;
7930 struct triple *expr;
7931 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7932 struct triple *def, *asm_str;
7933 int out, in, clobbers, more, colons, i;
7935 eat(state, TOK_ASM);
7936 /* For now ignore the qualifiers */
7937 switch(peek(state)) {
7939 eat(state, TOK_CONST);
7942 eat(state, TOK_VOLATILE);
7945 eat(state, TOK_LPAREN);
7946 asm_str = string_constant(state);
7949 out = in = clobbers = 0;
7951 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7952 eat(state, TOK_COLON);
7954 more = (peek(state) == TOK_LIT_STRING);
7957 struct triple *constraint;
7960 if (out > MAX_LHS) {
7961 error(state, 0, "Maximum output count exceeded.");
7963 constraint = string_constant(state);
7964 str = constraint->u.blob;
7965 if (str[0] != '=') {
7966 error(state, 0, "Output constraint does not start with =");
7968 constraint->u.blob = str + 1;
7969 eat(state, TOK_LPAREN);
7970 var = conditional_expr(state);
7971 eat(state, TOK_RPAREN);
7974 out_param[out].constraint = constraint;
7975 out_param[out].expr = var;
7976 if (peek(state) == TOK_COMMA) {
7977 eat(state, TOK_COMMA);
7984 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7985 eat(state, TOK_COLON);
7987 more = (peek(state) == TOK_LIT_STRING);
7990 struct triple *constraint;
7994 error(state, 0, "Maximum input count exceeded.");
7996 constraint = string_constant(state);
7997 str = constraint->u.blob;
7998 if (digitp(str[0] && str[1] == '\0')) {
8000 val = digval(str[0]);
8001 if ((val < 0) || (val >= out)) {
8002 error(state, 0, "Invalid input constraint %d", val);
8005 eat(state, TOK_LPAREN);
8006 val = conditional_expr(state);
8007 eat(state, TOK_RPAREN);
8009 in_param[in].constraint = constraint;
8010 in_param[in].expr = val;
8011 if (peek(state) == TOK_COMMA) {
8012 eat(state, TOK_COMMA);
8020 if ((colons == 2) && (peek(state) == TOK_COLON)) {
8021 eat(state, TOK_COLON);
8023 more = (peek(state) == TOK_LIT_STRING);
8025 struct triple *clobber;
8027 if ((clobbers + out) > MAX_LHS) {
8028 error(state, 0, "Maximum clobber limit exceeded.");
8030 clobber = string_constant(state);
8031 eat(state, TOK_RPAREN);
8033 clob_param[clobbers].constraint = clobber;
8034 if (peek(state) == TOK_COMMA) {
8035 eat(state, TOK_COMMA);
8041 eat(state, TOK_RPAREN);
8042 eat(state, TOK_SEMI);
8045 info = xcmalloc(sizeof(*info), "asm_info");
8046 info->str = asm_str->u.blob;
8047 free_triple(state, asm_str);
8049 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8050 def->u.ainfo = info;
8052 /* Find the register constraints */
8053 for(i = 0; i < out; i++) {
8054 struct triple *constraint;
8055 constraint = out_param[i].constraint;
8056 info->tmpl.lhs[i] = arch_reg_constraint(state,
8057 out_param[i].expr->type, constraint->u.blob);
8058 free_triple(state, constraint);
8060 for(; i - out < clobbers; i++) {
8061 struct triple *constraint;
8062 constraint = clob_param[i - out].constraint;
8063 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8064 free_triple(state, constraint);
8066 for(i = 0; i < in; i++) {
8067 struct triple *constraint;
8069 constraint = in_param[i].constraint;
8070 str = constraint->u.blob;
8071 if (digitp(str[0]) && str[1] == '\0') {
8072 struct reg_info cinfo;
8074 val = digval(str[0]);
8075 cinfo.reg = info->tmpl.lhs[val].reg;
8076 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8077 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8078 if (cinfo.reg == REG_UNSET) {
8079 cinfo.reg = REG_VIRT0 + val;
8081 if (cinfo.regcm == 0) {
8082 error(state, 0, "No registers for %d", val);
8084 info->tmpl.lhs[val] = cinfo;
8085 info->tmpl.rhs[i] = cinfo;
8088 info->tmpl.rhs[i] = arch_reg_constraint(state,
8089 in_param[i].expr->type, str);
8091 free_triple(state, constraint);
8094 /* Now build the helper expressions */
8095 for(i = 0; i < in; i++) {
8096 RHS(def, i) = read_expr(state,in_param[i].expr);
8098 flatten(state, first, def);
8099 for(i = 0; i < out; i++) {
8100 struct triple *piece;
8101 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8103 LHS(def, i) = piece;
8104 flatten(state, first,
8105 write_expr(state, out_param[i].expr, piece));
8107 for(; i - out < clobbers; i++) {
8108 struct triple *piece;
8109 piece = triple(state, OP_PIECE, &void_type, def, 0);
8111 LHS(def, i) = piece;
8112 flatten(state, first, piece);
8117 static int isdecl(int tok)
8140 case TOK_TYPE_NAME: /* typedef name */
8147 static void compound_statement(struct compile_state *state, struct triple *first)
8149 eat(state, TOK_LBRACE);
8152 /* statement-list opt */
8153 while (peek(state) != TOK_RBRACE) {
8154 statement(state, first);
8157 eat(state, TOK_RBRACE);
8160 static void statement(struct compile_state *state, struct triple *first)
8164 if (tok == TOK_LBRACE) {
8165 compound_statement(state, first);
8167 else if (tok == TOK_IF) {
8168 if_statement(state, first);
8170 else if (tok == TOK_FOR) {
8171 for_statement(state, first);
8173 else if (tok == TOK_WHILE) {
8174 while_statement(state, first);
8176 else if (tok == TOK_DO) {
8177 do_statement(state, first);
8179 else if (tok == TOK_RETURN) {
8180 return_statement(state, first);
8182 else if (tok == TOK_BREAK) {
8183 break_statement(state, first);
8185 else if (tok == TOK_CONTINUE) {
8186 continue_statement(state, first);
8188 else if (tok == TOK_GOTO) {
8189 goto_statement(state, first);
8191 else if (tok == TOK_SWITCH) {
8192 switch_statement(state, first);
8194 else if (tok == TOK_ASM) {
8195 asm_statement(state, first);
8197 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8198 labeled_statement(state, first);
8200 else if (tok == TOK_CASE) {
8201 case_statement(state, first);
8203 else if (tok == TOK_DEFAULT) {
8204 default_statement(state, first);
8206 else if (isdecl(tok)) {
8207 /* This handles C99 intermixing of statements and decls */
8211 expr_statement(state, first);
8215 static struct type *param_decl(struct compile_state *state)
8218 struct hash_entry *ident;
8219 /* Cheat so the declarator will know we are not global */
8222 type = decl_specifiers(state);
8223 type = declarator(state, type, &ident, 0);
8224 type->field_ident = ident;
8229 static struct type *param_type_list(struct compile_state *state, struct type *type)
8231 struct type *ftype, **next;
8232 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8233 next = &ftype->right;
8234 while(peek(state) == TOK_COMMA) {
8235 eat(state, TOK_COMMA);
8236 if (peek(state) == TOK_DOTS) {
8237 eat(state, TOK_DOTS);
8238 error(state, 0, "variadic functions not supported");
8241 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8242 next = &((*next)->right);
8249 static struct type *type_name(struct compile_state *state)
8252 type = specifier_qualifier_list(state);
8253 /* abstract-declarator (may consume no tokens) */
8254 type = declarator(state, type, 0, 0);
8258 static struct type *direct_declarator(
8259 struct compile_state *state, struct type *type,
8260 struct hash_entry **ident, int need_ident)
8265 arrays_complete(state, type);
8266 switch(peek(state)) {
8268 eat(state, TOK_IDENT);
8270 error(state, 0, "Unexpected identifier found");
8272 /* The name of what we are declaring */
8273 *ident = state->token[0].ident;
8276 eat(state, TOK_LPAREN);
8277 outer = declarator(state, type, ident, need_ident);
8278 eat(state, TOK_RPAREN);
8282 error(state, 0, "Identifier expected");
8288 arrays_complete(state, type);
8289 switch(peek(state)) {
8291 eat(state, TOK_LPAREN);
8292 type = param_type_list(state, type);
8293 eat(state, TOK_RPAREN);
8297 unsigned int qualifiers;
8298 struct triple *value;
8300 eat(state, TOK_LBRACKET);
8301 if (peek(state) != TOK_RBRACKET) {
8302 value = constant_expr(state);
8303 integral(state, value);
8305 eat(state, TOK_RBRACKET);
8307 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8308 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8310 type->elements = value->u.cval;
8311 free_triple(state, value);
8313 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8325 arrays_complete(state, type);
8327 for(inner = outer; inner->left; inner = inner->left)
8335 static struct type *declarator(
8336 struct compile_state *state, struct type *type,
8337 struct hash_entry **ident, int need_ident)
8339 while(peek(state) == TOK_STAR) {
8340 eat(state, TOK_STAR);
8341 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8343 type = direct_declarator(state, type, ident, need_ident);
8348 static struct type *typedef_name(
8349 struct compile_state *state, unsigned int specifiers)
8351 struct hash_entry *ident;
8353 eat(state, TOK_TYPE_NAME);
8354 ident = state->token[0].ident;
8355 type = ident->sym_ident->type;
8356 specifiers |= type->type & QUAL_MASK;
8357 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8358 (type->type & (STOR_MASK | QUAL_MASK))) {
8359 type = clone_type(specifiers, type);
8364 static struct type *enum_specifier(
8365 struct compile_state *state, unsigned int specifiers)
8371 eat(state, TOK_ENUM);
8373 if (tok == TOK_IDENT) {
8374 eat(state, TOK_IDENT);
8376 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8377 eat(state, TOK_LBRACE);
8379 eat(state, TOK_IDENT);
8380 if (peek(state) == TOK_EQ) {
8382 constant_expr(state);
8384 if (peek(state) == TOK_COMMA) {
8385 eat(state, TOK_COMMA);
8387 } while(peek(state) != TOK_RBRACE);
8388 eat(state, TOK_RBRACE);
8395 static struct type *struct_declarator(
8396 struct compile_state *state, struct type *type, struct hash_entry **ident)
8399 #warning "struct_declarator is complicated because of bitfields, kill them?"
8401 if (tok != TOK_COLON) {
8402 type = declarator(state, type, ident, 1);
8404 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8405 eat(state, TOK_COLON);
8406 constant_expr(state);
8413 static struct type *struct_or_union_specifier(
8414 struct compile_state *state, unsigned int spec)
8416 struct type *struct_type;
8417 struct hash_entry *ident;
8418 unsigned int type_join;
8422 switch(peek(state)) {
8424 eat(state, TOK_STRUCT);
8425 type_join = TYPE_PRODUCT;
8428 eat(state, TOK_UNION);
8429 type_join = TYPE_OVERLAP;
8430 error(state, 0, "unions not yet supported\n");
8433 eat(state, TOK_STRUCT);
8434 type_join = TYPE_PRODUCT;
8438 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8440 ident = state->token[0].ident;
8442 if (!ident || (peek(state) == TOK_LBRACE)) {
8445 eat(state, TOK_LBRACE);
8447 struct type *base_type;
8450 base_type = specifier_qualifier_list(state);
8451 next = &struct_type;
8454 struct hash_entry *fident;
8456 type = declarator(state, base_type, &fident, 1);
8458 if (peek(state) == TOK_COMMA) {
8460 eat(state, TOK_COMMA);
8462 type = clone_type(0, type);
8463 type->field_ident = fident;
8465 *next = new_type(type_join, *next, type);
8466 next = &((*next)->right);
8471 eat(state, TOK_SEMI);
8472 } while(peek(state) != TOK_RBRACE);
8473 eat(state, TOK_RBRACE);
8474 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8475 struct_type->type_ident = ident;
8476 struct_type->elements = elements;
8477 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8479 if (ident && ident->sym_struct) {
8480 struct_type = clone_type(spec, ident->sym_struct->type);
8482 else if (ident && !ident->sym_struct) {
8483 error(state, 0, "struct %s undeclared", ident->name);
8488 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8490 unsigned int specifiers;
8491 switch(peek(state)) {
8493 eat(state, TOK_AUTO);
8494 specifiers = STOR_AUTO;
8497 eat(state, TOK_REGISTER);
8498 specifiers = STOR_REGISTER;
8501 eat(state, TOK_STATIC);
8502 specifiers = STOR_STATIC;
8505 eat(state, TOK_EXTERN);
8506 specifiers = STOR_EXTERN;
8509 eat(state, TOK_TYPEDEF);
8510 specifiers = STOR_TYPEDEF;
8513 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8514 specifiers = STOR_STATIC;
8517 specifiers = STOR_AUTO;
8523 static unsigned int function_specifier_opt(struct compile_state *state)
8525 /* Ignore the inline keyword */
8526 unsigned int specifiers;
8528 switch(peek(state)) {
8530 eat(state, TOK_INLINE);
8531 specifiers = STOR_INLINE;
8536 static unsigned int type_qualifiers(struct compile_state *state)
8538 unsigned int specifiers;
8541 specifiers = QUAL_NONE;
8543 switch(peek(state)) {
8545 eat(state, TOK_CONST);
8546 specifiers = QUAL_CONST;
8549 eat(state, TOK_VOLATILE);
8550 specifiers = QUAL_VOLATILE;
8553 eat(state, TOK_RESTRICT);
8554 specifiers = QUAL_RESTRICT;
8564 static struct type *type_specifier(
8565 struct compile_state *state, unsigned int spec)
8569 switch(peek(state)) {
8571 eat(state, TOK_VOID);
8572 type = new_type(TYPE_VOID | spec, 0, 0);
8575 eat(state, TOK_CHAR);
8576 type = new_type(TYPE_CHAR | spec, 0, 0);
8579 eat(state, TOK_SHORT);
8580 if (peek(state) == TOK_INT) {
8581 eat(state, TOK_INT);
8583 type = new_type(TYPE_SHORT | spec, 0, 0);
8586 eat(state, TOK_INT);
8587 type = new_type(TYPE_INT | spec, 0, 0);
8590 eat(state, TOK_LONG);
8591 switch(peek(state)) {
8593 eat(state, TOK_LONG);
8594 error(state, 0, "long long not supported");
8597 eat(state, TOK_DOUBLE);
8598 error(state, 0, "long double not supported");
8601 eat(state, TOK_INT);
8602 type = new_type(TYPE_LONG | spec, 0, 0);
8605 type = new_type(TYPE_LONG | spec, 0, 0);
8610 eat(state, TOK_FLOAT);
8611 error(state, 0, "type float not supported");
8614 eat(state, TOK_DOUBLE);
8615 error(state, 0, "type double not supported");
8618 eat(state, TOK_SIGNED);
8619 switch(peek(state)) {
8621 eat(state, TOK_LONG);
8622 switch(peek(state)) {
8624 eat(state, TOK_LONG);
8625 error(state, 0, "type long long not supported");
8628 eat(state, TOK_INT);
8629 type = new_type(TYPE_LONG | spec, 0, 0);
8632 type = new_type(TYPE_LONG | spec, 0, 0);
8637 eat(state, TOK_INT);
8638 type = new_type(TYPE_INT | spec, 0, 0);
8641 eat(state, TOK_SHORT);
8642 type = new_type(TYPE_SHORT | spec, 0, 0);
8645 eat(state, TOK_CHAR);
8646 type = new_type(TYPE_CHAR | spec, 0, 0);
8649 type = new_type(TYPE_INT | spec, 0, 0);
8654 eat(state, TOK_UNSIGNED);
8655 switch(peek(state)) {
8657 eat(state, TOK_LONG);
8658 switch(peek(state)) {
8660 eat(state, TOK_LONG);
8661 error(state, 0, "unsigned long long not supported");
8664 eat(state, TOK_INT);
8665 type = new_type(TYPE_ULONG | spec, 0, 0);
8668 type = new_type(TYPE_ULONG | spec, 0, 0);
8673 eat(state, TOK_INT);
8674 type = new_type(TYPE_UINT | spec, 0, 0);
8677 eat(state, TOK_SHORT);
8678 type = new_type(TYPE_USHORT | spec, 0, 0);
8681 eat(state, TOK_CHAR);
8682 type = new_type(TYPE_UCHAR | spec, 0, 0);
8685 type = new_type(TYPE_UINT | spec, 0, 0);
8689 /* struct or union specifier */
8692 type = struct_or_union_specifier(state, spec);
8694 /* enum-spefifier */
8696 type = enum_specifier(state, spec);
8700 type = typedef_name(state, spec);
8703 error(state, 0, "bad type specifier %s",
8704 tokens[peek(state)]);
8710 static int istype(int tok)
8736 static struct type *specifier_qualifier_list(struct compile_state *state)
8739 unsigned int specifiers = 0;
8741 /* type qualifiers */
8742 specifiers |= type_qualifiers(state);
8744 /* type specifier */
8745 type = type_specifier(state, specifiers);
8750 static int isdecl_specifier(int tok)
8753 /* storage class specifier */
8759 /* type qualifier */
8763 /* type specifiers */
8773 /* struct or union specifier */
8776 /* enum-spefifier */
8780 /* function specifiers */
8788 static struct type *decl_specifiers(struct compile_state *state)
8791 unsigned int specifiers;
8792 /* I am overly restrictive in the arragement of specifiers supported.
8793 * C is overly flexible in this department it makes interpreting
8794 * the parse tree difficult.
8798 /* storage class specifier */
8799 specifiers |= storage_class_specifier_opt(state);
8801 /* function-specifier */
8802 specifiers |= function_specifier_opt(state);
8804 /* type qualifier */
8805 specifiers |= type_qualifiers(state);
8807 /* type specifier */
8808 type = type_specifier(state, specifiers);
8817 static struct field_info designator(struct compile_state *state, struct type *type)
8820 struct field_info info;
8824 switch(peek(state)) {
8827 struct triple *value;
8828 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8829 error(state, 0, "Array designator not in array initializer");
8831 eat(state, TOK_LBRACKET);
8832 value = constant_expr(state);
8833 eat(state, TOK_RBRACKET);
8835 info.type = type->left;
8836 info.offset = value->u.cval * size_of(state, info.type);
8841 struct hash_entry *field;
8842 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8843 error(state, 0, "Struct designator not in struct initializer");
8845 eat(state, TOK_DOT);
8846 eat(state, TOK_IDENT);
8847 field = state->token[0].ident;
8848 info.offset = field_offset(state, type, field);
8849 info.type = field_type(state, type, field);
8853 error(state, 0, "Invalid designator");
8856 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8861 static struct triple *initializer(
8862 struct compile_state *state, struct type *type)
8864 struct triple *result;
8865 if (peek(state) != TOK_LBRACE) {
8866 result = assignment_expr(state);
8871 struct field_info info;
8873 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8874 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8875 internal_error(state, 0, "unknown initializer type");
8878 info.type = type->left;
8879 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8880 info.type = next_field(state, type, 0);
8882 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8885 max_offset = size_of(state, type);
8887 buf = xcmalloc(max_offset, "initializer");
8888 eat(state, TOK_LBRACE);
8890 struct triple *value;
8891 struct type *value_type;
8897 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8898 info = designator(state, type);
8900 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8901 (info.offset >= max_offset)) {
8902 error(state, 0, "element beyond bounds");
8904 value_type = info.type;
8905 value = eval_const_expr(state, initializer(state, value_type));
8906 value_size = size_of(state, value_type);
8907 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8908 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8909 (max_offset <= info.offset)) {
8913 old_size = max_offset;
8914 max_offset = info.offset + value_size;
8915 buf = xmalloc(max_offset, "initializer");
8916 memcpy(buf, old_buf, old_size);
8919 dest = ((char *)buf) + info.offset;
8920 if (value->op == OP_BLOBCONST) {
8921 memcpy(dest, value->u.blob, value_size);
8923 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8924 *((uint8_t *)dest) = value->u.cval & 0xff;
8926 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8927 *((uint16_t *)dest) = value->u.cval & 0xffff;
8929 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8930 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8933 internal_error(state, 0, "unhandled constant initializer");
8935 free_triple(state, value);
8936 if (peek(state) == TOK_COMMA) {
8937 eat(state, TOK_COMMA);
8940 info.offset += value_size;
8941 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8942 info.type = next_field(state, type, info.type);
8943 info.offset = field_offset(state, type,
8944 info.type->field_ident);
8946 } while(comma && (peek(state) != TOK_RBRACE));
8947 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8948 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8949 type->elements = max_offset / size_of(state, type->left);
8951 eat(state, TOK_RBRACE);
8952 result = triple(state, OP_BLOBCONST, type, 0, 0);
8953 result->u.blob = buf;
8958 static void resolve_branches(struct compile_state *state)
8960 /* Make a second pass and finish anything outstanding
8961 * with respect to branches. The only outstanding item
8962 * is to see if there are goto to labels that have not
8963 * been defined and to error about them.
8966 for(i = 0; i < HASH_TABLE_SIZE; i++) {
8967 struct hash_entry *entry;
8968 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8970 if (!entry->sym_label) {
8973 ins = entry->sym_label->def;
8974 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8975 error(state, ins, "label `%s' used but not defined",
8982 static struct triple *function_definition(
8983 struct compile_state *state, struct type *type)
8985 struct triple *def, *tmp, *first, *end;
8986 struct hash_entry *ident;
8989 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8990 error(state, 0, "Invalid function header");
8993 /* Verify the function type */
8994 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8995 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8996 (type->right->field_ident == 0)) {
8997 error(state, 0, "Invalid function parameters");
8999 param = type->right;
9001 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9003 if (!param->left->field_ident) {
9004 error(state, 0, "No identifier for parameter %d\n", i);
9006 param = param->right;
9009 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9010 error(state, 0, "No identifier for paramter %d\n", i);
9013 /* Get a list of statements for this function. */
9014 def = triple(state, OP_LIST, type, 0, 0);
9016 /* Start a new scope for the passed parameters */
9019 /* Put a label at the very start of a function */
9020 first = label(state);
9021 RHS(def, 0) = first;
9023 /* Put a label at the very end of a function */
9025 flatten(state, first, end);
9027 /* Walk through the parameters and create symbol table entries
9030 param = type->right;
9031 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9032 ident = param->left->field_ident;
9033 tmp = variable(state, param->left);
9034 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9035 flatten(state, end, tmp);
9036 param = param->right;
9038 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9039 /* And don't forget the last parameter */
9040 ident = param->field_ident;
9041 tmp = variable(state, param);
9042 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9043 flatten(state, end, tmp);
9045 /* Add a variable for the return value */
9047 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9048 /* Remove all type qualifiers from the return type */
9049 tmp = variable(state, clone_type(0, type->left));
9050 flatten(state, end, tmp);
9051 /* Remember where the return value is */
9055 /* Remember which function I am compiling.
9056 * Also assume the last defined function is the main function.
9058 state->main_function = def;
9060 /* Now get the actual function definition */
9061 compound_statement(state, end);
9063 /* Finish anything unfinished with branches */
9064 resolve_branches(state);
9066 /* Remove the parameter scope */
9070 fprintf(stdout, "\n");
9071 loc(stdout, state, 0);
9072 fprintf(stdout, "\n__________ function_definition _________\n");
9073 print_triple(state, def);
9074 fprintf(stdout, "__________ function_definition _________ done\n\n");
9080 static struct triple *do_decl(struct compile_state *state,
9081 struct type *type, struct hash_entry *ident)
9085 /* Clean up the storage types used */
9086 switch (type->type & STOR_MASK) {
9089 /* These are the good types I am aiming for */
9092 type->type &= ~STOR_MASK;
9093 type->type |= STOR_AUTO;
9096 type->type &= ~STOR_MASK;
9097 type->type |= STOR_STATIC;
9101 error(state, 0, "typedef without name");
9103 symbol(state, ident, &ident->sym_ident, 0, type);
9104 ident->tok = TOK_TYPE_NAME;
9108 internal_error(state, 0, "Undefined storage class");
9111 ((type->type & STOR_MASK) == STOR_STATIC) &&
9112 ((type->type & QUAL_CONST) == 0)) {
9113 error(state, 0, "non const static variables not supported");
9116 def = variable(state, type);
9117 symbol(state, ident, &ident->sym_ident, def, type);
9122 static void decl(struct compile_state *state, struct triple *first)
9124 struct type *base_type, *type;
9125 struct hash_entry *ident;
9128 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9129 base_type = decl_specifiers(state);
9131 type = declarator(state, base_type, &ident, 0);
9132 if (global && ident && (peek(state) == TOK_LBRACE)) {
9134 state->function = ident->name;
9135 def = function_definition(state, type);
9136 symbol(state, ident, &ident->sym_ident, def, type);
9137 state->function = 0;
9141 flatten(state, first, do_decl(state, type, ident));
9142 /* type or variable definition */
9145 if (peek(state) == TOK_EQ) {
9147 error(state, 0, "cannot assign to a type");
9150 flatten(state, first,
9152 ident->sym_ident->def,
9153 initializer(state, type)));
9155 arrays_complete(state, type);
9156 if (peek(state) == TOK_COMMA) {
9157 eat(state, TOK_COMMA);
9159 type = declarator(state, base_type, &ident, 0);
9160 flatten(state, first, do_decl(state, type, ident));
9164 eat(state, TOK_SEMI);
9168 static void decls(struct compile_state *state)
9170 struct triple *list;
9172 list = label(state);
9175 if (tok == TOK_EOF) {
9178 if (tok == TOK_SPACE) {
9179 eat(state, TOK_SPACE);
9182 if (list->next != list) {
9183 error(state, 0, "global variables not supported");
9189 * Data structurs for optimation.
9192 static void do_use_block(
9193 struct block *used, struct block_set **head, struct block *user,
9196 struct block_set **ptr, *new;
9203 if ((*ptr)->member == user) {
9206 ptr = &(*ptr)->next;
9208 new = xcmalloc(sizeof(*new), "block_set");
9219 static void do_unuse_block(
9220 struct block *used, struct block_set **head, struct block *unuser)
9222 struct block_set *use, **ptr;
9226 if (use->member == unuser) {
9228 memset(use, -1, sizeof(*use));
9237 static void use_block(struct block *used, struct block *user)
9239 /* Append new to the head of the list, print_block
9242 do_use_block(used, &used->use, user, 1);
9245 static void unuse_block(struct block *used, struct block *unuser)
9247 do_unuse_block(used, &used->use, unuser);
9251 static void idom_block(struct block *idom, struct block *user)
9253 do_use_block(idom, &idom->idominates, user, 0);
9256 static void unidom_block(struct block *idom, struct block *unuser)
9258 do_unuse_block(idom, &idom->idominates, unuser);
9261 static void domf_block(struct block *block, struct block *domf)
9263 do_use_block(block, &block->domfrontier, domf, 0);
9266 static void undomf_block(struct block *block, struct block *undomf)
9268 do_unuse_block(block, &block->domfrontier, undomf);
9271 static void ipdom_block(struct block *ipdom, struct block *user)
9273 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9276 static void unipdom_block(struct block *ipdom, struct block *unuser)
9278 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9281 static void ipdomf_block(struct block *block, struct block *ipdomf)
9283 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9286 static void unipdomf_block(struct block *block, struct block *unipdomf)
9288 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9293 static int do_walk_triple(struct compile_state *state,
9294 struct triple *ptr, int depth,
9295 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9298 result = cb(state, ptr, depth);
9299 if ((result == 0) && (ptr->op == OP_LIST)) {
9300 struct triple *list;
9304 result = do_walk_triple(state, ptr, depth + 1, cb);
9305 if (ptr->next->prev != ptr) {
9306 internal_error(state, ptr->next, "bad prev");
9310 } while((result == 0) && (ptr != RHS(list, 0)));
9315 static int walk_triple(
9316 struct compile_state *state,
9318 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9320 return do_walk_triple(state, ptr, 0, cb);
9323 static void do_print_prefix(int depth)
9326 for(i = 0; i < depth; i++) {
9331 #define PRINT_LIST 1
9332 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9336 if (op == OP_LIST) {
9341 if ((op == OP_LABEL) && (ins->use)) {
9342 printf("\n%p:\n", ins);
9344 do_print_prefix(depth);
9345 display_triple(stdout, ins);
9347 if ((ins->op == OP_BRANCH) && ins->use) {
9348 internal_error(state, ins, "branch used?");
9352 struct triple_set *user;
9353 for(user = ins->use; user; user = user->next) {
9354 printf("use: %p\n", user->member);
9358 if (triple_is_branch(state, ins)) {
9364 static void print_triple(struct compile_state *state, struct triple *ins)
9366 walk_triple(state, ins, do_print_triple);
9369 static void print_triples(struct compile_state *state)
9371 print_triple(state, state->main_function);
9375 struct block *block;
9377 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9379 if (!block || (cf[block->vertex].block == block)) {
9382 cf[block->vertex].block = block;
9383 find_cf_blocks(cf, block->left);
9384 find_cf_blocks(cf, block->right);
9387 static void print_control_flow(struct compile_state *state)
9389 struct cf_block *cf;
9391 printf("\ncontrol flow\n");
9392 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9393 find_cf_blocks(cf, state->first_block);
9395 for(i = 1; i <= state->last_vertex; i++) {
9396 struct block *block;
9397 block = cf[i].block;
9400 printf("(%p) %d:", block, block->vertex);
9402 printf(" %d", block->left->vertex);
9404 if (block->right && (block->right != block->left)) {
9405 printf(" %d", block->right->vertex);
9414 static struct block *basic_block(struct compile_state *state,
9415 struct triple *first)
9417 struct block *block;
9420 if (first->op != OP_LABEL) {
9421 internal_error(state, 0, "block does not start with a label");
9423 /* See if this basic block has already been setup */
9424 if (first->u.block != 0) {
9425 return first->u.block;
9427 /* Allocate another basic block structure */
9428 state->last_vertex += 1;
9429 block = xcmalloc(sizeof(*block), "block");
9430 block->first = block->last = first;
9431 block->vertex = state->last_vertex;
9434 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9438 /* If ptr->u is not used remember where the baic block is */
9439 if (triple_stores_block(state, ptr)) {
9440 ptr->u.block = block;
9442 if (ptr->op == OP_BRANCH) {
9446 } while (ptr != RHS(state->main_function, 0));
9447 if (ptr == RHS(state->main_function, 0))
9450 if (op == OP_LABEL) {
9451 block->left = basic_block(state, ptr);
9453 use_block(block->left, block);
9455 else if (op == OP_BRANCH) {
9457 /* Trace the branch target */
9458 block->right = basic_block(state, TARG(ptr, 0));
9459 use_block(block->right, block);
9460 /* If there is a test trace the branch as well */
9461 if (TRIPLE_RHS(ptr->sizes)) {
9462 block->left = basic_block(state, ptr->next);
9463 use_block(block->left, block);
9467 internal_error(state, 0, "Bad basic block split");
9473 static void walk_blocks(struct compile_state *state,
9474 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9477 struct triple *ptr, *first;
9478 struct block *last_block;
9480 first = RHS(state->main_function, 0);
9483 struct block *block;
9484 if (ptr->op == OP_LABEL) {
9485 block = ptr->u.block;
9486 if (block && (block != last_block)) {
9487 cb(state, block, arg);
9492 } while(ptr != first);
9495 static void print_block(
9496 struct compile_state *state, struct block *block, void *arg)
9501 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9505 block->left && block->left->use?block->left->use->member : 0,
9507 block->right && block->right->use?block->right->use->member : 0);
9508 if (block->first->op == OP_LABEL) {
9509 fprintf(fp, "%p:\n", block->first);
9511 for(ptr = block->first; ; ptr = ptr->next) {
9512 struct triple_set *user;
9515 if (triple_stores_block(state, ptr)) {
9516 if (ptr->u.block != block) {
9517 internal_error(state, ptr,
9518 "Wrong block pointer: %p\n",
9522 if (op == OP_ADECL) {
9523 for(user = ptr->use; user; user = user->next) {
9524 if (!user->member->u.block) {
9525 internal_error(state, user->member,
9526 "Use %p not in a block?\n",
9531 display_triple(fp, ptr);
9534 for(user = ptr->use; user; user = user->next) {
9535 fprintf(fp, "use: %p\n", user->member);
9539 /* Sanity checks... */
9540 valid_ins(state, ptr);
9541 for(user = ptr->use; user; user = user->next) {
9544 valid_ins(state, use);
9545 if (triple_stores_block(state, user->member) &&
9546 !user->member->u.block) {
9547 internal_error(state, user->member,
9548 "Use %p not in a block?",
9553 if (ptr == block->last)
9560 static void print_blocks(struct compile_state *state, FILE *fp)
9562 fprintf(fp, "--------------- blocks ---------------\n");
9563 walk_blocks(state, print_block, fp);
9566 static void prune_nonblock_triples(struct compile_state *state)
9568 struct block *block;
9569 struct triple *first, *ins, *next;
9570 /* Delete the triples not in a basic block */
9571 first = RHS(state->main_function, 0);
9576 if (ins->op == OP_LABEL) {
9577 block = ins->u.block;
9580 release_triple(state, ins);
9583 } while(ins != first);
9586 static void setup_basic_blocks(struct compile_state *state)
9588 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9589 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9590 internal_error(state, 0, "ins will not store block?");
9592 /* Find the basic blocks */
9593 state->last_vertex = 0;
9594 state->first_block = basic_block(state, RHS(state->main_function,0));
9595 /* Delete the triples not in a basic block */
9596 prune_nonblock_triples(state);
9597 /* Find the last basic block */
9598 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9599 if (!state->last_block) {
9600 internal_error(state, 0, "end not used?");
9602 /* Insert an extra unused edge from start to the end
9603 * This helps with reverse control flow calculations.
9605 use_block(state->first_block, state->last_block);
9606 /* If we are debugging print what I have just done */
9607 if (state->debug & DEBUG_BASIC_BLOCKS) {
9608 print_blocks(state, stdout);
9609 print_control_flow(state);
9613 static void free_basic_block(struct compile_state *state, struct block *block)
9615 struct block_set *entry, *next;
9616 struct block *child;
9620 if (block->vertex == -1) {
9625 unuse_block(block->left, block);
9628 unuse_block(block->right, block);
9631 unidom_block(block->idom, block);
9635 unipdom_block(block->ipdom, block);
9638 for(entry = block->use; entry; entry = next) {
9640 child = entry->member;
9641 unuse_block(block, child);
9642 if (child->left == block) {
9645 if (child->right == block) {
9649 for(entry = block->idominates; entry; entry = next) {
9651 child = entry->member;
9652 unidom_block(block, child);
9655 for(entry = block->domfrontier; entry; entry = next) {
9657 child = entry->member;
9658 undomf_block(block, child);
9660 for(entry = block->ipdominates; entry; entry = next) {
9662 child = entry->member;
9663 unipdom_block(block, child);
9666 for(entry = block->ipdomfrontier; entry; entry = next) {
9668 child = entry->member;
9669 unipdomf_block(block, child);
9671 if (block->users != 0) {
9672 internal_error(state, 0, "block still has users");
9674 free_basic_block(state, block->left);
9676 free_basic_block(state, block->right);
9678 memset(block, -1, sizeof(*block));
9682 static void free_basic_blocks(struct compile_state *state)
9684 struct triple *first, *ins;
9685 free_basic_block(state, state->first_block);
9686 state->last_vertex = 0;
9687 state->first_block = state->last_block = 0;
9688 first = RHS(state->main_function, 0);
9691 if (triple_stores_block(state, ins)) {
9695 } while(ins != first);
9700 struct block *block;
9701 struct sdom_block *sdominates;
9702 struct sdom_block *sdom_next;
9703 struct sdom_block *sdom;
9704 struct sdom_block *label;
9705 struct sdom_block *parent;
9706 struct sdom_block *ancestor;
9711 static void unsdom_block(struct sdom_block *block)
9713 struct sdom_block **ptr;
9714 if (!block->sdom_next) {
9717 ptr = &block->sdom->sdominates;
9719 if ((*ptr) == block) {
9720 *ptr = block->sdom_next;
9723 ptr = &(*ptr)->sdom_next;
9727 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9729 unsdom_block(block);
9731 block->sdom_next = sdom->sdominates;
9732 sdom->sdominates = block;
9737 static int initialize_sdblock(struct sdom_block *sd,
9738 struct block *parent, struct block *block, int vertex)
9740 if (!block || (sd[block->vertex].block == block)) {
9744 /* Renumber the blocks in a convinient fashion */
9745 block->vertex = vertex;
9746 sd[vertex].block = block;
9747 sd[vertex].sdom = &sd[vertex];
9748 sd[vertex].label = &sd[vertex];
9749 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9750 sd[vertex].ancestor = 0;
9751 sd[vertex].vertex = vertex;
9752 vertex = initialize_sdblock(sd, block, block->left, vertex);
9753 vertex = initialize_sdblock(sd, block, block->right, vertex);
9757 static int initialize_sdpblock(struct sdom_block *sd,
9758 struct block *parent, struct block *block, int vertex)
9760 struct block_set *user;
9761 if (!block || (sd[block->vertex].block == block)) {
9765 /* Renumber the blocks in a convinient fashion */
9766 block->vertex = vertex;
9767 sd[vertex].block = block;
9768 sd[vertex].sdom = &sd[vertex];
9769 sd[vertex].label = &sd[vertex];
9770 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9771 sd[vertex].ancestor = 0;
9772 sd[vertex].vertex = vertex;
9773 for(user = block->use; user; user = user->next) {
9774 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9779 static void compress_ancestors(struct sdom_block *v)
9781 /* This procedure assumes ancestor(v) != 0 */
9782 /* if (ancestor(ancestor(v)) != 0) {
9783 * compress(ancestor(ancestor(v)));
9784 * if (semi(label(ancestor(v))) < semi(label(v))) {
9785 * label(v) = label(ancestor(v));
9787 * ancestor(v) = ancestor(ancestor(v));
9793 if (v->ancestor->ancestor) {
9794 compress_ancestors(v->ancestor->ancestor);
9795 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9796 v->label = v->ancestor->label;
9798 v->ancestor = v->ancestor->ancestor;
9802 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9806 * for each v <= pred(w) {
9808 * if (semi[u] < semi[w] {
9809 * semi[w] = semi[u];
9812 * add w to bucket(vertex(semi[w]));
9813 * LINK(parent(w), w);
9816 * for each v <= bucket(parent(w)) {
9817 * delete v from bucket(parent(w));
9819 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9822 for(i = state->last_vertex; i >= 2; i--) {
9823 struct sdom_block *v, *parent, *next;
9824 struct block_set *user;
9825 struct block *block;
9826 block = sd[i].block;
9827 parent = sd[i].parent;
9829 for(user = block->use; user; user = user->next) {
9830 struct sdom_block *v, *u;
9831 v = &sd[user->member->vertex];
9832 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9833 if (u->sdom->vertex < sd[i].sdom->vertex) {
9834 sd[i].sdom = u->sdom;
9837 sdom_block(sd[i].sdom, &sd[i]);
9838 sd[i].ancestor = parent;
9840 for(v = parent->sdominates; v; v = next) {
9841 struct sdom_block *u;
9842 next = v->sdom_next;
9844 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9845 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9846 u->block : parent->block;
9851 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9855 * for each v <= pred(w) {
9857 * if (semi[u] < semi[w] {
9858 * semi[w] = semi[u];
9861 * add w to bucket(vertex(semi[w]));
9862 * LINK(parent(w), w);
9865 * for each v <= bucket(parent(w)) {
9866 * delete v from bucket(parent(w));
9868 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9871 for(i = state->last_vertex; i >= 2; i--) {
9872 struct sdom_block *u, *v, *parent, *next;
9873 struct block *block;
9874 block = sd[i].block;
9875 parent = sd[i].parent;
9878 v = &sd[block->left->vertex];
9879 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9880 if (u->sdom->vertex < sd[i].sdom->vertex) {
9881 sd[i].sdom = u->sdom;
9884 if (block->right && (block->right != block->left)) {
9885 v = &sd[block->right->vertex];
9886 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9887 if (u->sdom->vertex < sd[i].sdom->vertex) {
9888 sd[i].sdom = u->sdom;
9891 sdom_block(sd[i].sdom, &sd[i]);
9892 sd[i].ancestor = parent;
9894 for(v = parent->sdominates; v; v = next) {
9895 struct sdom_block *u;
9896 next = v->sdom_next;
9898 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9899 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9900 u->block : parent->block;
9905 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9908 for(i = 2; i <= state->last_vertex; i++) {
9909 struct block *block;
9910 block = sd[i].block;
9911 if (block->idom->vertex != sd[i].sdom->vertex) {
9912 block->idom = block->idom->idom;
9914 idom_block(block->idom, block);
9916 sd[1].block->idom = 0;
9919 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9922 for(i = 2; i <= state->last_vertex; i++) {
9923 struct block *block;
9924 block = sd[i].block;
9925 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9926 block->ipdom = block->ipdom->ipdom;
9928 ipdom_block(block->ipdom, block);
9930 sd[1].block->ipdom = 0;
9934 * Every vertex of a flowgraph G = (V, E, r) except r has
9935 * a unique immediate dominator.
9936 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9937 * rooted at r, called the dominator tree of G, such that
9938 * v dominates w if and only if v is a proper ancestor of w in
9939 * the dominator tree.
9942 * If v and w are vertices of G such that v <= w,
9943 * than any path from v to w must contain a common ancestor
9946 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9947 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9948 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9950 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9951 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9954 * Let w != r and let u be a vertex for which sdom(u) is
9955 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9956 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9958 /* Lemma 5: Let vertices v,w satisfy v -> w.
9959 * Then v -> idom(w) or idom(w) -> idom(v)
9962 static void find_immediate_dominators(struct compile_state *state)
9964 struct sdom_block *sd;
9965 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9966 * vi > w for (1 <= i <= k - 1}
9969 * For any vertex w != r.
9971 * {v|(v,w) <= E and v < w } U
9972 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9975 * Let w != r and let u be a vertex for which sdom(u) is
9976 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9978 * { sdom(w) if sdom(w) = sdom(u),
9980 * { idom(u) otherwise
9982 /* The algorithm consists of the following 4 steps.
9983 * Step 1. Carry out a depth-first search of the problem graph.
9984 * Number the vertices from 1 to N as they are reached during
9985 * the search. Initialize the variables used in succeeding steps.
9986 * Step 2. Compute the semidominators of all vertices by applying
9987 * theorem 4. Carry out the computation vertex by vertex in
9988 * decreasing order by number.
9989 * Step 3. Implicitly define the immediate dominator of each vertex
9990 * by applying Corollary 1.
9991 * Step 4. Explicitly define the immediate dominator of each vertex,
9992 * carrying out the computation vertex by vertex in increasing order
9995 /* Step 1 initialize the basic block information */
9996 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9997 initialize_sdblock(sd, 0, state->first_block, 0);
10003 /* Step 2 compute the semidominators */
10004 /* Step 3 implicitly define the immediate dominator of each vertex */
10005 compute_sdom(state, sd);
10006 /* Step 4 explicitly define the immediate dominator of each vertex */
10007 compute_idom(state, sd);
10011 static void find_post_dominators(struct compile_state *state)
10013 struct sdom_block *sd;
10014 /* Step 1 initialize the basic block information */
10015 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10017 initialize_sdpblock(sd, 0, state->last_block, 0);
10019 /* Step 2 compute the semidominators */
10020 /* Step 3 implicitly define the immediate dominator of each vertex */
10021 compute_spdom(state, sd);
10022 /* Step 4 explicitly define the immediate dominator of each vertex */
10023 compute_ipdom(state, sd);
10029 static void find_block_domf(struct compile_state *state, struct block *block)
10031 struct block *child;
10032 struct block_set *user;
10033 if (block->domfrontier != 0) {
10034 internal_error(state, block->first, "domfrontier present?");
10036 for(user = block->idominates; user; user = user->next) {
10037 child = user->member;
10038 if (child->idom != block) {
10039 internal_error(state, block->first, "bad idom");
10041 find_block_domf(state, child);
10043 if (block->left && block->left->idom != block) {
10044 domf_block(block, block->left);
10046 if (block->right && block->right->idom != block) {
10047 domf_block(block, block->right);
10049 for(user = block->idominates; user; user = user->next) {
10050 struct block_set *frontier;
10051 child = user->member;
10052 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10053 if (frontier->member->idom != block) {
10054 domf_block(block, frontier->member);
10060 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10062 struct block *child;
10063 struct block_set *user;
10064 if (block->ipdomfrontier != 0) {
10065 internal_error(state, block->first, "ipdomfrontier present?");
10067 for(user = block->ipdominates; user; user = user->next) {
10068 child = user->member;
10069 if (child->ipdom != block) {
10070 internal_error(state, block->first, "bad ipdom");
10072 find_block_ipdomf(state, child);
10074 if (block->left && block->left->ipdom != block) {
10075 ipdomf_block(block, block->left);
10077 if (block->right && block->right->ipdom != block) {
10078 ipdomf_block(block, block->right);
10080 for(user = block->idominates; user; user = user->next) {
10081 struct block_set *frontier;
10082 child = user->member;
10083 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10084 if (frontier->member->ipdom != block) {
10085 ipdomf_block(block, frontier->member);
10091 static void print_dominated(
10092 struct compile_state *state, struct block *block, void *arg)
10094 struct block_set *user;
10097 fprintf(fp, "%d:", block->vertex);
10098 for(user = block->idominates; user; user = user->next) {
10099 fprintf(fp, " %d", user->member->vertex);
10100 if (user->member->idom != block) {
10101 internal_error(state, user->member->first, "bad idom");
10107 static void print_dominators(struct compile_state *state, FILE *fp)
10109 fprintf(fp, "\ndominates\n");
10110 walk_blocks(state, print_dominated, fp);
10114 static int print_frontiers(
10115 struct compile_state *state, struct block *block, int vertex)
10117 struct block_set *user;
10119 if (!block || (block->vertex != vertex + 1)) {
10124 printf("%d:", block->vertex);
10125 for(user = block->domfrontier; user; user = user->next) {
10126 printf(" %d", user->member->vertex);
10130 vertex = print_frontiers(state, block->left, vertex);
10131 vertex = print_frontiers(state, block->right, vertex);
10134 static void print_dominance_frontiers(struct compile_state *state)
10136 printf("\ndominance frontiers\n");
10137 print_frontiers(state, state->first_block, 0);
10141 static void analyze_idominators(struct compile_state *state)
10143 /* Find the immediate dominators */
10144 find_immediate_dominators(state);
10145 /* Find the dominance frontiers */
10146 find_block_domf(state, state->first_block);
10147 /* If debuging print the print what I have just found */
10148 if (state->debug & DEBUG_FDOMINATORS) {
10149 print_dominators(state, stdout);
10150 print_dominance_frontiers(state);
10151 print_control_flow(state);
10157 static void print_ipdominated(
10158 struct compile_state *state, struct block *block, void *arg)
10160 struct block_set *user;
10163 fprintf(fp, "%d:", block->vertex);
10164 for(user = block->ipdominates; user; user = user->next) {
10165 fprintf(fp, " %d", user->member->vertex);
10166 if (user->member->ipdom != block) {
10167 internal_error(state, user->member->first, "bad ipdom");
10173 static void print_ipdominators(struct compile_state *state, FILE *fp)
10175 fprintf(fp, "\nipdominates\n");
10176 walk_blocks(state, print_ipdominated, fp);
10179 static int print_pfrontiers(
10180 struct compile_state *state, struct block *block, int vertex)
10182 struct block_set *user;
10184 if (!block || (block->vertex != vertex + 1)) {
10189 printf("%d:", block->vertex);
10190 for(user = block->ipdomfrontier; user; user = user->next) {
10191 printf(" %d", user->member->vertex);
10194 for(user = block->use; user; user = user->next) {
10195 vertex = print_pfrontiers(state, user->member, vertex);
10199 static void print_ipdominance_frontiers(struct compile_state *state)
10201 printf("\nipdominance frontiers\n");
10202 print_pfrontiers(state, state->last_block, 0);
10206 static void analyze_ipdominators(struct compile_state *state)
10208 /* Find the post dominators */
10209 find_post_dominators(state);
10210 /* Find the control dependencies (post dominance frontiers) */
10211 find_block_ipdomf(state, state->last_block);
10212 /* If debuging print the print what I have just found */
10213 if (state->debug & DEBUG_RDOMINATORS) {
10214 print_ipdominators(state, stdout);
10215 print_ipdominance_frontiers(state);
10216 print_control_flow(state);
10220 static int bdominates(struct compile_state *state,
10221 struct block *dom, struct block *sub)
10223 while(sub && (sub != dom)) {
10229 static int tdominates(struct compile_state *state,
10230 struct triple *dom, struct triple *sub)
10232 struct block *bdom, *bsub;
10234 bdom = block_of_triple(state, dom);
10235 bsub = block_of_triple(state, sub);
10236 if (bdom != bsub) {
10237 result = bdominates(state, bdom, bsub);
10240 struct triple *ins;
10242 while((ins != bsub->first) && (ins != dom)) {
10245 result = (ins == dom);
10250 static void insert_phi_operations(struct compile_state *state)
10253 struct triple *first;
10254 int *has_already, *work;
10255 struct block *work_list, **work_list_tail;
10257 struct triple *var;
10259 size = sizeof(int) * (state->last_vertex + 1);
10260 has_already = xcmalloc(size, "has_already");
10261 work = xcmalloc(size, "work");
10264 first = RHS(state->main_function, 0);
10265 for(var = first->next; var != first ; var = var->next) {
10266 struct block *block;
10267 struct triple_set *user;
10268 if ((var->op != OP_ADECL) || !var->use) {
10273 work_list_tail = &work_list;
10274 for(user = var->use; user; user = user->next) {
10275 if (user->member->op == OP_READ) {
10278 if (user->member->op != OP_WRITE) {
10279 internal_error(state, user->member,
10280 "bad variable access");
10282 block = user->member->u.block;
10284 warning(state, user->member, "dead code");
10286 if (work[block->vertex] >= iter) {
10289 work[block->vertex] = iter;
10290 *work_list_tail = block;
10291 block->work_next = 0;
10292 work_list_tail = &block->work_next;
10294 for(block = work_list; block; block = block->work_next) {
10295 struct block_set *df;
10296 for(df = block->domfrontier; df; df = df->next) {
10297 struct triple *phi;
10298 struct block *front;
10300 front = df->member;
10302 if (has_already[front->vertex] >= iter) {
10305 /* Count how many edges flow into this block */
10306 in_edges = front->users;
10307 /* Insert a phi function for this variable */
10308 get_occurance(front->first->occurance);
10309 phi = alloc_triple(
10310 state, OP_PHI, var->type, -1, in_edges,
10311 front->first->occurance);
10312 phi->u.block = front;
10313 MISC(phi, 0) = var;
10314 use_triple(var, phi);
10315 /* Insert the phi functions immediately after the label */
10316 insert_triple(state, front->first->next, phi);
10317 if (front->first == front->last) {
10318 front->last = front->first->next;
10320 has_already[front->vertex] = iter;
10322 /* If necessary plan to visit the basic block */
10323 if (work[front->vertex] >= iter) {
10326 work[front->vertex] = iter;
10327 *work_list_tail = front;
10328 front->work_next = 0;
10329 work_list_tail = &front->work_next;
10333 xfree(has_already);
10341 static void fixup_block_phi_variables(
10342 struct compile_state *state, struct block *parent, struct block *block)
10344 struct block_set *set;
10345 struct triple *ptr;
10347 if (!parent || !block)
10349 /* Find the edge I am coming in on */
10351 for(set = block->use; set; set = set->next, edge++) {
10352 if (set->member == parent) {
10357 internal_error(state, 0, "phi input is not on a control predecessor");
10359 for(ptr = block->first; ; ptr = ptr->next) {
10360 if (ptr->op == OP_PHI) {
10361 struct triple *var, *val, **slot;
10362 var = MISC(ptr, 0);
10364 internal_error(state, ptr, "no var???");
10366 /* Find the current value of the variable */
10367 val = var->use->member;
10368 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10369 internal_error(state, val, "bad value in phi");
10371 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10372 internal_error(state, ptr, "edges > phi rhs");
10374 slot = &RHS(ptr, edge);
10375 if ((*slot != 0) && (*slot != val)) {
10376 internal_error(state, ptr, "phi already bound on this edge");
10379 use_triple(val, ptr);
10381 if (ptr == block->last) {
10388 static void rename_block_variables(
10389 struct compile_state *state, struct block *block)
10391 struct block_set *user;
10392 struct triple *ptr, *next, *last;
10396 last = block->first;
10398 for(ptr = block->first; !done; ptr = next) {
10400 if (ptr == block->last) {
10404 if (ptr->op == OP_READ) {
10405 struct triple *var, *val;
10407 unuse_triple(var, ptr);
10409 error(state, ptr, "variable used without being set");
10411 /* Find the current value of the variable */
10412 val = var->use->member;
10413 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10414 internal_error(state, val, "bad value in read");
10416 propogate_use(state, ptr, val);
10417 release_triple(state, ptr);
10421 if (ptr->op == OP_WRITE) {
10422 struct triple *var, *val;
10425 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10426 internal_error(state, val, "bad value in write");
10428 propogate_use(state, ptr, val);
10429 unuse_triple(var, ptr);
10430 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10431 push_triple(var, val);
10433 if (ptr->op == OP_PHI) {
10434 struct triple *var;
10435 var = MISC(ptr, 0);
10436 /* Push OP_PHI onto a stack of variable uses */
10437 push_triple(var, ptr);
10441 block->last = last;
10443 /* Fixup PHI functions in the cf successors */
10444 fixup_block_phi_variables(state, block, block->left);
10445 fixup_block_phi_variables(state, block, block->right);
10446 /* rename variables in the dominated nodes */
10447 for(user = block->idominates; user; user = user->next) {
10448 rename_block_variables(state, user->member);
10450 /* pop the renamed variable stack */
10451 last = block->first;
10453 for(ptr = block->first; !done ; ptr = next) {
10455 if (ptr == block->last) {
10458 if (ptr->op == OP_WRITE) {
10459 struct triple *var;
10461 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10462 pop_triple(var, RHS(ptr, 0));
10463 release_triple(state, ptr);
10466 if (ptr->op == OP_PHI) {
10467 struct triple *var;
10468 var = MISC(ptr, 0);
10469 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10470 pop_triple(var, ptr);
10474 block->last = last;
10477 static void prune_block_variables(struct compile_state *state,
10478 struct block *block)
10480 struct block_set *user;
10481 struct triple *next, *last, *ptr;
10483 last = block->first;
10485 for(ptr = block->first; !done; ptr = next) {
10487 if (ptr == block->last) {
10490 if (ptr->op == OP_ADECL) {
10491 struct triple_set *user, *next;
10492 for(user = ptr->use; user; user = next) {
10493 struct triple *use;
10495 use = user->member;
10496 if (use->op != OP_PHI) {
10497 internal_error(state, use, "decl still used");
10499 if (MISC(use, 0) != ptr) {
10500 internal_error(state, use, "bad phi use of decl");
10502 unuse_triple(ptr, use);
10505 release_triple(state, ptr);
10510 block->last = last;
10511 for(user = block->idominates; user; user = user->next) {
10512 prune_block_variables(state, user->member);
10516 static void transform_to_ssa_form(struct compile_state *state)
10518 insert_phi_operations(state);
10520 printf("@%s:%d\n", __FILE__, __LINE__);
10521 print_blocks(state, stdout);
10523 rename_block_variables(state, state->first_block);
10524 prune_block_variables(state, state->first_block);
10528 static void clear_vertex(
10529 struct compile_state *state, struct block *block, void *arg)
10534 static void mark_live_block(
10535 struct compile_state *state, struct block *block, int *next_vertex)
10537 /* See if this is a block that has not been marked */
10538 if (block->vertex != 0) {
10541 block->vertex = *next_vertex;
10543 if (triple_is_branch(state, block->last)) {
10544 struct triple **targ;
10545 targ = triple_targ(state, block->last, 0);
10546 for(; targ; targ = triple_targ(state, block->last, targ)) {
10550 if (!triple_stores_block(state, *targ)) {
10551 internal_error(state, 0, "bad targ");
10553 mark_live_block(state, (*targ)->u.block, next_vertex);
10556 else if (block->last->next != RHS(state->main_function, 0)) {
10557 struct triple *ins;
10558 ins = block->last->next;
10559 if (!triple_stores_block(state, ins)) {
10560 internal_error(state, 0, "bad block start");
10562 mark_live_block(state, ins->u.block, next_vertex);
10566 static void transform_from_ssa_form(struct compile_state *state)
10568 /* To get out of ssa form we insert moves on the incoming
10569 * edges to blocks containting phi functions.
10571 struct triple *first;
10572 struct triple *phi, *next;
10575 /* Walk the control flow to see which blocks remain alive */
10576 walk_blocks(state, clear_vertex, 0);
10578 mark_live_block(state, state->first_block, &next_vertex);
10580 /* Walk all of the operations to find the phi functions */
10581 first = RHS(state->main_function, 0);
10582 for(phi = first->next; phi != first ; phi = next) {
10583 struct block_set *set;
10584 struct block *block;
10585 struct triple **slot;
10586 struct triple *var, *read;
10587 struct triple_set *use, *use_next;
10590 if (phi->op != OP_PHI) {
10593 block = phi->u.block;
10594 slot = &RHS(phi, 0);
10596 /* Forget uses from code in dead blocks */
10597 for(use = phi->use; use; use = use_next) {
10598 struct block *ublock;
10599 struct triple **expr;
10600 use_next = use->next;
10601 ublock = block_of_triple(state, use->member);
10602 if ((use->member == phi) || (ublock->vertex != 0)) {
10605 expr = triple_rhs(state, use->member, 0);
10606 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10607 if (*expr == phi) {
10611 unuse_triple(phi, use->member);
10614 /* A variable to replace the phi function */
10615 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10616 /* A read of the single value that is set into the variable */
10617 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10618 use_triple(var, read);
10620 /* Replaces uses of the phi with variable reads */
10621 propogate_use(state, phi, read);
10623 /* Walk all of the incoming edges/blocks and insert moves.
10625 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10626 struct block *eblock;
10627 struct triple *move;
10628 struct triple *val;
10629 eblock = set->member;
10632 unuse_triple(val, phi);
10634 if (!val || (val == &zero_triple) ||
10635 (block->vertex == 0) || (eblock->vertex == 0) ||
10636 (val == phi) || (val == read)) {
10640 move = post_triple(state,
10641 val, OP_WRITE, phi->type, var, val);
10642 use_triple(val, move);
10643 use_triple(var, move);
10645 /* See if there are any writers of var */
10647 for(use = var->use; use; use = use->next) {
10648 struct triple **expr;
10649 expr = triple_lhs(state, use->member, 0);
10650 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10651 if (*expr == var) {
10656 /* If var is not used free it */
10658 unuse_triple(var, read);
10659 free_triple(state, read);
10660 free_triple(state, var);
10663 /* Release the phi function */
10664 release_triple(state, phi);
10671 * Register conflict resolution
10672 * =========================================================
10675 static struct reg_info find_def_color(
10676 struct compile_state *state, struct triple *def)
10678 struct triple_set *set;
10679 struct reg_info info;
10680 info.reg = REG_UNSET;
10682 if (!triple_is_def(state, def)) {
10685 info = arch_reg_lhs(state, def, 0);
10686 if (info.reg >= MAX_REGISTERS) {
10687 info.reg = REG_UNSET;
10689 for(set = def->use; set; set = set->next) {
10690 struct reg_info tinfo;
10692 i = find_rhs_use(state, set->member, def);
10696 tinfo = arch_reg_rhs(state, set->member, i);
10697 if (tinfo.reg >= MAX_REGISTERS) {
10698 tinfo.reg = REG_UNSET;
10700 if ((tinfo.reg != REG_UNSET) &&
10701 (info.reg != REG_UNSET) &&
10702 (tinfo.reg != info.reg)) {
10703 internal_error(state, def, "register conflict");
10705 if ((info.regcm & tinfo.regcm) == 0) {
10706 internal_error(state, def, "regcm conflict %x & %x == 0",
10707 info.regcm, tinfo.regcm);
10709 if (info.reg == REG_UNSET) {
10710 info.reg = tinfo.reg;
10712 info.regcm &= tinfo.regcm;
10714 if (info.reg >= MAX_REGISTERS) {
10715 internal_error(state, def, "register out of range");
10720 static struct reg_info find_lhs_pre_color(
10721 struct compile_state *state, struct triple *ins, int index)
10723 struct reg_info info;
10725 zrhs = TRIPLE_RHS(ins->sizes);
10726 zlhs = TRIPLE_LHS(ins->sizes);
10727 if (!zlhs && triple_is_def(state, ins)) {
10730 if (index >= zlhs) {
10731 internal_error(state, ins, "Bad lhs %d", index);
10733 info = arch_reg_lhs(state, ins, index);
10734 for(i = 0; i < zrhs; i++) {
10735 struct reg_info rinfo;
10736 rinfo = arch_reg_rhs(state, ins, i);
10737 if ((info.reg == rinfo.reg) &&
10738 (rinfo.reg >= MAX_REGISTERS)) {
10739 struct reg_info tinfo;
10740 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10741 info.reg = tinfo.reg;
10742 info.regcm &= tinfo.regcm;
10746 if (info.reg >= MAX_REGISTERS) {
10747 info.reg = REG_UNSET;
10752 static struct reg_info find_rhs_post_color(
10753 struct compile_state *state, struct triple *ins, int index);
10755 static struct reg_info find_lhs_post_color(
10756 struct compile_state *state, struct triple *ins, int index)
10758 struct triple_set *set;
10759 struct reg_info info;
10760 struct triple *lhs;
10762 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10765 if ((index == 0) && triple_is_def(state, ins)) {
10768 else if (index < TRIPLE_LHS(ins->sizes)) {
10769 lhs = LHS(ins, index);
10772 internal_error(state, ins, "Bad lhs %d", index);
10775 info = arch_reg_lhs(state, ins, index);
10776 if (info.reg >= MAX_REGISTERS) {
10777 info.reg = REG_UNSET;
10779 for(set = lhs->use; set; set = set->next) {
10780 struct reg_info rinfo;
10781 struct triple *user;
10783 user = set->member;
10784 zrhs = TRIPLE_RHS(user->sizes);
10785 for(i = 0; i < zrhs; i++) {
10786 if (RHS(user, i) != lhs) {
10789 rinfo = find_rhs_post_color(state, user, i);
10790 if ((info.reg != REG_UNSET) &&
10791 (rinfo.reg != REG_UNSET) &&
10792 (info.reg != rinfo.reg)) {
10793 internal_error(state, ins, "register conflict");
10795 if ((info.regcm & rinfo.regcm) == 0) {
10796 internal_error(state, ins, "regcm conflict %x & %x == 0",
10797 info.regcm, rinfo.regcm);
10799 if (info.reg == REG_UNSET) {
10800 info.reg = rinfo.reg;
10802 info.regcm &= rinfo.regcm;
10806 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10807 ins, index, info.reg, info.regcm);
10812 static struct reg_info find_rhs_post_color(
10813 struct compile_state *state, struct triple *ins, int index)
10815 struct reg_info info, rinfo;
10818 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10821 rinfo = arch_reg_rhs(state, ins, index);
10822 zlhs = TRIPLE_LHS(ins->sizes);
10823 if (!zlhs && triple_is_def(state, ins)) {
10827 if (info.reg >= MAX_REGISTERS) {
10828 info.reg = REG_UNSET;
10830 for(i = 0; i < zlhs; i++) {
10831 struct reg_info linfo;
10832 linfo = arch_reg_lhs(state, ins, i);
10833 if ((linfo.reg == rinfo.reg) &&
10834 (linfo.reg >= MAX_REGISTERS)) {
10835 struct reg_info tinfo;
10836 tinfo = find_lhs_post_color(state, ins, i);
10837 if (tinfo.reg >= MAX_REGISTERS) {
10838 tinfo.reg = REG_UNSET;
10840 info.regcm &= linfo.reg;
10841 info.regcm &= tinfo.regcm;
10842 if (info.reg != REG_UNSET) {
10843 internal_error(state, ins, "register conflict");
10845 if (info.regcm == 0) {
10846 internal_error(state, ins, "regcm conflict");
10848 info.reg = tinfo.reg;
10852 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10853 ins, index, info.reg, info.regcm);
10858 static struct reg_info find_lhs_color(
10859 struct compile_state *state, struct triple *ins, int index)
10861 struct reg_info pre, post, info;
10863 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10866 pre = find_lhs_pre_color(state, ins, index);
10867 post = find_lhs_post_color(state, ins, index);
10868 if ((pre.reg != post.reg) &&
10869 (pre.reg != REG_UNSET) &&
10870 (post.reg != REG_UNSET)) {
10871 internal_error(state, ins, "register conflict");
10873 info.regcm = pre.regcm & post.regcm;
10874 info.reg = pre.reg;
10875 if (info.reg == REG_UNSET) {
10876 info.reg = post.reg;
10879 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10880 ins, index, info.reg, info.regcm);
10885 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10887 struct triple_set *entry, *next;
10888 struct triple *out;
10889 struct reg_info info, rinfo;
10891 info = arch_reg_lhs(state, ins, 0);
10892 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10893 use_triple(RHS(out, 0), out);
10894 /* Get the users of ins to use out instead */
10895 for(entry = ins->use; entry; entry = next) {
10897 next = entry->next;
10898 if (entry->member == out) {
10901 i = find_rhs_use(state, entry->member, ins);
10905 rinfo = arch_reg_rhs(state, entry->member, i);
10906 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10909 replace_rhs_use(state, ins, out, entry->member);
10911 transform_to_arch_instruction(state, out);
10915 static struct triple *pre_copy(
10916 struct compile_state *state, struct triple *ins, int index)
10918 /* Carefully insert enough operations so that I can
10919 * enter any operation with a GPR32.
10922 struct triple **expr;
10923 if (ins->op == OP_PHI) {
10924 internal_error(state, ins, "pre_copy on a phi?");
10926 expr = &RHS(ins, index);
10927 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10928 unuse_triple(*expr, ins);
10930 use_triple(RHS(in, 0), in);
10931 use_triple(in, ins);
10932 transform_to_arch_instruction(state, in);
10937 static void insert_copies_to_phi(struct compile_state *state)
10939 /* To get out of ssa form we insert moves on the incoming
10940 * edges to blocks containting phi functions.
10942 struct triple *first;
10943 struct triple *phi;
10945 /* Walk all of the operations to find the phi functions */
10946 first = RHS(state->main_function, 0);
10947 for(phi = first->next; phi != first ; phi = phi->next) {
10948 struct block_set *set;
10949 struct block *block;
10950 struct triple **slot;
10952 if (phi->op != OP_PHI) {
10955 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10956 block = phi->u.block;
10957 slot = &RHS(phi, 0);
10958 /* Walk all of the incoming edges/blocks and insert moves.
10960 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10961 struct block *eblock;
10962 struct triple *move;
10963 struct triple *val;
10964 struct triple *ptr;
10965 eblock = set->member;
10972 get_occurance(val->occurance);
10973 move = build_triple(state, OP_COPY, phi->type, val, 0,
10975 move->u.block = eblock;
10976 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10977 use_triple(val, move);
10980 unuse_triple(val, phi);
10981 use_triple(move, phi);
10983 /* Walk through the block backwards to find
10984 * an appropriate location for the OP_COPY.
10986 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10987 struct triple **expr;
10988 if ((ptr == phi) || (ptr == val)) {
10991 expr = triple_rhs(state, ptr, 0);
10992 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10993 if ((*expr) == phi) {
10999 if (triple_is_branch(state, ptr)) {
11000 internal_error(state, ptr,
11001 "Could not insert write to phi");
11003 insert_triple(state, ptr->next, move);
11004 if (eblock->last == ptr) {
11005 eblock->last = move;
11007 transform_to_arch_instruction(state, move);
11012 struct triple_reg_set {
11013 struct triple_reg_set *next;
11014 struct triple *member;
11015 struct triple *new;
11019 struct block *block;
11020 struct triple_reg_set *in;
11021 struct triple_reg_set *out;
11025 static int do_triple_set(struct triple_reg_set **head,
11026 struct triple *member, struct triple *new_member)
11028 struct triple_reg_set **ptr, *new;
11033 if ((*ptr)->member == member) {
11036 ptr = &(*ptr)->next;
11038 new = xcmalloc(sizeof(*new), "triple_set");
11039 new->member = member;
11040 new->new = new_member;
11046 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11048 struct triple_reg_set *entry, **ptr;
11052 if (entry->member == member) {
11053 *ptr = entry->next;
11058 ptr = &entry->next;
11063 static int in_triple(struct reg_block *rb, struct triple *in)
11065 return do_triple_set(&rb->in, in, 0);
11067 static void unin_triple(struct reg_block *rb, struct triple *unin)
11069 do_triple_unset(&rb->in, unin);
11072 static int out_triple(struct reg_block *rb, struct triple *out)
11074 return do_triple_set(&rb->out, out, 0);
11076 static void unout_triple(struct reg_block *rb, struct triple *unout)
11078 do_triple_unset(&rb->out, unout);
11081 static int initialize_regblock(struct reg_block *blocks,
11082 struct block *block, int vertex)
11084 struct block_set *user;
11085 if (!block || (blocks[block->vertex].block == block)) {
11089 /* Renumber the blocks in a convinient fashion */
11090 block->vertex = vertex;
11091 blocks[vertex].block = block;
11092 blocks[vertex].vertex = vertex;
11093 for(user = block->use; user; user = user->next) {
11094 vertex = initialize_regblock(blocks, user->member, vertex);
11099 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11100 struct reg_block *rb, struct block *suc)
11102 /* Read the conditional input set of a successor block
11103 * (i.e. the input to the phi nodes) and place it in the
11104 * current blocks output set.
11106 struct block_set *set;
11107 struct triple *ptr;
11111 /* Find the edge I am coming in on */
11112 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11113 if (set->member == rb->block) {
11118 internal_error(state, 0, "Not coming on a control edge?");
11120 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11121 struct triple **slot, *expr, *ptr2;
11122 int out_change, done2;
11123 done = (ptr == suc->last);
11124 if (ptr->op != OP_PHI) {
11127 slot = &RHS(ptr, 0);
11129 out_change = out_triple(rb, expr);
11133 /* If we don't define the variable also plast it
11134 * in the current blocks input set.
11136 ptr2 = rb->block->first;
11137 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11138 if (ptr2 == expr) {
11141 done2 = (ptr2 == rb->block->last);
11146 change |= in_triple(rb, expr);
11151 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11152 struct reg_block *rb, struct block *suc)
11154 struct triple_reg_set *in_set;
11157 /* Read the input set of a successor block
11158 * and place it in the current blocks output set.
11160 in_set = blocks[suc->vertex].in;
11161 for(; in_set; in_set = in_set->next) {
11162 int out_change, done;
11163 struct triple *first, *last, *ptr;
11164 out_change = out_triple(rb, in_set->member);
11168 /* If we don't define the variable also place it
11169 * in the current blocks input set.
11171 first = rb->block->first;
11172 last = rb->block->last;
11174 for(ptr = first; !done; ptr = ptr->next) {
11175 if (ptr == in_set->member) {
11178 done = (ptr == last);
11183 change |= in_triple(rb, in_set->member);
11185 change |= phi_in(state, blocks, rb, suc);
11190 static int use_in(struct compile_state *state, struct reg_block *rb)
11192 /* Find the variables we use but don't define and add
11193 * it to the current blocks input set.
11195 #warning "FIXME is this O(N^2) algorithm bad?"
11196 struct block *block;
11197 struct triple *ptr;
11202 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11203 struct triple **expr;
11204 done = (ptr == block->first);
11205 /* The variable a phi function uses depends on the
11206 * control flow, and is handled in phi_in, not
11209 if (ptr->op == OP_PHI) {
11212 expr = triple_rhs(state, ptr, 0);
11213 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11214 struct triple *rhs, *test;
11220 /* See if rhs is defined in this block */
11221 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11222 tdone = (test == block->first);
11228 /* If I still have a valid rhs add it to in */
11229 change |= in_triple(rb, rhs);
11235 static struct reg_block *compute_variable_lifetimes(
11236 struct compile_state *state)
11238 struct reg_block *blocks;
11241 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11242 initialize_regblock(blocks, state->last_block, 0);
11246 for(i = 1; i <= state->last_vertex; i++) {
11247 struct reg_block *rb;
11249 /* Add the left successor's input set to in */
11250 if (rb->block->left) {
11251 change |= reg_in(state, blocks, rb, rb->block->left);
11253 /* Add the right successor's input set to in */
11254 if ((rb->block->right) &&
11255 (rb->block->right != rb->block->left)) {
11256 change |= reg_in(state, blocks, rb, rb->block->right);
11258 /* Add use to in... */
11259 change |= use_in(state, rb);
11265 static void free_variable_lifetimes(
11266 struct compile_state *state, struct reg_block *blocks)
11269 /* free in_set && out_set on each block */
11270 for(i = 1; i <= state->last_vertex; i++) {
11271 struct triple_reg_set *entry, *next;
11272 struct reg_block *rb;
11274 for(entry = rb->in; entry ; entry = next) {
11275 next = entry->next;
11276 do_triple_unset(&rb->in, entry->member);
11278 for(entry = rb->out; entry; entry = next) {
11279 next = entry->next;
11280 do_triple_unset(&rb->out, entry->member);
11287 typedef void (*wvl_cb_t)(
11288 struct compile_state *state,
11289 struct reg_block *blocks, struct triple_reg_set *live,
11290 struct reg_block *rb, struct triple *ins, void *arg);
11292 static void walk_variable_lifetimes(struct compile_state *state,
11293 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11297 for(i = 1; i <= state->last_vertex; i++) {
11298 struct triple_reg_set *live;
11299 struct triple_reg_set *entry, *next;
11300 struct triple *ptr, *prev;
11301 struct reg_block *rb;
11302 struct block *block;
11305 /* Get the blocks */
11309 /* Copy out into live */
11311 for(entry = rb->out; entry; entry = next) {
11312 next = entry->next;
11313 do_triple_set(&live, entry->member, entry->new);
11315 /* Walk through the basic block calculating live */
11316 for(done = 0, ptr = block->last; !done; ptr = prev) {
11317 struct triple **expr;
11320 done = (ptr == block->first);
11322 /* Ensure the current definition is in live */
11323 if (triple_is_def(state, ptr)) {
11324 do_triple_set(&live, ptr, 0);
11327 /* Inform the callback function of what is
11330 cb(state, blocks, live, rb, ptr, arg);
11332 /* Remove the current definition from live */
11333 do_triple_unset(&live, ptr);
11335 /* Add the current uses to live.
11337 * It is safe to skip phi functions because they do
11338 * not have any block local uses, and the block
11339 * output sets already properly account for what
11340 * control flow depedent uses phi functions do have.
11342 if (ptr->op == OP_PHI) {
11345 expr = triple_rhs(state, ptr, 0);
11346 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11347 /* If the triple is not a definition skip it. */
11348 if (!*expr || !triple_is_def(state, *expr)) {
11351 do_triple_set(&live, *expr, 0);
11355 for(entry = live; entry; entry = next) {
11356 next = entry->next;
11357 do_triple_unset(&live, entry->member);
11362 static int count_triples(struct compile_state *state)
11364 struct triple *first, *ins;
11366 first = RHS(state->main_function, 0);
11371 } while (ins != first);
11374 struct dead_triple {
11375 struct triple *triple;
11376 struct dead_triple *work_next;
11377 struct block *block;
11380 #define TRIPLE_FLAG_ALIVE 1
11384 static void awaken(
11385 struct compile_state *state,
11386 struct dead_triple *dtriple, struct triple **expr,
11387 struct dead_triple ***work_list_tail)
11389 struct triple *triple;
11390 struct dead_triple *dt;
11398 if (triple->id <= 0) {
11399 internal_error(state, triple, "bad triple id: %d",
11402 if (triple->op == OP_NOOP) {
11403 internal_warning(state, triple, "awakening noop?");
11406 dt = &dtriple[triple->id];
11407 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11408 dt->flags |= TRIPLE_FLAG_ALIVE;
11409 if (!dt->work_next) {
11410 **work_list_tail = dt;
11411 *work_list_tail = &dt->work_next;
11416 static void eliminate_inefectual_code(struct compile_state *state)
11418 struct block *block;
11419 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11421 struct triple *first, *ins;
11423 /* Setup the work list */
11425 work_list_tail = &work_list;
11427 first = RHS(state->main_function, 0);
11429 /* Count how many triples I have */
11430 triples = count_triples(state);
11432 /* Now put then in an array and mark all of the triples dead */
11433 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11439 if (ins->op == OP_LABEL) {
11440 block = ins->u.block;
11442 dtriple[i].triple = ins;
11443 dtriple[i].block = block;
11444 dtriple[i].flags = 0;
11445 dtriple[i].color = ins->id;
11447 /* See if it is an operation we always keep */
11448 #warning "FIXME handle the case of killing a branch instruction"
11449 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11450 awaken(state, dtriple, &ins, &work_list_tail);
11454 } while(ins != first);
11456 struct dead_triple *dt;
11457 struct block_set *user;
11458 struct triple **expr;
11460 work_list = dt->work_next;
11462 work_list_tail = &work_list;
11464 /* Wake up the data depencencies of this triple */
11467 expr = triple_rhs(state, dt->triple, expr);
11468 awaken(state, dtriple, expr, &work_list_tail);
11471 expr = triple_lhs(state, dt->triple, expr);
11472 awaken(state, dtriple, expr, &work_list_tail);
11475 expr = triple_misc(state, dt->triple, expr);
11476 awaken(state, dtriple, expr, &work_list_tail);
11478 /* Wake up the forward control dependencies */
11480 expr = triple_targ(state, dt->triple, expr);
11481 awaken(state, dtriple, expr, &work_list_tail);
11483 /* Wake up the reverse control dependencies of this triple */
11484 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11485 awaken(state, dtriple, &user->member->last, &work_list_tail);
11488 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11489 if ((dt->triple->op == OP_NOOP) &&
11490 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11491 internal_error(state, dt->triple, "noop effective?");
11493 dt->triple->id = dt->color; /* Restore the color */
11494 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11495 #warning "FIXME handle the case of killing a basic block"
11496 if (dt->block->first == dt->triple) {
11499 if (dt->block->last == dt->triple) {
11500 dt->block->last = dt->triple->prev;
11502 release_triple(state, dt->triple);
11509 static void insert_mandatory_copies(struct compile_state *state)
11511 struct triple *ins, *first;
11513 /* The object is with a minimum of inserted copies,
11514 * to resolve in fundamental register conflicts between
11515 * register value producers and consumers.
11516 * Theoretically we may be greater than minimal when we
11517 * are inserting copies before instructions but that
11518 * case should be rare.
11520 first = RHS(state->main_function, 0);
11523 struct triple_set *entry, *next;
11524 struct triple *tmp;
11525 struct reg_info info;
11526 unsigned reg, regcm;
11527 int do_post_copy, do_pre_copy;
11529 if (!triple_is_def(state, ins)) {
11532 /* Find the architecture specific color information */
11533 info = arch_reg_lhs(state, ins, 0);
11534 if (info.reg >= MAX_REGISTERS) {
11535 info.reg = REG_UNSET;
11539 regcm = arch_type_to_regcm(state, ins->type);
11540 do_post_copy = do_pre_copy = 0;
11542 /* Walk through the uses of ins and check for conflicts */
11543 for(entry = ins->use; entry; entry = next) {
11544 struct reg_info rinfo;
11546 next = entry->next;
11547 i = find_rhs_use(state, entry->member, ins);
11552 /* Find the users color requirements */
11553 rinfo = arch_reg_rhs(state, entry->member, i);
11554 if (rinfo.reg >= MAX_REGISTERS) {
11555 rinfo.reg = REG_UNSET;
11558 /* See if I need a pre_copy */
11559 if (rinfo.reg != REG_UNSET) {
11560 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11565 regcm &= rinfo.regcm;
11566 regcm = arch_regcm_normalize(state, regcm);
11573 (((info.reg != REG_UNSET) &&
11574 (reg != REG_UNSET) &&
11575 (info.reg != reg)) ||
11576 ((info.regcm & regcm) == 0));
11579 regcm = info.regcm;
11580 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11581 for(entry = ins->use; entry; entry = next) {
11582 struct reg_info rinfo;
11584 next = entry->next;
11585 i = find_rhs_use(state, entry->member, ins);
11590 /* Find the users color requirements */
11591 rinfo = arch_reg_rhs(state, entry->member, i);
11592 if (rinfo.reg >= MAX_REGISTERS) {
11593 rinfo.reg = REG_UNSET;
11596 /* Now see if it is time to do the pre_copy */
11597 if (rinfo.reg != REG_UNSET) {
11598 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11599 ((regcm & rinfo.regcm) == 0) ||
11600 /* Don't let a mandatory coalesce sneak
11601 * into a operation that is marked to prevent
11604 ((reg != REG_UNNEEDED) &&
11605 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11606 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11609 struct triple *user;
11610 user = entry->member;
11611 if (RHS(user, i) != ins) {
11612 internal_error(state, user, "bad rhs");
11614 tmp = pre_copy(state, user, i);
11615 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11623 if ((regcm & rinfo.regcm) == 0) {
11625 struct triple *user;
11626 user = entry->member;
11627 if (RHS(user, i) != ins) {
11628 internal_error(state, user, "bad rhs");
11630 tmp = pre_copy(state, user, i);
11631 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11637 regcm &= rinfo.regcm;
11640 if (do_post_copy) {
11641 struct reg_info pre, post;
11642 tmp = post_copy(state, ins);
11643 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11644 pre = arch_reg_lhs(state, ins, 0);
11645 post = arch_reg_lhs(state, tmp, 0);
11646 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11647 internal_error(state, tmp, "useless copy");
11652 } while(ins != first);
11656 struct live_range_edge;
11657 struct live_range_def;
11658 struct live_range {
11659 struct live_range_edge *edges;
11660 struct live_range_def *defs;
11661 /* Note. The list pointed to by defs is kept in order.
11662 * That is baring splits in the flow control
11663 * defs dominates defs->next wich dominates defs->next->next
11670 struct live_range *group_next, **group_prev;
11673 struct live_range_edge {
11674 struct live_range_edge *next;
11675 struct live_range *node;
11678 struct live_range_def {
11679 struct live_range_def *next;
11680 struct live_range_def *prev;
11681 struct live_range *lr;
11682 struct triple *def;
11686 #define LRE_HASH_SIZE 2048
11688 struct lre_hash *next;
11689 struct live_range *left;
11690 struct live_range *right;
11695 struct lre_hash *hash[LRE_HASH_SIZE];
11696 struct reg_block *blocks;
11697 struct live_range_def *lrd;
11698 struct live_range *lr;
11699 struct live_range *low, **low_tail;
11700 struct live_range *high, **high_tail;
11703 int passes, max_passes;
11704 #define MAX_ALLOCATION_PASSES 100
11708 static unsigned regc_max_size(struct compile_state *state, int classes)
11713 for(i = 0; i < MAX_REGC; i++) {
11714 if (classes & (1 << i)) {
11716 size = arch_regc_size(state, i);
11717 if (size > max_size) {
11725 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11727 unsigned equivs[MAX_REG_EQUIVS];
11729 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11730 internal_error(state, 0, "invalid register");
11732 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11733 internal_error(state, 0, "invalid register");
11735 arch_reg_equivs(state, equivs, reg1);
11736 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11737 if (equivs[i] == reg2) {
11744 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11746 unsigned equivs[MAX_REG_EQUIVS];
11748 if (reg == REG_UNNEEDED) {
11751 arch_reg_equivs(state, equivs, reg);
11752 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11753 used[equivs[i]] = 1;
11758 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11760 unsigned equivs[MAX_REG_EQUIVS];
11762 if (reg == REG_UNNEEDED) {
11765 arch_reg_equivs(state, equivs, reg);
11766 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11767 used[equivs[i]] += 1;
11772 static unsigned int hash_live_edge(
11773 struct live_range *left, struct live_range *right)
11775 unsigned int hash, val;
11776 unsigned long lval, rval;
11777 lval = ((unsigned long)left)/sizeof(struct live_range);
11778 rval = ((unsigned long)right)/sizeof(struct live_range);
11783 hash = (hash *263) + val;
11788 hash = (hash *263) + val;
11790 hash = hash & (LRE_HASH_SIZE - 1);
11794 static struct lre_hash **lre_probe(struct reg_state *rstate,
11795 struct live_range *left, struct live_range *right)
11797 struct lre_hash **ptr;
11798 unsigned int index;
11799 /* Ensure left <= right */
11800 if (left > right) {
11801 struct live_range *tmp;
11806 index = hash_live_edge(left, right);
11808 ptr = &rstate->hash[index];
11810 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
11813 ptr = &(*ptr)->next;
11818 static int interfere(struct reg_state *rstate,
11819 struct live_range *left, struct live_range *right)
11821 struct lre_hash **ptr;
11822 ptr = lre_probe(rstate, left, right);
11823 return ptr && *ptr;
11826 static void add_live_edge(struct reg_state *rstate,
11827 struct live_range *left, struct live_range *right)
11829 /* FIXME the memory allocation overhead is noticeable here... */
11830 struct lre_hash **ptr, *new_hash;
11831 struct live_range_edge *edge;
11833 if (left == right) {
11836 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11839 /* Ensure left <= right */
11840 if (left > right) {
11841 struct live_range *tmp;
11846 ptr = lre_probe(rstate, left, right);
11851 fprintf(stderr, "new_live_edge(%p, %p)\n",
11854 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11855 new_hash->next = *ptr;
11856 new_hash->left = left;
11857 new_hash->right = right;
11860 edge = xmalloc(sizeof(*edge), "live_range_edge");
11861 edge->next = left->edges;
11862 edge->node = right;
11863 left->edges = edge;
11866 edge = xmalloc(sizeof(*edge), "live_range_edge");
11867 edge->next = right->edges;
11869 right->edges = edge;
11870 right->degree += 1;
11873 static void remove_live_edge(struct reg_state *rstate,
11874 struct live_range *left, struct live_range *right)
11876 struct live_range_edge *edge, **ptr;
11877 struct lre_hash **hptr, *entry;
11878 hptr = lre_probe(rstate, left, right);
11879 if (!hptr || !*hptr) {
11883 *hptr = entry->next;
11886 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11888 if (edge->node == right) {
11890 memset(edge, 0, sizeof(*edge));
11896 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11898 if (edge->node == left) {
11900 memset(edge, 0, sizeof(*edge));
11908 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11910 struct live_range_edge *edge, *next;
11911 for(edge = range->edges; edge; edge = next) {
11913 remove_live_edge(rstate, range, edge->node);
11917 static void transfer_live_edges(struct reg_state *rstate,
11918 struct live_range *dest, struct live_range *src)
11920 struct live_range_edge *edge, *next;
11921 for(edge = src->edges; edge; edge = next) {
11922 struct live_range *other;
11924 other = edge->node;
11925 remove_live_edge(rstate, src, other);
11926 add_live_edge(rstate, dest, other);
11931 /* Interference graph...
11933 * new(n) --- Return a graph with n nodes but no edges.
11934 * add(g,x,y) --- Return a graph including g with an between x and y
11935 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11936 * x and y in the graph g
11937 * degree(g, x) --- Return the degree of the node x in the graph g
11938 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11940 * Implement with a hash table && a set of adjcency vectors.
11941 * The hash table supports constant time implementations of add and interfere.
11942 * The adjacency vectors support an efficient implementation of neighbors.
11946 * +---------------------------------------------------+
11947 * | +--------------+ |
11949 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11951 * -- In simplify implment optimistic coloring... (No backtracking)
11952 * -- Implement Rematerialization it is the only form of spilling we can perform
11953 * Essentially this means dropping a constant from a register because
11954 * we can regenerate it later.
11956 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11957 * coalesce at phi points...
11958 * --- Bias coloring if at all possible do the coalesing a compile time.
11963 static void different_colored(
11964 struct compile_state *state, struct reg_state *rstate,
11965 struct triple *parent, struct triple *ins)
11967 struct live_range *lr;
11968 struct triple **expr;
11969 lr = rstate->lrd[ins->id].lr;
11970 expr = triple_rhs(state, ins, 0);
11971 for(;expr; expr = triple_rhs(state, ins, expr)) {
11972 struct live_range *lr2;
11973 if (!*expr || (*expr == parent) || (*expr == ins)) {
11976 lr2 = rstate->lrd[(*expr)->id].lr;
11977 if (lr->color == lr2->color) {
11978 internal_error(state, ins, "live range too big");
11984 static struct live_range *coalesce_ranges(
11985 struct compile_state *state, struct reg_state *rstate,
11986 struct live_range *lr1, struct live_range *lr2)
11988 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11994 if (!lr1->defs || !lr2->defs) {
11995 internal_error(state, 0,
11996 "cannot coalese dead live ranges");
11998 if ((lr1->color == REG_UNNEEDED) ||
11999 (lr2->color == REG_UNNEEDED)) {
12000 internal_error(state, 0,
12001 "cannot coalesce live ranges without a possible color");
12003 if ((lr1->color != lr2->color) &&
12004 (lr1->color != REG_UNSET) &&
12005 (lr2->color != REG_UNSET)) {
12006 internal_error(state, lr1->defs->def,
12007 "cannot coalesce live ranges of different colors");
12009 color = lr1->color;
12010 if (color == REG_UNSET) {
12011 color = lr2->color;
12013 classes = lr1->classes & lr2->classes;
12015 internal_error(state, lr1->defs->def,
12016 "cannot coalesce live ranges with dissimilar register classes");
12018 /* If there is a clear dominate live range put it in lr1,
12019 * For purposes of this test phi functions are
12020 * considered dominated by the definitions that feed into
12023 if ((lr1->defs->prev->def->op == OP_PHI) ||
12024 ((lr2->defs->prev->def->op != OP_PHI) &&
12025 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12026 struct live_range *tmp;
12032 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12033 fprintf(stderr, "lr1 post\n");
12035 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12036 fprintf(stderr, "lr1 pre\n");
12038 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12039 fprintf(stderr, "lr2 post\n");
12041 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12042 fprintf(stderr, "lr2 pre\n");
12046 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12053 lr1->classes = classes;
12054 /* Append lr2 onto lr1 */
12055 #warning "FIXME should this be a merge instead of a splice?"
12056 /* This FIXME item applies to the correctness of live_range_end
12057 * and to the necessity of making multiple passes of coalesce_live_ranges.
12058 * A failure to find some coalesce opportunities in coaleace_live_ranges
12059 * does not impact the correct of the compiler just the efficiency with
12060 * which registers are allocated.
12063 mid1 = lr1->defs->prev;
12065 end = lr2->defs->prev;
12073 /* Fixup the live range in the added live range defs */
12078 } while(lrd != head);
12080 /* Mark lr2 as free. */
12082 lr2->color = REG_UNNEEDED;
12086 internal_error(state, 0, "lr1->defs == 0 ?");
12089 lr1->color = color;
12090 lr1->classes = classes;
12092 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12093 transfer_live_edges(rstate, lr1, lr2);
12098 static struct live_range_def *live_range_head(
12099 struct compile_state *state, struct live_range *lr,
12100 struct live_range_def *last)
12102 struct live_range_def *result;
12107 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12108 result = last->next;
12113 static struct live_range_def *live_range_end(
12114 struct compile_state *state, struct live_range *lr,
12115 struct live_range_def *last)
12117 struct live_range_def *result;
12120 result = lr->defs->prev;
12122 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12123 result = last->prev;
12129 static void initialize_live_ranges(
12130 struct compile_state *state, struct reg_state *rstate)
12132 struct triple *ins, *first;
12133 size_t count, size;
12136 first = RHS(state->main_function, 0);
12137 /* First count how many instructions I have.
12139 count = count_triples(state);
12140 /* Potentially I need one live range definitions for each
12141 * instruction, plus an extra for the split routines.
12143 rstate->defs = count + 1;
12144 /* Potentially I need one live range for each instruction
12145 * plus an extra for the dummy live range.
12147 rstate->ranges = count + 1;
12148 size = sizeof(rstate->lrd[0]) * rstate->defs;
12149 rstate->lrd = xcmalloc(size, "live_range_def");
12150 size = sizeof(rstate->lr[0]) * rstate->ranges;
12151 rstate->lr = xcmalloc(size, "live_range");
12153 /* Setup the dummy live range */
12154 rstate->lr[0].classes = 0;
12155 rstate->lr[0].color = REG_UNSET;
12156 rstate->lr[0].defs = 0;
12160 /* If the triple is a variable give it a live range */
12161 if (triple_is_def(state, ins)) {
12162 struct reg_info info;
12163 /* Find the architecture specific color information */
12164 info = find_def_color(state, ins);
12167 rstate->lr[i].defs = &rstate->lrd[j];
12168 rstate->lr[i].color = info.reg;
12169 rstate->lr[i].classes = info.regcm;
12170 rstate->lr[i].degree = 0;
12171 rstate->lrd[j].lr = &rstate->lr[i];
12173 /* Otherwise give the triple the dummy live range. */
12175 rstate->lrd[j].lr = &rstate->lr[0];
12178 /* Initalize the live_range_def */
12179 rstate->lrd[j].next = &rstate->lrd[j];
12180 rstate->lrd[j].prev = &rstate->lrd[j];
12181 rstate->lrd[j].def = ins;
12182 rstate->lrd[j].orig_id = ins->id;
12187 } while(ins != first);
12188 rstate->ranges = i;
12191 /* Make a second pass to handle achitecture specific register
12196 int zlhs, zrhs, i, j;
12197 if (ins->id > rstate->defs) {
12198 internal_error(state, ins, "bad id");
12201 /* Walk through the template of ins and coalesce live ranges */
12202 zlhs = TRIPLE_LHS(ins->sizes);
12203 if ((zlhs == 0) && triple_is_def(state, ins)) {
12206 zrhs = TRIPLE_RHS(ins->sizes);
12208 for(i = 0; i < zlhs; i++) {
12209 struct reg_info linfo;
12210 struct live_range_def *lhs;
12211 linfo = arch_reg_lhs(state, ins, i);
12212 if (linfo.reg < MAX_REGISTERS) {
12215 if (triple_is_def(state, ins)) {
12216 lhs = &rstate->lrd[ins->id];
12218 lhs = &rstate->lrd[LHS(ins, i)->id];
12220 for(j = 0; j < zrhs; j++) {
12221 struct reg_info rinfo;
12222 struct live_range_def *rhs;
12223 rinfo = arch_reg_rhs(state, ins, j);
12224 if (rinfo.reg < MAX_REGISTERS) {
12227 rhs = &rstate->lrd[RHS(ins, i)->id];
12228 if (rinfo.reg == linfo.reg) {
12229 coalesce_ranges(state, rstate,
12235 } while(ins != first);
12238 static void graph_ins(
12239 struct compile_state *state,
12240 struct reg_block *blocks, struct triple_reg_set *live,
12241 struct reg_block *rb, struct triple *ins, void *arg)
12243 struct reg_state *rstate = arg;
12244 struct live_range *def;
12245 struct triple_reg_set *entry;
12247 /* If the triple is not a definition
12248 * we do not have a definition to add to
12249 * the interference graph.
12251 if (!triple_is_def(state, ins)) {
12254 def = rstate->lrd[ins->id].lr;
12256 /* Create an edge between ins and everything that is
12257 * alive, unless the live_range cannot share
12258 * a physical register with ins.
12260 for(entry = live; entry; entry = entry->next) {
12261 struct live_range *lr;
12262 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12263 internal_error(state, 0, "bad entry?");
12265 lr = rstate->lrd[entry->member->id].lr;
12269 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12272 add_live_edge(rstate, def, lr);
12277 static struct live_range *get_verify_live_range(
12278 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12280 struct live_range *lr;
12281 struct live_range_def *lrd;
12283 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12284 internal_error(state, ins, "bad ins?");
12286 lr = rstate->lrd[ins->id].lr;
12290 if (lrd->def == ins) {
12294 } while(lrd != lr->defs);
12296 internal_error(state, ins, "ins not in live range");
12301 static void verify_graph_ins(
12302 struct compile_state *state,
12303 struct reg_block *blocks, struct triple_reg_set *live,
12304 struct reg_block *rb, struct triple *ins, void *arg)
12306 struct reg_state *rstate = arg;
12307 struct triple_reg_set *entry1, *entry2;
12310 /* Compare live against edges and make certain the code is working */
12311 for(entry1 = live; entry1; entry1 = entry1->next) {
12312 struct live_range *lr1;
12313 lr1 = get_verify_live_range(state, rstate, entry1->member);
12314 for(entry2 = live; entry2; entry2 = entry2->next) {
12315 struct live_range *lr2;
12316 struct live_range_edge *edge2;
12319 if (entry2 == entry1) {
12322 lr2 = get_verify_live_range(state, rstate, entry2->member);
12324 internal_error(state, entry2->member,
12325 "live range with 2 values simultaneously alive");
12327 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12330 if (!interfere(rstate, lr1, lr2)) {
12331 internal_error(state, entry2->member,
12332 "edges don't interfere?");
12337 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12339 if (edge2->node == lr1) {
12343 if (lr2_degree != lr2->degree) {
12344 internal_error(state, entry2->member,
12345 "computed degree: %d does not match reported degree: %d\n",
12346 lr2_degree, lr2->degree);
12349 internal_error(state, entry2->member, "missing edge");
12357 static void print_interference_ins(
12358 struct compile_state *state,
12359 struct reg_block *blocks, struct triple_reg_set *live,
12360 struct reg_block *rb, struct triple *ins, void *arg)
12362 struct reg_state *rstate = arg;
12363 struct live_range *lr;
12366 lr = rstate->lrd[ins->id].lr;
12368 ins->id = rstate->lrd[id].orig_id;
12369 SET_REG(ins->id, lr->color);
12370 display_triple(stdout, ins);
12374 struct live_range_def *lrd;
12378 printf(" %-10p", lrd->def);
12380 } while(lrd != lr->defs);
12384 struct triple_reg_set *entry;
12386 for(entry = live; entry; entry = entry->next) {
12387 printf(" %-10p", entry->member);
12392 struct live_range_edge *entry;
12394 for(entry = lr->edges; entry; entry = entry->next) {
12395 struct live_range_def *lrd;
12396 lrd = entry->node->defs;
12398 printf(" %-10p", lrd->def);
12400 } while(lrd != entry->node->defs);
12405 if (triple_is_branch(state, ins)) {
12411 static int coalesce_live_ranges(
12412 struct compile_state *state, struct reg_state *rstate)
12414 /* At the point where a value is moved from one
12415 * register to another that value requires two
12416 * registers, thus increasing register pressure.
12417 * Live range coaleescing reduces the register
12418 * pressure by keeping a value in one register
12421 * In the case of a phi function all paths leading
12422 * into it must be allocated to the same register
12423 * otherwise the phi function may not be removed.
12425 * Forcing a value to stay in a single register
12426 * for an extended period of time does have
12427 * limitations when applied to non homogenous
12430 * The two cases I have identified are:
12431 * 1) Two forced register assignments may
12433 * 2) Registers may go unused because they
12434 * are only good for storing the value
12435 * and not manipulating it.
12437 * Because of this I need to split live ranges,
12438 * even outside of the context of coalesced live
12439 * ranges. The need to split live ranges does
12440 * impose some constraints on live range coalescing.
12442 * - Live ranges may not be coalesced across phi
12443 * functions. This creates a 2 headed live
12444 * range that cannot be sanely split.
12446 * - phi functions (coalesced in initialize_live_ranges)
12447 * are handled as pre split live ranges so we will
12448 * never attempt to split them.
12454 for(i = 0; i <= rstate->ranges; i++) {
12455 struct live_range *lr1;
12456 struct live_range_def *lrd1;
12457 lr1 = &rstate->lr[i];
12461 lrd1 = live_range_end(state, lr1, 0);
12462 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12463 struct triple_set *set;
12464 if (lrd1->def->op != OP_COPY) {
12467 /* Skip copies that are the result of a live range split. */
12468 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12471 for(set = lrd1->def->use; set; set = set->next) {
12472 struct live_range_def *lrd2;
12473 struct live_range *lr2, *res;
12475 lrd2 = &rstate->lrd[set->member->id];
12477 /* Don't coalesce with instructions
12478 * that are the result of a live range
12481 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12484 lr2 = rstate->lrd[set->member->id].lr;
12488 if ((lr1->color != lr2->color) &&
12489 (lr1->color != REG_UNSET) &&
12490 (lr2->color != REG_UNSET)) {
12493 if ((lr1->classes & lr2->classes) == 0) {
12497 if (interfere(rstate, lr1, lr2)) {
12501 res = coalesce_ranges(state, rstate, lr1, lr2);
12515 static void fix_coalesce_conflicts(struct compile_state *state,
12516 struct reg_block *blocks, struct triple_reg_set *live,
12517 struct reg_block *rb, struct triple *ins, void *arg)
12519 int zlhs, zrhs, i, j;
12521 /* See if we have a mandatory coalesce operation between
12522 * a lhs and a rhs value. If so and the rhs value is also
12523 * alive then this triple needs to be pre copied. Otherwise
12524 * we would have two definitions in the same live range simultaneously
12527 zlhs = TRIPLE_LHS(ins->sizes);
12528 if ((zlhs == 0) && triple_is_def(state, ins)) {
12531 zrhs = TRIPLE_RHS(ins->sizes);
12532 for(i = 0; i < zlhs; i++) {
12533 struct reg_info linfo;
12534 linfo = arch_reg_lhs(state, ins, i);
12535 if (linfo.reg < MAX_REGISTERS) {
12538 for(j = 0; j < zrhs; j++) {
12539 struct reg_info rinfo;
12540 struct triple *rhs;
12541 struct triple_reg_set *set;
12544 rinfo = arch_reg_rhs(state, ins, j);
12545 if (rinfo.reg != linfo.reg) {
12549 for(set = live; set && !found; set = set->next) {
12550 if (set->member == rhs) {
12555 struct triple *copy;
12556 copy = pre_copy(state, ins, j);
12557 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12564 static void replace_set_use(struct compile_state *state,
12565 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12567 struct triple_reg_set *set;
12568 for(set = head; set; set = set->next) {
12569 if (set->member == orig) {
12575 static void replace_block_use(struct compile_state *state,
12576 struct reg_block *blocks, struct triple *orig, struct triple *new)
12579 #warning "WISHLIST visit just those blocks that need it *"
12580 for(i = 1; i <= state->last_vertex; i++) {
12581 struct reg_block *rb;
12583 replace_set_use(state, rb->in, orig, new);
12584 replace_set_use(state, rb->out, orig, new);
12588 static void color_instructions(struct compile_state *state)
12590 struct triple *ins, *first;
12591 first = RHS(state->main_function, 0);
12594 if (triple_is_def(state, ins)) {
12595 struct reg_info info;
12596 info = find_lhs_color(state, ins, 0);
12597 if (info.reg >= MAX_REGISTERS) {
12598 info.reg = REG_UNSET;
12600 SET_INFO(ins->id, info);
12603 } while(ins != first);
12606 static struct reg_info read_lhs_color(
12607 struct compile_state *state, struct triple *ins, int index)
12609 struct reg_info info;
12610 if ((index == 0) && triple_is_def(state, ins)) {
12611 info.reg = ID_REG(ins->id);
12612 info.regcm = ID_REGCM(ins->id);
12614 else if (index < TRIPLE_LHS(ins->sizes)) {
12615 info = read_lhs_color(state, LHS(ins, index), 0);
12618 internal_error(state, ins, "Bad lhs %d", index);
12619 info.reg = REG_UNSET;
12625 static struct triple *resolve_tangle(
12626 struct compile_state *state, struct triple *tangle)
12628 struct reg_info info, uinfo;
12629 struct triple_set *set, *next;
12630 struct triple *copy;
12632 #warning "WISHLIST recalculate all affected instructions colors"
12633 info = find_lhs_color(state, tangle, 0);
12634 for(set = tangle->use; set; set = next) {
12635 struct triple *user;
12638 user = set->member;
12639 zrhs = TRIPLE_RHS(user->sizes);
12640 for(i = 0; i < zrhs; i++) {
12641 if (RHS(user, i) != tangle) {
12644 uinfo = find_rhs_post_color(state, user, i);
12645 if (uinfo.reg == info.reg) {
12646 copy = pre_copy(state, user, i);
12647 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12648 SET_INFO(copy->id, uinfo);
12653 uinfo = find_lhs_pre_color(state, tangle, 0);
12654 if (uinfo.reg == info.reg) {
12655 struct reg_info linfo;
12656 copy = post_copy(state, tangle);
12657 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12658 linfo = find_lhs_color(state, copy, 0);
12659 SET_INFO(copy->id, linfo);
12661 info = find_lhs_color(state, tangle, 0);
12662 SET_INFO(tangle->id, info);
12668 static void fix_tangles(struct compile_state *state,
12669 struct reg_block *blocks, struct triple_reg_set *live,
12670 struct reg_block *rb, struct triple *ins, void *arg)
12672 int *tangles = arg;
12673 struct triple *tangle;
12675 char used[MAX_REGISTERS];
12676 struct triple_reg_set *set;
12679 /* Find out which registers have multiple uses at this point */
12680 memset(used, 0, sizeof(used));
12681 for(set = live; set; set = set->next) {
12682 struct reg_info info;
12683 info = read_lhs_color(state, set->member, 0);
12684 if (info.reg == REG_UNSET) {
12687 reg_inc_used(state, used, info.reg);
12690 /* Now find the least dominated definition of a register in
12691 * conflict I have seen so far.
12693 for(set = live; set; set = set->next) {
12694 struct reg_info info;
12695 info = read_lhs_color(state, set->member, 0);
12696 if (used[info.reg] < 2) {
12699 /* Changing copies that feed into phi functions
12702 if (set->member->use &&
12703 (set->member->use->member->op == OP_PHI)) {
12706 if (!tangle || tdominates(state, set->member, tangle)) {
12707 tangle = set->member;
12710 /* If I have found a tangle resolve it */
12712 struct triple *post_copy;
12714 post_copy = resolve_tangle(state, tangle);
12716 replace_block_use(state, blocks, tangle, post_copy);
12718 if (post_copy && (tangle != ins)) {
12719 replace_set_use(state, live, tangle, post_copy);
12726 static int correct_tangles(
12727 struct compile_state *state, struct reg_block *blocks)
12731 color_instructions(state);
12732 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
12736 struct least_conflict {
12737 struct reg_state *rstate;
12738 struct live_range *ref_range;
12739 struct triple *ins;
12740 struct triple_reg_set *live;
12744 static void least_conflict(struct compile_state *state,
12745 struct reg_block *blocks, struct triple_reg_set *live,
12746 struct reg_block *rb, struct triple *ins, void *arg)
12748 struct least_conflict *conflict = arg;
12749 struct live_range_edge *edge;
12750 struct triple_reg_set *set;
12754 #warning "FIXME handle instructions with left hand sides..."
12755 /* Only instructions that introduce a new definition
12756 * can be the conflict instruction.
12758 if (!triple_is_def(state, ins)) {
12762 /* See if live ranges at this instruction are a
12763 * strict subset of the live ranges that are in conflict.
12766 for(set = live; set; set = set->next) {
12767 struct live_range *lr;
12768 lr = conflict->rstate->lrd[set->member->id].lr;
12769 /* Ignore it if there cannot be an edge between these two nodes */
12770 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12773 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12774 if (edge->node == lr) {
12778 if (!edge && (lr != conflict->ref_range)) {
12788 /* See if there is an uncolored member in this subset.
12790 for(set = live; set; set = set->next) {
12791 struct live_range *lr;
12792 lr = conflict->rstate->lrd[set->member->id].lr;
12793 if (lr->color == REG_UNSET) {
12797 if (!set && (conflict->ref_range != REG_UNSET)) {
12802 /* See if any of the live registers are constrained,
12803 * if not it won't be productive to pick this as
12804 * a conflict instruction.
12807 for(set = live; set; set = set->next) {
12808 struct triple_set *uset;
12809 struct reg_info info;
12811 unsigned cur_size, size;
12812 /* Skip this instruction */
12813 if (set->member == ins) {
12816 /* Find how many registers this value can potentially
12819 classes = arch_type_to_regcm(state, set->member->type);
12820 size = regc_max_size(state, classes);
12822 /* Find how many registers we allow this value to
12825 info = arch_reg_lhs(state, set->member, 0);
12827 /* If the value does not live in a register it
12828 * isn't constrained.
12830 if (info.reg == REG_UNNEEDED) {
12834 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12835 cur_size = regc_max_size(state, info.regcm);
12840 /* If there is no difference between potential and
12841 * actual register count there is not a constraint
12843 if (cur_size >= size) {
12847 /* If this live_range feeds into conflict->inds
12848 * it isn't a constraint we can relieve.
12850 for(uset = set->member->use; uset; uset = uset->next) {
12851 if (uset->member == ins) {
12861 /* Don't drop canidates with constraints */
12862 if (conflict->constraints && !constraints) {
12868 fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12869 ins, tops(ins->op), count, constraints);
12871 /* Find the instruction with the largest possible subset of
12872 * conflict ranges and that dominates any other instruction
12873 * with an equal sized set of conflicting ranges.
12875 if ((count > conflict->count) ||
12876 ((count == conflict->count) &&
12877 tdominates(state, ins, conflict->ins))) {
12878 struct triple_reg_set *next;
12879 /* Remember the canidate instruction */
12880 conflict->ins = ins;
12881 conflict->count = count;
12882 conflict->constraints = constraints;
12883 /* Free the old collection of live registers */
12884 for(set = conflict->live; set; set = next) {
12886 do_triple_unset(&conflict->live, set->member);
12888 conflict->live = 0;
12889 /* Rember the registers that are alive but do not feed
12890 * into or out of conflict->ins.
12892 for(set = live; set; set = set->next) {
12893 struct triple **expr;
12894 if (set->member == ins) {
12897 expr = triple_rhs(state, ins, 0);
12898 for(;expr; expr = triple_rhs(state, ins, expr)) {
12899 if (*expr == set->member) {
12903 expr = triple_lhs(state, ins, 0);
12904 for(; expr; expr = triple_lhs(state, ins, expr)) {
12905 if (*expr == set->member) {
12909 do_triple_set(&conflict->live, set->member, set->new);
12917 static void find_range_conflict(struct compile_state *state,
12918 struct reg_state *rstate, char *used, struct live_range *ref_range,
12919 struct least_conflict *conflict)
12922 /* there are 3 kinds ways conflicts can occure.
12923 * 1) the life time of 2 values simply overlap.
12924 * 2) the 2 values feed into the same instruction.
12925 * 3) the 2 values feed into a phi function.
12928 /* find the instruction where the problematic conflict comes
12929 * into existance. that the instruction where all of
12930 * the values are alive, and among such instructions it is
12931 * the least dominated one.
12933 * a value is alive an an instruction if either;
12934 * 1) the value defintion dominates the instruction and there
12935 * is a use at or after that instrction
12936 * 2) the value definition feeds into a phi function in the
12937 * same block as the instruction. and the phi function
12938 * is at or after the instruction.
12940 memset(conflict, 0, sizeof(*conflict));
12941 conflict->rstate = rstate;
12942 conflict->ref_range = ref_range;
12944 conflict->live = 0;
12945 conflict->count = 0;
12946 conflict->constraints = 0;
12947 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12949 if (!conflict->ins) {
12950 internal_error(state, ref_range->defs->def, "No conflict ins?");
12952 if (!conflict->live) {
12953 internal_error(state, ref_range->defs->def, "No conflict live?");
12956 fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n",
12957 conflict->ins, tops(conflict->ins->op),
12958 conflict->count, conflict->constraints);
12963 static struct triple *split_constrained_range(struct compile_state *state,
12964 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12966 unsigned constrained_size;
12967 struct triple *new, *constrained;
12968 struct triple_reg_set *cset;
12969 /* Find a range that is having problems because it is
12970 * artificially constrained.
12972 constrained_size = ~0;
12975 for(cset = conflict->live; cset; cset = cset->next) {
12976 struct triple_set *set;
12977 struct reg_info info;
12979 unsigned cur_size, size;
12980 /* Skip the live range that starts with conflict->ins */
12981 if (cset->member == conflict->ins) {
12984 /* Find how many registers this value can potentially
12987 classes = arch_type_to_regcm(state, cset->member->type);
12988 size = regc_max_size(state, classes);
12990 /* Find how many registers we allow this value to
12993 info = arch_reg_lhs(state, cset->member, 0);
12995 /* If the register doesn't need a register
12996 * splitting it can't help.
12998 if (info.reg == REG_UNNEEDED) {
13001 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
13002 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
13003 cur_size = regc_max_size(state, info.regcm);
13007 /* If this live_range feeds into conflict->ins
13008 * splitting it is unlikely to help.
13010 for(set = cset->member->use; set; set = set->next) {
13011 if (set->member == conflict->ins) {
13016 /* If there is no difference between potential and
13017 * actual register count there is nothing to do.
13019 if (cur_size >= size) {
13022 /* Of the constrained registers deal with the
13023 * most constrained one first.
13025 if (!constrained ||
13026 (size < constrained_size)) {
13027 constrained = cset->member;
13028 constrained_size = size;
13034 new = post_copy(state, constrained);
13035 new->id |= TRIPLE_FLAG_POST_SPLIT;
13040 static int split_ranges(
13041 struct compile_state *state, struct reg_state *rstate,
13042 char *used, struct live_range *range)
13044 struct triple *new;
13047 fprintf(stderr, "split_ranges %d %s %p\n",
13048 rstate->passes, tops(range->defs->def->op), range->defs->def);
13050 if ((range->color == REG_UNNEEDED) ||
13051 (rstate->passes >= rstate->max_passes)) {
13055 /* If I can't allocate a register something needs to be split */
13056 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
13057 struct least_conflict conflict;
13060 fprintf(stderr, "find_range_conflict\n");
13062 /* Find where in the set of registers the conflict
13065 find_range_conflict(state, rstate, used, range, &conflict);
13067 /* If a range has been artifically constrained split it */
13068 new = split_constrained_range(state, rstate, used, &conflict);
13071 /* Ideally I would split the live range that will not be used
13072 * for the longest period of time in hopes that this will
13073 * (a) allow me to spill a register or
13074 * (b) allow me to place a value in another register.
13076 * So far I don't have a test case for this, the resolving
13077 * of mandatory constraints has solved all of my
13078 * know issues. So I have choosen not to write any
13079 * code until I cat get a better feel for cases where
13080 * it would be useful to have.
13083 #warning "WISHLIST implement live range splitting..."
13085 print_blocks(state, stderr);
13086 print_dominators(state, stderr);
13093 rstate->lrd[rstate->defs].orig_id = new->id;
13094 new->id = rstate->defs;
13097 fprintf(stderr, "new: %p old: %s %p\n",
13098 new, tops(RHS(new, 0)->op), RHS(new, 0));
13101 print_blocks(state, stderr);
13102 print_dominators(state, stderr);
13110 #if DEBUG_COLOR_GRAPH > 1
13111 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13112 #define cgdebug_flush() fflush(stdout)
13113 #elif DEBUG_COLOR_GRAPH == 1
13114 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13115 #define cgdebug_flush() fflush(stderr)
13117 #define cgdebug_printf(...)
13118 #define cgdebug_flush()
13122 static int select_free_color(struct compile_state *state,
13123 struct reg_state *rstate, struct live_range *range)
13125 struct triple_set *entry;
13126 struct live_range_def *lrd;
13127 struct live_range_def *phi;
13128 struct live_range_edge *edge;
13129 char used[MAX_REGISTERS];
13130 struct triple **expr;
13132 /* Instead of doing just the trivial color select here I try
13133 * a few extra things because a good color selection will help reduce
13137 /* Find the registers currently in use */
13138 memset(used, 0, sizeof(used));
13139 for(edge = range->edges; edge; edge = edge->next) {
13140 if (edge->node->color == REG_UNSET) {
13143 reg_fill_used(state, used, edge->node->color);
13145 #if DEBUG_COLOR_GRAPH > 1
13149 for(edge = range->edges; edge; edge = edge->next) {
13152 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13153 tops(range->def->op), i,
13154 range->def->filename, range->def->line, range->def->col);
13155 for(i = 0; i < MAX_REGISTERS; i++) {
13157 cgdebug_printf("used: %s\n",
13164 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13166 /* If a color is already assigned see if it will work */
13167 if (range->color != REG_UNSET) {
13168 struct live_range_def *lrd;
13169 if (!used[range->color]) {
13172 for(edge = range->edges; edge; edge = edge->next) {
13173 if (edge->node->color != range->color) {
13176 warning(state, edge->node->defs->def, "edge: ");
13177 lrd = edge->node->defs;
13179 warning(state, lrd->def, " %p %s",
13180 lrd->def, tops(lrd->def->op));
13182 } while(lrd != edge->node->defs);
13185 warning(state, range->defs->def, "def: ");
13187 warning(state, lrd->def, " %p %s",
13188 lrd->def, tops(lrd->def->op));
13190 } while(lrd != range->defs);
13191 internal_error(state, range->defs->def,
13192 "live range with already used color %s",
13193 arch_reg_str(range->color));
13196 /* If I feed into an expression reuse it's color.
13197 * This should help remove copies in the case of 2 register instructions
13198 * and phi functions.
13201 lrd = live_range_end(state, range, 0);
13202 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13203 entry = lrd->def->use;
13204 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13205 struct live_range_def *insd;
13206 insd = &rstate->lrd[entry->member->id];
13207 if (insd->lr->defs == 0) {
13210 if (!phi && (insd->def->op == OP_PHI) &&
13211 !interfere(rstate, range, insd->lr)) {
13214 if ((insd->lr->color == REG_UNSET) ||
13215 ((insd->lr->classes & range->classes) == 0) ||
13216 (used[insd->lr->color])) {
13219 if (interfere(rstate, range, insd->lr)) {
13222 range->color = insd->lr->color;
13225 /* If I feed into a phi function reuse it's color or the color
13226 * of something else that feeds into the phi function.
13229 if (phi->lr->color != REG_UNSET) {
13230 if (used[phi->lr->color]) {
13231 range->color = phi->lr->color;
13235 expr = triple_rhs(state, phi->def, 0);
13236 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13237 struct live_range *lr;
13241 lr = rstate->lrd[(*expr)->id].lr;
13242 if ((lr->color == REG_UNSET) ||
13243 ((lr->classes & range->classes) == 0) ||
13244 (used[lr->color])) {
13247 if (interfere(rstate, range, lr)) {
13250 range->color = lr->color;
13254 /* If I don't interfere with a rhs node reuse it's color */
13255 lrd = live_range_head(state, range, 0);
13256 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13257 expr = triple_rhs(state, lrd->def, 0);
13258 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13259 struct live_range *lr;
13263 lr = rstate->lrd[(*expr)->id].lr;
13264 if ((lr->color == -1) ||
13265 ((lr->classes & range->classes) == 0) ||
13266 (used[lr->color])) {
13269 if (interfere(rstate, range, lr)) {
13272 range->color = lr->color;
13276 /* If I have not opportunitically picked a useful color
13277 * pick the first color that is free.
13279 if (range->color == REG_UNSET) {
13281 arch_select_free_register(state, used, range->classes);
13283 if (range->color == REG_UNSET) {
13284 struct live_range_def *lrd;
13286 if (split_ranges(state, rstate, used, range)) {
13289 for(edge = range->edges; edge; edge = edge->next) {
13290 warning(state, edge->node->defs->def, "edge reg %s",
13291 arch_reg_str(edge->node->color));
13292 lrd = edge->node->defs;
13294 warning(state, lrd->def, " %s",
13295 tops(lrd->def->op));
13297 } while(lrd != edge->node->defs);
13299 warning(state, range->defs->def, "range: ");
13302 warning(state, lrd->def, " %s",
13303 tops(lrd->def->op));
13305 } while(lrd != range->defs);
13307 warning(state, range->defs->def, "classes: %x",
13309 for(i = 0; i < MAX_REGISTERS; i++) {
13311 warning(state, range->defs->def, "used: %s",
13315 #if DEBUG_COLOR_GRAPH < 2
13316 error(state, range->defs->def, "too few registers");
13318 internal_error(state, range->defs->def, "too few registers");
13321 range->classes = arch_reg_regcm(state, range->color);
13322 if (range->color == -1) {
13323 internal_error(state, range->defs->def, "select_free_color did not?");
13328 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13331 struct live_range_edge *edge;
13332 struct live_range *range;
13334 cgdebug_printf("Lo: ");
13335 range = rstate->low;
13336 if (*range->group_prev != range) {
13337 internal_error(state, 0, "lo: *prev != range?");
13339 *range->group_prev = range->group_next;
13340 if (range->group_next) {
13341 range->group_next->group_prev = range->group_prev;
13343 if (&range->group_next == rstate->low_tail) {
13344 rstate->low_tail = range->group_prev;
13346 if (rstate->low == range) {
13347 internal_error(state, 0, "low: next != prev?");
13350 else if (rstate->high) {
13351 cgdebug_printf("Hi: ");
13352 range = rstate->high;
13353 if (*range->group_prev != range) {
13354 internal_error(state, 0, "hi: *prev != range?");
13356 *range->group_prev = range->group_next;
13357 if (range->group_next) {
13358 range->group_next->group_prev = range->group_prev;
13360 if (&range->group_next == rstate->high_tail) {
13361 rstate->high_tail = range->group_prev;
13363 if (rstate->high == range) {
13364 internal_error(state, 0, "high: next != prev?");
13370 cgdebug_printf(" %d\n", range - rstate->lr);
13371 range->group_prev = 0;
13372 for(edge = range->edges; edge; edge = edge->next) {
13373 struct live_range *node;
13375 /* Move nodes from the high to the low list */
13376 if (node->group_prev && (node->color == REG_UNSET) &&
13377 (node->degree == regc_max_size(state, node->classes))) {
13378 if (*node->group_prev != node) {
13379 internal_error(state, 0, "move: *prev != node?");
13381 *node->group_prev = node->group_next;
13382 if (node->group_next) {
13383 node->group_next->group_prev = node->group_prev;
13385 if (&node->group_next == rstate->high_tail) {
13386 rstate->high_tail = node->group_prev;
13388 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13389 node->group_prev = rstate->low_tail;
13390 node->group_next = 0;
13391 *rstate->low_tail = node;
13392 rstate->low_tail = &node->group_next;
13393 if (*node->group_prev != node) {
13394 internal_error(state, 0, "move2: *prev != node?");
13399 colored = color_graph(state, rstate);
13401 cgdebug_printf("Coloring %d @%s:%d.%d:",
13402 range - rstate->lr,
13403 range->def->filename, range->def->line, range->def->col);
13405 colored = select_free_color(state, rstate, range);
13406 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13411 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13413 struct live_range *lr;
13414 struct live_range_edge *edge;
13415 struct triple *ins, *first;
13416 char used[MAX_REGISTERS];
13417 first = RHS(state->main_function, 0);
13420 if (triple_is_def(state, ins)) {
13421 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13422 internal_error(state, ins,
13423 "triple without a live range def");
13425 lr = rstate->lrd[ins->id].lr;
13426 if (lr->color == REG_UNSET) {
13427 internal_error(state, ins,
13428 "triple without a color");
13430 /* Find the registers used by the edges */
13431 memset(used, 0, sizeof(used));
13432 for(edge = lr->edges; edge; edge = edge->next) {
13433 if (edge->node->color == REG_UNSET) {
13434 internal_error(state, 0,
13435 "live range without a color");
13437 reg_fill_used(state, used, edge->node->color);
13439 if (used[lr->color]) {
13440 internal_error(state, ins,
13441 "triple with already used color");
13445 } while(ins != first);
13448 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13450 struct live_range *lr;
13451 struct triple *first, *ins;
13452 first = RHS(state->main_function, 0);
13455 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13456 internal_error(state, ins,
13457 "triple without a live range");
13459 lr = rstate->lrd[ins->id].lr;
13460 SET_REG(ins->id, lr->color);
13462 } while (ins != first);
13465 static void print_interference_block(
13466 struct compile_state *state, struct block *block, void *arg)
13469 struct reg_state *rstate = arg;
13470 struct reg_block *rb;
13471 struct triple *ptr;
13474 rb = &rstate->blocks[block->vertex];
13476 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
13480 block->left && block->left->use?block->left->use->member : 0,
13482 block->right && block->right->use?block->right->use->member : 0);
13484 struct triple_reg_set *in_set;
13486 for(in_set = rb->in; in_set; in_set = in_set->next) {
13487 printf(" %-10p", in_set->member);
13492 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13493 done = (ptr == block->last);
13494 if (ptr->op == OP_PHI) {
13501 for(edge = 0; edge < block->users; edge++) {
13502 printf(" in(%d):", edge);
13503 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13504 struct triple **slot;
13505 done = (ptr == block->last);
13506 if (ptr->op != OP_PHI) {
13509 slot = &RHS(ptr, 0);
13510 printf(" %-10p", slot[edge]);
13515 if (block->first->op == OP_LABEL) {
13516 printf("%p:\n", block->first);
13518 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13519 struct triple_set *user;
13520 struct live_range *lr;
13524 done = (ptr == block->last);
13525 lr = rstate->lrd[ptr->id].lr;
13527 if (triple_stores_block(state, ptr)) {
13528 if (ptr->u.block != block) {
13529 internal_error(state, ptr,
13530 "Wrong block pointer: %p",
13534 if (op == OP_ADECL) {
13535 for(user = ptr->use; user; user = user->next) {
13536 if (!user->member->u.block) {
13537 internal_error(state, user->member,
13538 "Use %p not in a block?",
13545 ptr->id = rstate->lrd[id].orig_id;
13546 SET_REG(ptr->id, lr->color);
13547 display_triple(stdout, ptr);
13550 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13551 internal_error(state, ptr, "lr has no defs!");
13555 struct live_range_def *lrd;
13559 printf(" %-10p", lrd->def);
13561 } while(lrd != lr->defs);
13564 if (lr->edges > 0) {
13565 struct live_range_edge *edge;
13567 for(edge = lr->edges; edge; edge = edge->next) {
13568 struct live_range_def *lrd;
13569 lrd = edge->node->defs;
13571 printf(" %-10p", lrd->def);
13573 } while(lrd != edge->node->defs);
13578 /* Do a bunch of sanity checks */
13579 valid_ins(state, ptr);
13580 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13581 internal_error(state, ptr, "Invalid triple id: %d",
13584 for(user = ptr->use; user; user = user->next) {
13585 struct triple *use;
13586 struct live_range *ulr;
13587 use = user->member;
13588 valid_ins(state, use);
13589 if ((use->id < 0) || (use->id > rstate->defs)) {
13590 internal_error(state, use, "Invalid triple id: %d",
13593 ulr = rstate->lrd[user->member->id].lr;
13594 if (triple_stores_block(state, user->member) &&
13595 !user->member->u.block) {
13596 internal_error(state, user->member,
13597 "Use %p not in a block?",
13603 struct triple_reg_set *out_set;
13605 for(out_set = rb->out; out_set; out_set = out_set->next) {
13606 printf(" %-10p", out_set->member);
13613 static struct live_range *merge_sort_lr(
13614 struct live_range *first, struct live_range *last)
13616 struct live_range *mid, *join, **join_tail, *pick;
13618 size = (last - first) + 1;
13620 mid = first + size/2;
13621 first = merge_sort_lr(first, mid -1);
13622 mid = merge_sort_lr(mid, last);
13626 /* merge the two lists */
13627 while(first && mid) {
13628 if ((first->degree < mid->degree) ||
13629 ((first->degree == mid->degree) &&
13630 (first->length < mid->length))) {
13632 first = first->group_next;
13634 first->group_prev = 0;
13639 mid = mid->group_next;
13641 mid->group_prev = 0;
13644 pick->group_next = 0;
13645 pick->group_prev = join_tail;
13647 join_tail = &pick->group_next;
13649 /* Splice the remaining list */
13650 pick = (first)? first : mid;
13653 pick->group_prev = join_tail;
13657 if (!first->defs) {
13665 static void ids_from_rstate(struct compile_state *state,
13666 struct reg_state *rstate)
13668 struct triple *ins, *first;
13669 if (!rstate->defs) {
13672 /* Display the graph if desired */
13673 if (state->debug & DEBUG_INTERFERENCE) {
13674 print_blocks(state, stdout);
13675 print_control_flow(state);
13677 first = RHS(state->main_function, 0);
13681 struct live_range_def *lrd;
13682 lrd = &rstate->lrd[ins->id];
13683 ins->id = lrd->orig_id;
13686 } while(ins != first);
13689 static void cleanup_live_edges(struct reg_state *rstate)
13692 /* Free the edges on each node */
13693 for(i = 1; i <= rstate->ranges; i++) {
13694 remove_live_edges(rstate, &rstate->lr[i]);
13698 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13700 cleanup_live_edges(rstate);
13701 xfree(rstate->lrd);
13704 /* Free the variable lifetime information */
13705 if (rstate->blocks) {
13706 free_variable_lifetimes(state, rstate->blocks);
13709 rstate->ranges = 0;
13712 rstate->blocks = 0;
13715 static void verify_consistency(struct compile_state *state);
13716 static void allocate_registers(struct compile_state *state)
13718 struct reg_state rstate;
13721 /* Clear out the reg_state */
13722 memset(&rstate, 0, sizeof(rstate));
13723 rstate.max_passes = MAX_ALLOCATION_PASSES;
13726 struct live_range **point, **next;
13731 fprintf(stderr, "pass: %d\n", rstate.passes);
13735 ids_from_rstate(state, &rstate);
13737 /* Cleanup the temporary data structures */
13738 cleanup_rstate(state, &rstate);
13740 /* Compute the variable lifetimes */
13741 rstate.blocks = compute_variable_lifetimes(state);
13743 /* Fix invalid mandatory live range coalesce conflicts */
13744 walk_variable_lifetimes(
13745 state, rstate.blocks, fix_coalesce_conflicts, 0);
13747 /* Fix two simultaneous uses of the same register.
13748 * In a few pathlogical cases a partial untangle moves
13749 * the tangle to a part of the graph we won't revisit.
13750 * So we keep looping until we have no more tangle fixes
13754 tangles = correct_tangles(state, rstate.blocks);
13757 if (state->debug & DEBUG_INSERTED_COPIES) {
13758 printf("After resolve_tangles\n");
13759 print_blocks(state, stdout);
13760 print_control_flow(state);
13762 verify_consistency(state);
13764 /* Allocate and initialize the live ranges */
13765 initialize_live_ranges(state, &rstate);
13767 /* Note current doing coalescing in a loop appears to
13768 * buys me nothing. The code is left this way in case
13769 * there is some value in it. Or if a future bugfix
13770 * yields some benefit.
13774 fprintf(stderr, "coalescing\n");
13776 /* Remove any previous live edge calculations */
13777 cleanup_live_edges(&rstate);
13779 /* Compute the interference graph */
13780 walk_variable_lifetimes(
13781 state, rstate.blocks, graph_ins, &rstate);
13783 /* Display the interference graph if desired */
13784 if (state->debug & DEBUG_INTERFERENCE) {
13785 printf("\nlive variables by block\n");
13786 walk_blocks(state, print_interference_block, &rstate);
13787 printf("\nlive variables by instruction\n");
13788 walk_variable_lifetimes(
13789 state, rstate.blocks,
13790 print_interference_ins, &rstate);
13793 coalesced = coalesce_live_ranges(state, &rstate);
13796 fprintf(stderr, "coalesced: %d\n", coalesced);
13798 } while(coalesced);
13800 #if DEBUG_CONSISTENCY > 1
13802 fprintf(stderr, "verify_graph_ins...\n");
13804 /* Verify the interference graph */
13805 walk_variable_lifetimes(
13806 state, rstate.blocks, verify_graph_ins, &rstate);
13808 fprintf(stderr, "verify_graph_ins done\n");
13812 /* Build the groups low and high. But with the nodes
13813 * first sorted by degree order.
13815 rstate.low_tail = &rstate.low;
13816 rstate.high_tail = &rstate.high;
13817 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13819 rstate.high->group_prev = &rstate.high;
13821 for(point = &rstate.high; *point; point = &(*point)->group_next)
13823 rstate.high_tail = point;
13824 /* Walk through the high list and move everything that needs
13827 for(point = &rstate.high; *point; point = next) {
13828 struct live_range *range;
13829 next = &(*point)->group_next;
13832 /* If it has a low degree or it already has a color
13833 * place the node in low.
13835 if ((range->degree < regc_max_size(state, range->classes)) ||
13836 (range->color != REG_UNSET)) {
13837 cgdebug_printf("Lo: %5d degree %5d%s\n",
13838 range - rstate.lr, range->degree,
13839 (range->color != REG_UNSET) ? " (colored)": "");
13840 *range->group_prev = range->group_next;
13841 if (range->group_next) {
13842 range->group_next->group_prev = range->group_prev;
13844 if (&range->group_next == rstate.high_tail) {
13845 rstate.high_tail = range->group_prev;
13847 range->group_prev = rstate.low_tail;
13848 range->group_next = 0;
13849 *rstate.low_tail = range;
13850 rstate.low_tail = &range->group_next;
13854 cgdebug_printf("hi: %5d degree %5d%s\n",
13855 range - rstate.lr, range->degree,
13856 (range->color != REG_UNSET) ? " (colored)": "");
13859 /* Color the live_ranges */
13860 colored = color_graph(state, &rstate);
13862 } while (!colored);
13864 /* Verify the graph was properly colored */
13865 verify_colors(state, &rstate);
13867 /* Move the colors from the graph to the triples */
13868 color_triples(state, &rstate);
13870 /* Cleanup the temporary data structures */
13871 cleanup_rstate(state, &rstate);
13874 /* Sparce Conditional Constant Propogation
13875 * =========================================
13879 struct lattice_node {
13881 struct triple *def;
13882 struct ssa_edge *out;
13883 struct flow_block *fblock;
13884 struct triple *val;
13885 /* lattice high val && !is_const(val)
13886 * lattice const is_const(val)
13887 * lattice low val == 0
13891 struct lattice_node *src;
13892 struct lattice_node *dst;
13893 struct ssa_edge *work_next;
13894 struct ssa_edge *work_prev;
13895 struct ssa_edge *out_next;
13898 struct flow_block *src;
13899 struct flow_block *dst;
13900 struct flow_edge *work_next;
13901 struct flow_edge *work_prev;
13902 struct flow_edge *in_next;
13903 struct flow_edge *out_next;
13906 struct flow_block {
13907 struct block *block;
13908 struct flow_edge *in;
13909 struct flow_edge *out;
13910 struct flow_edge left, right;
13915 struct lattice_node *lattice;
13916 struct ssa_edge *ssa_edges;
13917 struct flow_block *flow_blocks;
13918 struct flow_edge *flow_work_list;
13919 struct ssa_edge *ssa_work_list;
13923 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13924 struct flow_edge *fedge)
13926 if (!scc->flow_work_list) {
13927 scc->flow_work_list = fedge;
13928 fedge->work_next = fedge->work_prev = fedge;
13931 struct flow_edge *ftail;
13932 ftail = scc->flow_work_list->work_prev;
13933 fedge->work_next = ftail->work_next;
13934 fedge->work_prev = ftail;
13935 fedge->work_next->work_prev = fedge;
13936 fedge->work_prev->work_next = fedge;
13940 static struct flow_edge *scc_next_fedge(
13941 struct compile_state *state, struct scc_state *scc)
13943 struct flow_edge *fedge;
13944 fedge = scc->flow_work_list;
13946 fedge->work_next->work_prev = fedge->work_prev;
13947 fedge->work_prev->work_next = fedge->work_next;
13948 if (fedge->work_next != fedge) {
13949 scc->flow_work_list = fedge->work_next;
13951 scc->flow_work_list = 0;
13957 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13958 struct ssa_edge *sedge)
13960 if (!scc->ssa_work_list) {
13961 scc->ssa_work_list = sedge;
13962 sedge->work_next = sedge->work_prev = sedge;
13965 struct ssa_edge *stail;
13966 stail = scc->ssa_work_list->work_prev;
13967 sedge->work_next = stail->work_next;
13968 sedge->work_prev = stail;
13969 sedge->work_next->work_prev = sedge;
13970 sedge->work_prev->work_next = sedge;
13974 static struct ssa_edge *scc_next_sedge(
13975 struct compile_state *state, struct scc_state *scc)
13977 struct ssa_edge *sedge;
13978 sedge = scc->ssa_work_list;
13980 sedge->work_next->work_prev = sedge->work_prev;
13981 sedge->work_prev->work_next = sedge->work_next;
13982 if (sedge->work_next != sedge) {
13983 scc->ssa_work_list = sedge->work_next;
13985 scc->ssa_work_list = 0;
13991 static void initialize_scc_state(
13992 struct compile_state *state, struct scc_state *scc)
13994 int ins_count, ssa_edge_count;
13995 int ins_index, ssa_edge_index, fblock_index;
13996 struct triple *first, *ins;
13997 struct block *block;
13998 struct flow_block *fblock;
14000 memset(scc, 0, sizeof(*scc));
14002 /* Inialize pass zero find out how much memory we need */
14003 first = RHS(state->main_function, 0);
14005 ins_count = ssa_edge_count = 0;
14007 struct triple_set *edge;
14009 for(edge = ins->use; edge; edge = edge->next) {
14013 } while(ins != first);
14015 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14016 ins_count, ssa_edge_count, state->last_vertex);
14018 scc->ins_count = ins_count;
14020 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14022 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14024 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
14027 /* Initialize pass one collect up the nodes */
14030 ins_index = ssa_edge_index = fblock_index = 0;
14033 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14034 block = ins->u.block;
14036 internal_error(state, ins, "label without block");
14039 block->vertex = fblock_index;
14040 fblock = &scc->flow_blocks[fblock_index];
14041 fblock->block = block;
14044 struct lattice_node *lnode;
14046 lnode = &scc->lattice[ins_index];
14049 lnode->fblock = fblock;
14050 lnode->val = ins; /* LATTICE HIGH */
14051 lnode->old_id = ins->id;
14052 ins->id = ins_index;
14055 } while(ins != first);
14056 /* Initialize pass two collect up the edges */
14061 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14062 struct flow_edge *fedge, **ftail;
14063 struct block_set *bedge;
14064 block = ins->u.block;
14065 fblock = &scc->flow_blocks[block->vertex];
14068 ftail = &fblock->out;
14070 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14071 if (fblock->left.dst->block != block->left) {
14072 internal_error(state, 0, "block mismatch");
14074 fblock->left.out_next = 0;
14075 *ftail = &fblock->left;
14076 ftail = &fblock->left.out_next;
14078 if (block->right) {
14079 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14080 if (fblock->right.dst->block != block->right) {
14081 internal_error(state, 0, "block mismatch");
14083 fblock->right.out_next = 0;
14084 *ftail = &fblock->right;
14085 ftail = &fblock->right.out_next;
14087 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14088 fedge->src = fblock;
14089 fedge->work_next = fedge->work_prev = fedge;
14090 fedge->executable = 0;
14092 ftail = &fblock->in;
14093 for(bedge = block->use; bedge; bedge = bedge->next) {
14094 struct block *src_block;
14095 struct flow_block *sfblock;
14096 struct flow_edge *sfedge;
14097 src_block = bedge->member;
14098 sfblock = &scc->flow_blocks[src_block->vertex];
14100 if (src_block->left == block) {
14101 sfedge = &sfblock->left;
14103 sfedge = &sfblock->right;
14106 ftail = &sfedge->in_next;
14107 sfedge->in_next = 0;
14111 struct triple_set *edge;
14112 struct ssa_edge **stail;
14113 struct lattice_node *lnode;
14114 lnode = &scc->lattice[ins->id];
14116 stail = &lnode->out;
14117 for(edge = ins->use; edge; edge = edge->next) {
14118 struct ssa_edge *sedge;
14119 ssa_edge_index += 1;
14120 sedge = &scc->ssa_edges[ssa_edge_index];
14122 stail = &sedge->out_next;
14123 sedge->src = lnode;
14124 sedge->dst = &scc->lattice[edge->member->id];
14125 sedge->work_next = sedge->work_prev = sedge;
14126 sedge->out_next = 0;
14130 } while(ins != first);
14131 /* Setup a dummy block 0 as a node above the start node */
14133 struct flow_block *fblock, *dst;
14134 struct flow_edge *fedge;
14135 fblock = &scc->flow_blocks[0];
14138 fblock->out = &fblock->left;
14139 dst = &scc->flow_blocks[state->first_block->vertex];
14140 fedge = &fblock->left;
14141 fedge->src = fblock;
14143 fedge->work_next = fedge;
14144 fedge->work_prev = fedge;
14145 fedge->in_next = fedge->dst->in;
14146 fedge->out_next = 0;
14147 fedge->executable = 0;
14148 fedge->dst->in = fedge;
14150 /* Initialize the work lists */
14151 scc->flow_work_list = 0;
14152 scc->ssa_work_list = 0;
14153 scc_add_fedge(state, scc, fedge);
14156 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14157 ins_index, ssa_edge_index, fblock_index);
14162 static void free_scc_state(
14163 struct compile_state *state, struct scc_state *scc)
14165 xfree(scc->flow_blocks);
14166 xfree(scc->ssa_edges);
14167 xfree(scc->lattice);
14171 static struct lattice_node *triple_to_lattice(
14172 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14174 if (ins->id <= 0) {
14175 internal_error(state, ins, "bad id");
14177 return &scc->lattice[ins->id];
14180 static struct triple *preserve_lval(
14181 struct compile_state *state, struct lattice_node *lnode)
14183 struct triple *old;
14184 /* Preserve the original value */
14186 old = dup_triple(state, lnode->val);
14187 if (lnode->val != lnode->def) {
14197 static int lval_changed(struct compile_state *state,
14198 struct triple *old, struct lattice_node *lnode)
14201 /* See if the lattice value has changed */
14203 if (!old && !lnode->val) {
14206 if (changed && lnode->val && !is_const(lnode->val)) {
14210 lnode->val && old &&
14211 (memcmp(lnode->val->param, old->param,
14212 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14213 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14223 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14224 struct lattice_node *lnode)
14226 struct lattice_node *tmp;
14227 struct triple **slot, *old;
14228 struct flow_edge *fedge;
14230 if (lnode->def->op != OP_PHI) {
14231 internal_error(state, lnode->def, "not phi");
14233 /* Store the original value */
14234 old = preserve_lval(state, lnode);
14236 /* default to lattice high */
14237 lnode->val = lnode->def;
14238 slot = &RHS(lnode->def, 0);
14240 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14241 if (!fedge->executable) {
14244 if (!slot[index]) {
14245 internal_error(state, lnode->def, "no phi value");
14247 tmp = triple_to_lattice(state, scc, slot[index]);
14248 /* meet(X, lattice low) = lattice low */
14252 /* meet(X, lattice high) = X */
14253 else if (!tmp->val) {
14254 lnode->val = lnode->val;
14256 /* meet(lattice high, X) = X */
14257 else if (!is_const(lnode->val)) {
14258 lnode->val = dup_triple(state, tmp->val);
14259 lnode->val->type = lnode->def->type;
14261 /* meet(const, const) = const or lattice low */
14262 else if (!constants_equal(state, lnode->val, tmp->val)) {
14270 fprintf(stderr, "phi: %d -> %s\n",
14272 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14274 /* If the lattice value has changed update the work lists. */
14275 if (lval_changed(state, old, lnode)) {
14276 struct ssa_edge *sedge;
14277 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14278 scc_add_sedge(state, scc, sedge);
14283 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14284 struct lattice_node *lnode)
14287 struct triple *old, *scratch;
14288 struct triple **dexpr, **vexpr;
14291 /* Store the original value */
14292 old = preserve_lval(state, lnode);
14294 /* Reinitialize the value */
14295 lnode->val = scratch = dup_triple(state, lnode->def);
14296 scratch->id = lnode->old_id;
14297 scratch->next = scratch;
14298 scratch->prev = scratch;
14301 count = TRIPLE_SIZE(scratch->sizes);
14302 for(i = 0; i < count; i++) {
14303 dexpr = &lnode->def->param[i];
14304 vexpr = &scratch->param[i];
14306 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14307 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14309 struct lattice_node *tmp;
14310 tmp = triple_to_lattice(state, scc, *dexpr);
14311 *vexpr = (tmp->val)? tmp->val : tmp->def;
14314 if (scratch->op == OP_BRANCH) {
14315 scratch->next = lnode->def->next;
14317 /* Recompute the value */
14318 #warning "FIXME see if simplify does anything bad"
14319 /* So far it looks like only the strength reduction
14320 * optimization are things I need to worry about.
14322 simplify(state, scratch);
14323 /* Cleanup my value */
14324 if (scratch->use) {
14325 internal_error(state, lnode->def, "scratch used?");
14327 if ((scratch->prev != scratch) ||
14328 ((scratch->next != scratch) &&
14329 ((lnode->def->op != OP_BRANCH) ||
14330 (scratch->next != lnode->def->next)))) {
14331 internal_error(state, lnode->def, "scratch in list?");
14333 /* undo any uses... */
14334 count = TRIPLE_SIZE(scratch->sizes);
14335 for(i = 0; i < count; i++) {
14336 vexpr = &scratch->param[i];
14338 unuse_triple(*vexpr, scratch);
14341 if (!is_const(scratch)) {
14342 for(i = 0; i < count; i++) {
14343 dexpr = &lnode->def->param[i];
14344 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14345 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14347 struct lattice_node *tmp;
14348 tmp = triple_to_lattice(state, scc, *dexpr);
14356 (lnode->val->op == lnode->def->op) &&
14357 (memcmp(lnode->val->param, lnode->def->param,
14358 count * sizeof(lnode->val->param[0])) == 0) &&
14359 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14360 lnode->val = lnode->def;
14362 /* Find the cases that are always lattice lo */
14364 triple_is_def(state, lnode->val) &&
14365 !triple_is_pure(state, lnode->val)) {
14369 (lnode->val->op == OP_SDECL) &&
14370 (lnode->val != lnode->def)) {
14371 internal_error(state, lnode->def, "bad sdecl");
14373 /* See if the lattice value has changed */
14374 changed = lval_changed(state, old, lnode);
14375 if (lnode->val != scratch) {
14381 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14382 struct lattice_node *lnode)
14384 struct lattice_node *cond;
14387 struct flow_edge *fedge;
14388 fprintf(stderr, "branch: %d (",
14391 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14392 fprintf(stderr, " %d", fedge->dst->block->vertex);
14394 fprintf(stderr, " )");
14395 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14396 fprintf(stderr, " <- %d",
14397 RHS(lnode->def, 0)->id);
14399 fprintf(stderr, "\n");
14402 if (lnode->def->op != OP_BRANCH) {
14403 internal_error(state, lnode->def, "not branch");
14405 /* This only applies to conditional branches */
14406 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14409 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14410 if (cond->val && !is_const(cond->val)) {
14411 #warning "FIXME do I need to do something here?"
14412 warning(state, cond->def, "condition not constant?");
14415 if (cond->val == 0) {
14416 scc_add_fedge(state, scc, cond->fblock->out);
14417 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14419 else if (cond->val->u.cval) {
14420 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14423 scc_add_fedge(state, scc, cond->fblock->out);
14428 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14429 struct lattice_node *lnode)
14433 changed = compute_lnode_val(state, scc, lnode);
14436 struct triple **expr;
14437 fprintf(stderr, "expr: %3d %10s (",
14438 lnode->def->id, tops(lnode->def->op));
14439 expr = triple_rhs(state, lnode->def, 0);
14440 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14442 fprintf(stderr, " %d", (*expr)->id);
14445 fprintf(stderr, " ) -> %s\n",
14446 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14449 if (lnode->def->op == OP_BRANCH) {
14450 scc_visit_branch(state, scc, lnode);
14453 else if (changed) {
14454 struct ssa_edge *sedge;
14455 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14456 scc_add_sedge(state, scc, sedge);
14461 static void scc_writeback_values(
14462 struct compile_state *state, struct scc_state *scc)
14464 struct triple *first, *ins;
14465 first = RHS(state->main_function, 0);
14468 struct lattice_node *lnode;
14469 lnode = triple_to_lattice(state, scc, ins);
14471 ins->id = lnode->old_id;
14473 if (lnode->val && !is_const(lnode->val)) {
14474 warning(state, lnode->def,
14475 "lattice node still high?");
14478 if (lnode->val && (lnode->val != ins)) {
14479 /* See if it something I know how to write back */
14480 switch(lnode->val->op) {
14482 mkconst(state, ins, lnode->val->u.cval);
14485 mkaddr_const(state, ins,
14486 MISC(lnode->val, 0), lnode->val->u.cval);
14489 /* By default don't copy the changes,
14490 * recompute them in place instead.
14492 simplify(state, ins);
14495 if (is_const(lnode->val) &&
14496 !constants_equal(state, lnode->val, ins)) {
14497 internal_error(state, 0, "constants not equal");
14499 /* Free the lattice nodes */
14504 } while(ins != first);
14507 static void scc_transform(struct compile_state *state)
14509 struct scc_state scc;
14511 initialize_scc_state(state, &scc);
14513 while(scc.flow_work_list || scc.ssa_work_list) {
14514 struct flow_edge *fedge;
14515 struct ssa_edge *sedge;
14516 struct flow_edge *fptr;
14517 while((fedge = scc_next_fedge(state, &scc))) {
14518 struct block *block;
14519 struct triple *ptr;
14520 struct flow_block *fblock;
14523 if (fedge->executable) {
14527 internal_error(state, 0, "fedge without dst");
14530 internal_error(state, 0, "fedge without src");
14532 fedge->executable = 1;
14533 fblock = fedge->dst;
14534 block = fblock->block;
14536 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14537 if (fptr->executable) {
14542 fprintf(stderr, "vertex: %d time: %d\n",
14543 block->vertex, time);
14547 for(ptr = block->first; !done; ptr = ptr->next) {
14548 struct lattice_node *lnode;
14549 done = (ptr == block->last);
14550 lnode = &scc.lattice[ptr->id];
14551 if (ptr->op == OP_PHI) {
14552 scc_visit_phi(state, &scc, lnode);
14554 else if (time == 1) {
14555 scc_visit_expr(state, &scc, lnode);
14558 if (fblock->out && !fblock->out->out_next) {
14559 scc_add_fedge(state, &scc, fblock->out);
14562 while((sedge = scc_next_sedge(state, &scc))) {
14563 struct lattice_node *lnode;
14564 struct flow_block *fblock;
14565 lnode = sedge->dst;
14566 fblock = lnode->fblock;
14568 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14569 sedge - scc.ssa_edges,
14570 sedge->src->def->id,
14571 sedge->dst->def->id);
14573 if (lnode->def->op == OP_PHI) {
14574 scc_visit_phi(state, &scc, lnode);
14577 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14578 if (fptr->executable) {
14583 scc_visit_expr(state, &scc, lnode);
14589 scc_writeback_values(state, &scc);
14590 free_scc_state(state, &scc);
14594 static void transform_to_arch_instructions(struct compile_state *state)
14596 struct triple *ins, *first;
14597 first = RHS(state->main_function, 0);
14600 ins = transform_to_arch_instruction(state, ins);
14601 } while(ins != first);
14604 #if DEBUG_CONSISTENCY
14605 static void verify_uses(struct compile_state *state)
14607 struct triple *first, *ins;
14608 struct triple_set *set;
14609 first = RHS(state->main_function, 0);
14612 struct triple **expr;
14613 expr = triple_rhs(state, ins, 0);
14614 for(; expr; expr = triple_rhs(state, ins, expr)) {
14615 struct triple *rhs;
14617 for(set = rhs?rhs->use:0; set; set = set->next) {
14618 if (set->member == ins) {
14623 internal_error(state, ins, "rhs not used");
14626 expr = triple_lhs(state, ins, 0);
14627 for(; expr; expr = triple_lhs(state, ins, expr)) {
14628 struct triple *lhs;
14630 for(set = lhs?lhs->use:0; set; set = set->next) {
14631 if (set->member == ins) {
14636 internal_error(state, ins, "lhs not used");
14640 } while(ins != first);
14643 static void verify_blocks(struct compile_state *state)
14645 struct triple *ins;
14646 struct block *block;
14647 block = state->first_block;
14652 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14653 if (!triple_stores_block(state, ins)) {
14656 if (ins->u.block != block) {
14657 internal_error(state, ins, "inconsitent block specified");
14660 if (!triple_stores_block(state, block->last->next)) {
14661 internal_error(state, block->last->next,
14662 "cannot find next block");
14664 block = block->last->next->u.block;
14666 internal_error(state, block->last->next,
14669 } while(block != state->first_block);
14672 static void verify_domination(struct compile_state *state)
14674 struct triple *first, *ins;
14675 struct triple_set *set;
14676 if (!state->first_block) {
14680 first = RHS(state->main_function, 0);
14683 for(set = ins->use; set; set = set->next) {
14684 struct triple **expr;
14685 if (set->member->op == OP_PHI) {
14688 /* See if the use is on the righ hand side */
14689 expr = triple_rhs(state, set->member, 0);
14690 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14691 if (*expr == ins) {
14696 !tdominates(state, ins, set->member)) {
14697 internal_error(state, set->member,
14698 "non dominated rhs use?");
14702 } while(ins != first);
14705 static void verify_piece(struct compile_state *state)
14707 struct triple *first, *ins;
14708 first = RHS(state->main_function, 0);
14711 struct triple *ptr;
14713 lhs = TRIPLE_LHS(ins->sizes);
14714 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14717 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14718 if (ptr != LHS(ins, i)) {
14719 internal_error(state, ins, "malformed lhs on %s",
14722 if (ptr->op != OP_PIECE) {
14723 internal_error(state, ins, "bad lhs op %s at %d on %s",
14724 tops(ptr->op), i, tops(ins->op));
14726 if (ptr->u.cval != i) {
14727 internal_error(state, ins, "bad u.cval of %d %d expected",
14732 } while(ins != first);
14734 static void verify_ins_colors(struct compile_state *state)
14736 struct triple *first, *ins;
14738 first = RHS(state->main_function, 0);
14742 } while(ins != first);
14744 static void verify_consistency(struct compile_state *state)
14746 verify_uses(state);
14747 verify_blocks(state);
14748 verify_domination(state);
14749 verify_piece(state);
14750 verify_ins_colors(state);
14753 static void verify_consistency(struct compile_state *state) {}
14754 #endif /* DEBUG_USES */
14756 static void optimize(struct compile_state *state)
14758 if (state->debug & DEBUG_TRIPLES) {
14759 print_triples(state);
14761 /* Replace structures with simpler data types */
14762 flatten_structures(state);
14763 if (state->debug & DEBUG_TRIPLES) {
14764 print_triples(state);
14766 verify_consistency(state);
14767 /* Analize the intermediate code */
14768 setup_basic_blocks(state);
14769 analyze_idominators(state);
14770 analyze_ipdominators(state);
14771 /* Transform the code to ssa form */
14772 transform_to_ssa_form(state);
14773 verify_consistency(state);
14774 if (state->debug & DEBUG_CODE_ELIMINATION) {
14775 fprintf(stdout, "After transform_to_ssa_form\n");
14776 print_blocks(state, stdout);
14778 /* Do strength reduction and simple constant optimizations */
14779 if (state->optimize >= 1) {
14780 simplify_all(state);
14782 verify_consistency(state);
14783 /* Propogate constants throughout the code */
14784 if (state->optimize >= 2) {
14785 #warning "FIXME fix scc_transform"
14786 scc_transform(state);
14787 transform_from_ssa_form(state);
14788 free_basic_blocks(state);
14789 setup_basic_blocks(state);
14790 analyze_idominators(state);
14791 analyze_ipdominators(state);
14792 transform_to_ssa_form(state);
14794 verify_consistency(state);
14795 #warning "WISHLIST implement single use constants (least possible register pressure)"
14796 #warning "WISHLIST implement induction variable elimination"
14797 /* Select architecture instructions and an initial partial
14798 * coloring based on architecture constraints.
14800 transform_to_arch_instructions(state);
14801 verify_consistency(state);
14802 if (state->debug & DEBUG_ARCH_CODE) {
14803 printf("After transform_to_arch_instructions\n");
14804 print_blocks(state, stdout);
14805 print_control_flow(state);
14807 eliminate_inefectual_code(state);
14808 verify_consistency(state);
14809 if (state->debug & DEBUG_CODE_ELIMINATION) {
14810 printf("After eliminate_inefectual_code\n");
14811 print_blocks(state, stdout);
14812 print_control_flow(state);
14814 verify_consistency(state);
14815 /* Color all of the variables to see if they will fit in registers */
14816 insert_copies_to_phi(state);
14817 if (state->debug & DEBUG_INSERTED_COPIES) {
14818 printf("After insert_copies_to_phi\n");
14819 print_blocks(state, stdout);
14820 print_control_flow(state);
14822 verify_consistency(state);
14823 insert_mandatory_copies(state);
14824 if (state->debug & DEBUG_INSERTED_COPIES) {
14825 printf("After insert_mandatory_copies\n");
14826 print_blocks(state, stdout);
14827 print_control_flow(state);
14829 verify_consistency(state);
14830 allocate_registers(state);
14831 verify_consistency(state);
14832 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14833 print_blocks(state, stdout);
14835 if (state->debug & DEBUG_CONTROL_FLOW) {
14836 print_control_flow(state);
14838 /* Remove the optimization information.
14839 * This is more to check for memory consistency than to free memory.
14841 free_basic_blocks(state);
14844 static void print_op_asm(struct compile_state *state,
14845 struct triple *ins, FILE *fp)
14847 struct asm_info *info;
14849 unsigned lhs, rhs, i;
14850 info = ins->u.ainfo;
14851 lhs = TRIPLE_LHS(ins->sizes);
14852 rhs = TRIPLE_RHS(ins->sizes);
14853 /* Don't count the clobbers in lhs */
14854 for(i = 0; i < lhs; i++) {
14855 if (LHS(ins, i)->type == &void_type) {
14860 fprintf(fp, "#ASM\n");
14862 for(ptr = info->str; *ptr; ptr++) {
14864 unsigned long param;
14865 struct triple *piece;
14875 param = strtoul(ptr, &next, 10);
14877 error(state, ins, "Invalid asm template");
14879 if (param >= (lhs + rhs)) {
14880 error(state, ins, "Invalid param %%%u in asm template",
14883 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14885 arch_reg_str(ID_REG(piece->id)));
14888 fprintf(fp, "\n#NOT ASM\n");
14892 /* Only use the low x86 byte registers. This allows me
14893 * allocate the entire register when a byte register is used.
14895 #define X86_4_8BIT_GPRS 1
14897 /* Recognized x86 cpu variants */
14905 #define CPU_DEFAULT CPU_I386
14907 /* The x86 register classes */
14908 #define REGC_FLAGS 0
14909 #define REGC_GPR8 1
14910 #define REGC_GPR16 2
14911 #define REGC_GPR32 3
14912 #define REGC_GPR64 4
14915 #define REGC_GPR32_8 7
14916 #define REGC_GPR16_8 8
14917 #define REGC_IMM32 9
14918 #define REGC_IMM16 10
14919 #define REGC_IMM8 11
14920 #define LAST_REGC REGC_IMM8
14921 #if LAST_REGC >= MAX_REGC
14922 #error "MAX_REGC is to low"
14925 /* Register class masks */
14926 #define REGCM_FLAGS (1 << REGC_FLAGS)
14927 #define REGCM_GPR8 (1 << REGC_GPR8)
14928 #define REGCM_GPR16 (1 << REGC_GPR16)
14929 #define REGCM_GPR32 (1 << REGC_GPR32)
14930 #define REGCM_GPR64 (1 << REGC_GPR64)
14931 #define REGCM_MMX (1 << REGC_MMX)
14932 #define REGCM_XMM (1 << REGC_XMM)
14933 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14934 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14935 #define REGCM_IMM32 (1 << REGC_IMM32)
14936 #define REGCM_IMM16 (1 << REGC_IMM16)
14937 #define REGCM_IMM8 (1 << REGC_IMM8)
14938 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14940 /* The x86 registers */
14941 #define REG_EFLAGS 2
14942 #define REGC_FLAGS_FIRST REG_EFLAGS
14943 #define REGC_FLAGS_LAST REG_EFLAGS
14952 #define REGC_GPR8_FIRST REG_AL
14953 #if X86_4_8BIT_GPRS
14954 #define REGC_GPR8_LAST REG_DL
14956 #define REGC_GPR8_LAST REG_DH
14966 #define REGC_GPR16_FIRST REG_AX
14967 #define REGC_GPR16_LAST REG_SP
14976 #define REGC_GPR32_FIRST REG_EAX
14977 #define REGC_GPR32_LAST REG_ESP
14978 #define REG_EDXEAX 27
14979 #define REGC_GPR64_FIRST REG_EDXEAX
14980 #define REGC_GPR64_LAST REG_EDXEAX
14981 #define REG_MMX0 28
14982 #define REG_MMX1 29
14983 #define REG_MMX2 30
14984 #define REG_MMX3 31
14985 #define REG_MMX4 32
14986 #define REG_MMX5 33
14987 #define REG_MMX6 34
14988 #define REG_MMX7 35
14989 #define REGC_MMX_FIRST REG_MMX0
14990 #define REGC_MMX_LAST REG_MMX7
14991 #define REG_XMM0 36
14992 #define REG_XMM1 37
14993 #define REG_XMM2 38
14994 #define REG_XMM3 39
14995 #define REG_XMM4 40
14996 #define REG_XMM5 41
14997 #define REG_XMM6 42
14998 #define REG_XMM7 43
14999 #define REGC_XMM_FIRST REG_XMM0
15000 #define REGC_XMM_LAST REG_XMM7
15001 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15002 #define LAST_REG REG_XMM7
15004 #define REGC_GPR32_8_FIRST REG_EAX
15005 #define REGC_GPR32_8_LAST REG_EDX
15006 #define REGC_GPR16_8_FIRST REG_AX
15007 #define REGC_GPR16_8_LAST REG_DX
15009 #define REGC_IMM8_FIRST -1
15010 #define REGC_IMM8_LAST -1
15011 #define REGC_IMM16_FIRST -2
15012 #define REGC_IMM16_LAST -1
15013 #define REGC_IMM32_FIRST -4
15014 #define REGC_IMM32_LAST -1
15016 #if LAST_REG >= MAX_REGISTERS
15017 #error "MAX_REGISTERS to low"
15021 static unsigned regc_size[LAST_REGC +1] = {
15022 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
15023 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
15024 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
15025 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
15026 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
15027 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
15028 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
15029 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15030 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15036 static const struct {
15038 } regcm_bound[LAST_REGC + 1] = {
15039 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
15040 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
15041 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
15042 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
15043 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
15044 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
15045 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
15046 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15047 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15048 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
15049 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
15050 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
15053 static int arch_encode_cpu(const char *cpu)
15059 { "i386", CPU_I386 },
15067 for(ptr = cpus; ptr->name; ptr++) {
15068 if (strcmp(ptr->name, cpu) == 0) {
15075 static unsigned arch_regc_size(struct compile_state *state, int class)
15077 if ((class < 0) || (class > LAST_REGC)) {
15080 return regc_size[class];
15082 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15084 /* See if two register classes may have overlapping registers */
15085 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15086 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
15088 /* Special case for the immediates */
15089 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15090 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15091 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15092 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
15095 return (regcm1 & regcm2) ||
15096 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15099 static void arch_reg_equivs(
15100 struct compile_state *state, unsigned *equiv, int reg)
15102 if ((reg < 0) || (reg > LAST_REG)) {
15103 internal_error(state, 0, "invalid register");
15108 #if X86_4_8BIT_GPRS
15112 *equiv++ = REG_EAX;
15113 *equiv++ = REG_EDXEAX;
15116 #if X86_4_8BIT_GPRS
15120 *equiv++ = REG_EAX;
15121 *equiv++ = REG_EDXEAX;
15124 #if X86_4_8BIT_GPRS
15128 *equiv++ = REG_EBX;
15132 #if X86_4_8BIT_GPRS
15136 *equiv++ = REG_EBX;
15139 #if X86_4_8BIT_GPRS
15143 *equiv++ = REG_ECX;
15147 #if X86_4_8BIT_GPRS
15151 *equiv++ = REG_ECX;
15154 #if X86_4_8BIT_GPRS
15158 *equiv++ = REG_EDX;
15159 *equiv++ = REG_EDXEAX;
15162 #if X86_4_8BIT_GPRS
15166 *equiv++ = REG_EDX;
15167 *equiv++ = REG_EDXEAX;
15172 *equiv++ = REG_EAX;
15173 *equiv++ = REG_EDXEAX;
15178 *equiv++ = REG_EBX;
15183 *equiv++ = REG_ECX;
15188 *equiv++ = REG_EDX;
15189 *equiv++ = REG_EDXEAX;
15192 *equiv++ = REG_ESI;
15195 *equiv++ = REG_EDI;
15198 *equiv++ = REG_EBP;
15201 *equiv++ = REG_ESP;
15207 *equiv++ = REG_EDXEAX;
15223 *equiv++ = REG_EDXEAX;
15244 *equiv++ = REG_EAX;
15245 *equiv++ = REG_EDX;
15248 *equiv++ = REG_UNSET;
15251 static unsigned arch_avail_mask(struct compile_state *state)
15253 unsigned avail_mask;
15254 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15255 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15256 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15257 switch(state->cpu) {
15260 avail_mask |= REGCM_MMX;
15264 avail_mask |= REGCM_MMX | REGCM_XMM;
15268 /* Don't enable 8 bit values until I can force both operands
15269 * to be 8bits simultaneously.
15271 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15276 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15278 unsigned mask, result;
15281 result &= arch_avail_mask(state);
15283 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15284 if ((result & mask) == 0) {
15287 if (class > LAST_REGC) {
15290 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15291 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15292 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15293 result |= (1 << class2);
15300 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15305 for(class = 0; class <= LAST_REGC; class++) {
15306 if ((reg >= regcm_bound[class].first) &&
15307 (reg <= regcm_bound[class].last)) {
15308 mask |= (1 << class);
15312 internal_error(state, 0, "reg %d not in any class", reg);
15317 static struct reg_info arch_reg_constraint(
15318 struct compile_state *state, struct type *type, const char *constraint)
15320 static const struct {
15324 } constraints[] = {
15325 { 'r', REGCM_GPR32, REG_UNSET },
15326 { 'g', REGCM_GPR32, REG_UNSET },
15327 { 'p', REGCM_GPR32, REG_UNSET },
15328 { 'q', REGCM_GPR8, REG_UNSET },
15329 { 'Q', REGCM_GPR32_8, REG_UNSET },
15330 { 'x', REGCM_XMM, REG_UNSET },
15331 { 'y', REGCM_MMX, REG_UNSET },
15332 { 'a', REGCM_GPR32, REG_EAX },
15333 { 'b', REGCM_GPR32, REG_EBX },
15334 { 'c', REGCM_GPR32, REG_ECX },
15335 { 'd', REGCM_GPR32, REG_EDX },
15336 { 'D', REGCM_GPR32, REG_EDI },
15337 { 'S', REGCM_GPR32, REG_ESI },
15338 { '\0', 0, REG_UNSET },
15340 unsigned int regcm;
15341 unsigned int mask, reg;
15342 struct reg_info result;
15344 regcm = arch_type_to_regcm(state, type);
15347 for(ptr = constraint; *ptr; ptr++) {
15352 for(i = 0; constraints[i].class != '\0'; i++) {
15353 if (constraints[i].class == *ptr) {
15357 if (constraints[i].class == '\0') {
15358 error(state, 0, "invalid register constraint ``%c''", *ptr);
15361 if ((constraints[i].mask & regcm) == 0) {
15362 error(state, 0, "invalid register class %c specified",
15365 mask |= constraints[i].mask;
15366 if (constraints[i].reg != REG_UNSET) {
15367 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15368 error(state, 0, "Only one register may be specified");
15370 reg = constraints[i].reg;
15374 result.regcm = mask;
15378 static struct reg_info arch_reg_clobber(
15379 struct compile_state *state, const char *clobber)
15381 struct reg_info result;
15382 if (strcmp(clobber, "memory") == 0) {
15383 result.reg = REG_UNSET;
15386 else if (strcmp(clobber, "%eax") == 0) {
15387 result.reg = REG_EAX;
15388 result.regcm = REGCM_GPR32;
15390 else if (strcmp(clobber, "%ebx") == 0) {
15391 result.reg = REG_EBX;
15392 result.regcm = REGCM_GPR32;
15394 else if (strcmp(clobber, "%ecx") == 0) {
15395 result.reg = REG_ECX;
15396 result.regcm = REGCM_GPR32;
15398 else if (strcmp(clobber, "%edx") == 0) {
15399 result.reg = REG_EDX;
15400 result.regcm = REGCM_GPR32;
15402 else if (strcmp(clobber, "%esi") == 0) {
15403 result.reg = REG_ESI;
15404 result.regcm = REGCM_GPR32;
15406 else if (strcmp(clobber, "%edi") == 0) {
15407 result.reg = REG_EDI;
15408 result.regcm = REGCM_GPR32;
15410 else if (strcmp(clobber, "%ebp") == 0) {
15411 result.reg = REG_EBP;
15412 result.regcm = REGCM_GPR32;
15414 else if (strcmp(clobber, "%esp") == 0) {
15415 result.reg = REG_ESP;
15416 result.regcm = REGCM_GPR32;
15418 else if (strcmp(clobber, "cc") == 0) {
15419 result.reg = REG_EFLAGS;
15420 result.regcm = REGCM_FLAGS;
15422 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15423 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15424 result.reg = REG_XMM0 + octdigval(clobber[3]);
15425 result.regcm = REGCM_XMM;
15427 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15428 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15429 result.reg = REG_MMX0 + octdigval(clobber[3]);
15430 result.regcm = REGCM_MMX;
15433 error(state, 0, "Invalid register clobber");
15434 result.reg = REG_UNSET;
15440 static int do_select_reg(struct compile_state *state,
15441 char *used, int reg, unsigned classes)
15447 mask = arch_reg_regcm(state, reg);
15448 return (classes & mask) ? reg : REG_UNSET;
15451 static int arch_select_free_register(
15452 struct compile_state *state, char *used, int classes)
15454 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
15455 * other types of registers.
15459 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15460 reg = do_select_reg(state, used, i, classes);
15462 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
15463 reg = do_select_reg(state, used, i, classes);
15465 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15466 reg = do_select_reg(state, used, i, classes);
15468 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15469 reg = do_select_reg(state, used, i, classes);
15471 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15472 reg = do_select_reg(state, used, i, classes);
15474 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15475 reg = do_select_reg(state, used, i, classes);
15477 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15478 reg = do_select_reg(state, used, i, classes);
15484 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15486 #warning "FIXME force types smaller (if legal) before I get here"
15487 unsigned avail_mask;
15490 avail_mask = arch_avail_mask(state);
15491 switch(type->type & TYPE_MASK) {
15498 mask = REGCM_GPR8 |
15499 REGCM_GPR16 | REGCM_GPR16_8 |
15500 REGCM_GPR32 | REGCM_GPR32_8 |
15502 REGCM_MMX | REGCM_XMM |
15503 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15507 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15508 REGCM_GPR32 | REGCM_GPR32_8 |
15510 REGCM_MMX | REGCM_XMM |
15511 REGCM_IMM32 | REGCM_IMM16;
15518 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15519 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15523 internal_error(state, 0, "no register class for type");
15526 mask &= avail_mask;
15530 static int is_imm32(struct triple *imm)
15532 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15533 (imm->op == OP_ADDRCONST);
15536 static int is_imm16(struct triple *imm)
15538 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15540 static int is_imm8(struct triple *imm)
15542 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15545 static int get_imm32(struct triple *ins, struct triple **expr)
15547 struct triple *imm;
15549 while(imm->op == OP_COPY) {
15552 if (!is_imm32(imm)) {
15555 unuse_triple(*expr, ins);
15556 use_triple(imm, ins);
15561 static int get_imm8(struct triple *ins, struct triple **expr)
15563 struct triple *imm;
15565 while(imm->op == OP_COPY) {
15568 if (!is_imm8(imm)) {
15571 unuse_triple(*expr, ins);
15572 use_triple(imm, ins);
15577 #define TEMPLATE_NOP 0
15578 #define TEMPLATE_INTCONST8 1
15579 #define TEMPLATE_INTCONST32 2
15580 #define TEMPLATE_COPY_REG 3
15581 #define TEMPLATE_COPY_IMM32 4
15582 #define TEMPLATE_COPY_IMM16 5
15583 #define TEMPLATE_COPY_IMM8 6
15584 #define TEMPLATE_PHI 7
15585 #define TEMPLATE_STORE8 8
15586 #define TEMPLATE_STORE16 9
15587 #define TEMPLATE_STORE32 10
15588 #define TEMPLATE_LOAD8 11
15589 #define TEMPLATE_LOAD16 12
15590 #define TEMPLATE_LOAD32 13
15591 #define TEMPLATE_BINARY_REG 14
15592 #define TEMPLATE_BINARY_IMM 15
15593 #define TEMPLATE_SL_CL 16
15594 #define TEMPLATE_SL_IMM 17
15595 #define TEMPLATE_UNARY 18
15596 #define TEMPLATE_CMP_REG 19
15597 #define TEMPLATE_CMP_IMM 20
15598 #define TEMPLATE_TEST 21
15599 #define TEMPLATE_SET 22
15600 #define TEMPLATE_JMP 23
15601 #define TEMPLATE_INB_DX 24
15602 #define TEMPLATE_INB_IMM 25
15603 #define TEMPLATE_INW_DX 26
15604 #define TEMPLATE_INW_IMM 27
15605 #define TEMPLATE_INL_DX 28
15606 #define TEMPLATE_INL_IMM 29
15607 #define TEMPLATE_OUTB_DX 30
15608 #define TEMPLATE_OUTB_IMM 31
15609 #define TEMPLATE_OUTW_DX 32
15610 #define TEMPLATE_OUTW_IMM 33
15611 #define TEMPLATE_OUTL_DX 34
15612 #define TEMPLATE_OUTL_IMM 35
15613 #define TEMPLATE_BSF 36
15614 #define TEMPLATE_RDMSR 37
15615 #define TEMPLATE_WRMSR 38
15616 #define LAST_TEMPLATE TEMPLATE_WRMSR
15617 #if LAST_TEMPLATE >= MAX_TEMPLATES
15618 #error "MAX_TEMPLATES to low"
15621 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15622 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15624 static struct ins_template templates[] = {
15625 [TEMPLATE_NOP] = {},
15626 [TEMPLATE_INTCONST8] = {
15627 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15629 [TEMPLATE_INTCONST32] = {
15630 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15632 [TEMPLATE_COPY_REG] = {
15633 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15634 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
15636 [TEMPLATE_COPY_IMM32] = {
15637 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15638 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15640 [TEMPLATE_COPY_IMM16] = {
15641 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15642 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15644 [TEMPLATE_COPY_IMM8] = {
15645 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15646 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15649 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15651 [ 0] = { REG_VIRT0, COPY_REGCM },
15652 [ 1] = { REG_VIRT0, COPY_REGCM },
15653 [ 2] = { REG_VIRT0, COPY_REGCM },
15654 [ 3] = { REG_VIRT0, COPY_REGCM },
15655 [ 4] = { REG_VIRT0, COPY_REGCM },
15656 [ 5] = { REG_VIRT0, COPY_REGCM },
15657 [ 6] = { REG_VIRT0, COPY_REGCM },
15658 [ 7] = { REG_VIRT0, COPY_REGCM },
15659 [ 8] = { REG_VIRT0, COPY_REGCM },
15660 [ 9] = { REG_VIRT0, COPY_REGCM },
15661 [10] = { REG_VIRT0, COPY_REGCM },
15662 [11] = { REG_VIRT0, COPY_REGCM },
15663 [12] = { REG_VIRT0, COPY_REGCM },
15664 [13] = { REG_VIRT0, COPY_REGCM },
15665 [14] = { REG_VIRT0, COPY_REGCM },
15666 [15] = { REG_VIRT0, COPY_REGCM },
15668 [TEMPLATE_STORE8] = {
15669 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15670 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15672 [TEMPLATE_STORE16] = {
15673 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15674 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15676 [TEMPLATE_STORE32] = {
15677 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15678 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15680 [TEMPLATE_LOAD8] = {
15681 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15682 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15684 [TEMPLATE_LOAD16] = {
15685 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15686 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15688 [TEMPLATE_LOAD32] = {
15689 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15690 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15692 [TEMPLATE_BINARY_REG] = {
15693 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15695 [0] = { REG_VIRT0, REGCM_GPR32 },
15696 [1] = { REG_UNSET, REGCM_GPR32 },
15699 [TEMPLATE_BINARY_IMM] = {
15700 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15702 [0] = { REG_VIRT0, REGCM_GPR32 },
15703 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15706 [TEMPLATE_SL_CL] = {
15707 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15709 [0] = { REG_VIRT0, REGCM_GPR32 },
15710 [1] = { REG_CL, REGCM_GPR8 },
15713 [TEMPLATE_SL_IMM] = {
15714 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15716 [0] = { REG_VIRT0, REGCM_GPR32 },
15717 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15720 [TEMPLATE_UNARY] = {
15721 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15722 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15724 [TEMPLATE_CMP_REG] = {
15725 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15727 [0] = { REG_UNSET, REGCM_GPR32 },
15728 [1] = { REG_UNSET, REGCM_GPR32 },
15731 [TEMPLATE_CMP_IMM] = {
15732 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15734 [0] = { REG_UNSET, REGCM_GPR32 },
15735 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15738 [TEMPLATE_TEST] = {
15739 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15740 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15743 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15744 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15747 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15749 [TEMPLATE_INB_DX] = {
15750 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15751 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15753 [TEMPLATE_INB_IMM] = {
15754 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15755 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15757 [TEMPLATE_INW_DX] = {
15758 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15759 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15761 [TEMPLATE_INW_IMM] = {
15762 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15763 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15765 [TEMPLATE_INL_DX] = {
15766 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15767 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15769 [TEMPLATE_INL_IMM] = {
15770 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15771 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15773 [TEMPLATE_OUTB_DX] = {
15775 [0] = { REG_AL, REGCM_GPR8 },
15776 [1] = { REG_DX, REGCM_GPR16 },
15779 [TEMPLATE_OUTB_IMM] = {
15781 [0] = { REG_AL, REGCM_GPR8 },
15782 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15785 [TEMPLATE_OUTW_DX] = {
15787 [0] = { REG_AX, REGCM_GPR16 },
15788 [1] = { REG_DX, REGCM_GPR16 },
15791 [TEMPLATE_OUTW_IMM] = {
15793 [0] = { REG_AX, REGCM_GPR16 },
15794 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15797 [TEMPLATE_OUTL_DX] = {
15799 [0] = { REG_EAX, REGCM_GPR32 },
15800 [1] = { REG_DX, REGCM_GPR16 },
15803 [TEMPLATE_OUTL_IMM] = {
15805 [0] = { REG_EAX, REGCM_GPR32 },
15806 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15810 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15811 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15813 [TEMPLATE_RDMSR] = {
15815 [0] = { REG_EAX, REGCM_GPR32 },
15816 [1] = { REG_EDX, REGCM_GPR32 },
15818 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15820 [TEMPLATE_WRMSR] = {
15822 [0] = { REG_ECX, REGCM_GPR32 },
15823 [1] = { REG_EAX, REGCM_GPR32 },
15824 [2] = { REG_EDX, REGCM_GPR32 },
15829 static void fixup_branches(struct compile_state *state,
15830 struct triple *cmp, struct triple *use, int jmp_op)
15832 struct triple_set *entry, *next;
15833 for(entry = use->use; entry; entry = next) {
15834 next = entry->next;
15835 if (entry->member->op == OP_COPY) {
15836 fixup_branches(state, cmp, entry->member, jmp_op);
15838 else if (entry->member->op == OP_BRANCH) {
15839 struct triple *branch, *test;
15840 struct triple *left, *right;
15842 left = RHS(cmp, 0);
15843 if (TRIPLE_RHS(cmp->sizes) > 1) {
15844 right = RHS(cmp, 1);
15846 branch = entry->member;
15847 test = pre_triple(state, branch,
15848 cmp->op, cmp->type, left, right);
15849 test->template_id = TEMPLATE_TEST;
15850 if (cmp->op == OP_CMP) {
15851 test->template_id = TEMPLATE_CMP_REG;
15852 if (get_imm32(test, &RHS(test, 1))) {
15853 test->template_id = TEMPLATE_CMP_IMM;
15856 use_triple(RHS(test, 0), test);
15857 use_triple(RHS(test, 1), test);
15858 unuse_triple(RHS(branch, 0), branch);
15859 RHS(branch, 0) = test;
15860 branch->op = jmp_op;
15861 branch->template_id = TEMPLATE_JMP;
15862 use_triple(RHS(branch, 0), branch);
15867 static void bool_cmp(struct compile_state *state,
15868 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15870 struct triple_set *entry, *next;
15871 struct triple *set;
15873 /* Put a barrier up before the cmp which preceeds the
15874 * copy instruction. If a set actually occurs this gives
15875 * us a chance to move variables in registers out of the way.
15878 /* Modify the comparison operator */
15880 ins->template_id = TEMPLATE_TEST;
15881 if (cmp_op == OP_CMP) {
15882 ins->template_id = TEMPLATE_CMP_REG;
15883 if (get_imm32(ins, &RHS(ins, 1))) {
15884 ins->template_id = TEMPLATE_CMP_IMM;
15887 /* Generate the instruction sequence that will transform the
15888 * result of the comparison into a logical value.
15890 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15891 use_triple(ins, set);
15892 set->template_id = TEMPLATE_SET;
15894 for(entry = ins->use; entry; entry = next) {
15895 next = entry->next;
15896 if (entry->member == set) {
15899 replace_rhs_use(state, ins, set, entry->member);
15901 fixup_branches(state, ins, set, jmp_op);
15904 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15906 struct triple *next;
15908 lhs = TRIPLE_LHS(ins->sizes);
15909 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15910 if (next != LHS(ins, i)) {
15911 internal_error(state, ins, "malformed lhs on %s",
15914 if (next->op != OP_PIECE) {
15915 internal_error(state, ins, "bad lhs op %s at %d on %s",
15916 tops(next->op), i, tops(ins->op));
15918 if (next->u.cval != i) {
15919 internal_error(state, ins, "bad u.cval of %d %d expected",
15926 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15928 struct ins_template *template;
15929 struct reg_info result;
15931 if (ins->op == OP_PIECE) {
15932 index = ins->u.cval;
15933 ins = MISC(ins, 0);
15935 zlhs = TRIPLE_LHS(ins->sizes);
15936 if (triple_is_def(state, ins)) {
15939 if (index >= zlhs) {
15940 internal_error(state, ins, "index %d out of range for %s\n",
15941 index, tops(ins->op));
15945 template = &ins->u.ainfo->tmpl;
15948 if (ins->template_id > LAST_TEMPLATE) {
15949 internal_error(state, ins, "bad template number %d",
15952 template = &templates[ins->template_id];
15955 result = template->lhs[index];
15956 result.regcm = arch_regcm_normalize(state, result.regcm);
15957 if (result.reg != REG_UNNEEDED) {
15958 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15960 if (result.regcm == 0) {
15961 internal_error(state, ins, "lhs %d regcm == 0", index);
15966 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15968 struct reg_info result;
15969 struct ins_template *template;
15970 if ((index > TRIPLE_RHS(ins->sizes)) ||
15971 (ins->op == OP_PIECE)) {
15972 internal_error(state, ins, "index %d out of range for %s\n",
15973 index, tops(ins->op));
15977 template = &ins->u.ainfo->tmpl;
15980 if (ins->template_id > LAST_TEMPLATE) {
15981 internal_error(state, ins, "bad template number %d",
15984 template = &templates[ins->template_id];
15987 result = template->rhs[index];
15988 result.regcm = arch_regcm_normalize(state, result.regcm);
15989 if (result.regcm == 0) {
15990 internal_error(state, ins, "rhs %d regcm == 0", index);
15995 static struct triple *transform_to_arch_instruction(
15996 struct compile_state *state, struct triple *ins)
15998 /* Transform from generic 3 address instructions
15999 * to archtecture specific instructions.
16000 * And apply architecture specific constrains to instructions.
16001 * Copies are inserted to preserve the register flexibility
16002 * of 3 address instructions.
16004 struct triple *next;
16008 ins->template_id = TEMPLATE_INTCONST32;
16009 if (ins->u.cval < 256) {
16010 ins->template_id = TEMPLATE_INTCONST8;
16014 ins->template_id = TEMPLATE_INTCONST32;
16020 ins->template_id = TEMPLATE_NOP;
16023 ins->template_id = TEMPLATE_COPY_REG;
16024 if (is_imm8(RHS(ins, 0))) {
16025 ins->template_id = TEMPLATE_COPY_IMM8;
16027 else if (is_imm16(RHS(ins, 0))) {
16028 ins->template_id = TEMPLATE_COPY_IMM16;
16030 else if (is_imm32(RHS(ins, 0))) {
16031 ins->template_id = TEMPLATE_COPY_IMM32;
16033 else if (is_const(RHS(ins, 0))) {
16034 internal_error(state, ins, "bad constant passed to copy");
16038 ins->template_id = TEMPLATE_PHI;
16041 switch(ins->type->type & TYPE_MASK) {
16042 case TYPE_CHAR: case TYPE_UCHAR:
16043 ins->template_id = TEMPLATE_STORE8;
16045 case TYPE_SHORT: case TYPE_USHORT:
16046 ins->template_id = TEMPLATE_STORE16;
16048 case TYPE_INT: case TYPE_UINT:
16049 case TYPE_LONG: case TYPE_ULONG:
16051 ins->template_id = TEMPLATE_STORE32;
16054 internal_error(state, ins, "unknown type in store");
16059 switch(ins->type->type & TYPE_MASK) {
16060 case TYPE_CHAR: case TYPE_UCHAR:
16061 ins->template_id = TEMPLATE_LOAD8;
16065 ins->template_id = TEMPLATE_LOAD16;
16072 ins->template_id = TEMPLATE_LOAD32;
16075 internal_error(state, ins, "unknown type in load");
16085 ins->template_id = TEMPLATE_BINARY_REG;
16086 if (get_imm32(ins, &RHS(ins, 1))) {
16087 ins->template_id = TEMPLATE_BINARY_IMM;
16093 ins->template_id = TEMPLATE_SL_CL;
16094 if (get_imm8(ins, &RHS(ins, 1))) {
16095 ins->template_id = TEMPLATE_SL_IMM;
16100 ins->template_id = TEMPLATE_UNARY;
16103 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16106 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16109 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16112 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16115 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16118 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16121 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16124 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16127 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16130 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16133 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16136 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16139 if (TRIPLE_RHS(ins->sizes) > 0) {
16140 internal_error(state, ins, "bad branch test");
16143 ins->template_id = TEMPLATE_NOP;
16149 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16150 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16151 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16153 if (get_imm8(ins, &RHS(ins, 0))) {
16154 ins->template_id += 1;
16161 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16162 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16163 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16165 if (get_imm8(ins, &RHS(ins, 1))) {
16166 ins->template_id += 1;
16171 ins->template_id = TEMPLATE_BSF;
16174 ins->template_id = TEMPLATE_RDMSR;
16175 next = after_lhs(state, ins);
16178 ins->template_id = TEMPLATE_WRMSR;
16181 ins->template_id = TEMPLATE_NOP;
16184 ins->template_id = TEMPLATE_NOP;
16185 next = after_lhs(state, ins);
16187 /* Already transformed instructions */
16189 ins->template_id = TEMPLATE_TEST;
16192 ins->template_id = TEMPLATE_CMP_REG;
16193 if (get_imm32(ins, &RHS(ins, 1))) {
16194 ins->template_id = TEMPLATE_CMP_IMM;
16197 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16198 case OP_JMP_SLESS: case OP_JMP_ULESS:
16199 case OP_JMP_SMORE: case OP_JMP_UMORE:
16200 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16201 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16202 ins->template_id = TEMPLATE_JMP;
16204 case OP_SET_EQ: case OP_SET_NOTEQ:
16205 case OP_SET_SLESS: case OP_SET_ULESS:
16206 case OP_SET_SMORE: case OP_SET_UMORE:
16207 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16208 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16209 ins->template_id = TEMPLATE_SET;
16211 /* Unhandled instructions */
16214 internal_error(state, ins, "unhandled ins: %d %s\n",
16215 ins->op, tops(ins->op));
16221 static void generate_local_labels(struct compile_state *state)
16223 struct triple *first, *label;
16226 first = RHS(state->main_function, 0);
16229 if ((label->op == OP_LABEL) ||
16230 (label->op == OP_SDECL)) {
16232 label->u.cval = ++label_counter;
16238 label = label->next;
16239 } while(label != first);
16242 static int check_reg(struct compile_state *state,
16243 struct triple *triple, int classes)
16247 reg = ID_REG(triple->id);
16248 if (reg == REG_UNSET) {
16249 internal_error(state, triple, "register not set");
16251 mask = arch_reg_regcm(state, reg);
16252 if (!(classes & mask)) {
16253 internal_error(state, triple, "reg %d in wrong class",
16259 static const char *arch_reg_str(int reg)
16261 static const char *regs[] = {
16265 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16266 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16267 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16269 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16270 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16271 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16273 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16280 static const char *reg(struct compile_state *state, struct triple *triple,
16284 reg = check_reg(state, triple, classes);
16285 return arch_reg_str(reg);
16288 const char *type_suffix(struct compile_state *state, struct type *type)
16290 const char *suffix;
16291 switch(size_of(state, type)) {
16292 case 1: suffix = "b"; break;
16293 case 2: suffix = "w"; break;
16294 case 4: suffix = "l"; break;
16296 internal_error(state, 0, "unknown suffix");
16303 static void print_const_val(
16304 struct compile_state *state, struct triple *ins, FILE *fp)
16308 fprintf(fp, " $%ld ",
16309 (long_t)(ins->u.cval));
16312 fprintf(fp, " $L%s%lu+%lu ",
16313 state->label_prefix,
16314 MISC(ins, 0)->u.cval,
16318 internal_error(state, ins, "unknown constant type");
16323 static void print_binary_op(struct compile_state *state,
16324 const char *op, struct triple *ins, FILE *fp)
16327 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16328 if (RHS(ins, 0)->id != ins->id) {
16329 internal_error(state, ins, "invalid register assignment");
16331 if (is_const(RHS(ins, 1))) {
16332 fprintf(fp, "\t%s ", op);
16333 print_const_val(state, RHS(ins, 1), fp);
16334 fprintf(fp, ", %s\n",
16335 reg(state, RHS(ins, 0), mask));
16338 unsigned lmask, rmask;
16340 lreg = check_reg(state, RHS(ins, 0), mask);
16341 rreg = check_reg(state, RHS(ins, 1), mask);
16342 lmask = arch_reg_regcm(state, lreg);
16343 rmask = arch_reg_regcm(state, rreg);
16344 mask = lmask & rmask;
16345 fprintf(fp, "\t%s %s, %s\n",
16347 reg(state, RHS(ins, 1), mask),
16348 reg(state, RHS(ins, 0), mask));
16351 static void print_unary_op(struct compile_state *state,
16352 const char *op, struct triple *ins, FILE *fp)
16355 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16356 fprintf(fp, "\t%s %s\n",
16358 reg(state, RHS(ins, 0), mask));
16361 static void print_op_shift(struct compile_state *state,
16362 const char *op, struct triple *ins, FILE *fp)
16365 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16366 if (RHS(ins, 0)->id != ins->id) {
16367 internal_error(state, ins, "invalid register assignment");
16369 if (is_const(RHS(ins, 1))) {
16370 fprintf(fp, "\t%s ", op);
16371 print_const_val(state, RHS(ins, 1), fp);
16372 fprintf(fp, ", %s\n",
16373 reg(state, RHS(ins, 0), mask));
16376 fprintf(fp, "\t%s %s, %s\n",
16378 reg(state, RHS(ins, 1), REGCM_GPR8),
16379 reg(state, RHS(ins, 0), mask));
16383 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16390 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16391 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16392 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16394 internal_error(state, ins, "not an in operation");
16398 dreg = check_reg(state, ins, mask);
16399 if (!reg_is_reg(state, dreg, REG_EAX)) {
16400 internal_error(state, ins, "dst != %%eax");
16402 if (is_const(RHS(ins, 0))) {
16403 fprintf(fp, "\t%s ", op);
16404 print_const_val(state, RHS(ins, 0), fp);
16405 fprintf(fp, ", %s\n",
16406 reg(state, ins, mask));
16410 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16411 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16412 internal_error(state, ins, "src != %%dx");
16414 fprintf(fp, "\t%s %s, %s\n",
16416 reg(state, RHS(ins, 0), REGCM_GPR16),
16417 reg(state, ins, mask));
16421 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16428 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16429 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16430 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16432 internal_error(state, ins, "not an out operation");
16436 lreg = check_reg(state, RHS(ins, 0), mask);
16437 if (!reg_is_reg(state, lreg, REG_EAX)) {
16438 internal_error(state, ins, "src != %%eax");
16440 if (is_const(RHS(ins, 1))) {
16441 fprintf(fp, "\t%s %s,",
16442 op, reg(state, RHS(ins, 0), mask));
16443 print_const_val(state, RHS(ins, 1), fp);
16448 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16449 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16450 internal_error(state, ins, "dst != %%dx");
16452 fprintf(fp, "\t%s %s, %s\n",
16454 reg(state, RHS(ins, 0), mask),
16455 reg(state, RHS(ins, 1), REGCM_GPR16));
16459 static void print_op_move(struct compile_state *state,
16460 struct triple *ins, FILE *fp)
16462 /* op_move is complex because there are many types
16463 * of registers we can move between.
16464 * Because OP_COPY will be introduced in arbitrary locations
16465 * OP_COPY must not affect flags.
16467 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16468 struct triple *dst, *src;
16469 if (ins->op == OP_COPY) {
16473 else if (ins->op == OP_WRITE) {
16478 internal_error(state, ins, "unknown move operation");
16481 if (!is_const(src)) {
16482 int src_reg, dst_reg;
16483 int src_regcm, dst_regcm;
16484 src_reg = ID_REG(src->id);
16485 dst_reg = ID_REG(dst->id);
16486 src_regcm = arch_reg_regcm(state, src_reg);
16487 dst_regcm = arch_reg_regcm(state, dst_reg);
16488 /* If the class is the same just move the register */
16489 if (src_regcm & dst_regcm &
16490 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16491 if ((src_reg != dst_reg) || !omit_copy) {
16492 fprintf(fp, "\tmov %s, %s\n",
16493 reg(state, src, src_regcm),
16494 reg(state, dst, dst_regcm));
16497 /* Move 32bit to 16bit */
16498 else if ((src_regcm & REGCM_GPR32) &&
16499 (dst_regcm & REGCM_GPR16)) {
16500 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16501 if ((src_reg != dst_reg) || !omit_copy) {
16502 fprintf(fp, "\tmovw %s, %s\n",
16503 arch_reg_str(src_reg),
16504 arch_reg_str(dst_reg));
16507 /* Move 32bit to 8bit */
16508 else if ((src_regcm & REGCM_GPR32_8) &&
16509 (dst_regcm & REGCM_GPR8))
16511 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16512 if ((src_reg != dst_reg) || !omit_copy) {
16513 fprintf(fp, "\tmovb %s, %s\n",
16514 arch_reg_str(src_reg),
16515 arch_reg_str(dst_reg));
16518 /* Move 16bit to 8bit */
16519 else if ((src_regcm & REGCM_GPR16_8) &&
16520 (dst_regcm & REGCM_GPR8))
16522 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16523 if ((src_reg != dst_reg) || !omit_copy) {
16524 fprintf(fp, "\tmovb %s, %s\n",
16525 arch_reg_str(src_reg),
16526 arch_reg_str(dst_reg));
16529 /* Move 8/16bit to 16/32bit */
16530 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
16531 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16533 op = is_signed(src->type)? "movsx": "movzx";
16534 fprintf(fp, "\t%s %s, %s\n",
16536 reg(state, src, src_regcm),
16537 reg(state, dst, dst_regcm));
16539 /* Move between sse registers */
16540 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16541 if ((src_reg != dst_reg) || !omit_copy) {
16542 fprintf(fp, "\tmovdqa %s, %s\n",
16543 reg(state, src, src_regcm),
16544 reg(state, dst, dst_regcm));
16547 /* Move between mmx registers or mmx & sse registers */
16548 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16549 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16550 if ((src_reg != dst_reg) || !omit_copy) {
16551 fprintf(fp, "\tmovq %s, %s\n",
16552 reg(state, src, src_regcm),
16553 reg(state, dst, dst_regcm));
16556 /* Move between 32bit gprs & mmx/sse registers */
16557 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16558 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16559 fprintf(fp, "\tmovd %s, %s\n",
16560 reg(state, src, src_regcm),
16561 reg(state, dst, dst_regcm));
16563 #if X86_4_8BIT_GPRS
16564 /* Move from 8bit gprs to mmx/sse registers */
16565 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16566 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16569 op = is_signed(src->type)? "movsx":"movzx";
16570 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16571 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16573 reg(state, src, src_regcm),
16574 arch_reg_str(mid_reg),
16575 arch_reg_str(mid_reg),
16576 reg(state, dst, dst_regcm));
16578 /* Move from mmx/sse registers and 8bit gprs */
16579 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16580 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16582 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16583 fprintf(fp, "\tmovd %s, %s\n",
16584 reg(state, src, src_regcm),
16585 arch_reg_str(mid_reg));
16587 /* Move from 32bit gprs to 16bit gprs */
16588 else if ((src_regcm & REGCM_GPR32) &&
16589 (dst_regcm & REGCM_GPR16)) {
16590 dst_reg = (dst_reg - REGC_GPR16_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 32bit gprs to 8bit gprs */
16598 else if ((src_regcm & REGCM_GPR32) &&
16599 (dst_regcm & REGCM_GPR8)) {
16600 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_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 /* Move from 16bit gprs to 8bit gprs */
16608 else if ((src_regcm & REGCM_GPR16) &&
16609 (dst_regcm & REGCM_GPR8)) {
16610 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16611 if ((src_reg != dst_reg) || !omit_copy) {
16612 fprintf(fp, "\tmov %s, %s\n",
16613 arch_reg_str(src_reg),
16614 arch_reg_str(dst_reg));
16617 #endif /* X86_4_8BIT_GPRS */
16619 internal_error(state, ins, "unknown copy type");
16623 fprintf(fp, "\tmov ");
16624 print_const_val(state, src, fp);
16625 fprintf(fp, ", %s\n",
16626 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16630 static void print_op_load(struct compile_state *state,
16631 struct triple *ins, FILE *fp)
16633 struct triple *dst, *src;
16636 if (is_const(src) || is_const(dst)) {
16637 internal_error(state, ins, "unknown load operation");
16639 fprintf(fp, "\tmov (%s), %s\n",
16640 reg(state, src, REGCM_GPR32),
16641 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16645 static void print_op_store(struct compile_state *state,
16646 struct triple *ins, FILE *fp)
16648 struct triple *dst, *src;
16651 if (is_const(src) && (src->op == OP_INTCONST)) {
16653 value = (long_t)(src->u.cval);
16654 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16655 type_suffix(state, src->type),
16657 reg(state, dst, REGCM_GPR32));
16659 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16660 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16661 type_suffix(state, src->type),
16662 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16666 if (is_const(src) || is_const(dst)) {
16667 internal_error(state, ins, "unknown store operation");
16669 fprintf(fp, "\tmov%s %s, (%s)\n",
16670 type_suffix(state, src->type),
16671 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16672 reg(state, dst, REGCM_GPR32));
16678 static void print_op_smul(struct compile_state *state,
16679 struct triple *ins, FILE *fp)
16681 if (!is_const(RHS(ins, 1))) {
16682 fprintf(fp, "\timul %s, %s\n",
16683 reg(state, RHS(ins, 1), REGCM_GPR32),
16684 reg(state, RHS(ins, 0), REGCM_GPR32));
16687 fprintf(fp, "\timul ");
16688 print_const_val(state, RHS(ins, 1), fp);
16689 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16693 static void print_op_cmp(struct compile_state *state,
16694 struct triple *ins, FILE *fp)
16698 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16699 dreg = check_reg(state, ins, REGCM_FLAGS);
16700 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16701 internal_error(state, ins, "bad dest register for cmp");
16703 if (is_const(RHS(ins, 1))) {
16704 fprintf(fp, "\tcmp ");
16705 print_const_val(state, RHS(ins, 1), fp);
16706 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16709 unsigned lmask, rmask;
16711 lreg = check_reg(state, RHS(ins, 0), mask);
16712 rreg = check_reg(state, RHS(ins, 1), mask);
16713 lmask = arch_reg_regcm(state, lreg);
16714 rmask = arch_reg_regcm(state, rreg);
16715 mask = lmask & rmask;
16716 fprintf(fp, "\tcmp %s, %s\n",
16717 reg(state, RHS(ins, 1), mask),
16718 reg(state, RHS(ins, 0), mask));
16722 static void print_op_test(struct compile_state *state,
16723 struct triple *ins, FILE *fp)
16726 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16727 fprintf(fp, "\ttest %s, %s\n",
16728 reg(state, RHS(ins, 0), mask),
16729 reg(state, RHS(ins, 0), mask));
16732 static void print_op_branch(struct compile_state *state,
16733 struct triple *branch, FILE *fp)
16735 const char *bop = "j";
16736 if (branch->op == OP_JMP) {
16737 if (TRIPLE_RHS(branch->sizes) != 0) {
16738 internal_error(state, branch, "jmp with condition?");
16743 struct triple *ptr;
16744 if (TRIPLE_RHS(branch->sizes) != 1) {
16745 internal_error(state, branch, "jmpcc without condition?");
16747 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16748 if ((RHS(branch, 0)->op != OP_CMP) &&
16749 (RHS(branch, 0)->op != OP_TEST)) {
16750 internal_error(state, branch, "bad branch test");
16752 #warning "FIXME I have observed instructions between the test and branch instructions"
16753 ptr = RHS(branch, 0);
16754 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16755 if (ptr->op != OP_COPY) {
16756 internal_error(state, branch, "branch does not follow test");
16759 switch(branch->op) {
16760 case OP_JMP_EQ: bop = "jz"; break;
16761 case OP_JMP_NOTEQ: bop = "jnz"; break;
16762 case OP_JMP_SLESS: bop = "jl"; break;
16763 case OP_JMP_ULESS: bop = "jb"; break;
16764 case OP_JMP_SMORE: bop = "jg"; break;
16765 case OP_JMP_UMORE: bop = "ja"; break;
16766 case OP_JMP_SLESSEQ: bop = "jle"; break;
16767 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16768 case OP_JMP_SMOREEQ: bop = "jge"; break;
16769 case OP_JMP_UMOREEQ: bop = "jae"; break;
16771 internal_error(state, branch, "Invalid branch op");
16776 fprintf(fp, "\t%s L%s%lu\n",
16778 state->label_prefix,
16779 TARG(branch, 0)->u.cval);
16782 static void print_op_set(struct compile_state *state,
16783 struct triple *set, FILE *fp)
16785 const char *sop = "set";
16786 if (TRIPLE_RHS(set->sizes) != 1) {
16787 internal_error(state, set, "setcc without condition?");
16789 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16790 if ((RHS(set, 0)->op != OP_CMP) &&
16791 (RHS(set, 0)->op != OP_TEST)) {
16792 internal_error(state, set, "bad set test");
16794 if (RHS(set, 0)->next != set) {
16795 internal_error(state, set, "set does not follow test");
16798 case OP_SET_EQ: sop = "setz"; break;
16799 case OP_SET_NOTEQ: sop = "setnz"; break;
16800 case OP_SET_SLESS: sop = "setl"; break;
16801 case OP_SET_ULESS: sop = "setb"; break;
16802 case OP_SET_SMORE: sop = "setg"; break;
16803 case OP_SET_UMORE: sop = "seta"; break;
16804 case OP_SET_SLESSEQ: sop = "setle"; break;
16805 case OP_SET_ULESSEQ: sop = "setbe"; break;
16806 case OP_SET_SMOREEQ: sop = "setge"; break;
16807 case OP_SET_UMOREEQ: sop = "setae"; break;
16809 internal_error(state, set, "Invalid set op");
16812 fprintf(fp, "\t%s %s\n",
16813 sop, reg(state, set, REGCM_GPR8));
16816 static void print_op_bit_scan(struct compile_state *state,
16817 struct triple *ins, FILE *fp)
16821 case OP_BSF: op = "bsf"; break;
16822 case OP_BSR: op = "bsr"; break;
16824 internal_error(state, ins, "unknown bit scan");
16834 reg(state, RHS(ins, 0), REGCM_GPR32),
16835 reg(state, ins, REGCM_GPR32),
16836 reg(state, ins, REGCM_GPR32));
16839 static void print_const(struct compile_state *state,
16840 struct triple *ins, FILE *fp)
16844 switch(ins->type->type & TYPE_MASK) {
16847 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16851 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16857 fprintf(fp, ".int %lu\n", ins->u.cval);
16860 internal_error(state, ins, "Unknown constant type");
16865 unsigned char *blob;
16867 size = size_of(state, ins->type);
16868 blob = ins->u.blob;
16869 for(i = 0; i < size; i++) {
16870 fprintf(fp, ".byte 0x%02x\n",
16876 internal_error(state, ins, "Unknown constant type");
16881 #define TEXT_SECTION ".rom.text"
16882 #define DATA_SECTION ".rom.data"
16884 static void print_sdecl(struct compile_state *state,
16885 struct triple *ins, FILE *fp)
16887 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16888 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16889 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16890 print_const(state, MISC(ins, 0), fp);
16891 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16895 static void print_instruction(struct compile_state *state,
16896 struct triple *ins, FILE *fp)
16898 /* Assumption: after I have exted the register allocator
16899 * everything is in a valid register.
16903 print_op_asm(state, ins, fp);
16905 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16906 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16907 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16908 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16909 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16910 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16911 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16912 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16913 case OP_POS: break;
16914 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16915 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16919 /* Don't generate anything here for constants */
16921 /* Don't generate anything for variable declarations. */
16924 print_sdecl(state, ins, fp);
16928 print_op_move(state, ins, fp);
16931 print_op_load(state, ins, fp);
16934 print_op_store(state, ins, fp);
16937 print_op_smul(state, ins, fp);
16939 case OP_CMP: print_op_cmp(state, ins, fp); break;
16940 case OP_TEST: print_op_test(state, ins, fp); break;
16942 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16943 case OP_JMP_SLESS: case OP_JMP_ULESS:
16944 case OP_JMP_SMORE: case OP_JMP_UMORE:
16945 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16946 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16947 print_op_branch(state, ins, fp);
16949 case OP_SET_EQ: case OP_SET_NOTEQ:
16950 case OP_SET_SLESS: case OP_SET_ULESS:
16951 case OP_SET_SMORE: case OP_SET_UMORE:
16952 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16953 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16954 print_op_set(state, ins, fp);
16956 case OP_INB: case OP_INW: case OP_INL:
16957 print_op_in(state, ins, fp);
16959 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16960 print_op_out(state, ins, fp);
16964 print_op_bit_scan(state, ins, fp);
16967 after_lhs(state, ins);
16968 fprintf(fp, "\trdmsr\n");
16971 fprintf(fp, "\twrmsr\n");
16974 fprintf(fp, "\thlt\n");
16980 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16982 /* Ignore OP_PIECE */
16985 /* Operations I am not yet certain how to handle */
16987 case OP_SDIV: case OP_UDIV:
16988 case OP_SMOD: case OP_UMOD:
16989 /* Operations that should never get here */
16990 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16991 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16992 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16994 internal_error(state, ins, "unknown op: %d %s",
16995 ins->op, tops(ins->op));
17000 static void print_instructions(struct compile_state *state)
17002 struct triple *first, *ins;
17003 int print_location;
17004 struct occurance *last_occurance;
17006 print_location = 1;
17007 last_occurance = 0;
17008 fp = state->output;
17009 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17010 first = RHS(state->main_function, 0);
17013 if (print_location &&
17014 last_occurance != ins->occurance) {
17015 if (!ins->occurance->parent) {
17016 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17017 ins->occurance->function,
17018 ins->occurance->filename,
17019 ins->occurance->line,
17020 ins->occurance->col);
17023 struct occurance *ptr;
17024 fprintf(fp, "\t/*\n");
17025 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17026 fprintf(fp, "\t * %s,%s:%d.%d\n",
17032 fprintf(fp, "\t */\n");
17035 if (last_occurance) {
17036 put_occurance(last_occurance);
17038 get_occurance(ins->occurance);
17039 last_occurance = ins->occurance;
17042 print_instruction(state, ins, fp);
17044 } while(ins != first);
17047 static void generate_code(struct compile_state *state)
17049 generate_local_labels(state);
17050 print_instructions(state);
17054 static void print_tokens(struct compile_state *state)
17057 tk = &state->token[0];
17062 next_token(state, 0);
17064 loc(stdout, state, 0);
17065 printf("%s <- `%s'\n",
17067 tk->ident ? tk->ident->name :
17068 tk->str_len ? tk->val.str : "");
17070 } while(tk->tok != TOK_EOF);
17073 static void compile(const char *filename, const char *ofilename,
17074 int cpu, int debug, int opt, const char *label_prefix)
17077 struct compile_state state;
17078 memset(&state, 0, sizeof(state));
17080 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17081 memset(&state.token[i], 0, sizeof(state.token[i]));
17082 state.token[i].tok = -1;
17084 /* Remember the debug settings */
17086 state.debug = debug;
17087 state.optimize = opt;
17088 /* Remember the output filename */
17089 state.ofilename = ofilename;
17090 state.output = fopen(state.ofilename, "w");
17091 if (!state.output) {
17092 error(&state, 0, "Cannot open output file %s\n",
17095 /* Remember the label prefix */
17096 state.label_prefix = label_prefix;
17097 /* Prep the preprocessor */
17098 state.if_depth = 0;
17099 state.if_value = 0;
17100 /* register the C keywords */
17101 register_keywords(&state);
17102 /* register the keywords the macro preprocessor knows */
17103 register_macro_keywords(&state);
17104 /* Memorize where some special keywords are. */
17105 state.i_continue = lookup(&state, "continue", 8);
17106 state.i_break = lookup(&state, "break", 5);
17107 /* Enter the globl definition scope */
17108 start_scope(&state);
17109 register_builtins(&state);
17110 compile_file(&state, filename, 1);
17112 print_tokens(&state);
17115 /* Exit the global definition scope */
17118 /* Now that basic compilation has happened
17119 * optimize the intermediate code
17123 generate_code(&state);
17125 fprintf(stderr, "done\n");
17129 static void version(void)
17131 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17134 static void usage(void)
17138 "Usage: romcc <source>.c\n"
17139 "Compile a C source file without using ram\n"
17143 static void arg_error(char *fmt, ...)
17146 va_start(args, fmt);
17147 vfprintf(stderr, fmt, args);
17153 int main(int argc, char **argv)
17155 const char *filename;
17156 const char *ofilename;
17157 const char *label_prefix;
17164 ofilename = "auto.inc";
17168 while((argc > 1) && (argc != last_argc)) {
17170 if (strncmp(argv[1], "--debug=", 8) == 0) {
17171 debug = atoi(argv[1] + 8);
17175 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17176 label_prefix= argv[1] + 15;
17180 else if ((strcmp(argv[1],"-O") == 0) ||
17181 (strcmp(argv[1], "-O1") == 0)) {
17186 else if (strcmp(argv[1],"-O2") == 0) {
17191 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17192 ofilename = argv[2];
17196 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17197 cpu = arch_encode_cpu(argv[1] + 6);
17198 if (cpu == BAD_CPU) {
17199 arg_error("Invalid cpu specified: %s\n",
17207 arg_error("Wrong argument count %d\n", argc);
17209 filename = argv[1];
17210 compile(filename, ofilename, cpu, debug, optimize, label_prefix);