15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
18 #define DEBUG_CONSISTENCY 1
20 #warning "FIXME boundary cases with small types in larger registers"
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;
222 struct hash_entry *ident;
230 /* I have two classes of types:
232 * Logical types. (The type the C standard says the operation is of)
234 * The operational types are:
249 * No memory is useable by the compiler.
250 * There is no floating point support.
251 * All operations take place in general purpose registers.
252 * There is one type of general purpose register.
253 * Unsigned longs are stored in that general purpose register.
256 /* Operations on general purpose registers.
273 #define OP_POS 14 /* Dummy positive operator don't use it */
283 #define OP_SLESSEQ 26
284 #define OP_ULESSEQ 27
285 #define OP_SMOREEQ 28
286 #define OP_UMOREEQ 29
288 #define OP_LFALSE 30 /* Test if the expression is logically false */
289 #define OP_LTRUE 31 /* Test if the expression is logcially true */
296 #define OP_MIN_CONST 50
297 #define OP_MAX_CONST 59
298 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
299 #define OP_INTCONST 50
300 #define OP_BLOBCONST 51
301 /* For OP_BLOBCONST ->type holds the layout and size
302 * information. u.blob holds a pointer to the raw binary
303 * data for the constant initializer.
305 #define OP_ADDRCONST 52
306 /* For OP_ADDRCONST ->type holds the type.
307 * MISC(0) holds the reference to the static variable.
308 * ->u.cval holds an offset from that value.
312 /* OP_WRITE moves one pseudo register to another.
313 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
314 * RHS(0) holds the psuedo to move.
318 /* OP_READ reads the value of a variable and makes
319 * it available for the pseudo operation.
320 * Useful for things like def-use chains.
321 * RHS(0) holds points to the triple to read from.
324 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
327 /* OP_PIECE returns one piece of a instruction that returns a structure.
328 * MISC(0) is the instruction
329 * u.cval is the LHS piece of the instruction to return.
332 /* OP_ASM holds a sequence of assembly instructions, the result
333 * of a C asm directive.
334 * RHS(x) holds input value x to the assembly sequence.
335 * LHS(x) holds the output value x from the assembly sequence.
336 * u.blob holds the string of assembly instructions.
340 /* OP_DEREF generates an lvalue from a pointer.
341 * RHS(0) holds the pointer value.
342 * OP_DEREF serves as a place holder to indicate all necessary
343 * checks have been done to indicate a value is an lvalue.
346 /* OP_DOT references a submember of a structure lvalue.
347 * RHS(0) holds the lvalue.
348 * ->u.field holds the name of the field we want.
350 * Not seen outside of expressions.
353 /* OP_VAL returns the value of a subexpression of the current expression.
354 * Useful for operators that have side effects.
355 * RHS(0) holds the expression.
356 * MISC(0) holds the subexpression of RHS(0) that is the
357 * value of the expression.
359 * Not seen outside of expressions.
362 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
363 * Not seen outside of expressions.
366 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
367 * Not seen outside of expressions.
370 /* OP_CODE performas a C ? : operation.
371 * RHS(0) holds the test.
372 * RHS(1) holds the expression to evaluate if the test returns true.
373 * RHS(2) holds the expression to evaluate if the test returns false.
374 * Not seen outside of expressions.
377 /* OP_COMMA performacs a C comma operation.
378 * That is RHS(0) is evaluated, then RHS(1)
379 * and the value of RHS(1) is returned.
380 * Not seen outside of expressions.
384 /* OP_CALL performs a procedure call.
385 * MISC(0) holds a pointer to the OP_LIST of a function
386 * RHS(x) holds argument x of a function
388 * Currently not seen outside of expressions.
390 #define OP_VAL_VEC 74
391 /* OP_VAL_VEC is an array of triples that are either variable
392 * or values for a structure or an array.
393 * RHS(x) holds element x of the vector.
394 * triple->type->elements holds the size of the vector.
399 /* OP_LIST Holds a list of statements, and a result value.
400 * RHS(0) holds the list of statements.
401 * MISC(0) holds the value of the statements.
404 #define OP_BRANCH 81 /* branch */
405 /* For branch instructions
406 * TARG(0) holds the branch target.
407 * RHS(0) if present holds the branch condition.
408 * ->next holds where to branch to if the branch is not taken.
409 * The branch target can only be a decl...
413 /* OP_LABEL is a triple that establishes an target for branches.
414 * ->use is the list of all branches that use this label.
418 /* OP_DECL is a triple that establishes an lvalue for assignments.
419 * ->use is a list of statements that use the variable.
423 /* OP_SDECL is a triple that establishes a variable of static
425 * ->use is a list of statements that use the variable.
426 * MISC(0) holds the initializer expression.
431 /* OP_PHI is a triple used in SSA form code.
432 * It is used when multiple code paths merge and a variable needs
433 * a single assignment from any of those code paths.
434 * The operation is a cross between OP_DECL and OP_WRITE, which
435 * is what OP_PHI is geneared from.
437 * RHS(x) points to the value from code path x
438 * The number of RHS entries is the number of control paths into the block
439 * in which OP_PHI resides. The elements of the array point to point
440 * to the variables OP_PHI is derived from.
442 * MISC(0) holds a pointer to the orginal OP_DECL node.
445 /* Architecture specific instructions */
448 #define OP_SET_EQ 102
449 #define OP_SET_NOTEQ 103
450 #define OP_SET_SLESS 104
451 #define OP_SET_ULESS 105
452 #define OP_SET_SMORE 106
453 #define OP_SET_UMORE 107
454 #define OP_SET_SLESSEQ 108
455 #define OP_SET_ULESSEQ 109
456 #define OP_SET_SMOREEQ 110
457 #define OP_SET_UMOREEQ 111
460 #define OP_JMP_EQ 113
461 #define OP_JMP_NOTEQ 114
462 #define OP_JMP_SLESS 115
463 #define OP_JMP_ULESS 116
464 #define OP_JMP_SMORE 117
465 #define OP_JMP_UMORE 118
466 #define OP_JMP_SLESSEQ 119
467 #define OP_JMP_ULESSEQ 120
468 #define OP_JMP_SMOREEQ 121
469 #define OP_JMP_UMOREEQ 122
471 /* Builtin operators that it is just simpler to use the compiler for */
489 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
491 #define BLOCK 8 /* Triple stores the current block */
492 unsigned char lhs, rhs, misc, targ;
495 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
503 static const struct op_info table_ops[] = {
504 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
505 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
506 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
507 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
508 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
509 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
510 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
511 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
512 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
513 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
514 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
515 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
516 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
517 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
518 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
519 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
520 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
522 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
523 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
524 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
525 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
526 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
527 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
528 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
529 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
530 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
531 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
532 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
533 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
535 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
536 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE | BLOCK , "store"),
538 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
540 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
541 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
542 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
544 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE | BLOCK, "write"),
545 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
546 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
547 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
548 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
549 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
550 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
552 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
553 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
554 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
555 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
556 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
557 /* Call is special most it can stand in for anything so it depends on context */
558 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
559 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
560 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
562 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
563 /* The number of targets for OP_BRANCH depends on context */
564 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
565 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
566 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
567 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
568 /* The number of RHS elements of OP_PHI depend upon context */
569 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
571 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
572 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
573 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
574 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
575 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
576 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
577 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
578 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
579 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
580 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
581 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
582 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
583 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
584 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
585 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
586 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
587 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
588 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
589 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
590 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
591 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
592 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
593 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
595 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
596 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
597 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
598 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
599 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
600 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
601 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
602 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
603 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
604 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
605 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
608 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
610 static const char *tops(int index)
612 static const char unknown[] = "unknown op";
616 if (index > OP_MAX) {
619 return table_ops[index].name;
626 struct triple_set *next;
627 struct triple *member;
636 struct triple *next, *prev;
637 struct triple_set *use;
640 unsigned char template_id;
641 unsigned short sizes;
642 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
643 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
644 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
645 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
646 #define TRIPLE_SIZE(SIZES) \
647 ((((SIZES) >> 0) & 0x0f) + \
648 (((SIZES) >> 4) & 0x0f) + \
649 (((SIZES) >> 8) & 0x0f) + \
650 (((SIZES) >> 12) & 0x0f))
651 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
652 ((((LHS) & 0x0f) << 0) | \
653 (((RHS) & 0x0f) << 4) | \
654 (((MISC) & 0x0f) << 8) | \
655 (((TARG) & 0x0f) << 12))
656 #define TRIPLE_LHS_OFF(SIZES) (0)
657 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
658 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
659 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
660 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
661 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
662 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
663 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
664 unsigned id; /* A scratch value and finally the register */
665 #define TRIPLE_FLAG_FLATTENED (1 << 31)
666 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
667 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
668 const char *filename;
675 struct hash_entry *field;
676 struct asm_info *ainfo;
678 struct triple *param[2];
685 struct ins_template {
686 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
690 struct ins_template tmpl;
695 struct block_set *next;
696 struct block *member;
699 struct block *work_next;
700 struct block *left, *right;
701 struct triple *first, *last;
703 struct block_set *use;
704 struct block_set *idominates;
705 struct block_set *domfrontier;
707 struct block_set *ipdominates;
708 struct block_set *ipdomfrontier;
716 struct hash_entry *ident;
723 struct hash_entry *ident;
729 struct hash_entry *next;
733 struct macro *sym_define;
734 struct symbol *sym_label;
735 struct symbol *sym_struct;
736 struct symbol *sym_ident;
739 #define HASH_TABLE_SIZE 2048
741 struct compile_state {
742 const char *label_prefix;
743 const char *ofilename;
746 struct file_state *file;
747 struct token token[4];
748 struct hash_entry *hash_table[HASH_TABLE_SIZE];
749 struct hash_entry *i_continue;
750 struct hash_entry *i_break;
752 int if_depth, if_value;
754 struct file_state *macro_file;
755 struct triple *main_function;
756 struct block *first_block, *last_block;
763 /* visibility global/local */
764 /* static/auto duration */
765 /* typedef, register, inline */
767 #define STOR_MASK 0x000f
769 #define STOR_GLOBAL 0x0001
771 #define STOR_PERM 0x0002
772 /* Storage specifiers */
773 #define STOR_AUTO 0x0000
774 #define STOR_STATIC 0x0002
775 #define STOR_EXTERN 0x0003
776 #define STOR_REGISTER 0x0004
777 #define STOR_TYPEDEF 0x0008
778 #define STOR_INLINE 0x000c
781 #define QUAL_MASK 0x0070
782 #define QUAL_NONE 0x0000
783 #define QUAL_CONST 0x0010
784 #define QUAL_VOLATILE 0x0020
785 #define QUAL_RESTRICT 0x0040
788 #define TYPE_MASK 0x1f00
789 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
790 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
791 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
792 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
793 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
794 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
795 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
796 #define TYPE_DEFAULT 0x0000
797 #define TYPE_VOID 0x0100
798 #define TYPE_CHAR 0x0200
799 #define TYPE_UCHAR 0x0300
800 #define TYPE_SHORT 0x0400
801 #define TYPE_USHORT 0x0500
802 #define TYPE_INT 0x0600
803 #define TYPE_UINT 0x0700
804 #define TYPE_LONG 0x0800
805 #define TYPE_ULONG 0x0900
806 #define TYPE_LLONG 0x0a00 /* long long */
807 #define TYPE_ULLONG 0x0b00
808 #define TYPE_FLOAT 0x0c00
809 #define TYPE_DOUBLE 0x0d00
810 #define TYPE_LDOUBLE 0x0e00 /* long double */
811 #define TYPE_STRUCT 0x1000
812 #define TYPE_ENUM 0x1100
813 #define TYPE_POINTER 0x1200
815 * type->left holds the type pointed to.
817 #define TYPE_FUNCTION 0x1300
818 /* For TYPE_FUNCTION:
819 * type->left holds the return type.
820 * type->right holds the...
822 #define TYPE_PRODUCT 0x1400
823 /* TYPE_PRODUCT is a basic building block when defining structures
824 * type->left holds the type that appears first in memory.
825 * type->right holds the type that appears next in memory.
827 #define TYPE_OVERLAP 0x1500
828 /* TYPE_OVERLAP is a basic building block when defining unions
829 * type->left and type->right holds to types that overlap
830 * each other in memory.
832 #define TYPE_ARRAY 0x1600
833 /* TYPE_ARRAY is a basic building block when definitng arrays.
834 * type->left holds the type we are an array of.
835 * type-> holds the number of elements.
838 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
842 struct type *left, *right;
844 struct hash_entry *field_ident;
845 struct hash_entry *type_ident;
848 #define MAX_REGISTERS 75
849 #define MAX_REG_EQUIVS 16
851 #define REGISTER_BITS 16
853 #define REGISTER_BITS 28
855 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
856 #define TEMPLATE_BITS 6
857 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
860 #define REG_UNNEEDED 1
861 #define REG_VIRT0 (MAX_REGISTERS + 0)
862 #define REG_VIRT1 (MAX_REGISTERS + 1)
863 #define REG_VIRT2 (MAX_REGISTERS + 2)
864 #define REG_VIRT3 (MAX_REGISTERS + 3)
865 #define REG_VIRT4 (MAX_REGISTERS + 4)
866 #define REG_VIRT5 (MAX_REGISTERS + 5)
868 /* Provision for 8 register classes */
871 #define REGC_SHIFT REGISTER_BITS
872 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
873 #define REG_MASK (MAX_VIRT_REGISTERS -1)
874 #define ID_REG(ID) ((ID) & REG_MASK)
875 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
876 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
877 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
878 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
879 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
881 #define REG_MASK (MAX_VIRT_REGISTERS -1)
882 #define ID_REG(ID) ((ID) & REG_MASK)
883 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
886 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
887 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
888 static void arch_reg_equivs(
889 struct compile_state *state, unsigned *equiv, int reg);
890 static int arch_select_free_register(
891 struct compile_state *state, char *used, int classes);
892 static unsigned arch_regc_size(struct compile_state *state, int class);
893 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
894 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
895 static const char *arch_reg_str(int reg);
896 static struct reg_info arch_reg_constraint(
897 struct compile_state *state, struct type *type, const char *constraint);
898 static struct reg_info arch_reg_clobber(
899 struct compile_state *state, const char *clobber);
900 static struct reg_info arch_reg_lhs(struct compile_state *state,
901 struct triple *ins, int index);
902 static struct reg_info arch_reg_rhs(struct compile_state *state,
903 struct triple *ins, int index);
904 static struct triple *transform_to_arch_instruction(
905 struct compile_state *state, struct triple *ins);
909 #define DEBUG_ABORT_ON_ERROR 0x0001
910 #define DEBUG_INTERMEDIATE_CODE 0x0002
911 #define DEBUG_CONTROL_FLOW 0x0004
912 #define DEBUG_BASIC_BLOCKS 0x0008
913 #define DEBUG_FDOMINATORS 0x0010
914 #define DEBUG_RDOMINATORS 0x0020
915 #define DEBUG_TRIPLES 0x0040
916 #define DEBUG_INTERFERENCE 0x0080
917 #define DEBUG_ARCH_CODE 0x0100
918 #define DEBUG_CODE_ELIMINATION 0x0200
919 #define DEBUG_INSERTED_COPIES 0x0400
921 #define GLOBAL_SCOPE_DEPTH 1
923 static void compile_file(struct compile_state *old_state, const char *filename, int local);
925 static void do_cleanup(struct compile_state *state)
928 fclose(state->output);
929 unlink(state->ofilename);
933 static int get_col(struct file_state *file)
937 ptr = file->line_start;
939 for(col = 0; ptr < end; ptr++) {
944 col = (col & ~7) + 8;
950 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
954 fprintf(fp, "%s:%d.%d: ",
955 triple->filename, triple->line, triple->col);
961 col = get_col(state->file);
962 fprintf(fp, "%s:%d.%d: ",
963 state->file->basename, state->file->line, col);
966 static void __internal_error(struct compile_state *state, struct triple *ptr,
971 loc(stderr, state, ptr);
973 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
975 fprintf(stderr, "Internal compiler error: ");
976 vfprintf(stderr, fmt, args);
977 fprintf(stderr, "\n");
984 static void __internal_warning(struct compile_state *state, struct triple *ptr,
989 loc(stderr, state, ptr);
990 fprintf(stderr, "Internal compiler warning: ");
991 vfprintf(stderr, fmt, args);
992 fprintf(stderr, "\n");
998 static void __error(struct compile_state *state, struct triple *ptr,
1002 va_start(args, fmt);
1003 loc(stderr, state, ptr);
1004 vfprintf(stderr, fmt, args);
1006 fprintf(stderr, "\n");
1008 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1014 static void __warning(struct compile_state *state, struct triple *ptr,
1018 va_start(args, fmt);
1019 loc(stderr, state, ptr);
1020 fprintf(stderr, "warning: ");
1021 vfprintf(stderr, fmt, args);
1022 fprintf(stderr, "\n");
1026 #if DEBUG_ERROR_MESSAGES
1027 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1028 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1029 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1030 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1032 # define internal_error __internal_error
1033 # define internal_warning __internal_warning
1034 # define error __error
1035 # define warning __warning
1037 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1039 static void valid_op(struct compile_state *state, int op)
1041 char *fmt = "invalid op: %d";
1043 internal_error(state, 0, fmt, op);
1046 internal_error(state, 0, fmt, op);
1050 static void valid_ins(struct compile_state *state, struct triple *ptr)
1052 valid_op(state, ptr->op);
1055 static void process_trigraphs(struct compile_state *state)
1057 char *src, *dest, *end;
1058 struct file_state *file;
1060 src = dest = file->buf;
1061 end = file->buf + file->size;
1062 while((end - src) >= 3) {
1063 if ((src[0] == '?') && (src[1] == '?')) {
1066 case '=': c = '#'; break;
1067 case '/': c = '\\'; break;
1068 case '\'': c = '^'; break;
1069 case '(': c = '['; break;
1070 case ')': c = ']'; break;
1071 case '!': c = '!'; break;
1072 case '<': c = '{'; break;
1073 case '>': c = '}'; break;
1074 case '-': c = '~'; break;
1091 file->size = dest - file->buf;
1094 static void splice_lines(struct compile_state *state)
1096 char *src, *dest, *end;
1097 struct file_state *file;
1099 src = dest = file->buf;
1100 end = file->buf + file->size;
1101 while((end - src) >= 2) {
1102 if ((src[0] == '\\') && (src[1] == '\n')) {
1112 file->size = dest - file->buf;
1115 static struct type void_type;
1116 static void use_triple(struct triple *used, struct triple *user)
1118 struct triple_set **ptr, *new;
1125 if ((*ptr)->member == user) {
1128 ptr = &(*ptr)->next;
1130 /* Append new to the head of the list,
1131 * copy_func and rename_block_variables
1134 new = xcmalloc(sizeof(*new), "triple_set");
1136 new->next = used->use;
1140 static void unuse_triple(struct triple *used, struct triple *unuser)
1142 struct triple_set *use, **ptr;
1149 if (use->member == unuser) {
1159 static void push_triple(struct triple *used, struct triple *user)
1161 struct triple_set *new;
1166 /* Append new to the head of the list,
1167 * it's the only sensible behavoir for a stack.
1169 new = xcmalloc(sizeof(*new), "triple_set");
1171 new->next = used->use;
1175 static void pop_triple(struct triple *used, struct triple *unuser)
1177 struct triple_set *use, **ptr;
1181 if (use->member == unuser) {
1184 /* Only free one occurance from the stack */
1194 /* The zero triple is used as a place holder when we are removing pointers
1195 * from a triple. Having allows certain sanity checks to pass even
1196 * when the original triple that was pointed to is gone.
1198 static struct triple zero_triple = {
1199 .next = &zero_triple,
1200 .prev = &zero_triple,
1203 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1204 .id = -1, /* An invalid id */
1205 .u = { .cval = 0, },
1206 .filename = __FILE__,
1209 .param { [0] = 0, [1] = 0, },
1213 static unsigned short triple_sizes(struct compile_state *state,
1214 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1216 int lhs, rhs, misc, targ;
1217 valid_op(state, op);
1218 lhs = table_ops[op].lhs;
1219 rhs = table_ops[op].rhs;
1220 misc = table_ops[op].misc;
1221 targ = table_ops[op].targ;
1224 if (op == OP_CALL) {
1227 param = type->right;
1228 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1230 param = param->right;
1232 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1236 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1237 lhs = type->left->elements;
1240 else if (op == OP_VAL_VEC) {
1241 rhs = type->elements;
1243 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1246 else if (op == OP_ASM) {
1250 if ((rhs < 0) || (rhs > MAX_RHS)) {
1251 internal_error(state, 0, "bad rhs");
1253 if ((lhs < 0) || (lhs > MAX_LHS)) {
1254 internal_error(state, 0, "bad lhs");
1256 if ((misc < 0) || (misc > MAX_MISC)) {
1257 internal_error(state, 0, "bad misc");
1259 if ((targ < 0) || (targ > MAX_TARG)) {
1260 internal_error(state, 0, "bad targs");
1262 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1265 static struct triple *alloc_triple(struct compile_state *state,
1266 int op, struct type *type, int lhs, int rhs,
1267 const char *filename, int line, int col)
1269 size_t size, sizes, extra_count, min_count;
1271 sizes = triple_sizes(state, op, type, lhs, rhs);
1273 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1274 extra_count = TRIPLE_SIZE(sizes);
1275 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1277 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1278 ret = xcmalloc(size, "tripple");
1284 ret->filename = filename;
1290 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1293 int src_lhs, src_rhs, src_size;
1294 src_lhs = TRIPLE_LHS(src->sizes);
1295 src_rhs = TRIPLE_RHS(src->sizes);
1296 src_size = TRIPLE_SIZE(src->sizes);
1297 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1298 src->filename, src->line, src->col);
1299 memcpy(dup, src, sizeof(*src));
1300 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1304 static struct triple *new_triple(struct compile_state *state,
1305 int op, struct type *type, int lhs, int rhs)
1308 const char *filename;
1314 filename = state->file->basename;
1315 line = state->file->line;
1316 col = get_col(state->file);
1318 ret = alloc_triple(state, op, type, lhs, rhs,
1319 filename, line, col);
1323 static struct triple *build_triple(struct compile_state *state,
1324 int op, struct type *type, struct triple *left, struct triple *right,
1325 const char *filename, int line, int col)
1329 ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1330 count = TRIPLE_SIZE(ret->sizes);
1332 ret->param[0] = left;
1335 ret->param[1] = right;
1340 static struct triple *triple(struct compile_state *state,
1341 int op, struct type *type, struct triple *left, struct triple *right)
1345 ret = new_triple(state, op, type, -1, -1);
1346 count = TRIPLE_SIZE(ret->sizes);
1348 ret->param[0] = left;
1351 ret->param[1] = right;
1356 static struct triple *branch(struct compile_state *state,
1357 struct triple *targ, struct triple *test)
1360 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1364 TARG(ret, 0) = targ;
1365 /* record the branch target was used */
1366 if (!targ || (targ->op != OP_LABEL)) {
1367 internal_error(state, 0, "branch not to label");
1368 use_triple(targ, ret);
1374 static void insert_triple(struct compile_state *state,
1375 struct triple *first, struct triple *ptr)
1378 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1379 internal_error(state, ptr, "expression already used");
1382 ptr->prev = first->prev;
1383 ptr->prev->next = ptr;
1384 ptr->next->prev = ptr;
1385 if ((ptr->prev->op == OP_BRANCH) &&
1386 TRIPLE_RHS(ptr->prev->sizes)) {
1387 unuse_triple(first, ptr->prev);
1388 use_triple(ptr, ptr->prev);
1393 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1395 /* This function is used to determine if u.block
1396 * is utilized to store the current block number.
1399 valid_ins(state, ins);
1400 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1401 return stores_block;
1404 static struct block *block_of_triple(struct compile_state *state,
1407 struct triple *first;
1408 first = RHS(state->main_function, 0);
1409 while(ins != first && !triple_stores_block(state, ins)) {
1410 if (ins == ins->prev) {
1411 internal_error(state, 0, "ins == ins->prev?");
1415 if (!triple_stores_block(state, ins)) {
1416 internal_error(state, ins, "Cannot find block");
1418 return ins->u.block;
1421 static struct triple *pre_triple(struct compile_state *state,
1422 struct triple *base,
1423 int op, struct type *type, struct triple *left, struct triple *right)
1425 struct block *block;
1427 block = block_of_triple(state, base);
1428 ret = build_triple(state, op, type, left, right,
1429 base->filename, base->line, base->col);
1430 if (triple_stores_block(state, ret)) {
1431 ret->u.block = block;
1433 insert_triple(state, base, ret);
1434 if (block->first == base) {
1440 static struct triple *post_triple(struct compile_state *state,
1441 struct triple *base,
1442 int op, struct type *type, struct triple *left, struct triple *right)
1444 struct block *block;
1446 block = block_of_triple(state, base);
1447 ret = build_triple(state, op, type, left, right,
1448 base->filename, base->line, base->col);
1449 if (triple_stores_block(state, ret)) {
1450 ret->u.block = block;
1452 insert_triple(state, base->next, ret);
1453 if (block->last == base) {
1459 static struct triple *label(struct compile_state *state)
1461 /* Labels don't get a type */
1462 struct triple *result;
1463 result = triple(state, OP_LABEL, &void_type, 0, 0);
1467 static void display_triple(FILE *fp, struct triple *ins)
1469 if (ins->op == OP_INTCONST) {
1470 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx> @ %s:%d.%d\n",
1471 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1473 ins->filename, ins->line, ins->col);
1475 else if (ins->op == OP_ADDRCONST) {
1476 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1477 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1478 MISC(ins, 0), ins->u.cval,
1479 ins->filename, ins->line, ins->col);
1483 fprintf(fp, "(%p) %3d %-2d %-10s",
1484 ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1485 count = TRIPLE_SIZE(ins->sizes);
1486 for(i = 0; i < count; i++) {
1487 fprintf(fp, " %-10p", ins->param[i]);
1492 fprintf(fp, " @ %s:%d.%d\n",
1493 ins->filename, ins->line, ins->col);
1498 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1500 /* Does the triple have no side effects.
1501 * I.e. Rexecuting the triple with the same arguments
1502 * gives the same value.
1505 valid_ins(state, ins);
1506 pure = PURE_BITS(table_ops[ins->op].flags);
1507 if ((pure != PURE) && (pure != IMPURE)) {
1508 internal_error(state, 0, "Purity of %s not known\n",
1511 return pure == PURE;
1514 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1516 /* This function is used to determine which triples need
1520 valid_ins(state, ins);
1521 is_branch = (table_ops[ins->op].targ != 0);
1525 static int triple_is_def(struct compile_state *state, struct triple *ins)
1527 /* This function is used to determine which triples need
1531 valid_ins(state, ins);
1532 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1536 static struct triple **triple_iter(struct compile_state *state,
1537 size_t count, struct triple **vector,
1538 struct triple *ins, struct triple **last)
1540 struct triple **ret;
1546 else if ((last >= vector) && (last < (vector + count - 1))) {
1554 static struct triple **triple_lhs(struct compile_state *state,
1555 struct triple *ins, struct triple **last)
1557 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1561 static struct triple **triple_rhs(struct compile_state *state,
1562 struct triple *ins, struct triple **last)
1564 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1568 static struct triple **triple_misc(struct compile_state *state,
1569 struct triple *ins, struct triple **last)
1571 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1575 static struct triple **triple_targ(struct compile_state *state,
1576 struct triple *ins, struct triple **last)
1579 struct triple **ret, **vector;
1581 count = TRIPLE_TARG(ins->sizes);
1582 vector = &TARG(ins, 0);
1587 else if ((last >= vector) && (last < (vector + count - 1))) {
1590 else if ((last == (vector + count - 1)) &&
1591 TRIPLE_RHS(ins->sizes)) {
1599 static void verify_use(struct compile_state *state,
1600 struct triple *user, struct triple *used)
1603 size = TRIPLE_SIZE(user->sizes);
1604 for(i = 0; i < size; i++) {
1605 if (user->param[i] == used) {
1609 if (triple_is_branch(state, user)) {
1610 if (user->next == used) {
1615 internal_error(state, user, "%s(%p) does not use %s(%p)",
1616 tops(user->op), user, tops(used->op), used);
1620 static int find_rhs_use(struct compile_state *state,
1621 struct triple *user, struct triple *used)
1623 struct triple **param;
1625 verify_use(state, user, used);
1626 size = TRIPLE_RHS(user->sizes);
1627 param = &RHS(user, 0);
1628 for(i = 0; i < size; i++) {
1629 if (param[i] == used) {
1636 static void free_triple(struct compile_state *state, struct triple *ptr)
1639 size = sizeof(*ptr) - sizeof(ptr->param) +
1640 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1641 ptr->prev->next = ptr->next;
1642 ptr->next->prev = ptr->prev;
1644 internal_error(state, ptr, "ptr->use != 0");
1646 memset(ptr, -1, size);
1650 static void release_triple(struct compile_state *state, struct triple *ptr)
1652 struct triple_set *set, *next;
1653 struct triple **expr;
1654 /* Remove ptr from use chains where it is the user */
1655 expr = triple_rhs(state, ptr, 0);
1656 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1658 unuse_triple(*expr, ptr);
1661 expr = triple_lhs(state, ptr, 0);
1662 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1664 unuse_triple(*expr, ptr);
1667 expr = triple_misc(state, ptr, 0);
1668 for(; expr; expr = triple_misc(state, ptr, expr)) {
1670 unuse_triple(*expr, ptr);
1673 expr = triple_targ(state, ptr, 0);
1674 for(; expr; expr = triple_targ(state, ptr, expr)) {
1676 unuse_triple(*expr, ptr);
1679 /* Reomve ptr from use chains where it is used */
1680 for(set = ptr->use; set; set = next) {
1682 expr = triple_rhs(state, set->member, 0);
1683 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1685 *expr = &zero_triple;
1688 expr = triple_lhs(state, set->member, 0);
1689 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1691 *expr = &zero_triple;
1694 expr = triple_misc(state, set->member, 0);
1695 for(; expr; expr = triple_misc(state, set->member, expr)) {
1697 *expr = &zero_triple;
1700 expr = triple_targ(state, set->member, 0);
1701 for(; expr; expr = triple_targ(state, set->member, expr)) {
1703 *expr = &zero_triple;
1706 unuse_triple(ptr, set->member);
1708 free_triple(state, ptr);
1711 static void print_triple(struct compile_state *state, struct triple *ptr);
1713 #define TOK_UNKNOWN 0
1716 #define TOK_LBRACE 3
1717 #define TOK_RBRACE 4
1721 #define TOK_LBRACKET 8
1722 #define TOK_RBRACKET 9
1723 #define TOK_LPAREN 10
1724 #define TOK_RPAREN 11
1729 #define TOK_TIMESEQ 16
1730 #define TOK_DIVEQ 17
1731 #define TOK_MODEQ 18
1732 #define TOK_PLUSEQ 19
1733 #define TOK_MINUSEQ 20
1736 #define TOK_ANDEQ 23
1737 #define TOK_XOREQ 24
1740 #define TOK_NOTEQ 27
1741 #define TOK_QUEST 28
1742 #define TOK_LOGOR 29
1743 #define TOK_LOGAND 30
1747 #define TOK_LESSEQ 34
1748 #define TOK_MOREEQ 35
1752 #define TOK_MINUS 39
1755 #define TOK_PLUSPLUS 42
1756 #define TOK_MINUSMINUS 43
1758 #define TOK_ARROW 45
1760 #define TOK_TILDE 47
1761 #define TOK_LIT_STRING 48
1762 #define TOK_LIT_CHAR 49
1763 #define TOK_LIT_INT 50
1764 #define TOK_LIT_FLOAT 51
1765 #define TOK_MACRO 52
1766 #define TOK_CONCATENATE 53
1768 #define TOK_IDENT 54
1769 #define TOK_STRUCT_NAME 55
1770 #define TOK_ENUM_CONST 56
1771 #define TOK_TYPE_NAME 57
1774 #define TOK_BREAK 59
1777 #define TOK_CONST 62
1778 #define TOK_CONTINUE 63
1779 #define TOK_DEFAULT 64
1781 #define TOK_DOUBLE 66
1784 #define TOK_EXTERN 69
1785 #define TOK_FLOAT 70
1789 #define TOK_INLINE 74
1792 #define TOK_REGISTER 77
1793 #define TOK_RESTRICT 78
1794 #define TOK_RETURN 79
1795 #define TOK_SHORT 80
1796 #define TOK_SIGNED 81
1797 #define TOK_SIZEOF 82
1798 #define TOK_STATIC 83
1799 #define TOK_STRUCT 84
1800 #define TOK_SWITCH 85
1801 #define TOK_TYPEDEF 86
1802 #define TOK_UNION 87
1803 #define TOK_UNSIGNED 88
1805 #define TOK_VOLATILE 90
1806 #define TOK_WHILE 91
1808 #define TOK_ATTRIBUTE 93
1809 #define TOK_ALIGNOF 94
1810 #define TOK_FIRST_KEYWORD TOK_AUTO
1811 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1813 #define TOK_DEFINE 100
1814 #define TOK_UNDEF 101
1815 #define TOK_INCLUDE 102
1816 #define TOK_LINE 103
1817 #define TOK_ERROR 104
1818 #define TOK_WARNING 105
1819 #define TOK_PRAGMA 106
1820 #define TOK_IFDEF 107
1821 #define TOK_IFNDEF 108
1822 #define TOK_ELIF 109
1823 #define TOK_ENDIF 110
1825 #define TOK_FIRST_MACRO TOK_DEFINE
1826 #define TOK_LAST_MACRO TOK_ENDIF
1830 static const char *tokens[] = {
1831 [TOK_UNKNOWN ] = "unknown",
1832 [TOK_SPACE ] = ":space:",
1834 [TOK_LBRACE ] = "{",
1835 [TOK_RBRACE ] = "}",
1839 [TOK_LBRACKET ] = "[",
1840 [TOK_RBRACKET ] = "]",
1841 [TOK_LPAREN ] = "(",
1842 [TOK_RPAREN ] = ")",
1844 [TOK_DOTS ] = "...",
1847 [TOK_TIMESEQ ] = "*=",
1848 [TOK_DIVEQ ] = "/=",
1849 [TOK_MODEQ ] = "%=",
1850 [TOK_PLUSEQ ] = "+=",
1851 [TOK_MINUSEQ ] = "-=",
1852 [TOK_SLEQ ] = "<<=",
1853 [TOK_SREQ ] = ">>=",
1854 [TOK_ANDEQ ] = "&=",
1855 [TOK_XOREQ ] = "^=",
1858 [TOK_NOTEQ ] = "!=",
1860 [TOK_LOGOR ] = "||",
1861 [TOK_LOGAND ] = "&&",
1865 [TOK_LESSEQ ] = "<=",
1866 [TOK_MOREEQ ] = ">=",
1873 [TOK_PLUSPLUS ] = "++",
1874 [TOK_MINUSMINUS ] = "--",
1876 [TOK_ARROW ] = "->",
1879 [TOK_LIT_STRING ] = ":string:",
1880 [TOK_IDENT ] = ":ident:",
1881 [TOK_TYPE_NAME ] = ":typename:",
1882 [TOK_LIT_CHAR ] = ":char:",
1883 [TOK_LIT_INT ] = ":integer:",
1884 [TOK_LIT_FLOAT ] = ":float:",
1886 [TOK_CONCATENATE ] = "##",
1888 [TOK_AUTO ] = "auto",
1889 [TOK_BREAK ] = "break",
1890 [TOK_CASE ] = "case",
1891 [TOK_CHAR ] = "char",
1892 [TOK_CONST ] = "const",
1893 [TOK_CONTINUE ] = "continue",
1894 [TOK_DEFAULT ] = "default",
1896 [TOK_DOUBLE ] = "double",
1897 [TOK_ELSE ] = "else",
1898 [TOK_ENUM ] = "enum",
1899 [TOK_EXTERN ] = "extern",
1900 [TOK_FLOAT ] = "float",
1902 [TOK_GOTO ] = "goto",
1904 [TOK_INLINE ] = "inline",
1906 [TOK_LONG ] = "long",
1907 [TOK_REGISTER ] = "register",
1908 [TOK_RESTRICT ] = "restrict",
1909 [TOK_RETURN ] = "return",
1910 [TOK_SHORT ] = "short",
1911 [TOK_SIGNED ] = "signed",
1912 [TOK_SIZEOF ] = "sizeof",
1913 [TOK_STATIC ] = "static",
1914 [TOK_STRUCT ] = "struct",
1915 [TOK_SWITCH ] = "switch",
1916 [TOK_TYPEDEF ] = "typedef",
1917 [TOK_UNION ] = "union",
1918 [TOK_UNSIGNED ] = "unsigned",
1919 [TOK_VOID ] = "void",
1920 [TOK_VOLATILE ] = "volatile",
1921 [TOK_WHILE ] = "while",
1923 [TOK_ATTRIBUTE ] = "__attribute__",
1924 [TOK_ALIGNOF ] = "__alignof__",
1926 [TOK_DEFINE ] = "define",
1927 [TOK_UNDEF ] = "undef",
1928 [TOK_INCLUDE ] = "include",
1929 [TOK_LINE ] = "line",
1930 [TOK_ERROR ] = "error",
1931 [TOK_WARNING ] = "warning",
1932 [TOK_PRAGMA ] = "pragma",
1933 [TOK_IFDEF ] = "ifdef",
1934 [TOK_IFNDEF ] = "ifndef",
1935 [TOK_ELIF ] = "elif",
1936 [TOK_ENDIF ] = "endif",
1941 static unsigned int hash(const char *str, int str_len)
1945 end = str + str_len;
1947 for(; str < end; str++) {
1948 hash = (hash *263) + *str;
1950 hash = hash & (HASH_TABLE_SIZE -1);
1954 static struct hash_entry *lookup(
1955 struct compile_state *state, const char *name, int name_len)
1957 struct hash_entry *entry;
1959 index = hash(name, name_len);
1960 entry = state->hash_table[index];
1962 ((entry->name_len != name_len) ||
1963 (memcmp(entry->name, name, name_len) != 0))) {
1964 entry = entry->next;
1968 /* Get a private copy of the name */
1969 new_name = xmalloc(name_len + 1, "hash_name");
1970 memcpy(new_name, name, name_len);
1971 new_name[name_len] = '\0';
1973 /* Create a new hash entry */
1974 entry = xcmalloc(sizeof(*entry), "hash_entry");
1975 entry->next = state->hash_table[index];
1976 entry->name = new_name;
1977 entry->name_len = name_len;
1979 /* Place the new entry in the hash table */
1980 state->hash_table[index] = entry;
1985 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1987 struct hash_entry *entry;
1989 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1990 (entry->tok == TOK_ENUM_CONST) ||
1991 ((entry->tok >= TOK_FIRST_KEYWORD) &&
1992 (entry->tok <= TOK_LAST_KEYWORD)))) {
1993 tk->tok = entry->tok;
1997 static void ident_to_macro(struct compile_state *state, struct token *tk)
1999 struct hash_entry *entry;
2002 (entry->tok >= TOK_FIRST_MACRO) &&
2003 (entry->tok <= TOK_LAST_MACRO)) {
2004 tk->tok = entry->tok;
2008 static void hash_keyword(
2009 struct compile_state *state, const char *keyword, int tok)
2011 struct hash_entry *entry;
2012 entry = lookup(state, keyword, strlen(keyword));
2013 if (entry && entry->tok != TOK_UNKNOWN) {
2014 die("keyword %s already hashed", keyword);
2020 struct compile_state *state, struct hash_entry *ident,
2021 struct symbol **chain, struct triple *def, struct type *type)
2024 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2025 error(state, 0, "%s already defined", ident->name);
2027 sym = xcmalloc(sizeof(*sym), "symbol");
2031 sym->scope_depth = state->scope_depth;
2036 static void start_scope(struct compile_state *state)
2038 state->scope_depth++;
2041 static void end_scope_syms(struct symbol **chain, int depth)
2043 struct symbol *sym, *next;
2045 while(sym && (sym->scope_depth == depth)) {
2053 static void end_scope(struct compile_state *state)
2057 /* Walk through the hash table and remove all symbols
2058 * in the current scope.
2060 depth = state->scope_depth;
2061 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2062 struct hash_entry *entry;
2063 entry = state->hash_table[i];
2065 end_scope_syms(&entry->sym_label, depth);
2066 end_scope_syms(&entry->sym_struct, depth);
2067 end_scope_syms(&entry->sym_ident, depth);
2068 entry = entry->next;
2071 state->scope_depth = depth - 1;
2074 static void register_keywords(struct compile_state *state)
2076 hash_keyword(state, "auto", TOK_AUTO);
2077 hash_keyword(state, "break", TOK_BREAK);
2078 hash_keyword(state, "case", TOK_CASE);
2079 hash_keyword(state, "char", TOK_CHAR);
2080 hash_keyword(state, "const", TOK_CONST);
2081 hash_keyword(state, "continue", TOK_CONTINUE);
2082 hash_keyword(state, "default", TOK_DEFAULT);
2083 hash_keyword(state, "do", TOK_DO);
2084 hash_keyword(state, "double", TOK_DOUBLE);
2085 hash_keyword(state, "else", TOK_ELSE);
2086 hash_keyword(state, "enum", TOK_ENUM);
2087 hash_keyword(state, "extern", TOK_EXTERN);
2088 hash_keyword(state, "float", TOK_FLOAT);
2089 hash_keyword(state, "for", TOK_FOR);
2090 hash_keyword(state, "goto", TOK_GOTO);
2091 hash_keyword(state, "if", TOK_IF);
2092 hash_keyword(state, "inline", TOK_INLINE);
2093 hash_keyword(state, "int", TOK_INT);
2094 hash_keyword(state, "long", TOK_LONG);
2095 hash_keyword(state, "register", TOK_REGISTER);
2096 hash_keyword(state, "restrict", TOK_RESTRICT);
2097 hash_keyword(state, "return", TOK_RETURN);
2098 hash_keyword(state, "short", TOK_SHORT);
2099 hash_keyword(state, "signed", TOK_SIGNED);
2100 hash_keyword(state, "sizeof", TOK_SIZEOF);
2101 hash_keyword(state, "static", TOK_STATIC);
2102 hash_keyword(state, "struct", TOK_STRUCT);
2103 hash_keyword(state, "switch", TOK_SWITCH);
2104 hash_keyword(state, "typedef", TOK_TYPEDEF);
2105 hash_keyword(state, "union", TOK_UNION);
2106 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2107 hash_keyword(state, "void", TOK_VOID);
2108 hash_keyword(state, "volatile", TOK_VOLATILE);
2109 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2110 hash_keyword(state, "while", TOK_WHILE);
2111 hash_keyword(state, "asm", TOK_ASM);
2112 hash_keyword(state, "__asm__", TOK_ASM);
2113 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2114 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2117 static void register_macro_keywords(struct compile_state *state)
2119 hash_keyword(state, "define", TOK_DEFINE);
2120 hash_keyword(state, "undef", TOK_UNDEF);
2121 hash_keyword(state, "include", TOK_INCLUDE);
2122 hash_keyword(state, "line", TOK_LINE);
2123 hash_keyword(state, "error", TOK_ERROR);
2124 hash_keyword(state, "warning", TOK_WARNING);
2125 hash_keyword(state, "pragma", TOK_PRAGMA);
2126 hash_keyword(state, "ifdef", TOK_IFDEF);
2127 hash_keyword(state, "ifndef", TOK_IFNDEF);
2128 hash_keyword(state, "elif", TOK_ELIF);
2129 hash_keyword(state, "endif", TOK_ENDIF);
2132 static int spacep(int c)
2148 static int digitp(int c)
2152 case '0': case '1': case '2': case '3': case '4':
2153 case '5': case '6': case '7': case '8': case '9':
2160 static int hexdigitp(int c)
2164 case '0': case '1': case '2': case '3': case '4':
2165 case '5': case '6': case '7': case '8': case '9':
2166 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2167 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2173 static int hexdigval(int c)
2176 if ((c >= '0') && (c <= '9')) {
2179 else if ((c >= 'A') && (c <= 'F')) {
2180 val = 10 + (c - 'A');
2182 else if ((c >= 'a') && (c <= 'f')) {
2183 val = 10 + (c - 'a');
2188 static int octdigitp(int c)
2192 case '0': case '1': case '2': case '3':
2193 case '4': case '5': case '6': case '7':
2199 static int octdigval(int c)
2202 if ((c >= '0') && (c <= '7')) {
2208 static int letterp(int c)
2212 case 'a': case 'b': case 'c': case 'd': case 'e':
2213 case 'f': case 'g': case 'h': case 'i': case 'j':
2214 case 'k': case 'l': case 'm': case 'n': case 'o':
2215 case 'p': case 'q': case 'r': case 's': case 't':
2216 case 'u': case 'v': case 'w': case 'x': case 'y':
2218 case 'A': case 'B': case 'C': case 'D': case 'E':
2219 case 'F': case 'G': case 'H': case 'I': case 'J':
2220 case 'K': case 'L': case 'M': case 'N': case 'O':
2221 case 'P': case 'Q': case 'R': case 'S': case 'T':
2222 case 'U': case 'V': case 'W': case 'X': case 'Y':
2231 static int char_value(struct compile_state *state,
2232 const signed char **strp, const signed char *end)
2234 const signed char *str;
2238 if ((c == '\\') && (str < end)) {
2240 case 'n': c = '\n'; str++; break;
2241 case 't': c = '\t'; str++; break;
2242 case 'v': c = '\v'; str++; break;
2243 case 'b': c = '\b'; str++; break;
2244 case 'r': c = '\r'; str++; break;
2245 case 'f': c = '\f'; str++; break;
2246 case 'a': c = '\a'; str++; break;
2247 case '\\': c = '\\'; str++; break;
2248 case '?': c = '?'; str++; break;
2249 case '\'': c = '\''; str++; break;
2250 case '"': c = '"'; break;
2254 while((str < end) && hexdigitp(*str)) {
2256 c += hexdigval(*str);
2260 case '0': case '1': case '2': case '3':
2261 case '4': case '5': case '6': case '7':
2263 while((str < end) && octdigitp(*str)) {
2265 c += octdigval(*str);
2270 error(state, 0, "Invalid character constant");
2278 static char *after_digits(char *ptr, char *end)
2280 while((ptr < end) && digitp(*ptr)) {
2286 static char *after_octdigits(char *ptr, char *end)
2288 while((ptr < end) && octdigitp(*ptr)) {
2294 static char *after_hexdigits(char *ptr, char *end)
2296 while((ptr < end) && hexdigitp(*ptr)) {
2302 static void save_string(struct compile_state *state,
2303 struct token *tk, char *start, char *end, const char *id)
2307 /* Create a private copy of the string */
2308 str_len = end - start + 1;
2309 str = xmalloc(str_len + 1, id);
2310 memcpy(str, start, str_len);
2311 str[str_len] = '\0';
2313 /* Store the copy in the token */
2315 tk->str_len = str_len;
2317 static void next_token(struct compile_state *state, int index)
2319 struct file_state *file;
2327 tk = &state->token[index];
2330 token = tokp = file->pos;
2331 end = file->buf + file->size;
2338 if ((tokp + 1) < end) {
2342 if ((tokp + 2) < end) {
2346 if ((tokp + 3) < end) {
2354 else if (spacep(c)) {
2356 while ((tokp < end) && spacep(c)) {
2359 file->line_start = tokp + 1;
2368 else if ((c == '/') && (c1 == '/')) {
2370 for(tokp += 2; tokp < end; tokp++) {
2374 file->line_start = tokp +1;
2380 else if ((c == '/') && (c1 == '*')) {
2384 line_start = file->line_start;
2385 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2389 line_start = tokp +1;
2391 else if ((c == '*') && (tokp[1] == '/')) {
2397 if (tok == TOK_UNKNOWN) {
2398 error(state, 0, "unterminated comment");
2401 file->line_start = line_start;
2403 /* string constants */
2404 else if ((c == '"') ||
2405 ((c == 'L') && (c1 == '"'))) {
2410 line_start = file->line_start;
2416 for(tokp += 1; tokp < end; tokp++) {
2420 line_start = tokp + 1;
2422 else if ((c == '\\') && (tokp +1 < end)) {
2425 else if (c == '"') {
2426 tok = TOK_LIT_STRING;
2430 if (tok == TOK_UNKNOWN) {
2431 error(state, 0, "unterminated string constant");
2433 if (line != file->line) {
2434 warning(state, 0, "multiline string constant");
2437 file->line_start = line_start;
2439 /* Save the string value */
2440 save_string(state, tk, token, tokp, "literal string");
2442 /* character constants */
2443 else if ((c == '\'') ||
2444 ((c == 'L') && (c1 == '\''))) {
2449 line_start = file->line_start;
2455 for(tokp += 1; tokp < end; tokp++) {
2459 line_start = tokp + 1;
2461 else if ((c == '\\') && (tokp +1 < end)) {
2464 else if (c == '\'') {
2469 if (tok == TOK_UNKNOWN) {
2470 error(state, 0, "unterminated character constant");
2472 if (line != file->line) {
2473 warning(state, 0, "multiline character constant");
2476 file->line_start = line_start;
2478 /* Save the character value */
2479 save_string(state, tk, token, tokp, "literal character");
2481 /* integer and floating constants
2487 * Floating constants
2488 * {digits}.{digits}[Ee][+-]?{digits}
2490 * {digits}[Ee][+-]?{digits}
2491 * .{digits}[Ee][+-]?{digits}
2495 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2500 next = after_digits(tokp, end);
2505 if (next[0] == '.') {
2506 new = after_digits(next, end);
2507 is_float = (new != next);
2510 if ((next[0] == 'e') || (next[0] == 'E')) {
2511 if (((next + 1) < end) &&
2512 ((next[1] == '+') || (next[1] == '-'))) {
2515 new = after_digits(next, end);
2516 is_float = (new != next);
2520 tok = TOK_LIT_FLOAT;
2521 if ((next < end) && (
2530 if (!is_float && digitp(c)) {
2532 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2533 next = after_hexdigits(tokp + 2, end);
2535 else if (c == '0') {
2536 next = after_octdigits(tokp, end);
2539 next = after_digits(tokp, end);
2541 /* crazy integer suffixes */
2543 ((next[0] == 'u') || (next[0] == 'U'))) {
2546 ((next[0] == 'l') || (next[0] == 'L'))) {
2550 else if ((next < end) &&
2551 ((next[0] == 'l') || (next[0] == 'L'))) {
2554 ((next[0] == 'u') || (next[0] == 'U'))) {
2561 /* Save the integer/floating point value */
2562 save_string(state, tk, token, tokp, "literal number");
2565 else if (letterp(c)) {
2567 for(tokp += 1; tokp < end; tokp++) {
2569 if (!letterp(c) && !digitp(c)) {
2574 tk->ident = lookup(state, token, tokp +1 - token);
2576 /* C99 alternate macro characters */
2577 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2579 tok = TOK_CONCATENATE;
2581 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2582 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2583 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2584 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2585 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2586 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2587 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2588 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2589 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2590 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2591 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2592 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2593 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2594 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2595 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2596 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2597 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2598 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2599 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2600 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2601 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2602 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2603 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2604 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2605 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2606 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2607 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2608 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2609 else if (c == ';') { tok = TOK_SEMI; }
2610 else if (c == '{') { tok = TOK_LBRACE; }
2611 else if (c == '}') { tok = TOK_RBRACE; }
2612 else if (c == ',') { tok = TOK_COMMA; }
2613 else if (c == '=') { tok = TOK_EQ; }
2614 else if (c == ':') { tok = TOK_COLON; }
2615 else if (c == '[') { tok = TOK_LBRACKET; }
2616 else if (c == ']') { tok = TOK_RBRACKET; }
2617 else if (c == '(') { tok = TOK_LPAREN; }
2618 else if (c == ')') { tok = TOK_RPAREN; }
2619 else if (c == '*') { tok = TOK_STAR; }
2620 else if (c == '>') { tok = TOK_MORE; }
2621 else if (c == '<') { tok = TOK_LESS; }
2622 else if (c == '?') { tok = TOK_QUEST; }
2623 else if (c == '|') { tok = TOK_OR; }
2624 else if (c == '&') { tok = TOK_AND; }
2625 else if (c == '^') { tok = TOK_XOR; }
2626 else if (c == '+') { tok = TOK_PLUS; }
2627 else if (c == '-') { tok = TOK_MINUS; }
2628 else if (c == '/') { tok = TOK_DIV; }
2629 else if (c == '%') { tok = TOK_MOD; }
2630 else if (c == '!') { tok = TOK_BANG; }
2631 else if (c == '.') { tok = TOK_DOT; }
2632 else if (c == '~') { tok = TOK_TILDE; }
2633 else if (c == '#') { tok = TOK_MACRO; }
2634 if (tok == TOK_MACRO) {
2635 /* Only match preprocessor directives at the start of a line */
2637 for(ptr = file->line_start; spacep(*ptr); ptr++)
2643 if (tok == TOK_UNKNOWN) {
2644 error(state, 0, "unknown token");
2647 file->pos = tokp + 1;
2649 if (tok == TOK_IDENT) {
2650 ident_to_keyword(state, tk);
2652 /* Don't return space tokens. */
2653 if (tok == TOK_SPACE) {
2658 static void compile_macro(struct compile_state *state, struct token *tk)
2660 struct file_state *file;
2661 struct hash_entry *ident;
2663 file = xmalloc(sizeof(*file), "file_state");
2664 file->basename = xstrdup(tk->ident->name);
2665 file->dirname = xstrdup("");
2666 file->size = ident->sym_define->buf_len;
2667 file->buf = xmalloc(file->size +2, file->basename);
2668 memcpy(file->buf, ident->sym_define->buf, file->size);
2669 file->buf[file->size] = '\n';
2670 file->buf[file->size + 1] = '\0';
2671 file->pos = file->buf;
2672 file->line_start = file->pos;
2674 file->prev = state->file;
2679 static int mpeek(struct compile_state *state, int index)
2683 tk = &state->token[index + 1];
2684 if (tk->tok == -1) {
2685 next_token(state, index + 1);
2689 if ((tk->tok == TOK_EOF) &&
2690 (state->file != state->macro_file) &&
2691 (state->file->prev)) {
2692 struct file_state *file = state->file;
2693 state->file = file->prev;
2694 /* file->basename is used keep it */
2695 xfree(file->dirname);
2698 next_token(state, index + 1);
2701 else if (tk->ident && tk->ident->sym_define) {
2702 compile_macro(state, tk);
2703 next_token(state, index + 1);
2707 /* Don't show the token on the next line */
2708 if (state->macro_line < state->macro_file->line) {
2711 return state->token[index +1].tok;
2714 static void meat(struct compile_state *state, int index, int tok)
2718 next_tok = mpeek(state, index);
2719 if (next_tok != tok) {
2720 const char *name1, *name2;
2721 name1 = tokens[next_tok];
2723 if (next_tok == TOK_IDENT) {
2724 name2 = state->token[index + 1].ident->name;
2726 error(state, 0, "found %s %s expected %s",
2727 name1, name2, tokens[tok]);
2729 /* Free the old token value */
2730 if (state->token[index].str_len) {
2731 memset((void *)(state->token[index].val.str), -1,
2732 state->token[index].str_len);
2733 xfree(state->token[index].val.str);
2735 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2736 state->token[i] = state->token[i + 1];
2738 memset(&state->token[i], 0, sizeof(state->token[i]));
2739 state->token[i].tok = -1;
2742 static long_t mcexpr(struct compile_state *state, int index);
2744 static long_t mprimary_expr(struct compile_state *state, int index)
2748 tok = mpeek(state, index);
2749 while(state->token[index + 1].ident &&
2750 state->token[index + 1].ident->sym_define) {
2751 meat(state, index, tok);
2752 compile_macro(state, &state->token[index]);
2753 tok = mpeek(state, index);
2757 meat(state, index, TOK_LPAREN);
2758 val = mcexpr(state, index);
2759 meat(state, index, TOK_RPAREN);
2764 meat(state, index, TOK_LIT_INT);
2766 val = strtol(state->token[index].val.str, &end, 0);
2767 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2768 (errno == ERANGE)) {
2769 error(state, 0, "Integer constant to large");
2774 meat(state, index, TOK_LIT_INT);
2779 static long_t munary_expr(struct compile_state *state, int index)
2782 switch(mpeek(state, index)) {
2784 meat(state, index, TOK_PLUS);
2785 val = munary_expr(state, index);
2789 meat(state, index, TOK_MINUS);
2790 val = munary_expr(state, index);
2794 meat(state, index, TOK_BANG);
2795 val = munary_expr(state, index);
2799 meat(state, index, TOK_BANG);
2800 val = munary_expr(state, index);
2804 val = mprimary_expr(state, index);
2810 static long_t mmul_expr(struct compile_state *state, int index)
2814 val = munary_expr(state, index);
2818 switch(mpeek(state, index)) {
2820 meat(state, index, TOK_STAR);
2821 right = munary_expr(state, index);
2825 meat(state, index, TOK_DIV);
2826 right = munary_expr(state, index);
2830 meat(state, index, TOK_MOD);
2831 right = munary_expr(state, index);
2843 static long_t madd_expr(struct compile_state *state, int index)
2847 val = mmul_expr(state, index);
2851 switch(mpeek(state, index)) {
2853 meat(state, index, TOK_PLUS);
2854 right = mmul_expr(state, index);
2858 meat(state, index, TOK_MINUS);
2859 right = mmul_expr(state, index);
2871 static long_t mshift_expr(struct compile_state *state, int index)
2875 val = madd_expr(state, index);
2879 switch(mpeek(state, index)) {
2881 meat(state, index, TOK_SL);
2882 right = madd_expr(state, index);
2886 meat(state, index, TOK_SR);
2887 right = madd_expr(state, index);
2899 static long_t mrel_expr(struct compile_state *state, int index)
2903 val = mshift_expr(state, index);
2907 switch(mpeek(state, index)) {
2909 meat(state, index, TOK_LESS);
2910 right = mshift_expr(state, index);
2914 meat(state, index, TOK_MORE);
2915 right = mshift_expr(state, index);
2919 meat(state, index, TOK_LESSEQ);
2920 right = mshift_expr(state, index);
2924 meat(state, index, TOK_MOREEQ);
2925 right = mshift_expr(state, index);
2936 static long_t meq_expr(struct compile_state *state, int index)
2940 val = mrel_expr(state, index);
2944 switch(mpeek(state, index)) {
2946 meat(state, index, TOK_EQEQ);
2947 right = mrel_expr(state, index);
2951 meat(state, index, TOK_NOTEQ);
2952 right = mrel_expr(state, index);
2963 static long_t mand_expr(struct compile_state *state, int index)
2966 val = meq_expr(state, index);
2967 if (mpeek(state, index) == TOK_AND) {
2969 meat(state, index, TOK_AND);
2970 right = meq_expr(state, index);
2976 static long_t mxor_expr(struct compile_state *state, int index)
2979 val = mand_expr(state, index);
2980 if (mpeek(state, index) == TOK_XOR) {
2982 meat(state, index, TOK_XOR);
2983 right = mand_expr(state, index);
2989 static long_t mor_expr(struct compile_state *state, int index)
2992 val = mxor_expr(state, index);
2993 if (mpeek(state, index) == TOK_OR) {
2995 meat(state, index, TOK_OR);
2996 right = mxor_expr(state, index);
3002 static long_t mland_expr(struct compile_state *state, int index)
3005 val = mor_expr(state, index);
3006 if (mpeek(state, index) == TOK_LOGAND) {
3008 meat(state, index, TOK_LOGAND);
3009 right = mor_expr(state, index);
3014 static long_t mlor_expr(struct compile_state *state, int index)
3017 val = mland_expr(state, index);
3018 if (mpeek(state, index) == TOK_LOGOR) {
3020 meat(state, index, TOK_LOGOR);
3021 right = mland_expr(state, index);
3027 static long_t mcexpr(struct compile_state *state, int index)
3029 return mlor_expr(state, index);
3031 static void preprocess(struct compile_state *state, int index)
3033 /* Doing much more with the preprocessor would require
3034 * a parser and a major restructuring.
3035 * Postpone that for later.
3037 struct file_state *file;
3043 tk = &state->token[index];
3044 state->macro_line = line = file->line;
3045 state->macro_file = file;
3047 next_token(state, index);
3048 ident_to_macro(state, tk);
3049 if (tk->tok == TOK_IDENT) {
3050 error(state, 0, "undefined preprocessing directive `%s'",
3057 if (state->if_value < 0) {
3060 warning(state, 0, "Ignoring preprocessor directive: %s",
3064 error(state, 0, "#elif not supported");
3065 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3066 if (state->if_depth == 0) {
3067 error(state, 0, "#elif without #if");
3069 /* If the #if was taken the #elif just disables the following code */
3070 if (state->if_value >= 0) {
3071 state->if_value = - state->if_value;
3073 /* If the previous #if was not taken see if the #elif enables the
3076 else if ((state->if_value < 0) &&
3077 (state->if_depth == - state->if_value))
3079 if (mcexpr(state, index) != 0) {
3080 state->if_value = state->if_depth;
3083 state->if_value = - state->if_depth;
3089 if (state->if_value < 0) {
3092 if (mcexpr(state, index) != 0) {
3093 state->if_value = state->if_depth;
3096 state->if_value = - state->if_depth;
3101 if (state->if_value < 0) {
3104 next_token(state, index);
3105 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3106 error(state, 0, "Invalid macro name");
3108 if (tk->ident->sym_define == 0) {
3109 state->if_value = state->if_depth;
3112 state->if_value = - state->if_depth;
3117 if (state->if_value < 0) {
3120 next_token(state, index);
3121 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3122 error(state, 0, "Invalid macro name");
3124 if (tk->ident->sym_define != 0) {
3125 state->if_value = state->if_depth;
3128 state->if_value = - state->if_depth;
3132 if (state->if_depth == 0) {
3133 error(state, 0, "#else without #if");
3135 if ((state->if_value >= 0) ||
3136 ((state->if_value < 0) &&
3137 (state->if_depth == -state->if_value)))
3139 state->if_value = - state->if_value;
3143 if (state->if_depth == 0) {
3144 error(state, 0, "#endif without #if");
3146 if ((state->if_value >= 0) ||
3147 ((state->if_value < 0) &&
3148 (state->if_depth == -state->if_value)))
3150 state->if_value = state->if_depth - 1;
3156 struct hash_entry *ident;
3157 struct macro *macro;
3160 if (state->if_value < 0) /* quit early when #if'd out */
3163 meat(state, index, TOK_IDENT);
3167 if (*file->pos == '(') {
3168 #warning "FIXME macros with arguments not supported"
3169 error(state, 0, "Macros with arguments not supported");
3172 /* Find the end of the line to get an estimate of
3173 * the macro's length.
3175 for(ptr = file->pos; *ptr != '\n'; ptr++)
3178 if (ident->sym_define != 0) {
3179 error(state, 0, "macro %s already defined\n", ident->name);
3181 macro = xmalloc(sizeof(*macro), "macro");
3182 macro->ident = ident;
3183 macro->buf_len = ptr - file->pos +1;
3184 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3186 memcpy(macro->buf, file->pos, macro->buf_len);
3187 macro->buf[macro->buf_len] = '\n';
3188 macro->buf[macro->buf_len +1] = '\0';
3190 ident->sym_define = macro;
3197 /* Find the end of the line */
3198 for(end = file->pos; *end != '\n'; end++)
3200 len = (end - file->pos);
3201 if (state->if_value >= 0) {
3202 error(state, 0, "%*.*s", len, len, file->pos);
3211 /* Find the end of the line */
3212 for(end = file->pos; *end != '\n'; end++)
3214 len = (end - file->pos);
3215 if (state->if_value >= 0) {
3216 warning(state, 0, "%*.*s", len, len, file->pos);
3228 next_token(state, index);
3229 if (tk->tok == TOK_LIT_STRING) {
3232 name = xmalloc(tk->str_len, "include");
3233 token = tk->val.str +1;
3234 name_len = tk->str_len -2;
3235 if (*token == '"') {
3239 memcpy(name, token, name_len);
3240 name[name_len] = '\0';
3243 else if (tk->tok == TOK_LESS) {
3246 for(end = start; *end != '\n'; end++) {
3252 error(state, 0, "Unterminated included directive");
3254 name = xmalloc(end - start + 1, "include");
3255 memcpy(name, start, end - start);
3256 name[end - start] = '\0';
3261 error(state, 0, "Invalid include directive");
3263 /* Error if there are any characters after the include */
3264 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3265 if (!isspace(*ptr)) {
3266 error(state, 0, "garbage after include directive");
3269 if (state->if_value >= 0) {
3270 compile_file(state, name, local);
3273 next_token(state, index);
3277 /* Ignore # without a following ident */
3278 if (tk->tok == TOK_IDENT) {
3279 error(state, 0, "Invalid preprocessor directive: %s",
3284 /* Consume the rest of the macro line */
3286 tok = mpeek(state, index);
3287 meat(state, index, tok);
3288 } while(tok != TOK_EOF);
3292 static void token(struct compile_state *state, int index)
3294 struct file_state *file;
3298 tk = &state->token[index];
3299 next_token(state, index);
3303 if (tk->tok == TOK_EOF && file->prev) {
3304 state->file = file->prev;
3305 /* file->basename is used keep it */
3306 xfree(file->dirname);
3309 next_token(state, index);
3312 else if (tk->tok == TOK_MACRO) {
3313 preprocess(state, index);
3316 else if (tk->ident && tk->ident->sym_define) {
3317 compile_macro(state, tk);
3318 next_token(state, index);
3321 else if (state->if_value < 0) {
3322 next_token(state, index);
3328 static int peek(struct compile_state *state)
3330 if (state->token[1].tok == -1) {
3333 return state->token[1].tok;
3336 static int peek2(struct compile_state *state)
3338 if (state->token[1].tok == -1) {
3341 if (state->token[2].tok == -1) {
3344 return state->token[2].tok;
3347 static void eat(struct compile_state *state, int tok)
3351 next_tok = peek(state);
3352 if (next_tok != tok) {
3353 const char *name1, *name2;
3354 name1 = tokens[next_tok];
3356 if (next_tok == TOK_IDENT) {
3357 name2 = state->token[1].ident->name;
3359 error(state, 0, "\tfound %s %s expected %s",
3360 name1, name2 ,tokens[tok]);
3362 /* Free the old token value */
3363 if (state->token[0].str_len) {
3364 xfree((void *)(state->token[0].val.str));
3366 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3367 state->token[i] = state->token[i + 1];
3369 memset(&state->token[i], 0, sizeof(state->token[i]));
3370 state->token[i].tok = -1;
3373 #warning "FIXME do not hardcode the include paths"
3374 static char *include_paths[] = {
3375 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3376 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3377 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3381 static void compile_file(struct compile_state *state, const char *filename, int local)
3384 const char *subdir, *base;
3386 struct file_state *file;
3388 file = xmalloc(sizeof(*file), "file_state");
3390 base = strrchr(filename, '/');
3393 subdir_len = base - filename;
3400 basename = xmalloc(strlen(base) +1, "basename");
3401 strcpy(basename, base);
3402 file->basename = basename;
3404 if (getcwd(cwd, sizeof(cwd)) == 0) {
3405 die("cwd buffer to small");
3408 if (subdir[0] == '/') {
3409 file->dirname = xmalloc(subdir_len + 1, "dirname");
3410 memcpy(file->dirname, subdir, subdir_len);
3411 file->dirname[subdir_len] = '\0';
3417 /* Find the appropriate directory... */
3419 if (!state->file && exists(cwd, filename)) {
3422 if (local && state->file && exists(state->file->dirname, filename)) {
3423 dir = state->file->dirname;
3425 for(path = include_paths; !dir && *path; path++) {
3426 if (exists(*path, filename)) {
3431 error(state, 0, "Cannot find `%s'\n", filename);
3433 dirlen = strlen(dir);
3434 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3435 memcpy(file->dirname, dir, dirlen);
3436 file->dirname[dirlen] = '/';
3437 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3438 file->dirname[dirlen + 1 + subdir_len] = '\0';
3440 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3443 file->pos = file->buf;
3444 file->line_start = file->pos;
3447 file->prev = state->file;
3450 process_trigraphs(state);
3451 splice_lines(state);
3454 /* Type helper functions */
3456 static struct type *new_type(
3457 unsigned int type, struct type *left, struct type *right)
3459 struct type *result;
3460 result = xmalloc(sizeof(*result), "type");
3461 result->type = type;
3462 result->left = left;
3463 result->right = right;
3464 result->field_ident = 0;
3465 result->type_ident = 0;
3469 static struct type *clone_type(unsigned int specifiers, struct type *old)
3471 struct type *result;
3472 result = xmalloc(sizeof(*result), "type");
3473 memcpy(result, old, sizeof(*result));
3474 result->type &= TYPE_MASK;
3475 result->type |= specifiers;
3479 #define SIZEOF_SHORT 2
3480 #define SIZEOF_INT 4
3481 #define SIZEOF_LONG (sizeof(long_t))
3483 #define ALIGNOF_SHORT 2
3484 #define ALIGNOF_INT 4
3485 #define ALIGNOF_LONG (sizeof(long_t))
3487 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3488 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3489 static inline ulong_t mask_uint(ulong_t x)
3491 if (SIZEOF_INT < SIZEOF_LONG) {
3492 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3497 #define MASK_UINT(X) (mask_uint(X))
3498 #define MASK_ULONG(X) (X)
3500 static struct type void_type = { .type = TYPE_VOID };
3501 static struct type char_type = { .type = TYPE_CHAR };
3502 static struct type uchar_type = { .type = TYPE_UCHAR };
3503 static struct type short_type = { .type = TYPE_SHORT };
3504 static struct type ushort_type = { .type = TYPE_USHORT };
3505 static struct type int_type = { .type = TYPE_INT };
3506 static struct type uint_type = { .type = TYPE_UINT };
3507 static struct type long_type = { .type = TYPE_LONG };
3508 static struct type ulong_type = { .type = TYPE_ULONG };
3510 static struct triple *variable(struct compile_state *state, struct type *type)
3512 struct triple *result;
3513 if ((type->type & STOR_MASK) != STOR_PERM) {
3514 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3515 result = triple(state, OP_ADECL, type, 0, 0);
3518 struct triple **vector;
3520 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3521 vector = &result->param[0];
3525 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3526 vector[index] = variable(state, field->left);
3527 field = field->right;
3530 vector[index] = variable(state, field);
3534 result = triple(state, OP_SDECL, type, 0, 0);
3539 static void stor_of(FILE *fp, struct type *type)
3541 switch(type->type & STOR_MASK) {
3543 fprintf(fp, "auto ");
3546 fprintf(fp, "static ");
3549 fprintf(fp, "extern ");
3552 fprintf(fp, "register ");
3555 fprintf(fp, "typedef ");
3558 fprintf(fp, "inline ");
3562 static void qual_of(FILE *fp, struct type *type)
3564 if (type->type & QUAL_CONST) {
3565 fprintf(fp, " const");
3567 if (type->type & QUAL_VOLATILE) {
3568 fprintf(fp, " volatile");
3570 if (type->type & QUAL_RESTRICT) {
3571 fprintf(fp, " restrict");
3575 static void name_of(FILE *fp, struct type *type)
3578 switch(type->type & TYPE_MASK) {
3580 fprintf(fp, "void");
3584 fprintf(fp, "signed char");
3588 fprintf(fp, "unsigned char");
3592 fprintf(fp, "signed short");
3596 fprintf(fp, "unsigned short");
3600 fprintf(fp, "signed int");
3604 fprintf(fp, "unsigned int");
3608 fprintf(fp, "signed long");
3612 fprintf(fp, "unsigned long");
3616 name_of(fp, type->left);
3622 name_of(fp, type->left);
3624 name_of(fp, type->right);
3627 fprintf(fp, "enum %s", type->type_ident->name);
3631 fprintf(fp, "struct %s", type->type_ident->name);
3636 name_of(fp, type->left);
3637 fprintf(fp, " (*)(");
3638 name_of(fp, type->right);
3643 name_of(fp, type->left);
3644 fprintf(fp, " [%ld]", type->elements);
3647 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3652 static size_t align_of(struct compile_state *state, struct type *type)
3656 switch(type->type & TYPE_MASK) {
3666 align = ALIGNOF_SHORT;
3671 align = ALIGNOF_INT;
3676 align = ALIGNOF_LONG;
3681 size_t left_align, right_align;
3682 left_align = align_of(state, type->left);
3683 right_align = align_of(state, type->right);
3684 align = (left_align >= right_align) ? left_align : right_align;
3688 align = align_of(state, type->left);
3691 align = align_of(state, type->left);
3694 error(state, 0, "alignof not yet defined for type\n");
3700 static size_t size_of(struct compile_state *state, struct type *type)
3704 switch(type->type & TYPE_MASK) {
3714 size = SIZEOF_SHORT;
3729 size = size_of(state, type->left);
3730 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3732 align = align_of(state, type->left);
3733 pad = align - (size % align);
3734 size = size + pad + size_of(state, type->left);
3736 align = align_of(state, type->right);
3737 pad = align - (size % align);
3738 size = size + pad + sizeof(type->right);
3743 size_t size_left, size_right;
3744 size_left = size_of(state, type->left);
3745 size_right = size_of(state, type->right);
3746 size = (size_left >= size_right)? size_left : size_right;
3750 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3751 internal_error(state, 0, "Invalid array type");
3753 size = size_of(state, type->left) * type->elements;
3757 size = size_of(state, type->left);
3760 error(state, 0, "sizeof not yet defined for type\n");
3766 static size_t field_offset(struct compile_state *state,
3767 struct type *type, struct hash_entry *field)
3769 size_t size, align, pad;
3770 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3771 internal_error(state, 0, "field_offset only works on structures");
3775 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3776 if (type->left->field_ident == field) {
3779 size += size_of(state, type->left);
3781 align = align_of(state, type->left);
3782 pad = align - (size % align);
3785 if (type->field_ident != field) {
3786 internal_error(state, 0, "field_offset: member %s not present",
3792 static struct type *field_type(struct compile_state *state,
3793 struct type *type, struct hash_entry *field)
3795 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3796 internal_error(state, 0, "field_type only works on structures");
3799 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3800 if (type->left->field_ident == field) {
3806 if (type->field_ident != field) {
3807 internal_error(state, 0, "field_type: member %s not present",
3813 static struct triple *struct_field(struct compile_state *state,
3814 struct triple *decl, struct hash_entry *field)
3816 struct triple **vector;
3820 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3823 if (decl->op != OP_VAL_VEC) {
3824 internal_error(state, 0, "Invalid struct variable");
3827 internal_error(state, 0, "Missing structure field");
3830 vector = &RHS(decl, 0);
3832 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3833 if (type->left->field_ident == field) {
3840 if (type->field_ident != field) {
3841 internal_error(state, 0, "field %s not found?", field->name);
3843 return vector[index];
3846 static void arrays_complete(struct compile_state *state, struct type *type)
3848 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3849 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3850 error(state, 0, "array size not specified");
3852 arrays_complete(state, type->left);
3856 static unsigned int do_integral_promotion(unsigned int type)
3859 if (TYPE_INTEGER(type) &&
3860 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3866 static unsigned int do_arithmetic_conversion(
3867 unsigned int left, unsigned int right)
3871 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3872 return TYPE_LDOUBLE;
3874 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3877 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3880 left = do_integral_promotion(left);
3881 right = do_integral_promotion(right);
3882 /* If both operands have the same size done */
3883 if (left == right) {
3886 /* If both operands have the same signedness pick the larger */
3887 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3888 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3890 /* If the signed type can hold everything use it */
3891 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3894 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3897 /* Convert to the unsigned type with the same rank as the signed type */
3898 else if (TYPE_SIGNED(left)) {
3899 return TYPE_MKUNSIGNED(left);
3902 return TYPE_MKUNSIGNED(right);
3906 /* see if two types are the same except for qualifiers */
3907 static int equiv_types(struct type *left, struct type *right)
3910 /* Error if the basic types do not match */
3911 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3914 type = left->type & TYPE_MASK;
3915 /* if the basic types match and it is an arithmetic type we are done */
3916 if (TYPE_ARITHMETIC(type)) {
3919 /* If it is a pointer type recurse and keep testing */
3920 if (type == TYPE_POINTER) {
3921 return equiv_types(left->left, right->left);
3923 else if (type == TYPE_ARRAY) {
3924 return (left->elements == right->elements) &&
3925 equiv_types(left->left, right->left);
3927 /* test for struct/union equality */
3928 else if (type == TYPE_STRUCT) {
3929 return left->type_ident == right->type_ident;
3931 /* Test for equivalent functions */
3932 else if (type == TYPE_FUNCTION) {
3933 return equiv_types(left->left, right->left) &&
3934 equiv_types(left->right, right->right);
3936 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3937 else if (type == TYPE_PRODUCT) {
3938 return equiv_types(left->left, right->left) &&
3939 equiv_types(left->right, right->right);
3941 /* We should see TYPE_OVERLAP */
3947 static int equiv_ptrs(struct type *left, struct type *right)
3949 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3950 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3953 return equiv_types(left->left, right->left);
3956 static struct type *compatible_types(struct type *left, struct type *right)
3958 struct type *result;
3959 unsigned int type, qual_type;
3960 /* Error if the basic types do not match */
3961 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3964 type = left->type & TYPE_MASK;
3965 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3967 /* if the basic types match and it is an arithmetic type we are done */
3968 if (TYPE_ARITHMETIC(type)) {
3969 result = new_type(qual_type, 0, 0);
3971 /* If it is a pointer type recurse and keep testing */
3972 else if (type == TYPE_POINTER) {
3973 result = compatible_types(left->left, right->left);
3975 result = new_type(qual_type, result, 0);
3978 /* test for struct/union equality */
3979 else if (type == TYPE_STRUCT) {
3980 if (left->type_ident == right->type_ident) {
3984 /* Test for equivalent functions */
3985 else if (type == TYPE_FUNCTION) {
3986 struct type *lf, *rf;
3987 lf = compatible_types(left->left, right->left);
3988 rf = compatible_types(left->right, right->right);
3990 result = new_type(qual_type, lf, rf);
3993 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3994 else if (type == TYPE_PRODUCT) {
3995 struct type *lf, *rf;
3996 lf = compatible_types(left->left, right->left);
3997 rf = compatible_types(left->right, right->right);
3999 result = new_type(qual_type, lf, rf);
4003 /* Nothing else is compatible */
4008 static struct type *compatible_ptrs(struct type *left, struct type *right)
4010 struct type *result;
4011 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4012 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4015 result = compatible_types(left->left, right->left);
4017 unsigned int qual_type;
4018 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4019 result = new_type(qual_type, result, 0);
4024 static struct triple *integral_promotion(
4025 struct compile_state *state, struct triple *def)
4029 /* As all operations are carried out in registers
4030 * the values are converted on load I just convert
4031 * logical type of the operand.
4033 if (TYPE_INTEGER(type->type)) {
4034 unsigned int int_type;
4035 int_type = type->type & ~TYPE_MASK;
4036 int_type |= do_integral_promotion(type->type);
4037 if (int_type != type->type) {
4038 def->type = new_type(int_type, 0, 0);
4045 static void arithmetic(struct compile_state *state, struct triple *def)
4047 if (!TYPE_ARITHMETIC(def->type->type)) {
4048 error(state, 0, "arithmetic type expexted");
4052 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4054 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4055 error(state, def, "pointer or arithmetic type expected");
4059 static int is_integral(struct triple *ins)
4061 return TYPE_INTEGER(ins->type->type);
4064 static void integral(struct compile_state *state, struct triple *def)
4066 if (!is_integral(def)) {
4067 error(state, 0, "integral type expected");
4072 static void bool(struct compile_state *state, struct triple *def)
4074 if (!TYPE_ARITHMETIC(def->type->type) &&
4075 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4076 error(state, 0, "arithmetic or pointer type expected");
4080 static int is_signed(struct type *type)
4082 return !!TYPE_SIGNED(type->type);
4085 /* Is this value located in a register otherwise it must be in memory */
4086 static int is_in_reg(struct compile_state *state, struct triple *def)
4089 if (def->op == OP_ADECL) {
4092 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4095 else if (def->op == OP_VAL_VEC) {
4096 in_reg = is_in_reg(state, RHS(def, 0));
4098 else if (def->op == OP_DOT) {
4099 in_reg = is_in_reg(state, RHS(def, 0));
4102 internal_error(state, 0, "unknown expr storage location");
4108 /* Is this a stable variable location otherwise it must be a temporary */
4109 static int is_stable(struct compile_state *state, struct triple *def)
4116 if ((def->op == OP_ADECL) ||
4117 (def->op == OP_SDECL) ||
4118 (def->op == OP_DEREF) ||
4119 (def->op == OP_BLOBCONST)) {
4122 else if (def->op == OP_DOT) {
4123 ret = is_stable(state, RHS(def, 0));
4125 else if (def->op == OP_VAL_VEC) {
4126 struct triple **vector;
4129 vector = &RHS(def, 0);
4130 for(i = 0; i < def->type->elements; i++) {
4131 if (!is_stable(state, vector[i])) {
4140 static int is_lvalue(struct compile_state *state, struct triple *def)
4147 if (!is_stable(state, def)) {
4150 if (def->type->type & QUAL_CONST) {
4153 else if (def->op == OP_DOT) {
4154 ret = is_lvalue(state, RHS(def, 0));
4159 static void lvalue(struct compile_state *state, struct triple *def)
4162 internal_error(state, def, "nothing where lvalue expected?");
4164 if (!is_lvalue(state, def)) {
4165 error(state, def, "lvalue expected");
4169 static int is_pointer(struct triple *def)
4171 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4174 static void pointer(struct compile_state *state, struct triple *def)
4176 if (!is_pointer(def)) {
4177 error(state, def, "pointer expected");
4181 static struct triple *int_const(
4182 struct compile_state *state, struct type *type, ulong_t value)
4184 struct triple *result;
4185 switch(type->type & TYPE_MASK) {
4187 case TYPE_INT: case TYPE_UINT:
4188 case TYPE_LONG: case TYPE_ULONG:
4191 internal_error(state, 0, "constant for unkown type");
4193 result = triple(state, OP_INTCONST, type, 0, 0);
4194 result->u.cval = value;
4199 static struct triple *do_mk_addr_expr(struct compile_state *state,
4200 struct triple *expr, struct type *type, ulong_t offset)
4202 struct triple *result;
4203 lvalue(state, expr);
4206 if (expr->op == OP_ADECL) {
4207 error(state, expr, "address of auto variables not supported");
4209 else if (expr->op == OP_SDECL) {
4210 result = triple(state, OP_ADDRCONST, type, 0, 0);
4211 MISC(result, 0) = expr;
4212 result->u.cval = offset;
4214 else if (expr->op == OP_DEREF) {
4215 result = triple(state, OP_ADD, type,
4217 int_const(state, &ulong_type, offset));
4222 static struct triple *mk_addr_expr(
4223 struct compile_state *state, struct triple *expr, ulong_t offset)
4228 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4231 return do_mk_addr_expr(state, expr, type, offset);
4234 static struct triple *mk_deref_expr(
4235 struct compile_state *state, struct triple *expr)
4237 struct type *base_type;
4238 pointer(state, expr);
4239 base_type = expr->type->left;
4240 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4242 "Only pointer and arithmetic values can be dereferenced");
4244 return triple(state, OP_DEREF, base_type, expr, 0);
4247 static struct triple *deref_field(
4248 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4250 struct triple *result;
4251 struct type *type, *member;
4253 internal_error(state, 0, "No field passed to deref_field");
4257 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4258 error(state, 0, "request for member %s in something not a struct or union",
4261 member = type->left;
4262 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4263 if (member->left->field_ident == field) {
4264 member = member->left;
4267 member = member->right;
4269 if (member->field_ident != field) {
4270 error(state, 0, "%s is not a member", field->name);
4272 if ((type->type & STOR_MASK) == STOR_PERM) {
4273 /* Do the pointer arithmetic to get a deref the field */
4275 offset = field_offset(state, type, field);
4276 result = do_mk_addr_expr(state, expr, member, offset);
4277 result = mk_deref_expr(state, result);
4280 /* Find the variable for the field I want. */
4281 result = triple(state, OP_DOT,
4282 field_type(state, type, field), expr, 0);
4283 result->u.field = field;
4288 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4294 if (!is_stable(state, def)) {
4297 /* Tranform an array to a pointer to the first element */
4298 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4299 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4301 struct triple *result;
4303 TYPE_POINTER | (def->type->type & QUAL_MASK),
4304 def->type->left, 0);
4305 result = triple(state, OP_ADDRCONST, type, 0, 0);
4306 MISC(result, 0) = def;
4309 if (is_in_reg(state, def)) {
4314 return triple(state, op, def->type, def, 0);
4317 static void write_compatible(struct compile_state *state,
4318 struct type *dest, struct type *rval)
4321 /* Both operands have arithmetic type */
4322 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4325 /* One operand is a pointer and the other is a pointer to void */
4326 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4327 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4328 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4329 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4332 /* If both types are the same without qualifiers we are good */
4333 else if (equiv_ptrs(dest, rval)) {
4336 /* test for struct/union equality */
4337 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4338 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4339 (dest->type_ident == rval->type_ident)) {
4343 error(state, 0, "Incompatible types in assignment");
4347 static struct triple *write_expr(
4348 struct compile_state *state, struct triple *dest, struct triple *rval)
4355 internal_error(state, 0, "missing rval");
4358 if (rval->op == OP_LIST) {
4359 internal_error(state, 0, "expression of type OP_LIST?");
4361 if (!is_lvalue(state, dest)) {
4362 internal_error(state, 0, "writing to a non lvalue?");
4365 write_compatible(state, dest->type, rval->type);
4367 /* Now figure out which assignment operator to use */
4369 if (is_in_reg(state, dest)) {
4374 def = triple(state, op, dest->type, dest, rval);
4378 static struct triple *init_expr(
4379 struct compile_state *state, struct triple *dest, struct triple *rval)
4385 internal_error(state, 0, "missing rval");
4387 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4388 rval = read_expr(state, rval);
4389 def = write_expr(state, dest, rval);
4392 /* Fill in the array size if necessary */
4393 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4394 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4395 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4396 dest->type->elements = rval->type->elements;
4399 if (!equiv_types(dest->type, rval->type)) {
4400 error(state, 0, "Incompatible types in inializer");
4402 MISC(dest, 0) = rval;
4403 insert_triple(state, dest, rval);
4404 rval->id |= TRIPLE_FLAG_FLATTENED;
4405 use_triple(MISC(dest, 0), dest);
4410 struct type *arithmetic_result(
4411 struct compile_state *state, struct triple *left, struct triple *right)
4414 /* Sanity checks to ensure I am working with arithmetic types */
4415 arithmetic(state, left);
4416 arithmetic(state, right);
4418 do_arithmetic_conversion(
4420 right->type->type), 0, 0);
4424 struct type *ptr_arithmetic_result(
4425 struct compile_state *state, struct triple *left, struct triple *right)
4428 /* Sanity checks to ensure I am working with the proper types */
4429 ptr_arithmetic(state, left);
4430 arithmetic(state, right);
4431 if (TYPE_ARITHMETIC(left->type->type) &&
4432 TYPE_ARITHMETIC(right->type->type)) {
4433 type = arithmetic_result(state, left, right);
4435 else if (TYPE_PTR(left->type->type)) {
4439 internal_error(state, 0, "huh?");
4446 /* boolean helper function */
4448 static struct triple *ltrue_expr(struct compile_state *state,
4449 struct triple *expr)
4452 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4453 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4454 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4455 /* If the expression is already boolean do nothing */
4458 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4464 static struct triple *lfalse_expr(struct compile_state *state,
4465 struct triple *expr)
4467 return triple(state, OP_LFALSE, &int_type, expr, 0);
4470 static struct triple *cond_expr(
4471 struct compile_state *state,
4472 struct triple *test, struct triple *left, struct triple *right)
4475 struct type *result_type;
4476 unsigned int left_type, right_type;
4478 left_type = left->type->type;
4479 right_type = right->type->type;
4481 /* Both operands have arithmetic type */
4482 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4483 result_type = arithmetic_result(state, left, right);
4485 /* Both operands have void type */
4486 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4487 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4488 result_type = &void_type;
4490 /* pointers to the same type... */
4491 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4494 /* Both operands are pointers and left is a pointer to void */
4495 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4496 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4497 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4498 result_type = right->type;
4500 /* Both operands are pointers and right is a pointer to void */
4501 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4502 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4503 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4504 result_type = left->type;
4507 error(state, 0, "Incompatible types in conditional expression");
4509 /* Cleanup and invert the test */
4510 test = lfalse_expr(state, read_expr(state, test));
4511 def = new_triple(state, OP_COND, result_type, 0, 3);
4512 def->param[0] = test;
4513 def->param[1] = left;
4514 def->param[2] = right;
4519 static int expr_depth(struct compile_state *state, struct triple *ins)
4523 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4526 else if (ins->op == OP_DEREF) {
4527 count = expr_depth(state, RHS(ins, 0)) - 1;
4529 else if (ins->op == OP_VAL) {
4530 count = expr_depth(state, RHS(ins, 0)) - 1;
4532 else if (ins->op == OP_COMMA) {
4534 ldepth = expr_depth(state, RHS(ins, 0));
4535 rdepth = expr_depth(state, RHS(ins, 1));
4536 count = (ldepth >= rdepth)? ldepth : rdepth;
4538 else if (ins->op == OP_CALL) {
4539 /* Don't figure the depth of a call just guess it is huge */
4543 struct triple **expr;
4544 expr = triple_rhs(state, ins, 0);
4545 for(;expr; expr = triple_rhs(state, ins, expr)) {
4548 depth = expr_depth(state, *expr);
4549 if (depth > count) {
4558 static struct triple *flatten(
4559 struct compile_state *state, struct triple *first, struct triple *ptr);
4561 static struct triple *flatten_generic(
4562 struct compile_state *state, struct triple *first, struct triple *ptr)
4566 struct triple **ins;
4569 /* Only operations with just a rhs should come here */
4570 rhs = TRIPLE_RHS(ptr->sizes);
4571 lhs = TRIPLE_LHS(ptr->sizes);
4572 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4573 internal_error(state, ptr, "unexpected args for: %d %s",
4574 ptr->op, tops(ptr->op));
4576 /* Find the depth of the rhs elements */
4577 for(i = 0; i < rhs; i++) {
4578 vector[i].ins = &RHS(ptr, i);
4579 vector[i].depth = expr_depth(state, *vector[i].ins);
4581 /* Selection sort the rhs */
4582 for(i = 0; i < rhs; i++) {
4584 for(j = i + 1; j < rhs; j++ ) {
4585 if (vector[j].depth > vector[max].depth) {
4590 struct rhs_vector tmp;
4592 vector[i] = vector[max];
4596 /* Now flatten the rhs elements */
4597 for(i = 0; i < rhs; i++) {
4598 *vector[i].ins = flatten(state, first, *vector[i].ins);
4599 use_triple(*vector[i].ins, ptr);
4602 /* Now flatten the lhs elements */
4603 for(i = 0; i < lhs; i++) {
4604 struct triple **ins = &LHS(ptr, i);
4605 *ins = flatten(state, first, *ins);
4606 use_triple(*ins, ptr);
4611 static struct triple *flatten_land(
4612 struct compile_state *state, struct triple *first, struct triple *ptr)
4614 struct triple *left, *right;
4615 struct triple *val, *test, *jmp, *label1, *end;
4617 /* Find the triples */
4619 right = RHS(ptr, 1);
4621 /* Generate the needed triples */
4624 /* Thread the triples together */
4625 val = flatten(state, first, variable(state, ptr->type));
4626 left = flatten(state, first, write_expr(state, val, left));
4627 test = flatten(state, first,
4628 lfalse_expr(state, read_expr(state, val)));
4629 jmp = flatten(state, first, branch(state, end, test));
4630 label1 = flatten(state, first, label(state));
4631 right = flatten(state, first, write_expr(state, val, right));
4632 TARG(jmp, 0) = flatten(state, first, end);
4634 /* Now give the caller something to chew on */
4635 return read_expr(state, val);
4638 static struct triple *flatten_lor(
4639 struct compile_state *state, struct triple *first, struct triple *ptr)
4641 struct triple *left, *right;
4642 struct triple *val, *jmp, *label1, *end;
4644 /* Find the triples */
4646 right = RHS(ptr, 1);
4648 /* Generate the needed triples */
4651 /* Thread the triples together */
4652 val = flatten(state, first, variable(state, ptr->type));
4653 left = flatten(state, first, write_expr(state, val, left));
4654 jmp = flatten(state, first, branch(state, end, left));
4655 label1 = flatten(state, first, label(state));
4656 right = flatten(state, first, write_expr(state, val, right));
4657 TARG(jmp, 0) = flatten(state, first, end);
4660 /* Now give the caller something to chew on */
4661 return read_expr(state, val);
4664 static struct triple *flatten_cond(
4665 struct compile_state *state, struct triple *first, struct triple *ptr)
4667 struct triple *test, *left, *right;
4668 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4670 /* Find the triples */
4673 right = RHS(ptr, 2);
4675 /* Generate the needed triples */
4677 middle = label(state);
4679 /* Thread the triples together */
4680 val = flatten(state, first, variable(state, ptr->type));
4681 test = flatten(state, first, test);
4682 jmp1 = flatten(state, first, branch(state, middle, test));
4683 label1 = flatten(state, first, label(state));
4684 left = flatten(state, first, left);
4685 mv1 = flatten(state, first, write_expr(state, val, left));
4686 jmp2 = flatten(state, first, branch(state, end, 0));
4687 TARG(jmp1, 0) = flatten(state, first, middle);
4688 right = flatten(state, first, right);
4689 mv2 = flatten(state, first, write_expr(state, val, right));
4690 TARG(jmp2, 0) = flatten(state, first, end);
4692 /* Now give the caller something to chew on */
4693 return read_expr(state, val);
4696 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4698 struct triple *nfunc;
4699 struct triple *nfirst, *ofirst;
4700 struct triple *new, *old;
4703 fprintf(stdout, "\n");
4704 loc(stdout, state, 0);
4705 fprintf(stdout, "\n__________ copy_func _________\n");
4706 print_triple(state, ofunc);
4707 fprintf(stdout, "__________ copy_func _________ done\n\n");
4710 /* Make a new copy of the old function */
4711 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4713 ofirst = old = RHS(ofunc, 0);
4716 int old_lhs, old_rhs;
4717 old_lhs = TRIPLE_LHS(old->sizes);
4718 old_rhs = TRIPLE_RHS(old->sizes);
4719 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4720 old->filename, old->line, old->col);
4721 if (!triple_stores_block(state, new)) {
4722 memcpy(&new->u, &old->u, sizeof(new->u));
4725 RHS(nfunc, 0) = nfirst = new;
4728 insert_triple(state, nfirst, new);
4730 new->id |= TRIPLE_FLAG_FLATTENED;
4732 /* During the copy remember new as user of old */
4733 use_triple(old, new);
4735 /* Populate the return type if present */
4736 if (old == MISC(ofunc, 0)) {
4737 MISC(nfunc, 0) = new;
4740 } while(old != ofirst);
4742 /* Make a second pass to fix up any unresolved references */
4746 struct triple **oexpr, **nexpr;
4748 /* Lookup where the copy is, to join pointers */
4749 count = TRIPLE_SIZE(old->sizes);
4750 for(i = 0; i < count; i++) {
4751 oexpr = &old->param[i];
4752 nexpr = &new->param[i];
4753 if (!*nexpr && *oexpr && (*oexpr)->use) {
4754 *nexpr = (*oexpr)->use->member;
4755 if (*nexpr == old) {
4756 internal_error(state, 0, "new == old?");
4758 use_triple(*nexpr, new);
4760 if (!*nexpr && *oexpr) {
4761 internal_error(state, 0, "Could not copy %d\n", i);
4766 } while((old != ofirst) && (new != nfirst));
4768 /* Make a third pass to cleanup the extra useses */
4772 unuse_triple(old, new);
4775 } while ((old != ofirst) && (new != nfirst));
4779 static struct triple *flatten_call(
4780 struct compile_state *state, struct triple *first, struct triple *ptr)
4782 /* Inline the function call */
4784 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4785 struct triple *end, *nend;
4788 /* Find the triples */
4789 ofunc = MISC(ptr, 0);
4790 if (ofunc->op != OP_LIST) {
4791 internal_error(state, 0, "improper function");
4793 nfunc = copy_func(state, ofunc);
4794 nfirst = RHS(nfunc, 0)->next;
4795 /* Prepend the parameter reading into the new function list */
4796 ptype = nfunc->type->right;
4797 param = RHS(nfunc, 0)->next;
4798 pvals = TRIPLE_RHS(ptr->sizes);
4799 for(i = 0; i < pvals; i++) {
4803 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4804 atype = ptype->left;
4806 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4807 param = param->next;
4810 flatten(state, nfirst, write_expr(state, param, arg));
4811 ptype = ptype->right;
4812 param = param->next;
4815 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4816 result = read_expr(state, MISC(nfunc,0));
4819 fprintf(stdout, "\n");
4820 loc(stdout, state, 0);
4821 fprintf(stdout, "\n__________ flatten_call _________\n");
4822 print_triple(state, nfunc);
4823 fprintf(stdout, "__________ flatten_call _________ done\n\n");
4826 /* Get rid of the extra triples */
4827 nfirst = RHS(nfunc, 0)->next;
4828 free_triple(state, RHS(nfunc, 0));
4830 free_triple(state, nfunc);
4832 /* Append the new function list onto the return list */
4834 nend = nfirst->prev;
4843 static struct triple *flatten(
4844 struct compile_state *state, struct triple *first, struct triple *ptr)
4846 struct triple *orig_ptr;
4851 /* Only flatten triples once */
4852 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4858 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4859 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4860 use_triple(LHS(ptr, 0), ptr);
4861 use_triple(RHS(ptr, 0), ptr);
4864 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4868 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4869 return MISC(ptr, 0);
4872 ptr = flatten_land(state, first, ptr);
4875 ptr = flatten_lor(state, first, ptr);
4878 ptr = flatten_cond(state, first, ptr);
4881 ptr = flatten_call(state, first, ptr);
4885 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4886 use_triple(RHS(ptr, 0), ptr);
4889 use_triple(TARG(ptr, 0), ptr);
4890 if (TRIPLE_RHS(ptr->sizes)) {
4891 use_triple(RHS(ptr, 0), ptr);
4892 if (ptr->next != ptr) {
4893 use_triple(ptr->next, ptr);
4898 insert_triple(state, first, ptr);
4899 ptr->id |= TRIPLE_FLAG_FLATTENED;
4900 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4901 use_triple(MISC(ptr, 0), ptr);
4904 /* Since OP_DEREF is just a marker delete it when I flatten it */
4906 RHS(orig_ptr, 0) = 0;
4907 free_triple(state, orig_ptr);
4911 struct triple *base;
4913 base = flatten(state, first, base);
4914 if (base->op == OP_VAL_VEC) {
4915 ptr = struct_field(state, base, ptr->u.field);
4922 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4923 use_triple(MISC(ptr, 0), ptr);
4928 /* Flatten the easy cases we don't override */
4929 ptr = flatten_generic(state, first, ptr);
4932 } while(ptr && (ptr != orig_ptr));
4934 insert_triple(state, first, ptr);
4935 ptr->id |= TRIPLE_FLAG_FLATTENED;
4940 static void release_expr(struct compile_state *state, struct triple *expr)
4942 struct triple *head;
4943 head = label(state);
4944 flatten(state, head, expr);
4945 while(head->next != head) {
4946 release_triple(state, head->next);
4948 free_triple(state, head);
4951 static int replace_rhs_use(struct compile_state *state,
4952 struct triple *orig, struct triple *new, struct triple *use)
4954 struct triple **expr;
4957 expr = triple_rhs(state, use, 0);
4958 for(;expr; expr = triple_rhs(state, use, expr)) {
4959 if (*expr == orig) {
4965 unuse_triple(orig, use);
4966 use_triple(new, use);
4971 static int replace_lhs_use(struct compile_state *state,
4972 struct triple *orig, struct triple *new, struct triple *use)
4974 struct triple **expr;
4977 expr = triple_lhs(state, use, 0);
4978 for(;expr; expr = triple_lhs(state, use, expr)) {
4979 if (*expr == orig) {
4985 unuse_triple(orig, use);
4986 use_triple(new, use);
4991 static void propogate_use(struct compile_state *state,
4992 struct triple *orig, struct triple *new)
4994 struct triple_set *user, *next;
4995 for(user = orig->use; user; user = next) {
5001 found |= replace_rhs_use(state, orig, new, use);
5002 found |= replace_lhs_use(state, orig, new, use);
5004 internal_error(state, use, "use without use");
5008 internal_error(state, orig, "used after propogate_use");
5014 * ===========================
5017 static struct triple *mk_add_expr(
5018 struct compile_state *state, struct triple *left, struct triple *right)
5020 struct type *result_type;
5021 /* Put pointer operands on the left */
5022 if (is_pointer(right)) {
5028 left = read_expr(state, left);
5029 right = read_expr(state, right);
5030 result_type = ptr_arithmetic_result(state, left, right);
5031 if (is_pointer(left)) {
5032 right = triple(state,
5033 is_signed(right->type)? OP_SMUL : OP_UMUL,
5036 int_const(state, &ulong_type,
5037 size_of(state, left->type->left)));
5039 return triple(state, OP_ADD, result_type, left, right);
5042 static struct triple *mk_sub_expr(
5043 struct compile_state *state, struct triple *left, struct triple *right)
5045 struct type *result_type;
5046 result_type = ptr_arithmetic_result(state, left, right);
5047 left = read_expr(state, left);
5048 right = read_expr(state, right);
5049 if (is_pointer(left)) {
5050 right = triple(state,
5051 is_signed(right->type)? OP_SMUL : OP_UMUL,
5054 int_const(state, &ulong_type,
5055 size_of(state, left->type->left)));
5057 return triple(state, OP_SUB, result_type, left, right);
5060 static struct triple *mk_pre_inc_expr(
5061 struct compile_state *state, struct triple *def)
5065 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5066 return triple(state, OP_VAL, def->type,
5067 write_expr(state, def, val),
5071 static struct triple *mk_pre_dec_expr(
5072 struct compile_state *state, struct triple *def)
5076 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5077 return triple(state, OP_VAL, def->type,
5078 write_expr(state, def, val),
5082 static struct triple *mk_post_inc_expr(
5083 struct compile_state *state, struct triple *def)
5087 val = read_expr(state, def);
5088 return triple(state, OP_VAL, def->type,
5089 write_expr(state, def,
5090 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5094 static struct triple *mk_post_dec_expr(
5095 struct compile_state *state, struct triple *def)
5099 val = read_expr(state, def);
5100 return triple(state, OP_VAL, def->type,
5101 write_expr(state, def,
5102 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5106 static struct triple *mk_subscript_expr(
5107 struct compile_state *state, struct triple *left, struct triple *right)
5109 left = read_expr(state, left);
5110 right = read_expr(state, right);
5111 if (!is_pointer(left) && !is_pointer(right)) {
5112 error(state, left, "subscripted value is not a pointer");
5114 return mk_deref_expr(state, mk_add_expr(state, left, right));
5118 * Compile time evaluation
5119 * ===========================
5121 static int is_const(struct triple *ins)
5123 return IS_CONST_OP(ins->op);
5126 static int constants_equal(struct compile_state *state,
5127 struct triple *left, struct triple *right)
5130 if (!is_const(left) || !is_const(right)) {
5133 else if (left->op != right->op) {
5136 else if (!equiv_types(left->type, right->type)) {
5143 if (left->u.cval == right->u.cval) {
5149 size_t lsize, rsize;
5150 lsize = size_of(state, left->type);
5151 rsize = size_of(state, right->type);
5152 if (lsize != rsize) {
5155 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5161 if ((MISC(left, 0) == MISC(right, 0)) &&
5162 (left->u.cval == right->u.cval)) {
5167 internal_error(state, left, "uknown constant type");
5174 static int is_zero(struct triple *ins)
5176 return is_const(ins) && (ins->u.cval == 0);
5179 static int is_one(struct triple *ins)
5181 return is_const(ins) && (ins->u.cval == 1);
5184 static long_t bsr(ulong_t value)
5187 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5198 static long_t bsf(ulong_t value)
5201 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5212 static long_t log2(ulong_t value)
5217 static long_t tlog2(struct triple *ins)
5219 return log2(ins->u.cval);
5222 static int is_pow2(struct triple *ins)
5224 ulong_t value, mask;
5226 if (!is_const(ins)) {
5229 value = ins->u.cval;
5236 return ((value & mask) == value);
5239 static ulong_t read_const(struct compile_state *state,
5240 struct triple *ins, struct triple **expr)
5244 switch(rhs->type->type &TYPE_MASK) {
5256 internal_error(state, rhs, "bad type to read_const\n");
5262 static long_t read_sconst(struct triple *ins, struct triple **expr)
5266 return (long_t)(rhs->u.cval);
5269 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5271 struct triple **expr;
5272 expr = triple_rhs(state, ins, 0);
5273 for(;expr;expr = triple_rhs(state, ins, expr)) {
5275 unuse_triple(*expr, ins);
5281 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5283 struct triple **expr;
5284 expr = triple_lhs(state, ins, 0);
5285 for(;expr;expr = triple_lhs(state, ins, expr)) {
5286 unuse_triple(*expr, ins);
5291 static void check_lhs(struct compile_state *state, struct triple *ins)
5293 struct triple **expr;
5294 expr = triple_lhs(state, ins, 0);
5295 for(;expr;expr = triple_lhs(state, ins, expr)) {
5296 internal_error(state, ins, "unexpected lhs");
5300 static void check_targ(struct compile_state *state, struct triple *ins)
5302 struct triple **expr;
5303 expr = triple_targ(state, ins, 0);
5304 for(;expr;expr = triple_targ(state, ins, expr)) {
5305 internal_error(state, ins, "unexpected targ");
5309 static void wipe_ins(struct compile_state *state, struct triple *ins)
5311 /* Becareful which instructions you replace the wiped
5312 * instruction with, as there are not enough slots
5313 * in all instructions to hold all others.
5315 check_targ(state, ins);
5316 unuse_rhs(state, ins);
5317 unuse_lhs(state, ins);
5320 static void mkcopy(struct compile_state *state,
5321 struct triple *ins, struct triple *rhs)
5323 wipe_ins(state, ins);
5325 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5327 use_triple(RHS(ins, 0), ins);
5330 static void mkconst(struct compile_state *state,
5331 struct triple *ins, ulong_t value)
5333 if (!is_integral(ins) && !is_pointer(ins)) {
5334 internal_error(state, ins, "unknown type to make constant\n");
5336 wipe_ins(state, ins);
5337 ins->op = OP_INTCONST;
5338 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5339 ins->u.cval = value;
5342 static void mkaddr_const(struct compile_state *state,
5343 struct triple *ins, struct triple *sdecl, ulong_t value)
5345 wipe_ins(state, ins);
5346 ins->op = OP_ADDRCONST;
5347 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5348 MISC(ins, 0) = sdecl;
5349 ins->u.cval = value;
5350 use_triple(sdecl, ins);
5353 /* Transform multicomponent variables into simple register variables */
5354 static void flatten_structures(struct compile_state *state)
5356 struct triple *ins, *first;
5357 first = RHS(state->main_function, 0);
5359 /* Pass one expand structure values into valvecs.
5363 struct triple *next;
5365 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5366 if (ins->op == OP_VAL_VEC) {
5369 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5370 struct triple *def, **vector;
5377 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5378 ins->filename, ins->line, ins->col);
5380 vector = &RHS(next, 0);
5381 tptr = next->type->left;
5382 for(i = 0; i < next->type->elements; i++) {
5383 struct triple *sfield;
5386 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5387 mtype = mtype->left;
5389 sfield = deref_field(state, def, mtype->field_ident);
5392 state, op, mtype, sfield, 0);
5393 vector[i]->filename = next->filename;
5394 vector[i]->line = next->line;
5395 vector[i]->col = next->col;
5398 propogate_use(state, ins, next);
5399 flatten(state, ins, next);
5400 free_triple(state, ins);
5402 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5403 struct triple *src, *dst, **vector;
5411 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5412 ins->filename, ins->line, ins->col);
5414 vector = &RHS(next, 0);
5415 tptr = next->type->left;
5416 for(i = 0; i < ins->type->elements; i++) {
5417 struct triple *dfield, *sfield;
5420 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5421 mtype = mtype->left;
5423 sfield = deref_field(state, src, mtype->field_ident);
5424 dfield = deref_field(state, dst, mtype->field_ident);
5426 state, op, mtype, dfield, sfield);
5427 vector[i]->filename = next->filename;
5428 vector[i]->line = next->line;
5429 vector[i]->col = next->col;
5432 propogate_use(state, ins, next);
5433 flatten(state, ins, next);
5434 free_triple(state, ins);
5438 } while(ins != first);
5439 /* Pass two flatten the valvecs.
5443 struct triple *next;
5445 if (ins->op == OP_VAL_VEC) {
5446 release_triple(state, ins);
5449 } while(ins != first);
5450 /* Pass three verify the state and set ->id to 0.
5454 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5455 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5456 internal_error(state, 0, "STRUCT_TYPE remains?");
5458 if (ins->op == OP_DOT) {
5459 internal_error(state, 0, "OP_DOT remains?");
5461 if (ins->op == OP_VAL_VEC) {
5462 internal_error(state, 0, "OP_VAL_VEC remains?");
5465 } while(ins != first);
5468 /* For those operations that cannot be simplified */
5469 static void simplify_noop(struct compile_state *state, struct triple *ins)
5474 static void simplify_smul(struct compile_state *state, struct triple *ins)
5476 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5479 RHS(ins, 0) = RHS(ins, 1);
5482 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5484 left = read_sconst(ins, &RHS(ins, 0));
5485 right = read_sconst(ins, &RHS(ins, 1));
5486 mkconst(state, ins, left * right);
5488 else if (is_zero(RHS(ins, 1))) {
5489 mkconst(state, ins, 0);
5491 else if (is_one(RHS(ins, 1))) {
5492 mkcopy(state, ins, RHS(ins, 0));
5494 else if (is_pow2(RHS(ins, 1))) {
5496 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5498 insert_triple(state, ins, val);
5499 unuse_triple(RHS(ins, 1), ins);
5500 use_triple(val, ins);
5505 static void simplify_umul(struct compile_state *state, struct triple *ins)
5507 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5510 RHS(ins, 0) = RHS(ins, 1);
5513 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5514 ulong_t left, right;
5515 left = read_const(state, ins, &RHS(ins, 0));
5516 right = read_const(state, ins, &RHS(ins, 1));
5517 mkconst(state, ins, left * right);
5519 else if (is_zero(RHS(ins, 1))) {
5520 mkconst(state, ins, 0);
5522 else if (is_one(RHS(ins, 1))) {
5523 mkcopy(state, ins, RHS(ins, 0));
5525 else if (is_pow2(RHS(ins, 1))) {
5527 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5529 insert_triple(state, ins, val);
5530 unuse_triple(RHS(ins, 1), ins);
5531 use_triple(val, ins);
5536 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5538 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5540 left = read_sconst(ins, &RHS(ins, 0));
5541 right = read_sconst(ins, &RHS(ins, 1));
5542 mkconst(state, ins, left / right);
5544 else if (is_zero(RHS(ins, 0))) {
5545 mkconst(state, ins, 0);
5547 else if (is_zero(RHS(ins, 1))) {
5548 error(state, ins, "division by zero");
5550 else if (is_one(RHS(ins, 1))) {
5551 mkcopy(state, ins, RHS(ins, 0));
5553 else if (is_pow2(RHS(ins, 1))) {
5555 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5557 insert_triple(state, ins, val);
5558 unuse_triple(RHS(ins, 1), ins);
5559 use_triple(val, ins);
5564 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5566 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5567 ulong_t left, right;
5568 left = read_const(state, ins, &RHS(ins, 0));
5569 right = read_const(state, ins, &RHS(ins, 1));
5570 mkconst(state, ins, left / right);
5572 else if (is_zero(RHS(ins, 0))) {
5573 mkconst(state, ins, 0);
5575 else if (is_zero(RHS(ins, 1))) {
5576 error(state, ins, "division by zero");
5578 else if (is_one(RHS(ins, 1))) {
5579 mkcopy(state, ins, RHS(ins, 0));
5581 else if (is_pow2(RHS(ins, 1))) {
5583 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5585 insert_triple(state, ins, val);
5586 unuse_triple(RHS(ins, 1), ins);
5587 use_triple(val, ins);
5592 static void simplify_smod(struct compile_state *state, struct triple *ins)
5594 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5596 left = read_const(state, ins, &RHS(ins, 0));
5597 right = read_const(state, ins, &RHS(ins, 1));
5598 mkconst(state, ins, left % right);
5600 else if (is_zero(RHS(ins, 0))) {
5601 mkconst(state, ins, 0);
5603 else if (is_zero(RHS(ins, 1))) {
5604 error(state, ins, "division by zero");
5606 else if (is_one(RHS(ins, 1))) {
5607 mkconst(state, ins, 0);
5609 else if (is_pow2(RHS(ins, 1))) {
5611 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5613 insert_triple(state, ins, val);
5614 unuse_triple(RHS(ins, 1), ins);
5615 use_triple(val, ins);
5619 static void simplify_umod(struct compile_state *state, struct triple *ins)
5621 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5622 ulong_t left, right;
5623 left = read_const(state, ins, &RHS(ins, 0));
5624 right = read_const(state, ins, &RHS(ins, 1));
5625 mkconst(state, ins, left % right);
5627 else if (is_zero(RHS(ins, 0))) {
5628 mkconst(state, ins, 0);
5630 else if (is_zero(RHS(ins, 1))) {
5631 error(state, ins, "division by zero");
5633 else if (is_one(RHS(ins, 1))) {
5634 mkconst(state, ins, 0);
5636 else if (is_pow2(RHS(ins, 1))) {
5638 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5640 insert_triple(state, ins, val);
5641 unuse_triple(RHS(ins, 1), ins);
5642 use_triple(val, ins);
5647 static void simplify_add(struct compile_state *state, struct triple *ins)
5649 /* start with the pointer on the left */
5650 if (is_pointer(RHS(ins, 1))) {
5653 RHS(ins, 0) = RHS(ins, 1);
5656 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5657 if (!is_pointer(RHS(ins, 0))) {
5658 ulong_t left, right;
5659 left = read_const(state, ins, &RHS(ins, 0));
5660 right = read_const(state, ins, &RHS(ins, 1));
5661 mkconst(state, ins, left + right);
5663 else /* op == OP_ADDRCONST */ {
5664 struct triple *sdecl;
5665 ulong_t left, right;
5666 sdecl = MISC(RHS(ins, 0), 0);
5667 left = RHS(ins, 0)->u.cval;
5668 right = RHS(ins, 1)->u.cval;
5669 mkaddr_const(state, ins, sdecl, left + right);
5672 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5675 RHS(ins, 1) = RHS(ins, 0);
5680 static void simplify_sub(struct compile_state *state, struct triple *ins)
5682 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5683 if (!is_pointer(RHS(ins, 0))) {
5684 ulong_t left, right;
5685 left = read_const(state, ins, &RHS(ins, 0));
5686 right = read_const(state, ins, &RHS(ins, 1));
5687 mkconst(state, ins, left - right);
5689 else /* op == OP_ADDRCONST */ {
5690 struct triple *sdecl;
5691 ulong_t left, right;
5692 sdecl = MISC(RHS(ins, 0), 0);
5693 left = RHS(ins, 0)->u.cval;
5694 right = RHS(ins, 1)->u.cval;
5695 mkaddr_const(state, ins, sdecl, left - right);
5700 static void simplify_sl(struct compile_state *state, struct triple *ins)
5702 if (is_const(RHS(ins, 1))) {
5704 right = read_const(state, ins, &RHS(ins, 1));
5705 if (right >= (size_of(state, ins->type)*8)) {
5706 warning(state, ins, "left shift count >= width of type");
5709 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5710 ulong_t left, right;
5711 left = read_const(state, ins, &RHS(ins, 0));
5712 right = read_const(state, ins, &RHS(ins, 1));
5713 mkconst(state, ins, left << right);
5717 static void simplify_usr(struct compile_state *state, struct triple *ins)
5719 if (is_const(RHS(ins, 1))) {
5721 right = read_const(state, ins, &RHS(ins, 1));
5722 if (right >= (size_of(state, ins->type)*8)) {
5723 warning(state, ins, "right shift count >= width of type");
5726 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5727 ulong_t left, right;
5728 left = read_const(state, ins, &RHS(ins, 0));
5729 right = read_const(state, ins, &RHS(ins, 1));
5730 mkconst(state, ins, left >> right);
5734 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5736 if (is_const(RHS(ins, 1))) {
5738 right = read_const(state, ins, &RHS(ins, 1));
5739 if (right >= (size_of(state, ins->type)*8)) {
5740 warning(state, ins, "right shift count >= width of type");
5743 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5745 left = read_sconst(ins, &RHS(ins, 0));
5746 right = read_sconst(ins, &RHS(ins, 1));
5747 mkconst(state, ins, left >> right);
5751 static void simplify_and(struct compile_state *state, struct triple *ins)
5753 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5754 ulong_t left, right;
5755 left = read_const(state, ins, &RHS(ins, 0));
5756 right = read_const(state, ins, &RHS(ins, 1));
5757 mkconst(state, ins, left & right);
5761 static void simplify_or(struct compile_state *state, struct triple *ins)
5763 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5764 ulong_t left, right;
5765 left = read_const(state, ins, &RHS(ins, 0));
5766 right = read_const(state, ins, &RHS(ins, 1));
5767 mkconst(state, ins, left | right);
5771 static void simplify_xor(struct compile_state *state, struct triple *ins)
5773 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5774 ulong_t left, right;
5775 left = read_const(state, ins, &RHS(ins, 0));
5776 right = read_const(state, ins, &RHS(ins, 1));
5777 mkconst(state, ins, left ^ right);
5781 static void simplify_pos(struct compile_state *state, struct triple *ins)
5783 if (is_const(RHS(ins, 0))) {
5784 mkconst(state, ins, RHS(ins, 0)->u.cval);
5787 mkcopy(state, ins, RHS(ins, 0));
5791 static void simplify_neg(struct compile_state *state, struct triple *ins)
5793 if (is_const(RHS(ins, 0))) {
5795 left = read_const(state, ins, &RHS(ins, 0));
5796 mkconst(state, ins, -left);
5798 else if (RHS(ins, 0)->op == OP_NEG) {
5799 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5803 static void simplify_invert(struct compile_state *state, struct triple *ins)
5805 if (is_const(RHS(ins, 0))) {
5807 left = read_const(state, ins, &RHS(ins, 0));
5808 mkconst(state, ins, ~left);
5812 static void simplify_eq(struct compile_state *state, struct triple *ins)
5814 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5815 ulong_t left, right;
5816 left = read_const(state, ins, &RHS(ins, 0));
5817 right = read_const(state, ins, &RHS(ins, 1));
5818 mkconst(state, ins, left == right);
5820 else if (RHS(ins, 0) == RHS(ins, 1)) {
5821 mkconst(state, ins, 1);
5825 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5827 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5828 ulong_t left, right;
5829 left = read_const(state, ins, &RHS(ins, 0));
5830 right = read_const(state, ins, &RHS(ins, 1));
5831 mkconst(state, ins, left != right);
5833 else if (RHS(ins, 0) == RHS(ins, 1)) {
5834 mkconst(state, ins, 0);
5838 static void simplify_sless(struct compile_state *state, struct triple *ins)
5840 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5842 left = read_sconst(ins, &RHS(ins, 0));
5843 right = read_sconst(ins, &RHS(ins, 1));
5844 mkconst(state, ins, left < right);
5846 else if (RHS(ins, 0) == RHS(ins, 1)) {
5847 mkconst(state, ins, 0);
5851 static void simplify_uless(struct compile_state *state, struct triple *ins)
5853 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5854 ulong_t left, right;
5855 left = read_const(state, ins, &RHS(ins, 0));
5856 right = read_const(state, ins, &RHS(ins, 1));
5857 mkconst(state, ins, left < right);
5859 else if (is_zero(RHS(ins, 0))) {
5860 mkconst(state, ins, 1);
5862 else if (RHS(ins, 0) == RHS(ins, 1)) {
5863 mkconst(state, ins, 0);
5867 static void simplify_smore(struct compile_state *state, struct triple *ins)
5869 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5871 left = read_sconst(ins, &RHS(ins, 0));
5872 right = read_sconst(ins, &RHS(ins, 1));
5873 mkconst(state, ins, left > right);
5875 else if (RHS(ins, 0) == RHS(ins, 1)) {
5876 mkconst(state, ins, 0);
5880 static void simplify_umore(struct compile_state *state, struct triple *ins)
5882 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5883 ulong_t left, right;
5884 left = read_const(state, ins, &RHS(ins, 0));
5885 right = read_const(state, ins, &RHS(ins, 1));
5886 mkconst(state, ins, left > right);
5888 else if (is_zero(RHS(ins, 1))) {
5889 mkconst(state, ins, 1);
5891 else if (RHS(ins, 0) == RHS(ins, 1)) {
5892 mkconst(state, ins, 0);
5897 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5899 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5901 left = read_sconst(ins, &RHS(ins, 0));
5902 right = read_sconst(ins, &RHS(ins, 1));
5903 mkconst(state, ins, left <= right);
5905 else if (RHS(ins, 0) == RHS(ins, 1)) {
5906 mkconst(state, ins, 1);
5910 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5912 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5913 ulong_t left, right;
5914 left = read_const(state, ins, &RHS(ins, 0));
5915 right = read_const(state, ins, &RHS(ins, 1));
5916 mkconst(state, ins, left <= right);
5918 else if (is_zero(RHS(ins, 0))) {
5919 mkconst(state, ins, 1);
5921 else if (RHS(ins, 0) == RHS(ins, 1)) {
5922 mkconst(state, ins, 1);
5926 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5928 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5930 left = read_sconst(ins, &RHS(ins, 0));
5931 right = read_sconst(ins, &RHS(ins, 1));
5932 mkconst(state, ins, left >= right);
5934 else if (RHS(ins, 0) == RHS(ins, 1)) {
5935 mkconst(state, ins, 1);
5939 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5941 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5942 ulong_t left, right;
5943 left = read_const(state, ins, &RHS(ins, 0));
5944 right = read_const(state, ins, &RHS(ins, 1));
5945 mkconst(state, ins, left >= right);
5947 else if (is_zero(RHS(ins, 1))) {
5948 mkconst(state, ins, 1);
5950 else if (RHS(ins, 0) == RHS(ins, 1)) {
5951 mkconst(state, ins, 1);
5955 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5957 if (is_const(RHS(ins, 0))) {
5959 left = read_const(state, ins, &RHS(ins, 0));
5960 mkconst(state, ins, left == 0);
5962 /* Otherwise if I am the only user... */
5963 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5965 /* Invert a boolean operation */
5966 switch(RHS(ins, 0)->op) {
5967 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
5968 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
5969 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
5970 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
5971 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
5972 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
5973 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
5974 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
5975 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
5976 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
5977 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
5978 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
5984 mkcopy(state, ins, RHS(ins, 0));
5989 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5991 if (is_const(RHS(ins, 0))) {
5993 left = read_const(state, ins, &RHS(ins, 0));
5994 mkconst(state, ins, left != 0);
5996 else switch(RHS(ins, 0)->op) {
5997 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
5998 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
5999 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6000 mkcopy(state, ins, RHS(ins, 0));
6005 static void simplify_copy(struct compile_state *state, struct triple *ins)
6007 if (is_const(RHS(ins, 0))) {
6008 switch(RHS(ins, 0)->op) {
6012 left = read_const(state, ins, &RHS(ins, 0));
6013 mkconst(state, ins, left);
6018 struct triple *sdecl;
6020 sdecl = MISC(RHS(ins, 0), 0);
6021 offset = RHS(ins, 0)->u.cval;
6022 mkaddr_const(state, ins, sdecl, offset);
6026 internal_error(state, ins, "uknown constant");
6032 static void simplify_branch(struct compile_state *state, struct triple *ins)
6034 struct block *block;
6035 if (ins->op != OP_BRANCH) {
6036 internal_error(state, ins, "not branch");
6038 if (ins->use != 0) {
6039 internal_error(state, ins, "branch use");
6041 #warning "FIXME implement simplify branch."
6042 /* The challenge here with simplify branch is that I need to
6043 * make modifications to the control flow graph as well
6044 * as to the branch instruction itself.
6046 block = ins->u.block;
6048 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6049 struct triple *targ;
6051 value = read_const(state, ins, &RHS(ins, 0));
6052 unuse_triple(RHS(ins, 0), ins);
6053 targ = TARG(ins, 0);
6054 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6056 unuse_triple(ins->next, ins);
6057 TARG(ins, 0) = targ;
6060 unuse_triple(targ, ins);
6061 TARG(ins, 0) = ins->next;
6063 #warning "FIXME handle the case of making a branch unconditional"
6065 if (TARG(ins, 0) == ins->next) {
6066 unuse_triple(ins->next, ins);
6067 if (TRIPLE_RHS(ins->sizes)) {
6068 unuse_triple(RHS(ins, 0), ins);
6069 unuse_triple(ins->next, ins);
6071 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6074 internal_error(state, ins, "noop use != 0");
6076 #warning "FIXME handle the case of killing a branch"
6080 static void simplify_phi(struct compile_state *state, struct triple *ins)
6082 struct triple **expr;
6084 expr = triple_rhs(state, ins, 0);
6085 if (!*expr || !is_const(*expr)) {
6088 value = read_const(state, ins, expr);
6089 for(;expr;expr = triple_rhs(state, ins, expr)) {
6090 if (!*expr || !is_const(*expr)) {
6093 if (value != read_const(state, ins, expr)) {
6097 mkconst(state, ins, value);
6101 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6103 if (is_const(RHS(ins, 0))) {
6105 left = read_const(state, ins, &RHS(ins, 0));
6106 mkconst(state, ins, bsf(left));
6110 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6112 if (is_const(RHS(ins, 0))) {
6114 left = read_const(state, ins, &RHS(ins, 0));
6115 mkconst(state, ins, bsr(left));
6120 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6121 static const simplify_t table_simplify[] = {
6123 #define simplify_smul simplify_noop
6124 #define simplify_umul simplify_noop
6125 #define simplify_sdiv simplify_noop
6126 #define simplify_udiv simplify_noop
6127 #define simplify_smod simplify_noop
6128 #define simplify_umod simplify_noop
6131 #define simplify_add simplify_noop
6132 #define simplify_sub simplify_noop
6135 #define simplify_sl simplify_noop
6136 #define simplify_usr simplify_noop
6137 #define simplify_ssr simplify_noop
6140 #define simplify_and simplify_noop
6141 #define simplify_xor simplify_noop
6142 #define simplify_or simplify_noop
6145 #define simplify_pos simplify_noop
6146 #define simplify_neg simplify_noop
6147 #define simplify_invert simplify_noop
6151 #define simplify_eq simplify_noop
6152 #define simplify_noteq simplify_noop
6155 #define simplify_sless simplify_noop
6156 #define simplify_uless simplify_noop
6157 #define simplify_smore simplify_noop
6158 #define simplify_umore simplify_noop
6161 #define simplify_slesseq simplify_noop
6162 #define simplify_ulesseq simplify_noop
6163 #define simplify_smoreeq simplify_noop
6164 #define simplify_umoreeq simplify_noop
6167 #define simplify_lfalse simplify_noop
6170 #define simplify_ltrue simplify_noop
6174 #define simplify_copy simplify_noop
6178 #define simplify_branch simplify_noop
6182 #define simplify_phi simplify_noop
6186 #define simplify_bsf simplify_noop
6187 #define simplify_bsr simplify_noop
6190 [OP_SMUL ] = simplify_smul,
6191 [OP_UMUL ] = simplify_umul,
6192 [OP_SDIV ] = simplify_sdiv,
6193 [OP_UDIV ] = simplify_udiv,
6194 [OP_SMOD ] = simplify_smod,
6195 [OP_UMOD ] = simplify_umod,
6196 [OP_ADD ] = simplify_add,
6197 [OP_SUB ] = simplify_sub,
6198 [OP_SL ] = simplify_sl,
6199 [OP_USR ] = simplify_usr,
6200 [OP_SSR ] = simplify_ssr,
6201 [OP_AND ] = simplify_and,
6202 [OP_XOR ] = simplify_xor,
6203 [OP_OR ] = simplify_or,
6204 [OP_POS ] = simplify_pos,
6205 [OP_NEG ] = simplify_neg,
6206 [OP_INVERT ] = simplify_invert,
6208 [OP_EQ ] = simplify_eq,
6209 [OP_NOTEQ ] = simplify_noteq,
6210 [OP_SLESS ] = simplify_sless,
6211 [OP_ULESS ] = simplify_uless,
6212 [OP_SMORE ] = simplify_smore,
6213 [OP_UMORE ] = simplify_umore,
6214 [OP_SLESSEQ ] = simplify_slesseq,
6215 [OP_ULESSEQ ] = simplify_ulesseq,
6216 [OP_SMOREEQ ] = simplify_smoreeq,
6217 [OP_UMOREEQ ] = simplify_umoreeq,
6218 [OP_LFALSE ] = simplify_lfalse,
6219 [OP_LTRUE ] = simplify_ltrue,
6221 [OP_LOAD ] = simplify_noop,
6222 [OP_STORE ] = simplify_noop,
6224 [OP_NOOP ] = simplify_noop,
6226 [OP_INTCONST ] = simplify_noop,
6227 [OP_BLOBCONST ] = simplify_noop,
6228 [OP_ADDRCONST ] = simplify_noop,
6230 [OP_WRITE ] = simplify_noop,
6231 [OP_READ ] = simplify_noop,
6232 [OP_COPY ] = simplify_copy,
6233 [OP_PIECE ] = simplify_noop,
6234 [OP_ASM ] = simplify_noop,
6236 [OP_DOT ] = simplify_noop,
6237 [OP_VAL_VEC ] = simplify_noop,
6239 [OP_LIST ] = simplify_noop,
6240 [OP_BRANCH ] = simplify_branch,
6241 [OP_LABEL ] = simplify_noop,
6242 [OP_ADECL ] = simplify_noop,
6243 [OP_SDECL ] = simplify_noop,
6244 [OP_PHI ] = simplify_phi,
6246 [OP_INB ] = simplify_noop,
6247 [OP_INW ] = simplify_noop,
6248 [OP_INL ] = simplify_noop,
6249 [OP_OUTB ] = simplify_noop,
6250 [OP_OUTW ] = simplify_noop,
6251 [OP_OUTL ] = simplify_noop,
6252 [OP_BSF ] = simplify_bsf,
6253 [OP_BSR ] = simplify_bsr,
6254 [OP_RDMSR ] = simplify_noop,
6255 [OP_WRMSR ] = simplify_noop,
6256 [OP_HLT ] = simplify_noop,
6259 static void simplify(struct compile_state *state, struct triple *ins)
6262 simplify_t do_simplify;
6266 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6270 do_simplify = table_simplify[op];
6273 internal_error(state, ins, "cannot simplify op: %d %s\n",
6277 do_simplify(state, ins);
6278 } while(ins->op != op);
6281 static void simplify_all(struct compile_state *state)
6283 struct triple *ins, *first;
6284 first = RHS(state->main_function, 0);
6287 simplify(state, ins);
6289 } while(ins != first);
6294 * ============================
6297 static void register_builtin_function(struct compile_state *state,
6298 const char *name, int op, struct type *rtype, ...)
6300 struct type *ftype, *atype, *param, **next;
6301 struct triple *def, *arg, *result, *work, *last, *first;
6302 struct hash_entry *ident;
6303 struct file_state file;
6309 /* Dummy file state to get debug handling right */
6310 memset(&file, 0, sizeof(file));
6311 file.basename = name;
6313 file.prev = state->file;
6314 state->file = &file;
6316 /* Find the Parameter count */
6317 valid_op(state, op);
6318 parameters = table_ops[op].rhs;
6319 if (parameters < 0 ) {
6320 internal_error(state, 0, "Invalid builtin parameter count");
6323 /* Find the function type */
6324 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6325 next = &ftype->right;
6326 va_start(args, rtype);
6327 for(i = 0; i < parameters; i++) {
6328 atype = va_arg(args, struct type *);
6332 *next = new_type(TYPE_PRODUCT, *next, atype);
6333 next = &((*next)->right);
6341 /* Generate the needed triples */
6342 def = triple(state, OP_LIST, ftype, 0, 0);
6343 first = label(state);
6344 RHS(def, 0) = first;
6346 /* Now string them together */
6347 param = ftype->right;
6348 for(i = 0; i < parameters; i++) {
6349 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6350 atype = param->left;
6354 arg = flatten(state, first, variable(state, atype));
6355 param = param->right;
6358 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6359 result = flatten(state, first, variable(state, rtype));
6361 MISC(def, 0) = result;
6362 work = new_triple(state, op, rtype, -1, parameters);
6363 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6364 RHS(work, i) = read_expr(state, arg);
6366 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6368 /* Populate the LHS with the target registers */
6369 work = flatten(state, first, work);
6370 work->type = &void_type;
6371 param = rtype->left;
6372 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6373 internal_error(state, 0, "Invalid result type");
6375 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6376 for(i = 0; i < rtype->elements; i++) {
6377 struct triple *piece;
6379 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6380 atype = param->left;
6382 if (!TYPE_ARITHMETIC(atype->type) &&
6383 !TYPE_PTR(atype->type)) {
6384 internal_error(state, 0, "Invalid lhs type");
6386 piece = triple(state, OP_PIECE, atype, work, 0);
6388 LHS(work, i) = piece;
6389 RHS(val, i) = piece;
6394 work = write_expr(state, result, work);
6396 work = flatten(state, first, work);
6397 last = flatten(state, first, label(state));
6398 name_len = strlen(name);
6399 ident = lookup(state, name, name_len);
6400 symbol(state, ident, &ident->sym_ident, def, ftype);
6402 state->file = file.prev;
6404 fprintf(stdout, "\n");
6405 loc(stdout, state, 0);
6406 fprintf(stdout, "\n__________ builtin_function _________\n");
6407 print_triple(state, def);
6408 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6412 static struct type *partial_struct(struct compile_state *state,
6413 const char *field_name, struct type *type, struct type *rest)
6415 struct hash_entry *field_ident;
6416 struct type *result;
6419 field_name_len = strlen(field_name);
6420 field_ident = lookup(state, field_name, field_name_len);
6422 result = clone_type(0, type);
6423 result->field_ident = field_ident;
6426 result = new_type(TYPE_PRODUCT, result, rest);
6431 static struct type *register_builtin_type(struct compile_state *state,
6432 const char *name, struct type *type)
6434 struct hash_entry *ident;
6437 name_len = strlen(name);
6438 ident = lookup(state, name, name_len);
6440 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6441 ulong_t elements = 0;
6443 type = new_type(TYPE_STRUCT, type, 0);
6445 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6447 field = field->right;
6450 symbol(state, ident, &ident->sym_struct, 0, type);
6451 type->type_ident = ident;
6452 type->elements = elements;
6454 symbol(state, ident, &ident->sym_ident, 0, type);
6455 ident->tok = TOK_TYPE_NAME;
6460 static void register_builtins(struct compile_state *state)
6462 struct type *msr_type;
6464 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6466 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6468 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6471 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6472 &uchar_type, &ushort_type);
6473 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6474 &ushort_type, &ushort_type);
6475 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6476 &uint_type, &ushort_type);
6478 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6480 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6483 msr_type = register_builtin_type(state, "__builtin_msr_t",
6484 partial_struct(state, "lo", &ulong_type,
6485 partial_struct(state, "hi", &ulong_type, 0)));
6487 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6489 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6490 &ulong_type, &ulong_type, &ulong_type);
6492 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6496 static struct type *declarator(
6497 struct compile_state *state, struct type *type,
6498 struct hash_entry **ident, int need_ident);
6499 static void decl(struct compile_state *state, struct triple *first);
6500 static struct type *specifier_qualifier_list(struct compile_state *state);
6501 static int isdecl_specifier(int tok);
6502 static struct type *decl_specifiers(struct compile_state *state);
6503 static int istype(int tok);
6504 static struct triple *expr(struct compile_state *state);
6505 static struct triple *assignment_expr(struct compile_state *state);
6506 static struct type *type_name(struct compile_state *state);
6507 static void statement(struct compile_state *state, struct triple *fist);
6509 static struct triple *call_expr(
6510 struct compile_state *state, struct triple *func)
6513 struct type *param, *type;
6514 ulong_t pvals, index;
6516 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6517 error(state, 0, "Called object is not a function");
6519 if (func->op != OP_LIST) {
6520 internal_error(state, 0, "improper function");
6522 eat(state, TOK_LPAREN);
6523 /* Find the return type without any specifiers */
6524 type = clone_type(0, func->type->left);
6525 def = new_triple(state, OP_CALL, func->type, -1, -1);
6528 pvals = TRIPLE_RHS(def->sizes);
6529 MISC(def, 0) = func;
6531 param = func->type->right;
6532 for(index = 0; index < pvals; index++) {
6534 struct type *arg_type;
6535 val = read_expr(state, assignment_expr(state));
6537 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6538 arg_type = param->left;
6540 write_compatible(state, arg_type, val->type);
6541 RHS(def, index) = val;
6542 if (index != (pvals - 1)) {
6543 eat(state, TOK_COMMA);
6544 param = param->right;
6547 eat(state, TOK_RPAREN);
6552 static struct triple *character_constant(struct compile_state *state)
6556 const signed char *str, *end;
6559 eat(state, TOK_LIT_CHAR);
6560 tk = &state->token[0];
6561 str = tk->val.str + 1;
6562 str_len = tk->str_len - 2;
6564 error(state, 0, "empty character constant");
6566 end = str + str_len;
6567 c = char_value(state, &str, end);
6569 error(state, 0, "multibyte character constant not supported");
6571 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6575 static struct triple *string_constant(struct compile_state *state)
6580 const signed char *str, *end;
6581 signed char *buf, *ptr;
6585 type = new_type(TYPE_ARRAY, &char_type, 0);
6587 /* The while loop handles string concatenation */
6589 eat(state, TOK_LIT_STRING);
6590 tk = &state->token[0];
6591 str = tk->val.str + 1;
6592 str_len = tk->str_len - 2;
6594 error(state, 0, "negative string constant length");
6596 end = str + str_len;
6598 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6599 memcpy(buf, ptr, type->elements);
6600 ptr = buf + type->elements;
6602 *ptr++ = char_value(state, &str, end);
6604 type->elements = ptr - buf;
6605 } while(peek(state) == TOK_LIT_STRING);
6607 type->elements += 1;
6608 def = triple(state, OP_BLOBCONST, type, 0, 0);
6614 static struct triple *integer_constant(struct compile_state *state)
6623 eat(state, TOK_LIT_INT);
6624 tk = &state->token[0];
6626 decimal = (tk->val.str[0] != '0');
6627 val = strtoul(tk->val.str, &end, 0);
6628 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6629 error(state, 0, "Integer constant to large");
6632 if ((*end == 'u') || (*end == 'U')) {
6636 if ((*end == 'l') || (*end == 'L')) {
6640 if ((*end == 'u') || (*end == 'U')) {
6645 error(state, 0, "Junk at end of integer constant");
6652 if (!decimal && (val > LONG_MAX)) {
6658 if (val > UINT_MAX) {
6664 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6667 else if (!decimal && (val > LONG_MAX)) {
6670 else if (val > INT_MAX) {
6674 def = int_const(state, type, val);
6678 static struct triple *primary_expr(struct compile_state *state)
6686 struct hash_entry *ident;
6687 /* Here ident is either:
6690 * an enumeration constant.
6692 eat(state, TOK_IDENT);
6693 ident = state->token[0].ident;
6694 if (!ident->sym_ident) {
6695 error(state, 0, "%s undeclared", ident->name);
6697 def = ident->sym_ident->def;
6700 case TOK_ENUM_CONST:
6701 /* Here ident is an enumeration constant */
6702 eat(state, TOK_ENUM_CONST);
6707 eat(state, TOK_LPAREN);
6709 eat(state, TOK_RPAREN);
6712 def = integer_constant(state);
6715 eat(state, TOK_LIT_FLOAT);
6716 error(state, 0, "Floating point constants not supported");
6721 def = character_constant(state);
6723 case TOK_LIT_STRING:
6724 def = string_constant(state);
6728 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6733 static struct triple *postfix_expr(struct compile_state *state)
6737 def = primary_expr(state);
6739 struct triple *left;
6743 switch((tok = peek(state))) {
6745 eat(state, TOK_LBRACKET);
6746 def = mk_subscript_expr(state, left, expr(state));
6747 eat(state, TOK_RBRACKET);
6750 def = call_expr(state, def);
6754 struct hash_entry *field;
6755 eat(state, TOK_DOT);
6756 eat(state, TOK_IDENT);
6757 field = state->token[0].ident;
6758 def = deref_field(state, def, field);
6763 struct hash_entry *field;
6764 eat(state, TOK_ARROW);
6765 eat(state, TOK_IDENT);
6766 field = state->token[0].ident;
6767 def = mk_deref_expr(state, read_expr(state, def));
6768 def = deref_field(state, def, field);
6772 eat(state, TOK_PLUSPLUS);
6773 def = mk_post_inc_expr(state, left);
6775 case TOK_MINUSMINUS:
6776 eat(state, TOK_MINUSMINUS);
6777 def = mk_post_dec_expr(state, left);
6787 static struct triple *cast_expr(struct compile_state *state);
6789 static struct triple *unary_expr(struct compile_state *state)
6791 struct triple *def, *right;
6793 switch((tok = peek(state))) {
6795 eat(state, TOK_PLUSPLUS);
6796 def = mk_pre_inc_expr(state, unary_expr(state));
6798 case TOK_MINUSMINUS:
6799 eat(state, TOK_MINUSMINUS);
6800 def = mk_pre_dec_expr(state, unary_expr(state));
6803 eat(state, TOK_AND);
6804 def = mk_addr_expr(state, cast_expr(state), 0);
6807 eat(state, TOK_STAR);
6808 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6811 eat(state, TOK_PLUS);
6812 right = read_expr(state, cast_expr(state));
6813 arithmetic(state, right);
6814 def = integral_promotion(state, right);
6817 eat(state, TOK_MINUS);
6818 right = read_expr(state, cast_expr(state));
6819 arithmetic(state, right);
6820 def = integral_promotion(state, right);
6821 def = triple(state, OP_NEG, def->type, def, 0);
6824 eat(state, TOK_TILDE);
6825 right = read_expr(state, cast_expr(state));
6826 integral(state, right);
6827 def = integral_promotion(state, right);
6828 def = triple(state, OP_INVERT, def->type, def, 0);
6831 eat(state, TOK_BANG);
6832 right = read_expr(state, cast_expr(state));
6834 def = lfalse_expr(state, right);
6840 eat(state, TOK_SIZEOF);
6842 tok2 = peek2(state);
6843 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6844 eat(state, TOK_LPAREN);
6845 type = type_name(state);
6846 eat(state, TOK_RPAREN);
6849 struct triple *expr;
6850 expr = unary_expr(state);
6852 release_expr(state, expr);
6854 def = int_const(state, &ulong_type, size_of(state, type));
6861 eat(state, TOK_ALIGNOF);
6863 tok2 = peek2(state);
6864 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6865 eat(state, TOK_LPAREN);
6866 type = type_name(state);
6867 eat(state, TOK_RPAREN);
6870 struct triple *expr;
6871 expr = unary_expr(state);
6873 release_expr(state, expr);
6875 def = int_const(state, &ulong_type, align_of(state, type));
6879 def = postfix_expr(state);
6885 static struct triple *cast_expr(struct compile_state *state)
6890 tok2 = peek2(state);
6891 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6893 eat(state, TOK_LPAREN);
6894 type = type_name(state);
6895 eat(state, TOK_RPAREN);
6896 def = read_expr(state, cast_expr(state));
6897 def = triple(state, OP_COPY, type, def, 0);
6900 def = unary_expr(state);
6905 static struct triple *mult_expr(struct compile_state *state)
6909 def = cast_expr(state);
6911 struct triple *left, *right;
6912 struct type *result_type;
6915 switch(tok = (peek(state))) {
6919 left = read_expr(state, def);
6920 arithmetic(state, left);
6924 right = read_expr(state, cast_expr(state));
6925 arithmetic(state, right);
6927 result_type = arithmetic_result(state, left, right);
6928 sign = is_signed(result_type);
6931 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6932 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
6933 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
6935 def = triple(state, op, result_type, left, right);
6945 static struct triple *add_expr(struct compile_state *state)
6949 def = mult_expr(state);
6952 switch( peek(state)) {
6954 eat(state, TOK_PLUS);
6955 def = mk_add_expr(state, def, mult_expr(state));
6958 eat(state, TOK_MINUS);
6959 def = mk_sub_expr(state, def, mult_expr(state));
6969 static struct triple *shift_expr(struct compile_state *state)
6973 def = add_expr(state);
6975 struct triple *left, *right;
6978 switch((tok = peek(state))) {
6981 left = read_expr(state, def);
6982 integral(state, left);
6983 left = integral_promotion(state, left);
6987 right = read_expr(state, add_expr(state));
6988 integral(state, right);
6989 right = integral_promotion(state, right);
6991 op = (tok == TOK_SL)? OP_SL :
6992 is_signed(left->type)? OP_SSR: OP_USR;
6994 def = triple(state, op, left->type, left, right);
7004 static struct triple *relational_expr(struct compile_state *state)
7006 #warning "Extend relational exprs to work on more than arithmetic types"
7009 def = shift_expr(state);
7011 struct triple *left, *right;
7012 struct type *arg_type;
7015 switch((tok = peek(state))) {
7020 left = read_expr(state, def);
7021 arithmetic(state, left);
7025 right = read_expr(state, shift_expr(state));
7026 arithmetic(state, right);
7028 arg_type = arithmetic_result(state, left, right);
7029 sign = is_signed(arg_type);
7032 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7033 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7034 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7035 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7037 def = triple(state, op, &int_type, left, right);
7047 static struct triple *equality_expr(struct compile_state *state)
7049 #warning "Extend equality exprs to work on more than arithmetic types"
7052 def = relational_expr(state);
7054 struct triple *left, *right;
7057 switch((tok = peek(state))) {
7060 left = read_expr(state, def);
7061 arithmetic(state, left);
7063 right = read_expr(state, relational_expr(state));
7064 arithmetic(state, right);
7065 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7066 def = triple(state, op, &int_type, left, right);
7076 static struct triple *and_expr(struct compile_state *state)
7079 def = equality_expr(state);
7080 while(peek(state) == TOK_AND) {
7081 struct triple *left, *right;
7082 struct type *result_type;
7083 left = read_expr(state, def);
7084 integral(state, left);
7085 eat(state, TOK_AND);
7086 right = read_expr(state, equality_expr(state));
7087 integral(state, right);
7088 result_type = arithmetic_result(state, left, right);
7089 def = triple(state, OP_AND, result_type, left, right);
7094 static struct triple *xor_expr(struct compile_state *state)
7097 def = and_expr(state);
7098 while(peek(state) == TOK_XOR) {
7099 struct triple *left, *right;
7100 struct type *result_type;
7101 left = read_expr(state, def);
7102 integral(state, left);
7103 eat(state, TOK_XOR);
7104 right = read_expr(state, and_expr(state));
7105 integral(state, right);
7106 result_type = arithmetic_result(state, left, right);
7107 def = triple(state, OP_XOR, result_type, left, right);
7112 static struct triple *or_expr(struct compile_state *state)
7115 def = xor_expr(state);
7116 while(peek(state) == TOK_OR) {
7117 struct triple *left, *right;
7118 struct type *result_type;
7119 left = read_expr(state, def);
7120 integral(state, left);
7122 right = read_expr(state, xor_expr(state));
7123 integral(state, right);
7124 result_type = arithmetic_result(state, left, right);
7125 def = triple(state, OP_OR, result_type, left, right);
7130 static struct triple *land_expr(struct compile_state *state)
7133 def = or_expr(state);
7134 while(peek(state) == TOK_LOGAND) {
7135 struct triple *left, *right;
7136 left = read_expr(state, def);
7138 eat(state, TOK_LOGAND);
7139 right = read_expr(state, or_expr(state));
7142 def = triple(state, OP_LAND, &int_type,
7143 ltrue_expr(state, left),
7144 ltrue_expr(state, right));
7149 static struct triple *lor_expr(struct compile_state *state)
7152 def = land_expr(state);
7153 while(peek(state) == TOK_LOGOR) {
7154 struct triple *left, *right;
7155 left = read_expr(state, def);
7157 eat(state, TOK_LOGOR);
7158 right = read_expr(state, land_expr(state));
7161 def = triple(state, OP_LOR, &int_type,
7162 ltrue_expr(state, left),
7163 ltrue_expr(state, right));
7168 static struct triple *conditional_expr(struct compile_state *state)
7171 def = lor_expr(state);
7172 if (peek(state) == TOK_QUEST) {
7173 struct triple *test, *left, *right;
7175 test = ltrue_expr(state, read_expr(state, def));
7176 eat(state, TOK_QUEST);
7177 left = read_expr(state, expr(state));
7178 eat(state, TOK_COLON);
7179 right = read_expr(state, conditional_expr(state));
7181 def = cond_expr(state, test, left, right);
7186 static struct triple *eval_const_expr(
7187 struct compile_state *state, struct triple *expr)
7190 struct triple *head, *ptr;
7191 head = label(state); /* dummy initial triple */
7192 flatten(state, head, expr);
7193 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7194 simplify(state, ptr);
7196 /* Remove the constant value the tail of the list */
7198 def->prev->next = def->next;
7199 def->next->prev = def->prev;
7200 def->next = def->prev = def;
7201 if (!is_const(def)) {
7202 internal_error(state, 0, "Not a constant expression");
7204 /* Free the intermediate expressions */
7205 while(head->next != head) {
7206 release_triple(state, head->next);
7208 free_triple(state, head);
7212 static struct triple *constant_expr(struct compile_state *state)
7214 return eval_const_expr(state, conditional_expr(state));
7217 static struct triple *assignment_expr(struct compile_state *state)
7219 struct triple *def, *left, *right;
7221 /* The C grammer in K&R shows assignment expressions
7222 * only taking unary expressions as input on their
7223 * left hand side. But specifies the precedence of
7224 * assignemnt as the lowest operator except for comma.
7226 * Allowing conditional expressions on the left hand side
7227 * of an assignement results in a grammar that accepts
7228 * a larger set of statements than standard C. As long
7229 * as the subset of the grammar that is standard C behaves
7230 * correctly this should cause no problems.
7232 * For the extra token strings accepted by the grammar
7233 * none of them should produce a valid lvalue, so they
7234 * should not produce functioning programs.
7236 * GCC has this bug as well, so surprises should be minimal.
7238 def = conditional_expr(state);
7240 switch((tok = peek(state))) {
7242 lvalue(state, left);
7244 def = write_expr(state, left,
7245 read_expr(state, assignment_expr(state)));
7250 lvalue(state, left);
7251 arithmetic(state, left);
7253 right = read_expr(state, assignment_expr(state));
7254 arithmetic(state, right);
7256 sign = is_signed(left->type);
7259 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7260 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7261 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7263 def = write_expr(state, left,
7264 triple(state, op, left->type,
7265 read_expr(state, left), right));
7268 lvalue(state, left);
7269 eat(state, TOK_PLUSEQ);
7270 def = write_expr(state, left,
7271 mk_add_expr(state, left, assignment_expr(state)));
7274 lvalue(state, left);
7275 eat(state, TOK_MINUSEQ);
7276 def = write_expr(state, left,
7277 mk_sub_expr(state, left, assignment_expr(state)));
7284 lvalue(state, left);
7285 integral(state, left);
7287 right = read_expr(state, assignment_expr(state));
7288 integral(state, right);
7289 right = integral_promotion(state, right);
7290 sign = is_signed(left->type);
7293 case TOK_SLEQ: op = OP_SL; break;
7294 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7295 case TOK_ANDEQ: op = OP_AND; break;
7296 case TOK_XOREQ: op = OP_XOR; break;
7297 case TOK_OREQ: op = OP_OR; break;
7299 def = write_expr(state, left,
7300 triple(state, op, left->type,
7301 read_expr(state, left), right));
7307 static struct triple *expr(struct compile_state *state)
7310 def = assignment_expr(state);
7311 while(peek(state) == TOK_COMMA) {
7312 struct triple *left, *right;
7314 eat(state, TOK_COMMA);
7315 right = assignment_expr(state);
7316 def = triple(state, OP_COMMA, right->type, left, right);
7321 static void expr_statement(struct compile_state *state, struct triple *first)
7323 if (peek(state) != TOK_SEMI) {
7324 flatten(state, first, expr(state));
7326 eat(state, TOK_SEMI);
7329 static void if_statement(struct compile_state *state, struct triple *first)
7331 struct triple *test, *jmp1, *jmp2, *middle, *end;
7333 jmp1 = jmp2 = middle = 0;
7335 eat(state, TOK_LPAREN);
7338 /* Cleanup and invert the test */
7339 test = lfalse_expr(state, read_expr(state, test));
7340 eat(state, TOK_RPAREN);
7341 /* Generate the needed pieces */
7342 middle = label(state);
7343 jmp1 = branch(state, middle, test);
7344 /* Thread the pieces together */
7345 flatten(state, first, test);
7346 flatten(state, first, jmp1);
7347 flatten(state, first, label(state));
7348 statement(state, first);
7349 if (peek(state) == TOK_ELSE) {
7350 eat(state, TOK_ELSE);
7351 /* Generate the rest of the pieces */
7353 jmp2 = branch(state, end, 0);
7354 /* Thread them together */
7355 flatten(state, first, jmp2);
7356 flatten(state, first, middle);
7357 statement(state, first);
7358 flatten(state, first, end);
7361 flatten(state, first, middle);
7365 static void for_statement(struct compile_state *state, struct triple *first)
7367 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7368 struct triple *label1, *label2, *label3;
7369 struct hash_entry *ident;
7371 eat(state, TOK_FOR);
7372 eat(state, TOK_LPAREN);
7373 head = test = tail = jmp1 = jmp2 = 0;
7374 if (peek(state) != TOK_SEMI) {
7377 eat(state, TOK_SEMI);
7378 if (peek(state) != TOK_SEMI) {
7381 test = ltrue_expr(state, read_expr(state, test));
7383 eat(state, TOK_SEMI);
7384 if (peek(state) != TOK_RPAREN) {
7387 eat(state, TOK_RPAREN);
7388 /* Generate the needed pieces */
7389 label1 = label(state);
7390 label2 = label(state);
7391 label3 = label(state);
7393 jmp1 = branch(state, label3, 0);
7394 jmp2 = branch(state, label1, test);
7397 jmp2 = branch(state, label1, 0);
7400 /* Remember where break and continue go */
7402 ident = state->i_break;
7403 symbol(state, ident, &ident->sym_ident, end, end->type);
7404 ident = state->i_continue;
7405 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7406 /* Now include the body */
7407 flatten(state, first, head);
7408 flatten(state, first, jmp1);
7409 flatten(state, first, label1);
7410 statement(state, first);
7411 flatten(state, first, label2);
7412 flatten(state, first, tail);
7413 flatten(state, first, label3);
7414 flatten(state, first, test);
7415 flatten(state, first, jmp2);
7416 flatten(state, first, end);
7417 /* Cleanup the break/continue scope */
7421 static void while_statement(struct compile_state *state, struct triple *first)
7423 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7424 struct hash_entry *ident;
7425 eat(state, TOK_WHILE);
7426 eat(state, TOK_LPAREN);
7429 test = ltrue_expr(state, read_expr(state, test));
7430 eat(state, TOK_RPAREN);
7431 /* Generate the needed pieces */
7432 label1 = label(state);
7433 label2 = label(state);
7434 jmp1 = branch(state, label2, 0);
7435 jmp2 = branch(state, label1, test);
7437 /* Remember where break and continue go */
7439 ident = state->i_break;
7440 symbol(state, ident, &ident->sym_ident, end, end->type);
7441 ident = state->i_continue;
7442 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7443 /* Thread them together */
7444 flatten(state, first, jmp1);
7445 flatten(state, first, label1);
7446 statement(state, first);
7447 flatten(state, first, label2);
7448 flatten(state, first, test);
7449 flatten(state, first, jmp2);
7450 flatten(state, first, end);
7451 /* Cleanup the break/continue scope */
7455 static void do_statement(struct compile_state *state, struct triple *first)
7457 struct triple *label1, *label2, *test, *end;
7458 struct hash_entry *ident;
7460 /* Generate the needed pieces */
7461 label1 = label(state);
7462 label2 = label(state);
7464 /* Remember where break and continue go */
7466 ident = state->i_break;
7467 symbol(state, ident, &ident->sym_ident, end, end->type);
7468 ident = state->i_continue;
7469 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7470 /* Now include the body */
7471 flatten(state, first, label1);
7472 statement(state, first);
7473 /* Cleanup the break/continue scope */
7475 /* Eat the rest of the loop */
7476 eat(state, TOK_WHILE);
7477 eat(state, TOK_LPAREN);
7478 test = read_expr(state, expr(state));
7480 eat(state, TOK_RPAREN);
7481 eat(state, TOK_SEMI);
7482 /* Thread the pieces together */
7483 test = ltrue_expr(state, test);
7484 flatten(state, first, label2);
7485 flatten(state, first, test);
7486 flatten(state, first, branch(state, label1, test));
7487 flatten(state, first, end);
7491 static void return_statement(struct compile_state *state, struct triple *first)
7493 struct triple *jmp, *mv, *dest, *var, *val;
7495 eat(state, TOK_RETURN);
7497 #warning "FIXME implement a more general excess branch elimination"
7499 /* If we have a return value do some more work */
7500 if (peek(state) != TOK_SEMI) {
7501 val = read_expr(state, expr(state));
7503 eat(state, TOK_SEMI);
7505 /* See if this last statement in a function */
7506 last = ((peek(state) == TOK_RBRACE) &&
7507 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7509 /* Find the return variable */
7510 var = MISC(state->main_function, 0);
7511 /* Find the return destination */
7512 dest = RHS(state->main_function, 0)->prev;
7514 /* If needed generate a jump instruction */
7516 jmp = branch(state, dest, 0);
7518 /* If needed generate an assignment instruction */
7520 mv = write_expr(state, var, val);
7522 /* Now put the code together */
7524 flatten(state, first, mv);
7525 flatten(state, first, jmp);
7528 flatten(state, first, jmp);
7532 static void break_statement(struct compile_state *state, struct triple *first)
7534 struct triple *dest;
7535 eat(state, TOK_BREAK);
7536 eat(state, TOK_SEMI);
7537 if (!state->i_break->sym_ident) {
7538 error(state, 0, "break statement not within loop or switch");
7540 dest = state->i_break->sym_ident->def;
7541 flatten(state, first, branch(state, dest, 0));
7544 static void continue_statement(struct compile_state *state, struct triple *first)
7546 struct triple *dest;
7547 eat(state, TOK_CONTINUE);
7548 eat(state, TOK_SEMI);
7549 if (!state->i_continue->sym_ident) {
7550 error(state, 0, "continue statement outside of a loop");
7552 dest = state->i_continue->sym_ident->def;
7553 flatten(state, first, branch(state, dest, 0));
7556 static void goto_statement(struct compile_state *state, struct triple *first)
7559 eat(state, TOK_GOTO);
7560 eat(state, TOK_IDENT);
7561 eat(state, TOK_SEMI);
7562 error(state, 0, "goto is not implemeted");
7566 static void labeled_statement(struct compile_state *state, struct triple *first)
7569 eat(state, TOK_IDENT);
7570 eat(state, TOK_COLON);
7571 statement(state, first);
7572 error(state, 0, "labeled statements are not implemented");
7576 static void switch_statement(struct compile_state *state, struct triple *first)
7579 eat(state, TOK_SWITCH);
7580 eat(state, TOK_LPAREN);
7582 eat(state, TOK_RPAREN);
7583 statement(state, first);
7584 error(state, 0, "switch statements are not implemented");
7588 static void case_statement(struct compile_state *state, struct triple *first)
7591 eat(state, TOK_CASE);
7592 constant_expr(state);
7593 eat(state, TOK_COLON);
7594 statement(state, first);
7595 error(state, 0, "case statements are not implemented");
7599 static void default_statement(struct compile_state *state, struct triple *first)
7602 eat(state, TOK_DEFAULT);
7603 eat(state, TOK_COLON);
7604 statement(state, first);
7605 error(state, 0, "default statements are not implemented");
7609 static void asm_statement(struct compile_state *state, struct triple *first)
7611 struct asm_info *info;
7613 struct triple *constraint;
7614 struct triple *expr;
7615 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7616 struct triple *def, *asm_str;
7617 int out, in, clobbers, more, colons, i;
7619 eat(state, TOK_ASM);
7620 /* For now ignore the qualifiers */
7621 switch(peek(state)) {
7623 eat(state, TOK_CONST);
7626 eat(state, TOK_VOLATILE);
7629 eat(state, TOK_LPAREN);
7630 asm_str = string_constant(state);
7633 out = in = clobbers = 0;
7635 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7636 eat(state, TOK_COLON);
7638 more = (peek(state) == TOK_LIT_STRING);
7641 struct triple *constraint;
7643 if (out > MAX_LHS) {
7644 error(state, 0, "Maximum output count exceeded.");
7646 constraint = string_constant(state);
7647 eat(state, TOK_LPAREN);
7648 var = conditional_expr(state);
7649 eat(state, TOK_RPAREN);
7652 out_param[out].constraint = constraint;
7653 out_param[out].expr = var;
7654 if (peek(state) == TOK_COMMA) {
7655 eat(state, TOK_COMMA);
7662 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7663 eat(state, TOK_COLON);
7665 more = (peek(state) == TOK_LIT_STRING);
7668 struct triple *constraint;
7671 error(state, 0, "Maximum input count exceeded.");
7673 constraint = string_constant(state);
7674 eat(state, TOK_LPAREN);
7675 val = conditional_expr(state);
7676 eat(state, TOK_RPAREN);
7678 in_param[in].constraint = constraint;
7679 in_param[in].expr = val;
7680 if (peek(state) == TOK_COMMA) {
7681 eat(state, TOK_COMMA);
7689 if ((colons == 2) && (peek(state) == TOK_COLON)) {
7690 eat(state, TOK_COLON);
7692 more = (peek(state) == TOK_LIT_STRING);
7694 struct triple *clobber;
7696 if ((clobbers + out) > MAX_LHS) {
7697 error(state, 0, "Maximum clobber limit exceeded.");
7699 clobber = string_constant(state);
7700 eat(state, TOK_RPAREN);
7702 clob_param[clobbers].constraint = clobber;
7703 if (peek(state) == TOK_COMMA) {
7704 eat(state, TOK_COMMA);
7710 eat(state, TOK_RPAREN);
7711 eat(state, TOK_SEMI);
7714 info = xcmalloc(sizeof(*info), "asm_info");
7715 info->str = asm_str->u.blob;
7716 free_triple(state, asm_str);
7718 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7719 def->u.ainfo = info;
7720 for(i = 0; i < in; i++) {
7721 struct triple *constraint;
7722 constraint = in_param[i].constraint;
7723 info->tmpl.rhs[i] = arch_reg_constraint(state,
7724 in_param[i].expr->type, constraint->u.blob);
7726 RHS(def, i) = read_expr(state,in_param[i].expr);
7727 free_triple(state, constraint);
7729 flatten(state, first, def);
7730 for(i = 0; i < out; i++) {
7731 struct triple *piece;
7732 struct triple *constraint;
7733 constraint = out_param[i].constraint;
7734 info->tmpl.lhs[i] = arch_reg_constraint(state,
7735 out_param[i].expr->type, constraint->u.blob);
7737 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7739 LHS(def, i) = piece;
7740 flatten(state, first,
7741 write_expr(state, out_param[i].expr, piece));
7742 free_triple(state, constraint);
7744 for(; i - out < clobbers; i++) {
7745 struct triple *piece;
7746 struct triple *constraint;
7747 constraint = clob_param[i - out].constraint;
7748 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7750 piece = triple(state, OP_PIECE, &void_type, def, 0);
7752 LHS(def, i) = piece;
7753 flatten(state, first, piece);
7754 free_triple(state, constraint);
7759 static int isdecl(int tok)
7782 case TOK_TYPE_NAME: /* typedef name */
7789 static void compound_statement(struct compile_state *state, struct triple *first)
7791 eat(state, TOK_LBRACE);
7794 /* statement-list opt */
7795 while (peek(state) != TOK_RBRACE) {
7796 statement(state, first);
7799 eat(state, TOK_RBRACE);
7802 static void statement(struct compile_state *state, struct triple *first)
7806 if (tok == TOK_LBRACE) {
7807 compound_statement(state, first);
7809 else if (tok == TOK_IF) {
7810 if_statement(state, first);
7812 else if (tok == TOK_FOR) {
7813 for_statement(state, first);
7815 else if (tok == TOK_WHILE) {
7816 while_statement(state, first);
7818 else if (tok == TOK_DO) {
7819 do_statement(state, first);
7821 else if (tok == TOK_RETURN) {
7822 return_statement(state, first);
7824 else if (tok == TOK_BREAK) {
7825 break_statement(state, first);
7827 else if (tok == TOK_CONTINUE) {
7828 continue_statement(state, first);
7830 else if (tok == TOK_GOTO) {
7831 goto_statement(state, first);
7833 else if (tok == TOK_SWITCH) {
7834 switch_statement(state, first);
7836 else if (tok == TOK_ASM) {
7837 asm_statement(state, first);
7839 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7840 labeled_statement(state, first);
7842 else if (tok == TOK_CASE) {
7843 case_statement(state, first);
7845 else if (tok == TOK_DEFAULT) {
7846 default_statement(state, first);
7848 else if (isdecl(tok)) {
7849 /* This handles C99 intermixing of statements and decls */
7853 expr_statement(state, first);
7857 static struct type *param_decl(struct compile_state *state)
7860 struct hash_entry *ident;
7861 /* Cheat so the declarator will know we are not global */
7864 type = decl_specifiers(state);
7865 type = declarator(state, type, &ident, 0);
7866 type->field_ident = ident;
7871 static struct type *param_type_list(struct compile_state *state, struct type *type)
7873 struct type *ftype, **next;
7874 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7875 next = &ftype->right;
7876 while(peek(state) == TOK_COMMA) {
7877 eat(state, TOK_COMMA);
7878 if (peek(state) == TOK_DOTS) {
7879 eat(state, TOK_DOTS);
7880 error(state, 0, "variadic functions not supported");
7883 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7884 next = &((*next)->right);
7891 static struct type *type_name(struct compile_state *state)
7894 type = specifier_qualifier_list(state);
7895 /* abstract-declarator (may consume no tokens) */
7896 type = declarator(state, type, 0, 0);
7900 static struct type *direct_declarator(
7901 struct compile_state *state, struct type *type,
7902 struct hash_entry **ident, int need_ident)
7907 arrays_complete(state, type);
7908 switch(peek(state)) {
7910 eat(state, TOK_IDENT);
7912 error(state, 0, "Unexpected identifier found");
7914 /* The name of what we are declaring */
7915 *ident = state->token[0].ident;
7918 eat(state, TOK_LPAREN);
7919 outer = declarator(state, type, ident, need_ident);
7920 eat(state, TOK_RPAREN);
7924 error(state, 0, "Identifier expected");
7930 arrays_complete(state, type);
7931 switch(peek(state)) {
7933 eat(state, TOK_LPAREN);
7934 type = param_type_list(state, type);
7935 eat(state, TOK_RPAREN);
7939 unsigned int qualifiers;
7940 struct triple *value;
7942 eat(state, TOK_LBRACKET);
7943 if (peek(state) != TOK_RBRACKET) {
7944 value = constant_expr(state);
7945 integral(state, value);
7947 eat(state, TOK_RBRACKET);
7949 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7950 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7952 type->elements = value->u.cval;
7953 free_triple(state, value);
7955 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7967 arrays_complete(state, type);
7969 for(inner = outer; inner->left; inner = inner->left)
7977 static struct type *declarator(
7978 struct compile_state *state, struct type *type,
7979 struct hash_entry **ident, int need_ident)
7981 while(peek(state) == TOK_STAR) {
7982 eat(state, TOK_STAR);
7983 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7985 type = direct_declarator(state, type, ident, need_ident);
7990 static struct type *typedef_name(
7991 struct compile_state *state, unsigned int specifiers)
7993 struct hash_entry *ident;
7995 eat(state, TOK_TYPE_NAME);
7996 ident = state->token[0].ident;
7997 type = ident->sym_ident->type;
7998 specifiers |= type->type & QUAL_MASK;
7999 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8000 (type->type & (STOR_MASK | QUAL_MASK))) {
8001 type = clone_type(specifiers, type);
8006 static struct type *enum_specifier(
8007 struct compile_state *state, unsigned int specifiers)
8013 eat(state, TOK_ENUM);
8015 if (tok == TOK_IDENT) {
8016 eat(state, TOK_IDENT);
8018 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8019 eat(state, TOK_LBRACE);
8021 eat(state, TOK_IDENT);
8022 if (peek(state) == TOK_EQ) {
8024 constant_expr(state);
8026 if (peek(state) == TOK_COMMA) {
8027 eat(state, TOK_COMMA);
8029 } while(peek(state) != TOK_RBRACE);
8030 eat(state, TOK_RBRACE);
8037 static struct type *struct_declarator(
8038 struct compile_state *state, struct type *type, struct hash_entry **ident)
8041 #warning "struct_declarator is complicated because of bitfields, kill them?"
8043 if (tok != TOK_COLON) {
8044 type = declarator(state, type, ident, 1);
8046 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8047 eat(state, TOK_COLON);
8048 constant_expr(state);
8055 static struct type *struct_or_union_specifier(
8056 struct compile_state *state, unsigned int specifiers)
8058 struct type *struct_type;
8059 struct hash_entry *ident;
8060 unsigned int type_join;
8064 switch(peek(state)) {
8066 eat(state, TOK_STRUCT);
8067 type_join = TYPE_PRODUCT;
8070 eat(state, TOK_UNION);
8071 type_join = TYPE_OVERLAP;
8072 error(state, 0, "unions not yet supported\n");
8075 eat(state, TOK_STRUCT);
8076 type_join = TYPE_PRODUCT;
8080 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8082 ident = state->token[0].ident;
8084 if (!ident || (peek(state) == TOK_LBRACE)) {
8087 eat(state, TOK_LBRACE);
8089 struct type *base_type;
8092 base_type = specifier_qualifier_list(state);
8093 next = &struct_type;
8096 struct hash_entry *fident;
8098 type = declarator(state, base_type, &fident, 1);
8100 if (peek(state) == TOK_COMMA) {
8102 eat(state, TOK_COMMA);
8104 type = clone_type(0, type);
8105 type->field_ident = fident;
8107 *next = new_type(type_join, *next, type);
8108 next = &((*next)->right);
8113 eat(state, TOK_SEMI);
8114 } while(peek(state) != TOK_RBRACE);
8115 eat(state, TOK_RBRACE);
8116 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8117 struct_type->type_ident = ident;
8118 struct_type->elements = elements;
8119 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8121 if (ident && ident->sym_struct) {
8122 struct_type = ident->sym_struct->type;
8124 else if (ident && !ident->sym_struct) {
8125 error(state, 0, "struct %s undeclared", ident->name);
8130 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8132 unsigned int specifiers;
8133 switch(peek(state)) {
8135 eat(state, TOK_AUTO);
8136 specifiers = STOR_AUTO;
8139 eat(state, TOK_REGISTER);
8140 specifiers = STOR_REGISTER;
8143 eat(state, TOK_STATIC);
8144 specifiers = STOR_STATIC;
8147 eat(state, TOK_EXTERN);
8148 specifiers = STOR_EXTERN;
8151 eat(state, TOK_TYPEDEF);
8152 specifiers = STOR_TYPEDEF;
8155 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8156 specifiers = STOR_STATIC;
8159 specifiers = STOR_AUTO;
8165 static unsigned int function_specifier_opt(struct compile_state *state)
8167 /* Ignore the inline keyword */
8168 unsigned int specifiers;
8170 switch(peek(state)) {
8172 eat(state, TOK_INLINE);
8173 specifiers = STOR_INLINE;
8178 static unsigned int type_qualifiers(struct compile_state *state)
8180 unsigned int specifiers;
8183 specifiers = QUAL_NONE;
8185 switch(peek(state)) {
8187 eat(state, TOK_CONST);
8188 specifiers = QUAL_CONST;
8191 eat(state, TOK_VOLATILE);
8192 specifiers = QUAL_VOLATILE;
8195 eat(state, TOK_RESTRICT);
8196 specifiers = QUAL_RESTRICT;
8206 static struct type *type_specifier(
8207 struct compile_state *state, unsigned int spec)
8211 switch(peek(state)) {
8213 eat(state, TOK_VOID);
8214 type = new_type(TYPE_VOID | spec, 0, 0);
8217 eat(state, TOK_CHAR);
8218 type = new_type(TYPE_CHAR | spec, 0, 0);
8221 eat(state, TOK_SHORT);
8222 if (peek(state) == TOK_INT) {
8223 eat(state, TOK_INT);
8225 type = new_type(TYPE_SHORT | spec, 0, 0);
8228 eat(state, TOK_INT);
8229 type = new_type(TYPE_INT | spec, 0, 0);
8232 eat(state, TOK_LONG);
8233 switch(peek(state)) {
8235 eat(state, TOK_LONG);
8236 error(state, 0, "long long not supported");
8239 eat(state, TOK_DOUBLE);
8240 error(state, 0, "long double not supported");
8243 eat(state, TOK_INT);
8244 type = new_type(TYPE_LONG | spec, 0, 0);
8247 type = new_type(TYPE_LONG | spec, 0, 0);
8252 eat(state, TOK_FLOAT);
8253 error(state, 0, "type float not supported");
8256 eat(state, TOK_DOUBLE);
8257 error(state, 0, "type double not supported");
8260 eat(state, TOK_SIGNED);
8261 switch(peek(state)) {
8263 eat(state, TOK_LONG);
8264 switch(peek(state)) {
8266 eat(state, TOK_LONG);
8267 error(state, 0, "type long long not supported");
8270 eat(state, TOK_INT);
8271 type = new_type(TYPE_LONG | spec, 0, 0);
8274 type = new_type(TYPE_LONG | spec, 0, 0);
8279 eat(state, TOK_INT);
8280 type = new_type(TYPE_INT | spec, 0, 0);
8283 eat(state, TOK_SHORT);
8284 type = new_type(TYPE_SHORT | spec, 0, 0);
8287 eat(state, TOK_CHAR);
8288 type = new_type(TYPE_CHAR | spec, 0, 0);
8291 type = new_type(TYPE_INT | spec, 0, 0);
8296 eat(state, TOK_UNSIGNED);
8297 switch(peek(state)) {
8299 eat(state, TOK_LONG);
8300 switch(peek(state)) {
8302 eat(state, TOK_LONG);
8303 error(state, 0, "unsigned long long not supported");
8306 eat(state, TOK_INT);
8307 type = new_type(TYPE_ULONG | spec, 0, 0);
8310 type = new_type(TYPE_ULONG | spec, 0, 0);
8315 eat(state, TOK_INT);
8316 type = new_type(TYPE_UINT | spec, 0, 0);
8319 eat(state, TOK_SHORT);
8320 type = new_type(TYPE_USHORT | spec, 0, 0);
8323 eat(state, TOK_CHAR);
8324 type = new_type(TYPE_UCHAR | spec, 0, 0);
8327 type = new_type(TYPE_UINT | spec, 0, 0);
8331 /* struct or union specifier */
8334 type = struct_or_union_specifier(state, spec);
8336 /* enum-spefifier */
8338 type = enum_specifier(state, spec);
8342 type = typedef_name(state, spec);
8345 error(state, 0, "bad type specifier %s",
8346 tokens[peek(state)]);
8352 static int istype(int tok)
8378 static struct type *specifier_qualifier_list(struct compile_state *state)
8381 unsigned int specifiers = 0;
8383 /* type qualifiers */
8384 specifiers |= type_qualifiers(state);
8386 /* type specifier */
8387 type = type_specifier(state, specifiers);
8392 static int isdecl_specifier(int tok)
8395 /* storage class specifier */
8401 /* type qualifier */
8405 /* type specifiers */
8415 /* struct or union specifier */
8418 /* enum-spefifier */
8422 /* function specifiers */
8430 static struct type *decl_specifiers(struct compile_state *state)
8433 unsigned int specifiers;
8434 /* I am overly restrictive in the arragement of specifiers supported.
8435 * C is overly flexible in this department it makes interpreting
8436 * the parse tree difficult.
8440 /* storage class specifier */
8441 specifiers |= storage_class_specifier_opt(state);
8443 /* function-specifier */
8444 specifiers |= function_specifier_opt(state);
8446 /* type qualifier */
8447 specifiers |= type_qualifiers(state);
8449 /* type specifier */
8450 type = type_specifier(state, specifiers);
8454 static unsigned designator(struct compile_state *state)
8460 switch(peek(state)) {
8463 struct triple *value;
8464 eat(state, TOK_LBRACKET);
8465 value = constant_expr(state);
8466 eat(state, TOK_RBRACKET);
8467 index = value->u.cval;
8471 eat(state, TOK_DOT);
8472 eat(state, TOK_IDENT);
8473 error(state, 0, "Struct Designators not currently supported");
8476 error(state, 0, "Invalid designator");
8479 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8484 static struct triple *initializer(
8485 struct compile_state *state, struct type *type)
8487 struct triple *result;
8488 if (peek(state) != TOK_LBRACE) {
8489 result = assignment_expr(state);
8493 unsigned index, max_index;
8495 max_index = index = 0;
8496 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8497 max_index = type->elements;
8498 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8502 error(state, 0, "Struct initializers not currently supported");
8504 buf = xcmalloc(size_of(state, type), "initializer");
8505 eat(state, TOK_LBRACE);
8507 struct triple *value;
8508 struct type *value_type;
8513 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8514 index = designator(state);
8516 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8517 (index > max_index)) {
8518 error(state, 0, "element beyond bounds");
8521 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8522 value_type = type->left;
8524 value = eval_const_expr(state, initializer(state, value_type));
8525 value_size = size_of(state, value_type);
8526 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8527 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8528 (type->elements <= index)) {
8532 old_size = size_of(state, type);
8533 type->elements = index + 1;
8534 buf = xmalloc(size_of(state, type), "initializer");
8535 memcpy(buf, old_buf, old_size);
8538 if (value->op == OP_BLOBCONST) {
8539 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8541 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8542 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8544 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8545 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8547 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8548 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8551 fprintf(stderr, "%d %d\n",
8552 value->op, value_size);
8553 internal_error(state, 0, "unhandled constant initializer");
8555 if (peek(state) == TOK_COMMA) {
8556 eat(state, TOK_COMMA);
8560 } while(comma && (peek(state) != TOK_RBRACE));
8561 eat(state, TOK_RBRACE);
8562 result = triple(state, OP_BLOBCONST, type, 0, 0);
8563 result->u.blob = buf;
8568 static struct triple *function_definition(
8569 struct compile_state *state, struct type *type)
8571 struct triple *def, *tmp, *first, *end;
8572 struct hash_entry *ident;
8575 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8576 error(state, 0, "Invalid function header");
8579 /* Verify the function type */
8580 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8581 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8582 (type->right->field_ident == 0)) {
8583 error(state, 0, "Invalid function parameters");
8585 param = type->right;
8587 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8589 if (!param->left->field_ident) {
8590 error(state, 0, "No identifier for parameter %d\n", i);
8592 param = param->right;
8595 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8596 error(state, 0, "No identifier for paramter %d\n", i);
8599 /* Get a list of statements for this function. */
8600 def = triple(state, OP_LIST, type, 0, 0);
8602 /* Start a new scope for the passed parameters */
8605 /* Put a label at the very start of a function */
8606 first = label(state);
8607 RHS(def, 0) = first;
8609 /* Put a label at the very end of a function */
8611 flatten(state, first, end);
8613 /* Walk through the parameters and create symbol table entries
8616 param = type->right;
8617 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8618 ident = param->left->field_ident;
8619 tmp = variable(state, param->left);
8620 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8621 flatten(state, end, tmp);
8622 param = param->right;
8624 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8625 /* And don't forget the last parameter */
8626 ident = param->field_ident;
8627 tmp = variable(state, param);
8628 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8629 flatten(state, end, tmp);
8631 /* Add a variable for the return value */
8633 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8634 /* Remove all type qualifiers from the return type */
8635 tmp = variable(state, clone_type(0, type->left));
8636 flatten(state, end, tmp);
8637 /* Remember where the return value is */
8641 /* Remember which function I am compiling.
8642 * Also assume the last defined function is the main function.
8644 state->main_function = def;
8646 /* Now get the actual function definition */
8647 compound_statement(state, end);
8649 /* Remove the parameter scope */
8652 fprintf(stdout, "\n");
8653 loc(stdout, state, 0);
8654 fprintf(stdout, "\n__________ function_definition _________\n");
8655 print_triple(state, def);
8656 fprintf(stdout, "__________ function_definition _________ done\n\n");
8662 static struct triple *do_decl(struct compile_state *state,
8663 struct type *type, struct hash_entry *ident)
8667 /* Clean up the storage types used */
8668 switch (type->type & STOR_MASK) {
8671 /* These are the good types I am aiming for */
8674 type->type &= ~STOR_MASK;
8675 type->type |= STOR_AUTO;
8678 type->type &= ~STOR_MASK;
8679 type->type |= STOR_STATIC;
8683 error(state, 0, "typedef without name");
8685 symbol(state, ident, &ident->sym_ident, 0, type);
8686 ident->tok = TOK_TYPE_NAME;
8690 internal_error(state, 0, "Undefined storage class");
8692 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8693 ((type->type & QUAL_CONST) == 0)) {
8694 error(state, 0, "non const static variables not supported");
8697 def = variable(state, type);
8698 symbol(state, ident, &ident->sym_ident, def, type);
8703 static void decl(struct compile_state *state, struct triple *first)
8705 struct type *base_type, *type;
8706 struct hash_entry *ident;
8709 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8710 base_type = decl_specifiers(state);
8712 type = declarator(state, base_type, &ident, 0);
8713 if (global && ident && (peek(state) == TOK_LBRACE)) {
8715 def = function_definition(state, type);
8716 symbol(state, ident, &ident->sym_ident, def, type);
8720 flatten(state, first, do_decl(state, type, ident));
8721 /* type or variable definition */
8724 if (peek(state) == TOK_EQ) {
8726 error(state, 0, "cannot assign to a type");
8729 flatten(state, first,
8731 ident->sym_ident->def,
8732 initializer(state, type)));
8734 arrays_complete(state, type);
8735 if (peek(state) == TOK_COMMA) {
8736 eat(state, TOK_COMMA);
8738 type = declarator(state, base_type, &ident, 0);
8739 flatten(state, first, do_decl(state, type, ident));
8743 eat(state, TOK_SEMI);
8747 static void decls(struct compile_state *state)
8749 struct triple *list;
8751 list = label(state);
8754 if (tok == TOK_EOF) {
8757 if (tok == TOK_SPACE) {
8758 eat(state, TOK_SPACE);
8761 if (list->next != list) {
8762 error(state, 0, "global variables not supported");
8768 * Data structurs for optimation.
8771 static void do_use_block(
8772 struct block *used, struct block_set **head, struct block *user,
8775 struct block_set **ptr, *new;
8782 if ((*ptr)->member == user) {
8785 ptr = &(*ptr)->next;
8787 new = xcmalloc(sizeof(*new), "block_set");
8798 static void do_unuse_block(
8799 struct block *used, struct block_set **head, struct block *unuser)
8801 struct block_set *use, **ptr;
8805 if (use->member == unuser) {
8807 memset(use, -1, sizeof(*use));
8816 static void use_block(struct block *used, struct block *user)
8818 /* Append new to the head of the list, print_block
8821 do_use_block(used, &used->use, user, 1);
8824 static void unuse_block(struct block *used, struct block *unuser)
8826 do_unuse_block(used, &used->use, unuser);
8830 static void idom_block(struct block *idom, struct block *user)
8832 do_use_block(idom, &idom->idominates, user, 0);
8835 static void unidom_block(struct block *idom, struct block *unuser)
8837 do_unuse_block(idom, &idom->idominates, unuser);
8840 static void domf_block(struct block *block, struct block *domf)
8842 do_use_block(block, &block->domfrontier, domf, 0);
8845 static void undomf_block(struct block *block, struct block *undomf)
8847 do_unuse_block(block, &block->domfrontier, undomf);
8850 static void ipdom_block(struct block *ipdom, struct block *user)
8852 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8855 static void unipdom_block(struct block *ipdom, struct block *unuser)
8857 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8860 static void ipdomf_block(struct block *block, struct block *ipdomf)
8862 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8865 static void unipdomf_block(struct block *block, struct block *unipdomf)
8867 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8872 static int do_walk_triple(struct compile_state *state,
8873 struct triple *ptr, int depth,
8874 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8877 result = cb(state, ptr, depth);
8878 if ((result == 0) && (ptr->op == OP_LIST)) {
8879 struct triple *list;
8883 result = do_walk_triple(state, ptr, depth + 1, cb);
8884 if (ptr->next->prev != ptr) {
8885 internal_error(state, ptr->next, "bad prev");
8889 } while((result == 0) && (ptr != RHS(list, 0)));
8894 static int walk_triple(
8895 struct compile_state *state,
8897 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8899 return do_walk_triple(state, ptr, 0, cb);
8902 static void do_print_prefix(int depth)
8905 for(i = 0; i < depth; i++) {
8910 #define PRINT_LIST 1
8911 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8915 if (op == OP_LIST) {
8920 if ((op == OP_LABEL) && (ins->use)) {
8921 printf("\n%p:\n", ins);
8923 do_print_prefix(depth);
8924 display_triple(stdout, ins);
8926 if ((ins->op == OP_BRANCH) && ins->use) {
8927 internal_error(state, ins, "branch used?");
8931 struct triple_set *user;
8932 for(user = ins->use; user; user = user->next) {
8933 printf("use: %p\n", user->member);
8937 if (triple_is_branch(state, ins)) {
8943 static void print_triple(struct compile_state *state, struct triple *ins)
8945 walk_triple(state, ins, do_print_triple);
8948 static void print_triples(struct compile_state *state)
8950 print_triple(state, state->main_function);
8954 struct block *block;
8956 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8958 if (!block || (cf[block->vertex].block == block)) {
8961 cf[block->vertex].block = block;
8962 find_cf_blocks(cf, block->left);
8963 find_cf_blocks(cf, block->right);
8966 static void print_control_flow(struct compile_state *state)
8968 struct cf_block *cf;
8970 printf("\ncontrol flow\n");
8971 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8972 find_cf_blocks(cf, state->first_block);
8974 for(i = 1; i <= state->last_vertex; i++) {
8975 struct block *block;
8976 block = cf[i].block;
8979 printf("(%p) %d:", block, block->vertex);
8981 printf(" %d", block->left->vertex);
8983 if (block->right && (block->right != block->left)) {
8984 printf(" %d", block->right->vertex);
8993 static struct block *basic_block(struct compile_state *state,
8994 struct triple *first)
8996 struct block *block;
8999 if (first->op != OP_LABEL) {
9000 internal_error(state, 0, "block does not start with a label");
9002 /* See if this basic block has already been setup */
9003 if (first->u.block != 0) {
9004 return first->u.block;
9006 /* Allocate another basic block structure */
9007 state->last_vertex += 1;
9008 block = xcmalloc(sizeof(*block), "block");
9009 block->first = block->last = first;
9010 block->vertex = state->last_vertex;
9013 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9017 /* If ptr->u is not used remember where the baic block is */
9018 if (triple_stores_block(state, ptr)) {
9019 ptr->u.block = block;
9021 if (ptr->op == OP_BRANCH) {
9025 } while (ptr != RHS(state->main_function, 0));
9026 if (ptr == RHS(state->main_function, 0))
9029 if (op == OP_LABEL) {
9030 block->left = basic_block(state, ptr);
9032 use_block(block->left, block);
9034 else if (op == OP_BRANCH) {
9036 /* Trace the branch target */
9037 block->right = basic_block(state, TARG(ptr, 0));
9038 use_block(block->right, block);
9039 /* If there is a test trace the branch as well */
9040 if (TRIPLE_RHS(ptr->sizes)) {
9041 block->left = basic_block(state, ptr->next);
9042 use_block(block->left, block);
9046 internal_error(state, 0, "Bad basic block split");
9052 static void walk_blocks(struct compile_state *state,
9053 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9056 struct triple *ptr, *first;
9057 struct block *last_block;
9059 first = RHS(state->main_function, 0);
9062 struct block *block;
9063 if (ptr->op == OP_LABEL) {
9064 block = ptr->u.block;
9065 if (block && (block != last_block)) {
9066 cb(state, block, arg);
9071 } while(ptr != first);
9074 static void print_block(
9075 struct compile_state *state, struct block *block, void *arg)
9080 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9084 block->left && block->left->use?block->left->use->member : 0,
9086 block->right && block->right->use?block->right->use->member : 0);
9087 if (block->first->op == OP_LABEL) {
9088 fprintf(fp, "%p:\n", block->first);
9090 for(ptr = block->first; ; ptr = ptr->next) {
9091 struct triple_set *user;
9094 if (triple_stores_block(state, ptr)) {
9095 if (ptr->u.block != block) {
9096 internal_error(state, ptr,
9097 "Wrong block pointer: %p\n",
9101 if (op == OP_ADECL) {
9102 for(user = ptr->use; user; user = user->next) {
9103 if (!user->member->u.block) {
9104 internal_error(state, user->member,
9105 "Use %p not in a block?\n",
9110 display_triple(fp, ptr);
9113 for(user = ptr->use; user; user = user->next) {
9114 fprintf(fp, "use: %p\n", user->member);
9118 /* Sanity checks... */
9119 valid_ins(state, ptr);
9120 for(user = ptr->use; user; user = user->next) {
9123 valid_ins(state, use);
9124 if (triple_stores_block(state, user->member) &&
9125 !user->member->u.block) {
9126 internal_error(state, user->member,
9127 "Use %p not in a block?",
9132 if (ptr == block->last)
9139 static void print_blocks(struct compile_state *state, FILE *fp)
9141 fprintf(fp, "--------------- blocks ---------------\n");
9142 walk_blocks(state, print_block, fp);
9145 static void prune_nonblock_triples(struct compile_state *state)
9147 struct block *block;
9148 struct triple *first, *ins, *next;
9149 /* Delete the triples not in a basic block */
9150 first = RHS(state->main_function, 0);
9155 if (ins->op == OP_LABEL) {
9156 block = ins->u.block;
9159 release_triple(state, ins);
9162 } while(ins != first);
9165 static void setup_basic_blocks(struct compile_state *state)
9167 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9168 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9169 internal_error(state, 0, "ins will not store block?");
9171 /* Find the basic blocks */
9172 state->last_vertex = 0;
9173 state->first_block = basic_block(state, RHS(state->main_function,0));
9174 /* Delete the triples not in a basic block */
9175 prune_nonblock_triples(state);
9176 /* Find the last basic block */
9177 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9178 if (!state->last_block) {
9179 internal_error(state, 0, "end not used?");
9181 /* Insert an extra unused edge from start to the end
9182 * This helps with reverse control flow calculations.
9184 use_block(state->first_block, state->last_block);
9185 /* If we are debugging print what I have just done */
9186 if (state->debug & DEBUG_BASIC_BLOCKS) {
9187 print_blocks(state, stdout);
9188 print_control_flow(state);
9192 static void free_basic_block(struct compile_state *state, struct block *block)
9194 struct block_set *entry, *next;
9195 struct block *child;
9199 if (block->vertex == -1) {
9204 unuse_block(block->left, block);
9207 unuse_block(block->right, block);
9210 unidom_block(block->idom, block);
9214 unipdom_block(block->ipdom, block);
9217 for(entry = block->use; entry; entry = next) {
9219 child = entry->member;
9220 unuse_block(block, child);
9221 if (child->left == block) {
9224 if (child->right == block) {
9228 for(entry = block->idominates; entry; entry = next) {
9230 child = entry->member;
9231 unidom_block(block, child);
9234 for(entry = block->domfrontier; entry; entry = next) {
9236 child = entry->member;
9237 undomf_block(block, child);
9239 for(entry = block->ipdominates; entry; entry = next) {
9241 child = entry->member;
9242 unipdom_block(block, child);
9245 for(entry = block->ipdomfrontier; entry; entry = next) {
9247 child = entry->member;
9248 unipdomf_block(block, child);
9250 if (block->users != 0) {
9251 internal_error(state, 0, "block still has users");
9253 free_basic_block(state, block->left);
9255 free_basic_block(state, block->right);
9257 memset(block, -1, sizeof(*block));
9261 static void free_basic_blocks(struct compile_state *state)
9263 struct triple *first, *ins;
9264 free_basic_block(state, state->first_block);
9265 state->last_vertex = 0;
9266 state->first_block = state->last_block = 0;
9267 first = RHS(state->main_function, 0);
9270 if (triple_stores_block(state, ins)) {
9274 } while(ins != first);
9279 struct block *block;
9280 struct sdom_block *sdominates;
9281 struct sdom_block *sdom_next;
9282 struct sdom_block *sdom;
9283 struct sdom_block *label;
9284 struct sdom_block *parent;
9285 struct sdom_block *ancestor;
9290 static void unsdom_block(struct sdom_block *block)
9292 struct sdom_block **ptr;
9293 if (!block->sdom_next) {
9296 ptr = &block->sdom->sdominates;
9298 if ((*ptr) == block) {
9299 *ptr = block->sdom_next;
9302 ptr = &(*ptr)->sdom_next;
9306 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9308 unsdom_block(block);
9310 block->sdom_next = sdom->sdominates;
9311 sdom->sdominates = block;
9316 static int initialize_sdblock(struct sdom_block *sd,
9317 struct block *parent, struct block *block, int vertex)
9319 if (!block || (sd[block->vertex].block == block)) {
9323 /* Renumber the blocks in a convinient fashion */
9324 block->vertex = vertex;
9325 sd[vertex].block = block;
9326 sd[vertex].sdom = &sd[vertex];
9327 sd[vertex].label = &sd[vertex];
9328 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9329 sd[vertex].ancestor = 0;
9330 sd[vertex].vertex = vertex;
9331 vertex = initialize_sdblock(sd, block, block->left, vertex);
9332 vertex = initialize_sdblock(sd, block, block->right, vertex);
9336 static int initialize_sdpblock(struct sdom_block *sd,
9337 struct block *parent, struct block *block, int vertex)
9339 struct block_set *user;
9340 if (!block || (sd[block->vertex].block == block)) {
9344 /* Renumber the blocks in a convinient fashion */
9345 block->vertex = vertex;
9346 sd[vertex].block = block;
9347 sd[vertex].sdom = &sd[vertex];
9348 sd[vertex].label = &sd[vertex];
9349 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9350 sd[vertex].ancestor = 0;
9351 sd[vertex].vertex = vertex;
9352 for(user = block->use; user; user = user->next) {
9353 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9358 static void compress_ancestors(struct sdom_block *v)
9360 /* This procedure assumes ancestor(v) != 0 */
9361 /* if (ancestor(ancestor(v)) != 0) {
9362 * compress(ancestor(ancestor(v)));
9363 * if (semi(label(ancestor(v))) < semi(label(v))) {
9364 * label(v) = label(ancestor(v));
9366 * ancestor(v) = ancestor(ancestor(v));
9372 if (v->ancestor->ancestor) {
9373 compress_ancestors(v->ancestor->ancestor);
9374 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9375 v->label = v->ancestor->label;
9377 v->ancestor = v->ancestor->ancestor;
9381 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9385 * for each v <= pred(w) {
9387 * if (semi[u] < semi[w] {
9388 * semi[w] = semi[u];
9391 * add w to bucket(vertex(semi[w]));
9392 * LINK(parent(w), w);
9395 * for each v <= bucket(parent(w)) {
9396 * delete v from bucket(parent(w));
9398 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9401 for(i = state->last_vertex; i >= 2; i--) {
9402 struct sdom_block *v, *parent, *next;
9403 struct block_set *user;
9404 struct block *block;
9405 block = sd[i].block;
9406 parent = sd[i].parent;
9408 for(user = block->use; user; user = user->next) {
9409 struct sdom_block *v, *u;
9410 v = &sd[user->member->vertex];
9411 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9412 if (u->sdom->vertex < sd[i].sdom->vertex) {
9413 sd[i].sdom = u->sdom;
9416 sdom_block(sd[i].sdom, &sd[i]);
9417 sd[i].ancestor = parent;
9419 for(v = parent->sdominates; v; v = next) {
9420 struct sdom_block *u;
9421 next = v->sdom_next;
9423 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9424 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9425 u->block : parent->block;
9430 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9434 * for each v <= pred(w) {
9436 * if (semi[u] < semi[w] {
9437 * semi[w] = semi[u];
9440 * add w to bucket(vertex(semi[w]));
9441 * LINK(parent(w), w);
9444 * for each v <= bucket(parent(w)) {
9445 * delete v from bucket(parent(w));
9447 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9450 for(i = state->last_vertex; i >= 2; i--) {
9451 struct sdom_block *u, *v, *parent, *next;
9452 struct block *block;
9453 block = sd[i].block;
9454 parent = sd[i].parent;
9457 v = &sd[block->left->vertex];
9458 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9459 if (u->sdom->vertex < sd[i].sdom->vertex) {
9460 sd[i].sdom = u->sdom;
9463 if (block->right && (block->right != block->left)) {
9464 v = &sd[block->right->vertex];
9465 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9466 if (u->sdom->vertex < sd[i].sdom->vertex) {
9467 sd[i].sdom = u->sdom;
9470 sdom_block(sd[i].sdom, &sd[i]);
9471 sd[i].ancestor = parent;
9473 for(v = parent->sdominates; v; v = next) {
9474 struct sdom_block *u;
9475 next = v->sdom_next;
9477 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9478 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9479 u->block : parent->block;
9484 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9487 for(i = 2; i <= state->last_vertex; i++) {
9488 struct block *block;
9489 block = sd[i].block;
9490 if (block->idom->vertex != sd[i].sdom->vertex) {
9491 block->idom = block->idom->idom;
9493 idom_block(block->idom, block);
9495 sd[1].block->idom = 0;
9498 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9501 for(i = 2; i <= state->last_vertex; i++) {
9502 struct block *block;
9503 block = sd[i].block;
9504 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9505 block->ipdom = block->ipdom->ipdom;
9507 ipdom_block(block->ipdom, block);
9509 sd[1].block->ipdom = 0;
9513 * Every vertex of a flowgraph G = (V, E, r) except r has
9514 * a unique immediate dominator.
9515 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9516 * rooted at r, called the dominator tree of G, such that
9517 * v dominates w if and only if v is a proper ancestor of w in
9518 * the dominator tree.
9521 * If v and w are vertices of G such that v <= w,
9522 * than any path from v to w must contain a common ancestor
9525 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9526 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9527 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9529 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9530 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9533 * Let w != r and let u be a vertex for which sdom(u) is
9534 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9535 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9537 /* Lemma 5: Let vertices v,w satisfy v -> w.
9538 * Then v -> idom(w) or idom(w) -> idom(v)
9541 static void find_immediate_dominators(struct compile_state *state)
9543 struct sdom_block *sd;
9544 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9545 * vi > w for (1 <= i <= k - 1}
9548 * For any vertex w != r.
9550 * {v|(v,w) <= E and v < w } U
9551 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9554 * Let w != r and let u be a vertex for which sdom(u) is
9555 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9557 * { sdom(w) if sdom(w) = sdom(u),
9559 * { idom(u) otherwise
9561 /* The algorithm consists of the following 4 steps.
9562 * Step 1. Carry out a depth-first search of the problem graph.
9563 * Number the vertices from 1 to N as they are reached during
9564 * the search. Initialize the variables used in succeeding steps.
9565 * Step 2. Compute the semidominators of all vertices by applying
9566 * theorem 4. Carry out the computation vertex by vertex in
9567 * decreasing order by number.
9568 * Step 3. Implicitly define the immediate dominator of each vertex
9569 * by applying Corollary 1.
9570 * Step 4. Explicitly define the immediate dominator of each vertex,
9571 * carrying out the computation vertex by vertex in increasing order
9574 /* Step 1 initialize the basic block information */
9575 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9576 initialize_sdblock(sd, 0, state->first_block, 0);
9582 /* Step 2 compute the semidominators */
9583 /* Step 3 implicitly define the immediate dominator of each vertex */
9584 compute_sdom(state, sd);
9585 /* Step 4 explicitly define the immediate dominator of each vertex */
9586 compute_idom(state, sd);
9590 static void find_post_dominators(struct compile_state *state)
9592 struct sdom_block *sd;
9593 /* Step 1 initialize the basic block information */
9594 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9596 initialize_sdpblock(sd, 0, state->last_block, 0);
9598 /* Step 2 compute the semidominators */
9599 /* Step 3 implicitly define the immediate dominator of each vertex */
9600 compute_spdom(state, sd);
9601 /* Step 4 explicitly define the immediate dominator of each vertex */
9602 compute_ipdom(state, sd);
9608 static void find_block_domf(struct compile_state *state, struct block *block)
9610 struct block *child;
9611 struct block_set *user;
9612 if (block->domfrontier != 0) {
9613 internal_error(state, block->first, "domfrontier present?");
9615 for(user = block->idominates; user; user = user->next) {
9616 child = user->member;
9617 if (child->idom != block) {
9618 internal_error(state, block->first, "bad idom");
9620 find_block_domf(state, child);
9622 if (block->left && block->left->idom != block) {
9623 domf_block(block, block->left);
9625 if (block->right && block->right->idom != block) {
9626 domf_block(block, block->right);
9628 for(user = block->idominates; user; user = user->next) {
9629 struct block_set *frontier;
9630 child = user->member;
9631 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9632 if (frontier->member->idom != block) {
9633 domf_block(block, frontier->member);
9639 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9641 struct block *child;
9642 struct block_set *user;
9643 if (block->ipdomfrontier != 0) {
9644 internal_error(state, block->first, "ipdomfrontier present?");
9646 for(user = block->ipdominates; user; user = user->next) {
9647 child = user->member;
9648 if (child->ipdom != block) {
9649 internal_error(state, block->first, "bad ipdom");
9651 find_block_ipdomf(state, child);
9653 if (block->left && block->left->ipdom != block) {
9654 ipdomf_block(block, block->left);
9656 if (block->right && block->right->ipdom != block) {
9657 ipdomf_block(block, block->right);
9659 for(user = block->idominates; user; user = user->next) {
9660 struct block_set *frontier;
9661 child = user->member;
9662 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9663 if (frontier->member->ipdom != block) {
9664 ipdomf_block(block, frontier->member);
9670 static void print_dominated(
9671 struct compile_state *state, struct block *block, void *arg)
9673 struct block_set *user;
9676 fprintf(fp, "%d:", block->vertex);
9677 for(user = block->idominates; user; user = user->next) {
9678 fprintf(fp, " %d", user->member->vertex);
9679 if (user->member->idom != block) {
9680 internal_error(state, user->member->first, "bad idom");
9686 static void print_dominators(struct compile_state *state, FILE *fp)
9688 fprintf(fp, "\ndominates\n");
9689 walk_blocks(state, print_dominated, fp);
9693 static int print_frontiers(
9694 struct compile_state *state, struct block *block, int vertex)
9696 struct block_set *user;
9698 if (!block || (block->vertex != vertex + 1)) {
9703 printf("%d:", block->vertex);
9704 for(user = block->domfrontier; user; user = user->next) {
9705 printf(" %d", user->member->vertex);
9709 vertex = print_frontiers(state, block->left, vertex);
9710 vertex = print_frontiers(state, block->right, vertex);
9713 static void print_dominance_frontiers(struct compile_state *state)
9715 printf("\ndominance frontiers\n");
9716 print_frontiers(state, state->first_block, 0);
9720 static void analyze_idominators(struct compile_state *state)
9722 /* Find the immediate dominators */
9723 find_immediate_dominators(state);
9724 /* Find the dominance frontiers */
9725 find_block_domf(state, state->first_block);
9726 /* If debuging print the print what I have just found */
9727 if (state->debug & DEBUG_FDOMINATORS) {
9728 print_dominators(state, stdout);
9729 print_dominance_frontiers(state);
9730 print_control_flow(state);
9736 static void print_ipdominated(
9737 struct compile_state *state, struct block *block, void *arg)
9739 struct block_set *user;
9742 fprintf(fp, "%d:", block->vertex);
9743 for(user = block->ipdominates; user; user = user->next) {
9744 fprintf(fp, " %d", user->member->vertex);
9745 if (user->member->ipdom != block) {
9746 internal_error(state, user->member->first, "bad ipdom");
9752 static void print_ipdominators(struct compile_state *state, FILE *fp)
9754 fprintf(fp, "\nipdominates\n");
9755 walk_blocks(state, print_ipdominated, fp);
9758 static int print_pfrontiers(
9759 struct compile_state *state, struct block *block, int vertex)
9761 struct block_set *user;
9763 if (!block || (block->vertex != vertex + 1)) {
9768 printf("%d:", block->vertex);
9769 for(user = block->ipdomfrontier; user; user = user->next) {
9770 printf(" %d", user->member->vertex);
9773 for(user = block->use; user; user = user->next) {
9774 vertex = print_pfrontiers(state, user->member, vertex);
9778 static void print_ipdominance_frontiers(struct compile_state *state)
9780 printf("\nipdominance frontiers\n");
9781 print_pfrontiers(state, state->last_block, 0);
9785 static void analyze_ipdominators(struct compile_state *state)
9787 /* Find the post dominators */
9788 find_post_dominators(state);
9789 /* Find the control dependencies (post dominance frontiers) */
9790 find_block_ipdomf(state, state->last_block);
9791 /* If debuging print the print what I have just found */
9792 if (state->debug & DEBUG_RDOMINATORS) {
9793 print_ipdominators(state, stdout);
9794 print_ipdominance_frontiers(state);
9795 print_control_flow(state);
9799 static int bdominates(struct compile_state *state,
9800 struct block *dom, struct block *sub)
9802 while(sub && (sub != dom)) {
9808 static int tdominates(struct compile_state *state,
9809 struct triple *dom, struct triple *sub)
9811 struct block *bdom, *bsub;
9813 bdom = block_of_triple(state, dom);
9814 bsub = block_of_triple(state, sub);
9816 result = bdominates(state, bdom, bsub);
9821 while((ins != bsub->first) && (ins != dom)) {
9824 result = (ins == dom);
9829 static void insert_phi_operations(struct compile_state *state)
9832 struct triple *first;
9833 int *has_already, *work;
9834 struct block *work_list, **work_list_tail;
9838 size = sizeof(int) * (state->last_vertex + 1);
9839 has_already = xcmalloc(size, "has_already");
9840 work = xcmalloc(size, "work");
9843 first = RHS(state->main_function, 0);
9844 for(var = first->next; var != first ; var = var->next) {
9845 struct block *block;
9846 struct triple_set *user;
9847 if ((var->op != OP_ADECL) || !var->use) {
9852 work_list_tail = &work_list;
9853 for(user = var->use; user; user = user->next) {
9854 if (user->member->op == OP_READ) {
9857 if (user->member->op != OP_WRITE) {
9858 internal_error(state, user->member,
9859 "bad variable access");
9861 block = user->member->u.block;
9863 warning(state, user->member, "dead code");
9865 if (work[block->vertex] >= iter) {
9868 work[block->vertex] = iter;
9869 *work_list_tail = block;
9870 block->work_next = 0;
9871 work_list_tail = &block->work_next;
9873 for(block = work_list; block; block = block->work_next) {
9874 struct block_set *df;
9875 for(df = block->domfrontier; df; df = df->next) {
9877 struct block *front;
9881 if (has_already[front->vertex] >= iter) {
9884 /* Count how many edges flow into this block */
9885 in_edges = front->users;
9886 /* Insert a phi function for this variable */
9888 state, OP_PHI, var->type, -1, in_edges,
9889 front->first->filename,
9892 phi->u.block = front;
9894 use_triple(var, phi);
9895 /* Insert the phi functions immediately after the label */
9896 insert_triple(state, front->first->next, phi);
9897 if (front->first == front->last) {
9898 front->last = front->first->next;
9900 has_already[front->vertex] = iter;
9902 /* If necessary plan to visit the basic block */
9903 if (work[front->vertex] >= iter) {
9906 work[front->vertex] = iter;
9907 *work_list_tail = front;
9908 front->work_next = 0;
9909 work_list_tail = &front->work_next;
9921 static void fixup_block_phi_variables(
9922 struct compile_state *state, struct block *parent, struct block *block)
9924 struct block_set *set;
9927 if (!parent || !block)
9929 /* Find the edge I am coming in on */
9931 for(set = block->use; set; set = set->next, edge++) {
9932 if (set->member == parent) {
9937 internal_error(state, 0, "phi input is not on a control predecessor");
9939 for(ptr = block->first; ; ptr = ptr->next) {
9940 if (ptr->op == OP_PHI) {
9941 struct triple *var, *val, **slot;
9944 internal_error(state, ptr, "no var???");
9946 /* Find the current value of the variable */
9947 val = var->use->member;
9948 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9949 internal_error(state, val, "bad value in phi");
9951 if (edge >= TRIPLE_RHS(ptr->sizes)) {
9952 internal_error(state, ptr, "edges > phi rhs");
9954 slot = &RHS(ptr, edge);
9955 if ((*slot != 0) && (*slot != val)) {
9956 internal_error(state, ptr, "phi already bound on this edge");
9959 use_triple(val, ptr);
9961 if (ptr == block->last) {
9968 static void rename_block_variables(
9969 struct compile_state *state, struct block *block)
9971 struct block_set *user;
9972 struct triple *ptr, *next, *last;
9976 last = block->first;
9978 for(ptr = block->first; !done; ptr = next) {
9980 if (ptr == block->last) {
9984 if (ptr->op == OP_READ) {
9985 struct triple *var, *val;
9987 unuse_triple(var, ptr);
9989 error(state, ptr, "variable used without being set");
9991 /* Find the current value of the variable */
9992 val = var->use->member;
9993 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9994 internal_error(state, val, "bad value in read");
9996 propogate_use(state, ptr, val);
9997 release_triple(state, ptr);
10001 if (ptr->op == OP_WRITE) {
10002 struct triple *var, *val;
10005 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10006 internal_error(state, val, "bad value in write");
10008 propogate_use(state, ptr, val);
10009 unuse_triple(var, ptr);
10010 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10011 push_triple(var, val);
10013 if (ptr->op == OP_PHI) {
10014 struct triple *var;
10015 var = MISC(ptr, 0);
10016 /* Push OP_PHI onto a stack of variable uses */
10017 push_triple(var, ptr);
10021 block->last = last;
10023 /* Fixup PHI functions in the cf successors */
10024 fixup_block_phi_variables(state, block, block->left);
10025 fixup_block_phi_variables(state, block, block->right);
10026 /* rename variables in the dominated nodes */
10027 for(user = block->idominates; user; user = user->next) {
10028 rename_block_variables(state, user->member);
10030 /* pop the renamed variable stack */
10031 last = block->first;
10033 for(ptr = block->first; !done ; ptr = next) {
10035 if (ptr == block->last) {
10038 if (ptr->op == OP_WRITE) {
10039 struct triple *var;
10041 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10042 pop_triple(var, RHS(ptr, 0));
10043 release_triple(state, ptr);
10046 if (ptr->op == OP_PHI) {
10047 struct triple *var;
10048 var = MISC(ptr, 0);
10049 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10050 pop_triple(var, ptr);
10054 block->last = last;
10057 static void prune_block_variables(struct compile_state *state,
10058 struct block *block)
10060 struct block_set *user;
10061 struct triple *next, *last, *ptr;
10063 last = block->first;
10065 for(ptr = block->first; !done; ptr = next) {
10067 if (ptr == block->last) {
10070 if (ptr->op == OP_ADECL) {
10071 struct triple_set *user, *next;
10072 for(user = ptr->use; user; user = next) {
10073 struct triple *use;
10075 use = user->member;
10076 if (use->op != OP_PHI) {
10077 internal_error(state, use, "decl still used");
10079 if (MISC(use, 0) != ptr) {
10080 internal_error(state, use, "bad phi use of decl");
10082 unuse_triple(ptr, use);
10085 release_triple(state, ptr);
10090 block->last = last;
10091 for(user = block->idominates; user; user = user->next) {
10092 prune_block_variables(state, user->member);
10096 static void transform_to_ssa_form(struct compile_state *state)
10098 insert_phi_operations(state);
10100 printf("@%s:%d\n", __FILE__, __LINE__);
10101 print_blocks(state, stdout);
10103 rename_block_variables(state, state->first_block);
10104 prune_block_variables(state, state->first_block);
10108 static void clear_vertex(
10109 struct compile_state *state, struct block *block, void *arg)
10114 static void mark_live_block(
10115 struct compile_state *state, struct block *block, int *next_vertex)
10117 /* See if this is a block that has not been marked */
10118 if (block->vertex != 0) {
10121 block->vertex = *next_vertex;
10123 if (triple_is_branch(state, block->last)) {
10124 struct triple **targ;
10125 targ = triple_targ(state, block->last, 0);
10126 for(; targ; targ = triple_targ(state, block->last, targ)) {
10130 if (!triple_stores_block(state, *targ)) {
10131 internal_error(state, 0, "bad targ");
10133 mark_live_block(state, (*targ)->u.block, next_vertex);
10136 else if (block->last->next != RHS(state->main_function, 0)) {
10137 struct triple *ins;
10138 ins = block->last->next;
10139 if (!triple_stores_block(state, ins)) {
10140 internal_error(state, 0, "bad block start");
10142 mark_live_block(state, ins->u.block, next_vertex);
10146 static void transform_from_ssa_form(struct compile_state *state)
10148 /* To get out of ssa form we insert moves on the incoming
10149 * edges to blocks containting phi functions.
10151 struct triple *first;
10152 struct triple *phi, *next;
10155 /* Walk the control flow to see which blocks remain alive */
10156 walk_blocks(state, clear_vertex, 0);
10158 mark_live_block(state, state->first_block, &next_vertex);
10160 /* Walk all of the operations to find the phi functions */
10161 first = RHS(state->main_function, 0);
10162 for(phi = first->next; phi != first ; phi = next) {
10163 struct block_set *set;
10164 struct block *block;
10165 struct triple **slot;
10166 struct triple *var, *read;
10167 struct triple_set *use, *use_next;
10170 if (phi->op != OP_PHI) {
10173 block = phi->u.block;
10174 slot = &RHS(phi, 0);
10176 /* Forget uses from code in dead blocks */
10177 for(use = phi->use; use; use = use_next) {
10178 struct block *ublock;
10179 struct triple **expr;
10180 use_next = use->next;
10181 ublock = block_of_triple(state, use->member);
10182 if ((use->member == phi) || (ublock->vertex != 0)) {
10185 expr = triple_rhs(state, use->member, 0);
10186 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10187 if (*expr == phi) {
10191 unuse_triple(phi, use->member);
10194 /* A variable to replace the phi function */
10195 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10196 /* A read of the single value that is set into the variable */
10197 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10198 use_triple(var, read);
10200 /* Replaces uses of the phi with variable reads */
10201 propogate_use(state, phi, read);
10203 /* Walk all of the incoming edges/blocks and insert moves.
10205 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10206 struct block *eblock;
10207 struct triple *move;
10208 struct triple *val;
10209 eblock = set->member;
10212 unuse_triple(val, phi);
10214 if (!val || (val == &zero_triple) ||
10215 (block->vertex == 0) || (eblock->vertex == 0) ||
10216 (val == phi) || (val == read)) {
10220 move = post_triple(state,
10221 val, OP_WRITE, phi->type, var, val);
10222 use_triple(val, move);
10223 use_triple(var, move);
10225 /* See if there are any writers of var */
10227 for(use = var->use; use; use = use->next) {
10228 struct triple **expr;
10229 expr = triple_lhs(state, use->member, 0);
10230 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10231 if (*expr == var) {
10236 /* If var is not used free it */
10238 unuse_triple(var, read);
10239 free_triple(state, read);
10240 free_triple(state, var);
10243 /* Release the phi function */
10244 release_triple(state, phi);
10251 * Register conflict resolution
10252 * =========================================================
10255 static struct reg_info find_def_color(
10256 struct compile_state *state, struct triple *def)
10258 struct triple_set *set;
10259 struct reg_info info;
10260 info.reg = REG_UNSET;
10262 if (!triple_is_def(state, def)) {
10265 info = arch_reg_lhs(state, def, 0);
10266 if (info.reg >= MAX_REGISTERS) {
10267 info.reg = REG_UNSET;
10269 for(set = def->use; set; set = set->next) {
10270 struct reg_info tinfo;
10272 i = find_rhs_use(state, set->member, def);
10276 tinfo = arch_reg_rhs(state, set->member, i);
10277 if (tinfo.reg >= MAX_REGISTERS) {
10278 tinfo.reg = REG_UNSET;
10280 if ((tinfo.reg != REG_UNSET) &&
10281 (info.reg != REG_UNSET) &&
10282 (tinfo.reg != info.reg)) {
10283 internal_error(state, def, "register conflict");
10285 if ((info.regcm & tinfo.regcm) == 0) {
10286 internal_error(state, def, "regcm conflict %x & %x == 0",
10287 info.regcm, tinfo.regcm);
10289 if (info.reg == REG_UNSET) {
10290 info.reg = tinfo.reg;
10292 info.regcm &= tinfo.regcm;
10294 if (info.reg >= MAX_REGISTERS) {
10295 internal_error(state, def, "register out of range");
10300 static struct reg_info find_lhs_pre_color(
10301 struct compile_state *state, struct triple *ins, int index)
10303 struct reg_info info;
10305 zrhs = TRIPLE_RHS(ins->sizes);
10306 zlhs = TRIPLE_LHS(ins->sizes);
10307 if (!zlhs && triple_is_def(state, ins)) {
10310 if (index >= zlhs) {
10311 internal_error(state, ins, "Bad lhs %d", index);
10313 info = arch_reg_lhs(state, ins, index);
10314 for(i = 0; i < zrhs; i++) {
10315 struct reg_info rinfo;
10316 rinfo = arch_reg_rhs(state, ins, i);
10317 if ((info.reg == rinfo.reg) &&
10318 (rinfo.reg >= MAX_REGISTERS)) {
10319 struct reg_info tinfo;
10320 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10321 info.reg = tinfo.reg;
10322 info.regcm &= tinfo.regcm;
10326 if (info.reg >= MAX_REGISTERS) {
10327 info.reg = REG_UNSET;
10332 static struct reg_info find_rhs_post_color(
10333 struct compile_state *state, struct triple *ins, int index);
10335 static struct reg_info find_lhs_post_color(
10336 struct compile_state *state, struct triple *ins, int index)
10338 struct triple_set *set;
10339 struct reg_info info;
10340 struct triple *lhs;
10342 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10345 if ((index == 0) && triple_is_def(state, ins)) {
10348 else if (index < TRIPLE_LHS(ins->sizes)) {
10349 lhs = LHS(ins, index);
10352 internal_error(state, ins, "Bad lhs %d", index);
10355 info = arch_reg_lhs(state, ins, index);
10356 if (info.reg >= MAX_REGISTERS) {
10357 info.reg = REG_UNSET;
10359 for(set = lhs->use; set; set = set->next) {
10360 struct reg_info rinfo;
10361 struct triple *user;
10363 user = set->member;
10364 zrhs = TRIPLE_RHS(user->sizes);
10365 for(i = 0; i < zrhs; i++) {
10366 if (RHS(user, i) != lhs) {
10369 rinfo = find_rhs_post_color(state, user, i);
10370 if ((info.reg != REG_UNSET) &&
10371 (rinfo.reg != REG_UNSET) &&
10372 (info.reg != rinfo.reg)) {
10373 internal_error(state, ins, "register conflict");
10375 if ((info.regcm & rinfo.regcm) == 0) {
10376 internal_error(state, ins, "regcm conflict %x & %x == 0",
10377 info.regcm, rinfo.regcm);
10379 if (info.reg == REG_UNSET) {
10380 info.reg = rinfo.reg;
10382 info.regcm &= rinfo.regcm;
10386 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10387 ins, index, info.reg, info.regcm);
10392 static struct reg_info find_rhs_post_color(
10393 struct compile_state *state, struct triple *ins, int index)
10395 struct reg_info info, rinfo;
10398 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10401 rinfo = arch_reg_rhs(state, ins, index);
10402 zlhs = TRIPLE_LHS(ins->sizes);
10403 if (!zlhs && triple_is_def(state, ins)) {
10407 if (info.reg >= MAX_REGISTERS) {
10408 info.reg = REG_UNSET;
10410 for(i = 0; i < zlhs; i++) {
10411 struct reg_info linfo;
10412 linfo = arch_reg_lhs(state, ins, i);
10413 if ((linfo.reg == rinfo.reg) &&
10414 (linfo.reg >= MAX_REGISTERS)) {
10415 struct reg_info tinfo;
10416 tinfo = find_lhs_post_color(state, ins, i);
10417 if (tinfo.reg >= MAX_REGISTERS) {
10418 tinfo.reg = REG_UNSET;
10420 info.regcm &= linfo.reg;
10421 info.regcm &= tinfo.regcm;
10422 if (info.reg != REG_UNSET) {
10423 internal_error(state, ins, "register conflict");
10425 if (info.regcm == 0) {
10426 internal_error(state, ins, "regcm conflict");
10428 info.reg = tinfo.reg;
10432 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10433 ins, index, info.reg, info.regcm);
10438 static struct reg_info find_lhs_color(
10439 struct compile_state *state, struct triple *ins, int index)
10441 struct reg_info pre, post, info;
10443 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10446 pre = find_lhs_pre_color(state, ins, index);
10447 post = find_lhs_post_color(state, ins, index);
10448 if ((pre.reg != post.reg) &&
10449 (pre.reg != REG_UNSET) &&
10450 (post.reg != REG_UNSET)) {
10451 internal_error(state, ins, "register conflict");
10453 info.regcm = pre.regcm & post.regcm;
10454 info.reg = pre.reg;
10455 if (info.reg == REG_UNSET) {
10456 info.reg = post.reg;
10459 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10460 ins, index, info.reg, info.regcm);
10465 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10467 struct triple_set *entry, *next;
10468 struct triple *out;
10469 struct reg_info info, rinfo;
10471 info = arch_reg_lhs(state, ins, 0);
10472 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10473 use_triple(RHS(out, 0), out);
10474 /* Get the users of ins to use out instead */
10475 for(entry = ins->use; entry; entry = next) {
10477 next = entry->next;
10478 if (entry->member == out) {
10481 i = find_rhs_use(state, entry->member, ins);
10485 rinfo = arch_reg_rhs(state, entry->member, i);
10486 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10489 replace_rhs_use(state, ins, out, entry->member);
10491 transform_to_arch_instruction(state, out);
10495 static struct triple *pre_copy(
10496 struct compile_state *state, struct triple *ins, int index)
10498 /* Carefully insert enough operations so that I can
10499 * enter any operation with a GPR32.
10502 struct triple **expr;
10503 expr = &RHS(ins, index);
10504 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10505 unuse_triple(*expr, ins);
10507 use_triple(RHS(in, 0), in);
10508 use_triple(in, ins);
10509 transform_to_arch_instruction(state, in);
10514 static void insert_copies_to_phi(struct compile_state *state)
10516 /* To get out of ssa form we insert moves on the incoming
10517 * edges to blocks containting phi functions.
10519 struct triple *first;
10520 struct triple *phi;
10522 /* Walk all of the operations to find the phi functions */
10523 first = RHS(state->main_function, 0);
10524 for(phi = first->next; phi != first ; phi = phi->next) {
10525 struct block_set *set;
10526 struct block *block;
10527 struct triple **slot;
10529 if (phi->op != OP_PHI) {
10532 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10533 block = phi->u.block;
10534 slot = &RHS(phi, 0);
10535 /* Walk all of the incoming edges/blocks and insert moves.
10537 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10538 struct block *eblock;
10539 struct triple *move;
10540 struct triple *val;
10541 struct triple *ptr;
10542 eblock = set->member;
10549 move = build_triple(state, OP_COPY, phi->type, val, 0,
10550 val->filename, val->line, val->col);
10551 move->u.block = eblock;
10552 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10553 use_triple(val, move);
10556 unuse_triple(val, phi);
10557 use_triple(move, phi);
10559 /* Walk through the block backwards to find
10560 * an appropriate location for the OP_COPY.
10562 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10563 struct triple **expr;
10564 if ((ptr == phi) || (ptr == val)) {
10567 expr = triple_rhs(state, ptr, 0);
10568 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10569 if ((*expr) == phi) {
10575 if (triple_is_branch(state, ptr)) {
10576 internal_error(state, ptr,
10577 "Could not insert write to phi");
10579 insert_triple(state, ptr->next, move);
10580 if (eblock->last == ptr) {
10581 eblock->last = move;
10583 transform_to_arch_instruction(state, move);
10588 struct triple_reg_set {
10589 struct triple_reg_set *next;
10590 struct triple *member;
10591 struct triple *new;
10595 struct block *block;
10596 struct triple_reg_set *in;
10597 struct triple_reg_set *out;
10601 static int do_triple_set(struct triple_reg_set **head,
10602 struct triple *member, struct triple *new_member)
10604 struct triple_reg_set **ptr, *new;
10609 if ((*ptr)->member == member) {
10612 ptr = &(*ptr)->next;
10614 new = xcmalloc(sizeof(*new), "triple_set");
10615 new->member = member;
10616 new->new = new_member;
10622 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10624 struct triple_reg_set *entry, **ptr;
10628 if (entry->member == member) {
10629 *ptr = entry->next;
10634 ptr = &entry->next;
10639 static int in_triple(struct reg_block *rb, struct triple *in)
10641 return do_triple_set(&rb->in, in, 0);
10643 static void unin_triple(struct reg_block *rb, struct triple *unin)
10645 do_triple_unset(&rb->in, unin);
10648 static int out_triple(struct reg_block *rb, struct triple *out)
10650 return do_triple_set(&rb->out, out, 0);
10652 static void unout_triple(struct reg_block *rb, struct triple *unout)
10654 do_triple_unset(&rb->out, unout);
10657 static int initialize_regblock(struct reg_block *blocks,
10658 struct block *block, int vertex)
10660 struct block_set *user;
10661 if (!block || (blocks[block->vertex].block == block)) {
10665 /* Renumber the blocks in a convinient fashion */
10666 block->vertex = vertex;
10667 blocks[vertex].block = block;
10668 blocks[vertex].vertex = vertex;
10669 for(user = block->use; user; user = user->next) {
10670 vertex = initialize_regblock(blocks, user->member, vertex);
10675 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10676 struct reg_block *rb, struct block *suc)
10678 /* Read the conditional input set of a successor block
10679 * (i.e. the input to the phi nodes) and place it in the
10680 * current blocks output set.
10682 struct block_set *set;
10683 struct triple *ptr;
10687 /* Find the edge I am coming in on */
10688 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10689 if (set->member == rb->block) {
10694 internal_error(state, 0, "Not coming on a control edge?");
10696 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10697 struct triple **slot, *expr, *ptr2;
10698 int out_change, done2;
10699 done = (ptr == suc->last);
10700 if (ptr->op != OP_PHI) {
10703 slot = &RHS(ptr, 0);
10705 out_change = out_triple(rb, expr);
10709 /* If we don't define the variable also plast it
10710 * in the current blocks input set.
10712 ptr2 = rb->block->first;
10713 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10714 if (ptr2 == expr) {
10717 done2 = (ptr2 == rb->block->last);
10722 change |= in_triple(rb, expr);
10727 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10728 struct reg_block *rb, struct block *suc)
10730 struct triple_reg_set *in_set;
10733 /* Read the input set of a successor block
10734 * and place it in the current blocks output set.
10736 in_set = blocks[suc->vertex].in;
10737 for(; in_set; in_set = in_set->next) {
10738 int out_change, done;
10739 struct triple *first, *last, *ptr;
10740 out_change = out_triple(rb, in_set->member);
10744 /* If we don't define the variable also place it
10745 * in the current blocks input set.
10747 first = rb->block->first;
10748 last = rb->block->last;
10750 for(ptr = first; !done; ptr = ptr->next) {
10751 if (ptr == in_set->member) {
10754 done = (ptr == last);
10759 change |= in_triple(rb, in_set->member);
10761 change |= phi_in(state, blocks, rb, suc);
10766 static int use_in(struct compile_state *state, struct reg_block *rb)
10768 /* Find the variables we use but don't define and add
10769 * it to the current blocks input set.
10771 #warning "FIXME is this O(N^2) algorithm bad?"
10772 struct block *block;
10773 struct triple *ptr;
10778 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10779 struct triple **expr;
10780 done = (ptr == block->first);
10781 /* The variable a phi function uses depends on the
10782 * control flow, and is handled in phi_in, not
10785 if (ptr->op == OP_PHI) {
10788 expr = triple_rhs(state, ptr, 0);
10789 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10790 struct triple *rhs, *test;
10796 /* See if rhs is defined in this block */
10797 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10798 tdone = (test == block->first);
10804 /* If I still have a valid rhs add it to in */
10805 change |= in_triple(rb, rhs);
10811 static struct reg_block *compute_variable_lifetimes(
10812 struct compile_state *state)
10814 struct reg_block *blocks;
10817 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10818 initialize_regblock(blocks, state->last_block, 0);
10822 for(i = 1; i <= state->last_vertex; i++) {
10823 struct reg_block *rb;
10825 /* Add the left successor's input set to in */
10826 if (rb->block->left) {
10827 change |= reg_in(state, blocks, rb, rb->block->left);
10829 /* Add the right successor's input set to in */
10830 if ((rb->block->right) &&
10831 (rb->block->right != rb->block->left)) {
10832 change |= reg_in(state, blocks, rb, rb->block->right);
10834 /* Add use to in... */
10835 change |= use_in(state, rb);
10841 static void free_variable_lifetimes(
10842 struct compile_state *state, struct reg_block *blocks)
10845 /* free in_set && out_set on each block */
10846 for(i = 1; i <= state->last_vertex; i++) {
10847 struct triple_reg_set *entry, *next;
10848 struct reg_block *rb;
10850 for(entry = rb->in; entry ; entry = next) {
10851 next = entry->next;
10852 do_triple_unset(&rb->in, entry->member);
10854 for(entry = rb->out; entry; entry = next) {
10855 next = entry->next;
10856 do_triple_unset(&rb->out, entry->member);
10863 typedef void (*wvl_cb_t)(
10864 struct compile_state *state,
10865 struct reg_block *blocks, struct triple_reg_set *live,
10866 struct reg_block *rb, struct triple *ins, void *arg);
10868 static void walk_variable_lifetimes(struct compile_state *state,
10869 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10873 for(i = 1; i <= state->last_vertex; i++) {
10874 struct triple_reg_set *live;
10875 struct triple_reg_set *entry, *next;
10876 struct triple *ptr, *prev;
10877 struct reg_block *rb;
10878 struct block *block;
10881 /* Get the blocks */
10885 /* Copy out into live */
10887 for(entry = rb->out; entry; entry = next) {
10888 next = entry->next;
10889 do_triple_set(&live, entry->member, entry->new);
10891 /* Walk through the basic block calculating live */
10892 for(done = 0, ptr = block->last; !done; ptr = prev) {
10893 struct triple **expr;
10896 done = (ptr == block->first);
10898 /* Ensure the current definition is in live */
10899 if (triple_is_def(state, ptr)) {
10900 do_triple_set(&live, ptr, 0);
10903 /* Inform the callback function of what is
10906 cb(state, blocks, live, rb, ptr, arg);
10908 /* Remove the current definition from live */
10909 do_triple_unset(&live, ptr);
10911 /* Add the current uses to live.
10913 * It is safe to skip phi functions because they do
10914 * not have any block local uses, and the block
10915 * output sets already properly account for what
10916 * control flow depedent uses phi functions do have.
10918 if (ptr->op == OP_PHI) {
10921 expr = triple_rhs(state, ptr, 0);
10922 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10923 /* If the triple is not a definition skip it. */
10924 if (!*expr || !triple_is_def(state, *expr)) {
10927 do_triple_set(&live, *expr, 0);
10931 for(entry = live; entry; entry = next) {
10932 next = entry->next;
10933 do_triple_unset(&live, entry->member);
10938 static int count_triples(struct compile_state *state)
10940 struct triple *first, *ins;
10942 first = RHS(state->main_function, 0);
10947 } while (ins != first);
10950 struct dead_triple {
10951 struct triple *triple;
10952 struct dead_triple *work_next;
10953 struct block *block;
10956 #define TRIPLE_FLAG_ALIVE 1
10960 static void awaken(
10961 struct compile_state *state,
10962 struct dead_triple *dtriple, struct triple **expr,
10963 struct dead_triple ***work_list_tail)
10965 struct triple *triple;
10966 struct dead_triple *dt;
10974 if (triple->id <= 0) {
10975 internal_error(state, triple, "bad triple id: %d",
10978 if (triple->op == OP_NOOP) {
10979 internal_warning(state, triple, "awakening noop?");
10982 dt = &dtriple[triple->id];
10983 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10984 dt->flags |= TRIPLE_FLAG_ALIVE;
10985 if (!dt->work_next) {
10986 **work_list_tail = dt;
10987 *work_list_tail = &dt->work_next;
10992 static void eliminate_inefectual_code(struct compile_state *state)
10994 struct block *block;
10995 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10997 struct triple *first, *ins;
10999 /* Setup the work list */
11001 work_list_tail = &work_list;
11003 first = RHS(state->main_function, 0);
11005 /* Count how many triples I have */
11006 triples = count_triples(state);
11008 /* Now put then in an array and mark all of the triples dead */
11009 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11015 if (ins->op == OP_LABEL) {
11016 block = ins->u.block;
11018 dtriple[i].triple = ins;
11019 dtriple[i].block = block;
11020 dtriple[i].flags = 0;
11021 dtriple[i].color = ins->id;
11023 /* See if it is an operation we always keep */
11024 #warning "FIXME handle the case of killing a branch instruction"
11025 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11026 awaken(state, dtriple, &ins, &work_list_tail);
11030 } while(ins != first);
11032 struct dead_triple *dt;
11033 struct block_set *user;
11034 struct triple **expr;
11036 work_list = dt->work_next;
11038 work_list_tail = &work_list;
11040 /* Wake up the data depencencies of this triple */
11043 expr = triple_rhs(state, dt->triple, expr);
11044 awaken(state, dtriple, expr, &work_list_tail);
11047 expr = triple_lhs(state, dt->triple, expr);
11048 awaken(state, dtriple, expr, &work_list_tail);
11051 expr = triple_misc(state, dt->triple, expr);
11052 awaken(state, dtriple, expr, &work_list_tail);
11054 /* Wake up the forward control dependencies */
11056 expr = triple_targ(state, dt->triple, expr);
11057 awaken(state, dtriple, expr, &work_list_tail);
11059 /* Wake up the reverse control dependencies of this triple */
11060 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11061 awaken(state, dtriple, &user->member->last, &work_list_tail);
11064 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11065 if ((dt->triple->op == OP_NOOP) &&
11066 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11067 internal_error(state, dt->triple, "noop effective?");
11069 dt->triple->id = dt->color; /* Restore the color */
11070 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11071 #warning "FIXME handle the case of killing a basic block"
11072 if (dt->block->first == dt->triple) {
11075 if (dt->block->last == dt->triple) {
11076 dt->block->last = dt->triple->prev;
11078 release_triple(state, dt->triple);
11085 static void insert_mandatory_copies(struct compile_state *state)
11087 struct triple *ins, *first;
11089 /* The object is with a minimum of inserted copies,
11090 * to resolve in fundamental register conflicts between
11091 * register value producers and consumers.
11092 * Theoretically we may be greater than minimal when we
11093 * are inserting copies before instructions but that
11094 * case should be rare.
11096 first = RHS(state->main_function, 0);
11099 struct triple_set *entry, *next;
11100 struct triple *tmp;
11101 struct reg_info info;
11102 unsigned reg, regcm;
11103 int do_post_copy, do_pre_copy;
11105 if (!triple_is_def(state, ins)) {
11108 /* Find the architecture specific color information */
11109 info = arch_reg_lhs(state, ins, 0);
11110 if (info.reg >= MAX_REGISTERS) {
11111 info.reg = REG_UNSET;
11115 regcm = arch_type_to_regcm(state, ins->type);
11116 do_post_copy = do_pre_copy = 0;
11118 /* Walk through the uses of ins and check for conflicts */
11119 for(entry = ins->use; entry; entry = next) {
11120 struct reg_info rinfo;
11122 next = entry->next;
11123 i = find_rhs_use(state, entry->member, ins);
11128 /* Find the users color requirements */
11129 rinfo = arch_reg_rhs(state, entry->member, i);
11130 if (rinfo.reg >= MAX_REGISTERS) {
11131 rinfo.reg = REG_UNSET;
11134 /* See if I need a pre_copy */
11135 if (rinfo.reg != REG_UNSET) {
11136 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11141 regcm &= rinfo.regcm;
11142 regcm = arch_regcm_normalize(state, regcm);
11149 (((info.reg != REG_UNSET) &&
11150 (reg != REG_UNSET) &&
11151 (info.reg != reg)) ||
11152 ((info.regcm & regcm) == 0));
11155 regcm = info.regcm;
11156 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11157 for(entry = ins->use; entry; entry = next) {
11158 struct reg_info rinfo;
11160 next = entry->next;
11161 i = find_rhs_use(state, entry->member, ins);
11166 /* Find the users color requirements */
11167 rinfo = arch_reg_rhs(state, entry->member, i);
11168 if (rinfo.reg >= MAX_REGISTERS) {
11169 rinfo.reg = REG_UNSET;
11172 /* Now see if it is time to do the pre_copy */
11173 if (rinfo.reg != REG_UNSET) {
11174 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11175 ((regcm & rinfo.regcm) == 0) ||
11176 /* Don't let a mandatory coalesce sneak
11177 * into a operation that is marked to prevent
11180 ((reg != REG_UNNEEDED) &&
11181 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11182 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11185 struct triple *user;
11186 user = entry->member;
11187 if (RHS(user, i) != ins) {
11188 internal_error(state, user, "bad rhs");
11190 tmp = pre_copy(state, user, i);
11198 if ((regcm & rinfo.regcm) == 0) {
11200 struct triple *user;
11201 user = entry->member;
11202 if (RHS(user, i) != ins) {
11203 internal_error(state, user, "bad rhs");
11205 tmp = pre_copy(state, user, i);
11211 regcm &= rinfo.regcm;
11214 if (do_post_copy) {
11215 struct reg_info pre, post;
11216 tmp = post_copy(state, ins);
11217 pre = arch_reg_lhs(state, ins, 0);
11218 post = arch_reg_lhs(state, tmp, 0);
11219 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11220 internal_error(state, tmp, "useless copy");
11225 } while(ins != first);
11229 struct live_range_edge;
11230 struct live_range_def;
11231 struct live_range {
11232 struct live_range_edge *edges;
11233 struct live_range_def *defs;
11234 /* Note. The list pointed to by defs is kept in order.
11235 * That is baring splits in the flow control
11236 * defs dominates defs->next wich dominates defs->next->next
11243 struct live_range *group_next, **group_prev;
11246 struct live_range_edge {
11247 struct live_range_edge *next;
11248 struct live_range *node;
11251 struct live_range_def {
11252 struct live_range_def *next;
11253 struct live_range_def *prev;
11254 struct live_range *lr;
11255 struct triple *def;
11259 #define LRE_HASH_SIZE 2048
11261 struct lre_hash *next;
11262 struct live_range *left;
11263 struct live_range *right;
11268 struct lre_hash *hash[LRE_HASH_SIZE];
11269 struct reg_block *blocks;
11270 struct live_range_def *lrd;
11271 struct live_range *lr;
11272 struct live_range *low, **low_tail;
11273 struct live_range *high, **high_tail;
11276 int passes, max_passes;
11277 #define MAX_ALLOCATION_PASSES 100
11281 static unsigned regc_max_size(struct compile_state *state, int classes)
11286 for(i = 0; i < MAX_REGC; i++) {
11287 if (classes & (1 << i)) {
11289 size = arch_regc_size(state, i);
11290 if (size > max_size) {
11298 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11300 unsigned equivs[MAX_REG_EQUIVS];
11302 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11303 internal_error(state, 0, "invalid register");
11305 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11306 internal_error(state, 0, "invalid register");
11308 arch_reg_equivs(state, equivs, reg1);
11309 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11310 if (equivs[i] == reg2) {
11317 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11319 unsigned equivs[MAX_REG_EQUIVS];
11321 if (reg == REG_UNNEEDED) {
11324 arch_reg_equivs(state, equivs, reg);
11325 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11326 used[equivs[i]] = 1;
11331 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11333 unsigned equivs[MAX_REG_EQUIVS];
11335 if (reg == REG_UNNEEDED) {
11338 arch_reg_equivs(state, equivs, reg);
11339 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11340 used[equivs[i]] += 1;
11345 static unsigned int hash_live_edge(
11346 struct live_range *left, struct live_range *right)
11348 unsigned int hash, val;
11349 unsigned long lval, rval;
11350 lval = ((unsigned long)left)/sizeof(struct live_range);
11351 rval = ((unsigned long)right)/sizeof(struct live_range);
11356 hash = (hash *263) + val;
11361 hash = (hash *263) + val;
11363 hash = hash & (LRE_HASH_SIZE - 1);
11367 static struct lre_hash **lre_probe(struct reg_state *rstate,
11368 struct live_range *left, struct live_range *right)
11370 struct lre_hash **ptr;
11371 unsigned int index;
11372 /* Ensure left <= right */
11373 if (left > right) {
11374 struct live_range *tmp;
11379 index = hash_live_edge(left, right);
11381 ptr = &rstate->hash[index];
11382 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11383 ptr = &(*ptr)->next;
11388 static int interfere(struct reg_state *rstate,
11389 struct live_range *left, struct live_range *right)
11391 struct lre_hash **ptr;
11392 ptr = lre_probe(rstate, left, right);
11393 return ptr && *ptr;
11396 static void add_live_edge(struct reg_state *rstate,
11397 struct live_range *left, struct live_range *right)
11399 /* FIXME the memory allocation overhead is noticeable here... */
11400 struct lre_hash **ptr, *new_hash;
11401 struct live_range_edge *edge;
11403 if (left == right) {
11406 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11409 /* Ensure left <= right */
11410 if (left > right) {
11411 struct live_range *tmp;
11416 ptr = lre_probe(rstate, left, right);
11420 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11421 new_hash->next = *ptr;
11422 new_hash->left = left;
11423 new_hash->right = right;
11426 edge = xmalloc(sizeof(*edge), "live_range_edge");
11427 edge->next = left->edges;
11428 edge->node = right;
11429 left->edges = edge;
11432 edge = xmalloc(sizeof(*edge), "live_range_edge");
11433 edge->next = right->edges;
11435 right->edges = edge;
11436 right->degree += 1;
11439 static void remove_live_edge(struct reg_state *rstate,
11440 struct live_range *left, struct live_range *right)
11442 struct live_range_edge *edge, **ptr;
11443 struct lre_hash **hptr, *entry;
11444 hptr = lre_probe(rstate, left, right);
11445 if (!hptr || !*hptr) {
11449 *hptr = entry->next;
11452 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11454 if (edge->node == right) {
11456 memset(edge, 0, sizeof(*edge));
11461 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11463 if (edge->node == left) {
11465 memset(edge, 0, sizeof(*edge));
11472 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11474 struct live_range_edge *edge, *next;
11475 for(edge = range->edges; edge; edge = next) {
11477 remove_live_edge(rstate, range, edge->node);
11482 /* Interference graph...
11484 * new(n) --- Return a graph with n nodes but no edges.
11485 * add(g,x,y) --- Return a graph including g with an between x and y
11486 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11487 * x and y in the graph g
11488 * degree(g, x) --- Return the degree of the node x in the graph g
11489 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11491 * Implement with a hash table && a set of adjcency vectors.
11492 * The hash table supports constant time implementations of add and interfere.
11493 * The adjacency vectors support an efficient implementation of neighbors.
11497 * +---------------------------------------------------+
11498 * | +--------------+ |
11500 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11502 * -- In simplify implment optimistic coloring... (No backtracking)
11503 * -- Implement Rematerialization it is the only form of spilling we can perform
11504 * Essentially this means dropping a constant from a register because
11505 * we can regenerate it later.
11507 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11508 * coalesce at phi points...
11509 * --- Bias coloring if at all possible do the coalesing a compile time.
11514 static void different_colored(
11515 struct compile_state *state, struct reg_state *rstate,
11516 struct triple *parent, struct triple *ins)
11518 struct live_range *lr;
11519 struct triple **expr;
11520 lr = rstate->lrd[ins->id].lr;
11521 expr = triple_rhs(state, ins, 0);
11522 for(;expr; expr = triple_rhs(state, ins, expr)) {
11523 struct live_range *lr2;
11524 if (!*expr || (*expr == parent) || (*expr == ins)) {
11527 lr2 = rstate->lrd[(*expr)->id].lr;
11528 if (lr->color == lr2->color) {
11529 internal_error(state, ins, "live range too big");
11535 static struct live_range *coalesce_ranges(
11536 struct compile_state *state, struct reg_state *rstate,
11537 struct live_range *lr1, struct live_range *lr2)
11539 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11545 if (!lr1->defs || !lr2->defs) {
11546 internal_error(state, 0,
11547 "cannot coalese dead live ranges");
11549 if ((lr1->color == REG_UNNEEDED) ||
11550 (lr2->color == REG_UNNEEDED)) {
11551 internal_error(state, 0,
11552 "cannot coalesce live ranges without a possible color");
11554 if ((lr1->color != lr2->color) &&
11555 (lr1->color != REG_UNSET) &&
11556 (lr2->color != REG_UNSET)) {
11557 internal_error(state, lr1->defs->def,
11558 "cannot coalesce live ranges of different colors");
11560 color = lr1->color;
11561 if (color == REG_UNSET) {
11562 color = lr2->color;
11564 classes = lr1->classes & lr2->classes;
11566 internal_error(state, lr1->defs->def,
11567 "cannot coalesce live ranges with dissimilar register classes");
11569 /* If there is a clear dominate live range put it in lr1,
11570 * For purposes of this test phi functions are
11571 * considered dominated by the definitions that feed into
11574 if ((lr1->defs->prev->def->op == OP_PHI) ||
11575 ((lr2->defs->prev->def->op != OP_PHI) &&
11576 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11577 struct live_range *tmp;
11583 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11584 fprintf(stderr, "lr1 post\n");
11586 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11587 fprintf(stderr, "lr1 pre\n");
11589 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11590 fprintf(stderr, "lr2 post\n");
11592 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11593 fprintf(stderr, "lr2 pre\n");
11597 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11604 lr1->classes = classes;
11605 /* Append lr2 onto lr1 */
11606 #warning "FIXME should this be a merge instead of a splice?"
11608 mid1 = lr1->defs->prev;
11610 end = lr2->defs->prev;
11618 /* Fixup the live range in the added live range defs */
11623 } while(lrd != head);
11625 /* Mark lr2 as free. */
11627 lr2->color = REG_UNNEEDED;
11631 internal_error(state, 0, "lr1->defs == 0 ?");
11634 lr1->color = color;
11635 lr1->classes = classes;
11640 static struct live_range_def *live_range_head(
11641 struct compile_state *state, struct live_range *lr,
11642 struct live_range_def *last)
11644 struct live_range_def *result;
11649 else if (!tdominates(state, lr->defs->def, last->next->def)) {
11650 result = last->next;
11655 static struct live_range_def *live_range_end(
11656 struct compile_state *state, struct live_range *lr,
11657 struct live_range_def *last)
11659 struct live_range_def *result;
11662 result = lr->defs->prev;
11664 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11665 result = last->prev;
11671 static void initialize_live_ranges(
11672 struct compile_state *state, struct reg_state *rstate)
11674 struct triple *ins, *first;
11675 size_t count, size;
11678 first = RHS(state->main_function, 0);
11679 /* First count how many instructions I have.
11681 count = count_triples(state);
11682 /* Potentially I need one live range definitions for each
11683 * instruction, plus an extra for the split routines.
11685 rstate->defs = count + 1;
11686 /* Potentially I need one live range for each instruction
11687 * plus an extra for the dummy live range.
11689 rstate->ranges = count + 1;
11690 size = sizeof(rstate->lrd[0]) * rstate->defs;
11691 rstate->lrd = xcmalloc(size, "live_range_def");
11692 size = sizeof(rstate->lr[0]) * rstate->ranges;
11693 rstate->lr = xcmalloc(size, "live_range");
11695 /* Setup the dummy live range */
11696 rstate->lr[0].classes = 0;
11697 rstate->lr[0].color = REG_UNSET;
11698 rstate->lr[0].defs = 0;
11702 /* If the triple is a variable give it a live range */
11703 if (triple_is_def(state, ins)) {
11704 struct reg_info info;
11705 /* Find the architecture specific color information */
11706 info = find_def_color(state, ins);
11709 rstate->lr[i].defs = &rstate->lrd[j];
11710 rstate->lr[i].color = info.reg;
11711 rstate->lr[i].classes = info.regcm;
11712 rstate->lr[i].degree = 0;
11713 rstate->lrd[j].lr = &rstate->lr[i];
11715 /* Otherwise give the triple the dummy live range. */
11717 rstate->lrd[j].lr = &rstate->lr[0];
11720 /* Initalize the live_range_def */
11721 rstate->lrd[j].next = &rstate->lrd[j];
11722 rstate->lrd[j].prev = &rstate->lrd[j];
11723 rstate->lrd[j].def = ins;
11724 rstate->lrd[j].orig_id = ins->id;
11729 } while(ins != first);
11730 rstate->ranges = i;
11733 /* Make a second pass to handle achitecture specific register
11738 int zlhs, zrhs, i, j;
11739 if (ins->id > rstate->defs) {
11740 internal_error(state, ins, "bad id");
11743 /* Walk through the template of ins and coalesce live ranges */
11744 zlhs = TRIPLE_LHS(ins->sizes);
11745 if ((zlhs == 0) && triple_is_def(state, ins)) {
11748 zrhs = TRIPLE_RHS(ins->sizes);
11750 for(i = 0; i < zlhs; i++) {
11751 struct reg_info linfo;
11752 struct live_range_def *lhs;
11753 linfo = arch_reg_lhs(state, ins, i);
11754 if (linfo.reg < MAX_REGISTERS) {
11757 if (triple_is_def(state, ins)) {
11758 lhs = &rstate->lrd[ins->id];
11760 lhs = &rstate->lrd[LHS(ins, i)->id];
11762 for(j = 0; j < zrhs; j++) {
11763 struct reg_info rinfo;
11764 struct live_range_def *rhs;
11765 rinfo = arch_reg_rhs(state, ins, j);
11766 if (rinfo.reg < MAX_REGISTERS) {
11769 rhs = &rstate->lrd[RHS(ins, i)->id];
11770 if (rinfo.reg == linfo.reg) {
11771 coalesce_ranges(state, rstate,
11777 } while(ins != first);
11780 static void graph_ins(
11781 struct compile_state *state,
11782 struct reg_block *blocks, struct triple_reg_set *live,
11783 struct reg_block *rb, struct triple *ins, void *arg)
11785 struct reg_state *rstate = arg;
11786 struct live_range *def;
11787 struct triple_reg_set *entry;
11789 /* If the triple is not a definition
11790 * we do not have a definition to add to
11791 * the interference graph.
11793 if (!triple_is_def(state, ins)) {
11796 def = rstate->lrd[ins->id].lr;
11798 /* Create an edge between ins and everything that is
11799 * alive, unless the live_range cannot share
11800 * a physical register with ins.
11802 for(entry = live; entry; entry = entry->next) {
11803 struct live_range *lr;
11804 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11805 internal_error(state, 0, "bad entry?");
11807 lr = rstate->lrd[entry->member->id].lr;
11811 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11814 add_live_edge(rstate, def, lr);
11820 static void print_interference_ins(
11821 struct compile_state *state,
11822 struct reg_block *blocks, struct triple_reg_set *live,
11823 struct reg_block *rb, struct triple *ins, void *arg)
11825 struct reg_state *rstate = arg;
11826 struct live_range *lr;
11828 lr = rstate->lrd[ins->id].lr;
11829 display_triple(stdout, ins);
11832 struct live_range_def *lrd;
11836 printf(" %-10p", lrd->def);
11838 } while(lrd != lr->defs);
11842 struct triple_reg_set *entry;
11844 for(entry = live; entry; entry = entry->next) {
11845 printf(" %-10p", entry->member);
11850 struct live_range_edge *entry;
11852 for(entry = lr->edges; entry; entry = entry->next) {
11853 struct live_range_def *lrd;
11854 lrd = entry->node->defs;
11856 printf(" %-10p", lrd->def);
11858 } while(lrd != entry->node->defs);
11863 if (triple_is_branch(state, ins)) {
11869 static int coalesce_live_ranges(
11870 struct compile_state *state, struct reg_state *rstate)
11872 /* At the point where a value is moved from one
11873 * register to another that value requires two
11874 * registers, thus increasing register pressure.
11875 * Live range coaleescing reduces the register
11876 * pressure by keeping a value in one register
11879 * In the case of a phi function all paths leading
11880 * into it must be allocated to the same register
11881 * otherwise the phi function may not be removed.
11883 * Forcing a value to stay in a single register
11884 * for an extended period of time does have
11885 * limitations when applied to non homogenous
11888 * The two cases I have identified are:
11889 * 1) Two forced register assignments may
11891 * 2) Registers may go unused because they
11892 * are only good for storing the value
11893 * and not manipulating it.
11895 * Because of this I need to split live ranges,
11896 * even outside of the context of coalesced live
11897 * ranges. The need to split live ranges does
11898 * impose some constraints on live range coalescing.
11900 * - Live ranges may not be coalesced across phi
11901 * functions. This creates a 2 headed live
11902 * range that cannot be sanely split.
11904 * - phi functions (coalesced in initialize_live_ranges)
11905 * are handled as pre split live ranges so we will
11906 * never attempt to split them.
11912 for(i = 0; i <= rstate->ranges; i++) {
11913 struct live_range *lr1;
11914 struct live_range_def *lrd1;
11915 lr1 = &rstate->lr[i];
11919 lrd1 = live_range_end(state, lr1, 0);
11920 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11921 struct triple_set *set;
11922 if (lrd1->def->op != OP_COPY) {
11925 /* Skip copies that are the result of a live range split. */
11926 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11929 for(set = lrd1->def->use; set; set = set->next) {
11930 struct live_range_def *lrd2;
11931 struct live_range *lr2, *res;
11933 lrd2 = &rstate->lrd[set->member->id];
11935 /* Don't coalesce with instructions
11936 * that are the result of a live range
11939 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11942 lr2 = rstate->lrd[set->member->id].lr;
11946 if ((lr1->color != lr2->color) &&
11947 (lr1->color != REG_UNSET) &&
11948 (lr2->color != REG_UNSET)) {
11951 if ((lr1->classes & lr2->classes) == 0) {
11955 if (interfere(rstate, lr1, lr2)) {
11959 res = coalesce_ranges(state, rstate, lr1, lr2);
11973 static void fix_coalesce_conflicts(struct compile_state *state,
11974 struct reg_block *blocks, struct triple_reg_set *live,
11975 struct reg_block *rb, struct triple *ins, void *arg)
11977 int zlhs, zrhs, i, j;
11979 /* See if we have a mandatory coalesce operation between
11980 * a lhs and a rhs value. If so and the rhs value is also
11981 * alive then this triple needs to be pre copied. Otherwise
11982 * we would have two definitions in the same live range simultaneously
11985 zlhs = TRIPLE_LHS(ins->sizes);
11986 if ((zlhs == 0) && triple_is_def(state, ins)) {
11989 zrhs = TRIPLE_RHS(ins->sizes);
11990 for(i = 0; i < zlhs; i++) {
11991 struct reg_info linfo;
11992 linfo = arch_reg_lhs(state, ins, i);
11993 if (linfo.reg < MAX_REGISTERS) {
11996 for(j = 0; j < zrhs; j++) {
11997 struct reg_info rinfo;
11998 struct triple *rhs;
11999 struct triple_reg_set *set;
12002 rinfo = arch_reg_rhs(state, ins, j);
12003 if (rinfo.reg != linfo.reg) {
12007 for(set = live; set && !found; set = set->next) {
12008 if (set->member == rhs) {
12013 struct triple *copy;
12014 copy = pre_copy(state, ins, j);
12015 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12022 static void replace_set_use(struct compile_state *state,
12023 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12025 struct triple_reg_set *set;
12026 for(set = head; set; set = set->next) {
12027 if (set->member == orig) {
12033 static void replace_block_use(struct compile_state *state,
12034 struct reg_block *blocks, struct triple *orig, struct triple *new)
12037 #warning "WISHLIST visit just those blocks that need it *"
12038 for(i = 1; i <= state->last_vertex; i++) {
12039 struct reg_block *rb;
12041 replace_set_use(state, rb->in, orig, new);
12042 replace_set_use(state, rb->out, orig, new);
12046 static void color_instructions(struct compile_state *state)
12048 struct triple *ins, *first;
12049 first = RHS(state->main_function, 0);
12052 if (triple_is_def(state, ins)) {
12053 struct reg_info info;
12054 info = find_lhs_color(state, ins, 0);
12055 if (info.reg >= MAX_REGISTERS) {
12056 info.reg = REG_UNSET;
12058 SET_INFO(ins->id, info);
12061 } while(ins != first);
12064 static struct reg_info read_lhs_color(
12065 struct compile_state *state, struct triple *ins, int index)
12067 struct reg_info info;
12068 if ((index == 0) && triple_is_def(state, ins)) {
12069 info.reg = ID_REG(ins->id);
12070 info.regcm = ID_REGCM(ins->id);
12072 else if (index < TRIPLE_LHS(ins->sizes)) {
12073 info = read_lhs_color(state, LHS(ins, index), 0);
12076 internal_error(state, ins, "Bad lhs %d", index);
12077 info.reg = REG_UNSET;
12083 static struct triple *resolve_tangle(
12084 struct compile_state *state, struct triple *tangle)
12086 struct reg_info info, uinfo;
12087 struct triple_set *set, *next;
12088 struct triple *copy;
12090 #warning "WISHLIST recalculate all affected instructions colors"
12091 info = find_lhs_color(state, tangle, 0);
12092 for(set = tangle->use; set; set = next) {
12093 struct triple *user;
12096 user = set->member;
12097 zrhs = TRIPLE_RHS(user->sizes);
12098 for(i = 0; i < zrhs; i++) {
12099 if (RHS(user, i) != tangle) {
12102 uinfo = find_rhs_post_color(state, user, i);
12103 if (uinfo.reg == info.reg) {
12104 copy = pre_copy(state, user, i);
12105 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12106 SET_INFO(copy->id, uinfo);
12111 uinfo = find_lhs_pre_color(state, tangle, 0);
12112 if (uinfo.reg == info.reg) {
12113 struct reg_info linfo;
12114 copy = post_copy(state, tangle);
12115 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12116 linfo = find_lhs_color(state, copy, 0);
12117 SET_INFO(copy->id, linfo);
12119 info = find_lhs_color(state, tangle, 0);
12120 SET_INFO(tangle->id, info);
12126 static void fix_tangles(struct compile_state *state,
12127 struct reg_block *blocks, struct triple_reg_set *live,
12128 struct reg_block *rb, struct triple *ins, void *arg)
12130 struct triple *tangle;
12132 char used[MAX_REGISTERS];
12133 struct triple_reg_set *set;
12136 /* Find out which registers have multiple uses at this point */
12137 memset(used, 0, sizeof(used));
12138 for(set = live; set; set = set->next) {
12139 struct reg_info info;
12140 info = read_lhs_color(state, set->member, 0);
12141 if (info.reg == REG_UNSET) {
12144 reg_inc_used(state, used, info.reg);
12147 /* Now find the least dominated definition of a register in
12148 * conflict I have seen so far.
12150 for(set = live; set; set = set->next) {
12151 struct reg_info info;
12152 info = read_lhs_color(state, set->member, 0);
12153 if (used[info.reg] < 2) {
12156 if (!tangle || tdominates(state, set->member, tangle)) {
12157 tangle = set->member;
12160 /* If I have found a tangle resolve it */
12162 struct triple *post_copy;
12163 post_copy = resolve_tangle(state, tangle);
12165 replace_block_use(state, blocks, tangle, post_copy);
12167 if (post_copy && (tangle != ins)) {
12168 replace_set_use(state, live, tangle, post_copy);
12175 static void correct_tangles(
12176 struct compile_state *state, struct reg_block *blocks)
12178 color_instructions(state);
12179 walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12182 struct least_conflict {
12183 struct reg_state *rstate;
12184 struct live_range *ref_range;
12185 struct triple *ins;
12186 struct triple_reg_set *live;
12189 static void least_conflict(struct compile_state *state,
12190 struct reg_block *blocks, struct triple_reg_set *live,
12191 struct reg_block *rb, struct triple *ins, void *arg)
12193 struct least_conflict *conflict = arg;
12194 struct live_range_edge *edge;
12195 struct triple_reg_set *set;
12198 #warning "FIXME handle instructions with left hand sides..."
12199 /* Only instructions that introduce a new definition
12200 * can be the conflict instruction.
12202 if (!triple_is_def(state, ins)) {
12206 /* See if live ranges at this instruction are a
12207 * strict subset of the live ranges that are in conflict.
12210 for(set = live; set; set = set->next) {
12211 struct live_range *lr;
12212 lr = conflict->rstate->lrd[set->member->id].lr;
12213 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12214 if (edge->node == lr) {
12218 if (!edge && (lr != conflict->ref_range)) {
12227 /* See if there is an uncolored member in this subset.
12229 for(set = live; set; set = set->next) {
12230 struct live_range *lr;
12231 lr = conflict->rstate->lrd[set->member->id].lr;
12232 if (lr->color == REG_UNSET) {
12236 if (!set && (conflict->ref_range != REG_UNSET)) {
12241 /* Find the instruction with the largest possible subset of
12242 * conflict ranges and that dominates any other instruction
12243 * with an equal sized set of conflicting ranges.
12245 if ((count > conflict->count) ||
12246 ((count == conflict->count) &&
12247 tdominates(state, ins, conflict->ins))) {
12248 struct triple_reg_set *next;
12249 /* Remember the canidate instruction */
12250 conflict->ins = ins;
12251 conflict->count = count;
12252 /* Free the old collection of live registers */
12253 for(set = conflict->live; set; set = next) {
12255 do_triple_unset(&conflict->live, set->member);
12257 conflict->live = 0;
12258 /* Rember the registers that are alive but do not feed
12259 * into or out of conflict->ins.
12261 for(set = live; set; set = set->next) {
12262 struct triple **expr;
12263 if (set->member == ins) {
12266 expr = triple_rhs(state, ins, 0);
12267 for(;expr; expr = triple_rhs(state, ins, expr)) {
12268 if (*expr == set->member) {
12272 expr = triple_lhs(state, ins, 0);
12273 for(; expr; expr = triple_lhs(state, ins, expr)) {
12274 if (*expr == set->member) {
12278 do_triple_set(&conflict->live, set->member, set->new);
12286 static void find_range_conflict(struct compile_state *state,
12287 struct reg_state *rstate, char *used, struct live_range *ref_range,
12288 struct least_conflict *conflict)
12290 /* there are 3 kinds ways conflicts can occure.
12291 * 1) the life time of 2 values simply overlap.
12292 * 2) the 2 values feed into the same instruction.
12293 * 3) the 2 values feed into a phi function.
12296 /* find the instruction where the problematic conflict comes
12297 * into existance. that the instruction where all of
12298 * the values are alive, and among such instructions it is
12299 * the least dominated one.
12301 * a value is alive an an instruction if either;
12302 * 1) the value defintion dominates the instruction and there
12303 * is a use at or after that instrction
12304 * 2) the value definition feeds into a phi function in the
12305 * same block as the instruction. and the phi function
12306 * is at or after the instruction.
12308 memset(conflict, 0, sizeof(*conflict));
12309 conflict->rstate = rstate;
12310 conflict->ref_range = ref_range;
12312 conflict->count = 0;
12313 conflict->live = 0;
12314 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12316 if (!conflict->ins) {
12317 internal_error(state, 0, "No conflict ins?");
12319 if (!conflict->live) {
12320 internal_error(state, 0, "No conflict live?");
12325 static struct triple *split_constrained_range(struct compile_state *state,
12326 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12328 unsigned constrained_size;
12329 struct triple *new, *constrained;
12330 struct triple_reg_set *cset;
12331 /* Find a range that is having problems because it is
12332 * artificially constrained.
12334 constrained_size = ~0;
12337 for(cset = conflict->live; cset; cset = cset->next) {
12338 struct triple_set *set;
12339 struct reg_info info;
12341 unsigned cur_size, size;
12342 /* Skip the live range that starts with conflict->ins */
12343 if (cset->member == conflict->ins) {
12346 /* Find how many registers this value can potentially
12349 classes = arch_type_to_regcm(state, cset->member->type);
12350 size = regc_max_size(state, classes);
12352 /* Find how many registers we allow this value to
12355 info = arch_reg_lhs(state, cset->member, 0);
12356 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12357 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12358 cur_size = regc_max_size(state, info.regcm);
12362 /* If this live_range feeds into conflict->ins
12363 * splitting it is unlikely to help.
12365 for(set = cset->member->use; set; set = set->next) {
12366 if (set->member == conflict->ins) {
12371 /* If there is no difference between potential and
12372 * actual register count there is nothing to do.
12374 if (cur_size >= size) {
12377 /* Of the constrained registers deal with the
12378 * most constrained one first.
12380 if (!constrained ||
12381 (size < constrained_size)) {
12382 constrained = cset->member;
12383 constrained_size = size;
12389 new = post_copy(state, constrained);
12390 new->id |= TRIPLE_FLAG_POST_SPLIT;
12395 static int split_ranges(
12396 struct compile_state *state, struct reg_state *rstate,
12397 char *used, struct live_range *range)
12399 struct triple *new;
12401 if ((range->color == REG_UNNEEDED) ||
12402 (rstate->passes >= rstate->max_passes)) {
12406 /* If I can't allocate a register something needs to be split */
12407 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12408 struct least_conflict conflict;
12410 /* Find where in the set of registers the conflict
12413 find_range_conflict(state, rstate, used, range, &conflict);
12415 /* If a range has been artifically constrained split it */
12416 new = split_constrained_range(state, rstate, used, &conflict);
12419 /* Ideally I would split the live range that will not be used
12420 * for the longest period of time in hopes that this will
12421 * (a) allow me to spill a register or
12422 * (b) allow me to place a value in another register.
12424 * So far I don't have a test case for this, the resolving
12425 * of mandatory constraints has solved all of my
12426 * know issues. So I have choosen not to write any
12427 * code until I cat get a better feel for cases where
12428 * it would be useful to have.
12431 #warning "WISHLIST implement live range splitting..."
12436 rstate->lrd[rstate->defs].orig_id = new->id;
12437 new->id = rstate->defs;
12440 fprintf(stderr, "new: %p\n", new);
12447 #if DEBUG_COLOR_GRAPH > 1
12448 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12449 #define cgdebug_flush() fflush(stdout)
12450 #elif DEBUG_COLOR_GRAPH == 1
12451 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12452 #define cgdebug_flush() fflush(stderr)
12454 #define cgdebug_printf(...)
12455 #define cgdebug_flush()
12459 static int select_free_color(struct compile_state *state,
12460 struct reg_state *rstate, struct live_range *range)
12462 struct triple_set *entry;
12463 struct live_range_def *lrd;
12464 struct live_range_def *phi;
12465 struct live_range_edge *edge;
12466 char used[MAX_REGISTERS];
12467 struct triple **expr;
12469 /* Instead of doing just the trivial color select here I try
12470 * a few extra things because a good color selection will help reduce
12474 /* Find the registers currently in use */
12475 memset(used, 0, sizeof(used));
12476 for(edge = range->edges; edge; edge = edge->next) {
12477 if (edge->node->color == REG_UNSET) {
12480 reg_fill_used(state, used, edge->node->color);
12482 #if DEBUG_COLOR_GRAPH > 1
12486 for(edge = range->edges; edge; edge = edge->next) {
12489 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
12490 tops(range->def->op), i,
12491 range->def->filename, range->def->line, range->def->col);
12492 for(i = 0; i < MAX_REGISTERS; i++) {
12494 cgdebug_printf("used: %s\n",
12501 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12503 /* If a color is already assigned see if it will work */
12504 if (range->color != REG_UNSET) {
12505 struct live_range_def *lrd;
12506 if (!used[range->color]) {
12509 for(edge = range->edges; edge; edge = edge->next) {
12510 if (edge->node->color != range->color) {
12513 warning(state, edge->node->defs->def, "edge: ");
12514 lrd = edge->node->defs;
12516 warning(state, lrd->def, " %p %s",
12517 lrd->def, tops(lrd->def->op));
12519 } while(lrd != edge->node->defs);
12522 warning(state, range->defs->def, "def: ");
12524 warning(state, lrd->def, " %p %s",
12525 lrd->def, tops(lrd->def->op));
12527 } while(lrd != range->defs);
12528 internal_error(state, range->defs->def,
12529 "live range with already used color %s",
12530 arch_reg_str(range->color));
12533 /* If I feed into an expression reuse it's color.
12534 * This should help remove copies in the case of 2 register instructions
12535 * and phi functions.
12538 lrd = live_range_end(state, range, 0);
12539 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12540 entry = lrd->def->use;
12541 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12542 struct live_range_def *insd;
12543 insd = &rstate->lrd[entry->member->id];
12544 if (insd->lr->defs == 0) {
12547 if (!phi && (insd->def->op == OP_PHI) &&
12548 !interfere(rstate, range, insd->lr)) {
12551 if ((insd->lr->color == REG_UNSET) ||
12552 ((insd->lr->classes & range->classes) == 0) ||
12553 (used[insd->lr->color])) {
12556 if (interfere(rstate, range, insd->lr)) {
12559 range->color = insd->lr->color;
12562 /* If I feed into a phi function reuse it's color or the color
12563 * of something else that feeds into the phi function.
12566 if (phi->lr->color != REG_UNSET) {
12567 if (used[phi->lr->color]) {
12568 range->color = phi->lr->color;
12572 expr = triple_rhs(state, phi->def, 0);
12573 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12574 struct live_range *lr;
12578 lr = rstate->lrd[(*expr)->id].lr;
12579 if ((lr->color == REG_UNSET) ||
12580 ((lr->classes & range->classes) == 0) ||
12581 (used[lr->color])) {
12584 if (interfere(rstate, range, lr)) {
12587 range->color = lr->color;
12591 /* If I don't interfere with a rhs node reuse it's color */
12592 lrd = live_range_head(state, range, 0);
12593 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12594 expr = triple_rhs(state, lrd->def, 0);
12595 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12596 struct live_range *lr;
12600 lr = rstate->lrd[(*expr)->id].lr;
12601 if ((lr->color == -1) ||
12602 ((lr->classes & range->classes) == 0) ||
12603 (used[lr->color])) {
12606 if (interfere(rstate, range, lr)) {
12609 range->color = lr->color;
12613 /* If I have not opportunitically picked a useful color
12614 * pick the first color that is free.
12616 if (range->color == REG_UNSET) {
12618 arch_select_free_register(state, used, range->classes);
12620 if (range->color == REG_UNSET) {
12622 if (split_ranges(state, rstate, used, range)) {
12625 for(edge = range->edges; edge; edge = edge->next) {
12626 if (edge->node->color == REG_UNSET) {
12629 warning(state, edge->node->defs->def, "reg %s",
12630 arch_reg_str(edge->node->color));
12632 warning(state, range->defs->def, "classes: %x",
12634 for(i = 0; i < MAX_REGISTERS; i++) {
12636 warning(state, range->defs->def, "used: %s",
12640 #if DEBUG_COLOR_GRAPH < 2
12641 error(state, range->defs->def, "too few registers");
12643 internal_error(state, range->defs->def, "too few registers");
12646 range->classes = arch_reg_regcm(state, range->color);
12647 if (range->color == -1) {
12648 internal_error(state, range->defs->def, "select_free_color did not?");
12653 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12656 struct live_range_edge *edge;
12657 struct live_range *range;
12659 cgdebug_printf("Lo: ");
12660 range = rstate->low;
12661 if (*range->group_prev != range) {
12662 internal_error(state, 0, "lo: *prev != range?");
12664 *range->group_prev = range->group_next;
12665 if (range->group_next) {
12666 range->group_next->group_prev = range->group_prev;
12668 if (&range->group_next == rstate->low_tail) {
12669 rstate->low_tail = range->group_prev;
12671 if (rstate->low == range) {
12672 internal_error(state, 0, "low: next != prev?");
12675 else if (rstate->high) {
12676 cgdebug_printf("Hi: ");
12677 range = rstate->high;
12678 if (*range->group_prev != range) {
12679 internal_error(state, 0, "hi: *prev != range?");
12681 *range->group_prev = range->group_next;
12682 if (range->group_next) {
12683 range->group_next->group_prev = range->group_prev;
12685 if (&range->group_next == rstate->high_tail) {
12686 rstate->high_tail = range->group_prev;
12688 if (rstate->high == range) {
12689 internal_error(state, 0, "high: next != prev?");
12695 cgdebug_printf(" %d\n", range - rstate->lr);
12696 range->group_prev = 0;
12697 for(edge = range->edges; edge; edge = edge->next) {
12698 struct live_range *node;
12700 /* Move nodes from the high to the low list */
12701 if (node->group_prev && (node->color == REG_UNSET) &&
12702 (node->degree == regc_max_size(state, node->classes))) {
12703 if (*node->group_prev != node) {
12704 internal_error(state, 0, "move: *prev != node?");
12706 *node->group_prev = node->group_next;
12707 if (node->group_next) {
12708 node->group_next->group_prev = node->group_prev;
12710 if (&node->group_next == rstate->high_tail) {
12711 rstate->high_tail = node->group_prev;
12713 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12714 node->group_prev = rstate->low_tail;
12715 node->group_next = 0;
12716 *rstate->low_tail = node;
12717 rstate->low_tail = &node->group_next;
12718 if (*node->group_prev != node) {
12719 internal_error(state, 0, "move2: *prev != node?");
12724 colored = color_graph(state, rstate);
12726 cgdebug_printf("Coloring %d @%s:%d.%d:",
12727 range - rstate->lr,
12728 range->def->filename, range->def->line, range->def->col);
12730 colored = select_free_color(state, rstate, range);
12731 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12736 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12738 struct live_range *lr;
12739 struct live_range_edge *edge;
12740 struct triple *ins, *first;
12741 char used[MAX_REGISTERS];
12742 first = RHS(state->main_function, 0);
12745 if (triple_is_def(state, ins)) {
12746 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12747 internal_error(state, ins,
12748 "triple without a live range def");
12750 lr = rstate->lrd[ins->id].lr;
12751 if (lr->color == REG_UNSET) {
12752 internal_error(state, ins,
12753 "triple without a color");
12755 /* Find the registers used by the edges */
12756 memset(used, 0, sizeof(used));
12757 for(edge = lr->edges; edge; edge = edge->next) {
12758 if (edge->node->color == REG_UNSET) {
12759 internal_error(state, 0,
12760 "live range without a color");
12762 reg_fill_used(state, used, edge->node->color);
12764 if (used[lr->color]) {
12765 internal_error(state, ins,
12766 "triple with already used color");
12770 } while(ins != first);
12773 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12775 struct live_range *lr;
12776 struct triple *first, *ins;
12777 first = RHS(state->main_function, 0);
12780 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12781 internal_error(state, ins,
12782 "triple without a live range");
12784 lr = rstate->lrd[ins->id].lr;
12785 SET_REG(ins->id, lr->color);
12787 } while (ins != first);
12790 static void print_interference_block(
12791 struct compile_state *state, struct block *block, void *arg)
12794 struct reg_state *rstate = arg;
12795 struct reg_block *rb;
12796 struct triple *ptr;
12799 rb = &rstate->blocks[block->vertex];
12801 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
12805 block->left && block->left->use?block->left->use->member : 0,
12807 block->right && block->right->use?block->right->use->member : 0);
12809 struct triple_reg_set *in_set;
12811 for(in_set = rb->in; in_set; in_set = in_set->next) {
12812 printf(" %-10p", in_set->member);
12817 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12818 done = (ptr == block->last);
12819 if (ptr->op == OP_PHI) {
12826 for(edge = 0; edge < block->users; edge++) {
12827 printf(" in(%d):", edge);
12828 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12829 struct triple **slot;
12830 done = (ptr == block->last);
12831 if (ptr->op != OP_PHI) {
12834 slot = &RHS(ptr, 0);
12835 printf(" %-10p", slot[edge]);
12840 if (block->first->op == OP_LABEL) {
12841 printf("%p:\n", block->first);
12843 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12844 struct triple_set *user;
12845 struct live_range *lr;
12849 done = (ptr == block->last);
12850 lr = rstate->lrd[ptr->id].lr;
12852 if (triple_stores_block(state, ptr)) {
12853 if (ptr->u.block != block) {
12854 internal_error(state, ptr,
12855 "Wrong block pointer: %p",
12859 if (op == OP_ADECL) {
12860 for(user = ptr->use; user; user = user->next) {
12861 if (!user->member->u.block) {
12862 internal_error(state, user->member,
12863 "Use %p not in a block?",
12870 SET_REG(ptr->id, lr->color);
12871 display_triple(stdout, ptr);
12874 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12875 internal_error(state, ptr, "lr has no defs!");
12879 struct live_range_def *lrd;
12883 printf(" %-10p", lrd->def);
12885 } while(lrd != lr->defs);
12888 if (lr->edges > 0) {
12889 struct live_range_edge *edge;
12891 for(edge = lr->edges; edge; edge = edge->next) {
12892 struct live_range_def *lrd;
12893 lrd = edge->node->defs;
12895 printf(" %-10p", lrd->def);
12897 } while(lrd != edge->node->defs);
12902 /* Do a bunch of sanity checks */
12903 valid_ins(state, ptr);
12904 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12905 internal_error(state, ptr, "Invalid triple id: %d",
12908 for(user = ptr->use; user; user = user->next) {
12909 struct triple *use;
12910 struct live_range *ulr;
12911 use = user->member;
12912 valid_ins(state, use);
12913 if ((use->id < 0) || (use->id > rstate->defs)) {
12914 internal_error(state, use, "Invalid triple id: %d",
12917 ulr = rstate->lrd[user->member->id].lr;
12918 if (triple_stores_block(state, user->member) &&
12919 !user->member->u.block) {
12920 internal_error(state, user->member,
12921 "Use %p not in a block?",
12927 struct triple_reg_set *out_set;
12929 for(out_set = rb->out; out_set; out_set = out_set->next) {
12930 printf(" %-10p", out_set->member);
12937 static struct live_range *merge_sort_lr(
12938 struct live_range *first, struct live_range *last)
12940 struct live_range *mid, *join, **join_tail, *pick;
12942 size = (last - first) + 1;
12944 mid = first + size/2;
12945 first = merge_sort_lr(first, mid -1);
12946 mid = merge_sort_lr(mid, last);
12950 /* merge the two lists */
12951 while(first && mid) {
12952 if ((first->degree < mid->degree) ||
12953 ((first->degree == mid->degree) &&
12954 (first->length < mid->length))) {
12956 first = first->group_next;
12958 first->group_prev = 0;
12963 mid = mid->group_next;
12965 mid->group_prev = 0;
12968 pick->group_next = 0;
12969 pick->group_prev = join_tail;
12971 join_tail = &pick->group_next;
12973 /* Splice the remaining list */
12974 pick = (first)? first : mid;
12977 pick->group_prev = join_tail;
12981 if (!first->defs) {
12989 static void ids_from_rstate(struct compile_state *state,
12990 struct reg_state *rstate)
12992 struct triple *ins, *first;
12993 if (!rstate->defs) {
12996 /* Display the graph if desired */
12997 if (state->debug & DEBUG_INTERFERENCE) {
12998 print_blocks(state, stdout);
12999 print_control_flow(state);
13001 first = RHS(state->main_function, 0);
13005 struct live_range_def *lrd;
13006 lrd = &rstate->lrd[ins->id];
13007 ins->id = lrd->orig_id;
13010 } while(ins != first);
13013 static void cleanup_live_edges(struct reg_state *rstate)
13016 /* Free the edges on each node */
13017 for(i = 1; i <= rstate->ranges; i++) {
13018 remove_live_edges(rstate, &rstate->lr[i]);
13022 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13024 cleanup_live_edges(rstate);
13025 xfree(rstate->lrd);
13028 /* Free the variable lifetime information */
13029 if (rstate->blocks) {
13030 free_variable_lifetimes(state, rstate->blocks);
13033 rstate->ranges = 0;
13036 rstate->blocks = 0;
13039 static void allocate_registers(struct compile_state *state)
13041 struct reg_state rstate;
13044 /* Clear out the reg_state */
13045 memset(&rstate, 0, sizeof(rstate));
13046 rstate.max_passes = MAX_ALLOCATION_PASSES;
13049 struct live_range **point, **next;
13053 ids_from_rstate(state, &rstate);
13055 /* Cleanup the temporary data structures */
13056 cleanup_rstate(state, &rstate);
13058 /* Compute the variable lifetimes */
13059 rstate.blocks = compute_variable_lifetimes(state);
13061 /* Fix invalid mandatory live range coalesce conflicts */
13062 walk_variable_lifetimes(
13063 state, rstate.blocks, fix_coalesce_conflicts, 0);
13065 /* Fix two simultaneous uses of the same register */
13066 correct_tangles(state, rstate.blocks);
13068 if (state->debug & DEBUG_INSERTED_COPIES) {
13069 printf("After resolve_tangles\n");
13070 print_blocks(state, stdout);
13071 print_control_flow(state);
13075 /* Allocate and initialize the live ranges */
13076 initialize_live_ranges(state, &rstate);
13079 /* Forget previous live range edge calculations */
13080 cleanup_live_edges(&rstate);
13082 /* Compute the interference graph */
13083 walk_variable_lifetimes(
13084 state, rstate.blocks, graph_ins, &rstate);
13086 /* Display the interference graph if desired */
13087 if (state->debug & DEBUG_INTERFERENCE) {
13088 printf("\nlive variables by block\n");
13089 walk_blocks(state, print_interference_block, &rstate);
13090 printf("\nlive variables by instruction\n");
13091 walk_variable_lifetimes(
13092 state, rstate.blocks,
13093 print_interference_ins, &rstate);
13096 coalesced = coalesce_live_ranges(state, &rstate);
13097 } while(coalesced);
13099 /* Build the groups low and high. But with the nodes
13100 * first sorted by degree order.
13102 rstate.low_tail = &rstate.low;
13103 rstate.high_tail = &rstate.high;
13104 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13106 rstate.high->group_prev = &rstate.high;
13108 for(point = &rstate.high; *point; point = &(*point)->group_next)
13110 rstate.high_tail = point;
13111 /* Walk through the high list and move everything that needs
13114 for(point = &rstate.high; *point; point = next) {
13115 struct live_range *range;
13116 next = &(*point)->group_next;
13119 /* If it has a low degree or it already has a color
13120 * place the node in low.
13122 if ((range->degree < regc_max_size(state, range->classes)) ||
13123 (range->color != REG_UNSET)) {
13124 cgdebug_printf("Lo: %5d degree %5d%s\n",
13125 range - rstate.lr, range->degree,
13126 (range->color != REG_UNSET) ? " (colored)": "");
13127 *range->group_prev = range->group_next;
13128 if (range->group_next) {
13129 range->group_next->group_prev = range->group_prev;
13131 if (&range->group_next == rstate.high_tail) {
13132 rstate.high_tail = range->group_prev;
13134 range->group_prev = rstate.low_tail;
13135 range->group_next = 0;
13136 *rstate.low_tail = range;
13137 rstate.low_tail = &range->group_next;
13141 cgdebug_printf("hi: %5d degree %5d%s\n",
13142 range - rstate.lr, range->degree,
13143 (range->color != REG_UNSET) ? " (colored)": "");
13146 /* Color the live_ranges */
13147 colored = color_graph(state, &rstate);
13149 } while (!colored);
13151 /* Verify the graph was properly colored */
13152 verify_colors(state, &rstate);
13154 /* Move the colors from the graph to the triples */
13155 color_triples(state, &rstate);
13157 /* Cleanup the temporary data structures */
13158 cleanup_rstate(state, &rstate);
13161 /* Sparce Conditional Constant Propogation
13162 * =========================================
13166 struct lattice_node {
13168 struct triple *def;
13169 struct ssa_edge *out;
13170 struct flow_block *fblock;
13171 struct triple *val;
13172 /* lattice high val && !is_const(val)
13173 * lattice const is_const(val)
13174 * lattice low val == 0
13178 struct lattice_node *src;
13179 struct lattice_node *dst;
13180 struct ssa_edge *work_next;
13181 struct ssa_edge *work_prev;
13182 struct ssa_edge *out_next;
13185 struct flow_block *src;
13186 struct flow_block *dst;
13187 struct flow_edge *work_next;
13188 struct flow_edge *work_prev;
13189 struct flow_edge *in_next;
13190 struct flow_edge *out_next;
13193 struct flow_block {
13194 struct block *block;
13195 struct flow_edge *in;
13196 struct flow_edge *out;
13197 struct flow_edge left, right;
13202 struct lattice_node *lattice;
13203 struct ssa_edge *ssa_edges;
13204 struct flow_block *flow_blocks;
13205 struct flow_edge *flow_work_list;
13206 struct ssa_edge *ssa_work_list;
13210 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13211 struct flow_edge *fedge)
13213 if (!scc->flow_work_list) {
13214 scc->flow_work_list = fedge;
13215 fedge->work_next = fedge->work_prev = fedge;
13218 struct flow_edge *ftail;
13219 ftail = scc->flow_work_list->work_prev;
13220 fedge->work_next = ftail->work_next;
13221 fedge->work_prev = ftail;
13222 fedge->work_next->work_prev = fedge;
13223 fedge->work_prev->work_next = fedge;
13227 static struct flow_edge *scc_next_fedge(
13228 struct compile_state *state, struct scc_state *scc)
13230 struct flow_edge *fedge;
13231 fedge = scc->flow_work_list;
13233 fedge->work_next->work_prev = fedge->work_prev;
13234 fedge->work_prev->work_next = fedge->work_next;
13235 if (fedge->work_next != fedge) {
13236 scc->flow_work_list = fedge->work_next;
13238 scc->flow_work_list = 0;
13244 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13245 struct ssa_edge *sedge)
13247 if (!scc->ssa_work_list) {
13248 scc->ssa_work_list = sedge;
13249 sedge->work_next = sedge->work_prev = sedge;
13252 struct ssa_edge *stail;
13253 stail = scc->ssa_work_list->work_prev;
13254 sedge->work_next = stail->work_next;
13255 sedge->work_prev = stail;
13256 sedge->work_next->work_prev = sedge;
13257 sedge->work_prev->work_next = sedge;
13261 static struct ssa_edge *scc_next_sedge(
13262 struct compile_state *state, struct scc_state *scc)
13264 struct ssa_edge *sedge;
13265 sedge = scc->ssa_work_list;
13267 sedge->work_next->work_prev = sedge->work_prev;
13268 sedge->work_prev->work_next = sedge->work_next;
13269 if (sedge->work_next != sedge) {
13270 scc->ssa_work_list = sedge->work_next;
13272 scc->ssa_work_list = 0;
13278 static void initialize_scc_state(
13279 struct compile_state *state, struct scc_state *scc)
13281 int ins_count, ssa_edge_count;
13282 int ins_index, ssa_edge_index, fblock_index;
13283 struct triple *first, *ins;
13284 struct block *block;
13285 struct flow_block *fblock;
13287 memset(scc, 0, sizeof(*scc));
13289 /* Inialize pass zero find out how much memory we need */
13290 first = RHS(state->main_function, 0);
13292 ins_count = ssa_edge_count = 0;
13294 struct triple_set *edge;
13296 for(edge = ins->use; edge; edge = edge->next) {
13300 } while(ins != first);
13302 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13303 ins_count, ssa_edge_count, state->last_vertex);
13305 scc->ins_count = ins_count;
13307 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13309 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13311 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
13314 /* Initialize pass one collect up the nodes */
13317 ins_index = ssa_edge_index = fblock_index = 0;
13320 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13321 block = ins->u.block;
13323 internal_error(state, ins, "label without block");
13326 block->vertex = fblock_index;
13327 fblock = &scc->flow_blocks[fblock_index];
13328 fblock->block = block;
13331 struct lattice_node *lnode;
13333 lnode = &scc->lattice[ins_index];
13336 lnode->fblock = fblock;
13337 lnode->val = ins; /* LATTICE HIGH */
13338 lnode->old_id = ins->id;
13339 ins->id = ins_index;
13342 } while(ins != first);
13343 /* Initialize pass two collect up the edges */
13348 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13349 struct flow_edge *fedge, **ftail;
13350 struct block_set *bedge;
13351 block = ins->u.block;
13352 fblock = &scc->flow_blocks[block->vertex];
13355 ftail = &fblock->out;
13357 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13358 if (fblock->left.dst->block != block->left) {
13359 internal_error(state, 0, "block mismatch");
13361 fblock->left.out_next = 0;
13362 *ftail = &fblock->left;
13363 ftail = &fblock->left.out_next;
13365 if (block->right) {
13366 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13367 if (fblock->right.dst->block != block->right) {
13368 internal_error(state, 0, "block mismatch");
13370 fblock->right.out_next = 0;
13371 *ftail = &fblock->right;
13372 ftail = &fblock->right.out_next;
13374 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13375 fedge->src = fblock;
13376 fedge->work_next = fedge->work_prev = fedge;
13377 fedge->executable = 0;
13379 ftail = &fblock->in;
13380 for(bedge = block->use; bedge; bedge = bedge->next) {
13381 struct block *src_block;
13382 struct flow_block *sfblock;
13383 struct flow_edge *sfedge;
13384 src_block = bedge->member;
13385 sfblock = &scc->flow_blocks[src_block->vertex];
13387 if (src_block->left == block) {
13388 sfedge = &sfblock->left;
13390 sfedge = &sfblock->right;
13393 ftail = &sfedge->in_next;
13394 sfedge->in_next = 0;
13398 struct triple_set *edge;
13399 struct ssa_edge **stail;
13400 struct lattice_node *lnode;
13401 lnode = &scc->lattice[ins->id];
13403 stail = &lnode->out;
13404 for(edge = ins->use; edge; edge = edge->next) {
13405 struct ssa_edge *sedge;
13406 ssa_edge_index += 1;
13407 sedge = &scc->ssa_edges[ssa_edge_index];
13409 stail = &sedge->out_next;
13410 sedge->src = lnode;
13411 sedge->dst = &scc->lattice[edge->member->id];
13412 sedge->work_next = sedge->work_prev = sedge;
13413 sedge->out_next = 0;
13417 } while(ins != first);
13418 /* Setup a dummy block 0 as a node above the start node */
13420 struct flow_block *fblock, *dst;
13421 struct flow_edge *fedge;
13422 fblock = &scc->flow_blocks[0];
13425 fblock->out = &fblock->left;
13426 dst = &scc->flow_blocks[state->first_block->vertex];
13427 fedge = &fblock->left;
13428 fedge->src = fblock;
13430 fedge->work_next = fedge;
13431 fedge->work_prev = fedge;
13432 fedge->in_next = fedge->dst->in;
13433 fedge->out_next = 0;
13434 fedge->executable = 0;
13435 fedge->dst->in = fedge;
13437 /* Initialize the work lists */
13438 scc->flow_work_list = 0;
13439 scc->ssa_work_list = 0;
13440 scc_add_fedge(state, scc, fedge);
13443 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13444 ins_index, ssa_edge_index, fblock_index);
13449 static void free_scc_state(
13450 struct compile_state *state, struct scc_state *scc)
13452 xfree(scc->flow_blocks);
13453 xfree(scc->ssa_edges);
13454 xfree(scc->lattice);
13458 static struct lattice_node *triple_to_lattice(
13459 struct compile_state *state, struct scc_state *scc, struct triple *ins)
13461 if (ins->id <= 0) {
13462 internal_error(state, ins, "bad id");
13464 return &scc->lattice[ins->id];
13467 static struct triple *preserve_lval(
13468 struct compile_state *state, struct lattice_node *lnode)
13470 struct triple *old;
13471 /* Preserve the original value */
13473 old = dup_triple(state, lnode->val);
13474 if (lnode->val != lnode->def) {
13484 static int lval_changed(struct compile_state *state,
13485 struct triple *old, struct lattice_node *lnode)
13488 /* See if the lattice value has changed */
13490 if (!old && !lnode->val) {
13493 if (changed && lnode->val && !is_const(lnode->val)) {
13497 lnode->val && old &&
13498 (memcmp(lnode->val->param, old->param,
13499 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13500 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13510 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
13511 struct lattice_node *lnode)
13513 struct lattice_node *tmp;
13514 struct triple **slot, *old;
13515 struct flow_edge *fedge;
13517 if (lnode->def->op != OP_PHI) {
13518 internal_error(state, lnode->def, "not phi");
13520 /* Store the original value */
13521 old = preserve_lval(state, lnode);
13523 /* default to lattice high */
13524 lnode->val = lnode->def;
13525 slot = &RHS(lnode->def, 0);
13527 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13528 if (!fedge->executable) {
13531 if (!slot[index]) {
13532 internal_error(state, lnode->def, "no phi value");
13534 tmp = triple_to_lattice(state, scc, slot[index]);
13535 /* meet(X, lattice low) = lattice low */
13539 /* meet(X, lattice high) = X */
13540 else if (!tmp->val) {
13541 lnode->val = lnode->val;
13543 /* meet(lattice high, X) = X */
13544 else if (!is_const(lnode->val)) {
13545 lnode->val = dup_triple(state, tmp->val);
13546 lnode->val->type = lnode->def->type;
13548 /* meet(const, const) = const or lattice low */
13549 else if (!constants_equal(state, lnode->val, tmp->val)) {
13557 fprintf(stderr, "phi: %d -> %s\n",
13559 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13561 /* If the lattice value has changed update the work lists. */
13562 if (lval_changed(state, old, lnode)) {
13563 struct ssa_edge *sedge;
13564 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13565 scc_add_sedge(state, scc, sedge);
13570 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13571 struct lattice_node *lnode)
13574 struct triple *old, *scratch;
13575 struct triple **dexpr, **vexpr;
13578 /* Store the original value */
13579 old = preserve_lval(state, lnode);
13581 /* Reinitialize the value */
13582 lnode->val = scratch = dup_triple(state, lnode->def);
13583 scratch->id = lnode->old_id;
13584 scratch->next = scratch;
13585 scratch->prev = scratch;
13588 count = TRIPLE_SIZE(scratch->sizes);
13589 for(i = 0; i < count; i++) {
13590 dexpr = &lnode->def->param[i];
13591 vexpr = &scratch->param[i];
13593 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13594 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13596 struct lattice_node *tmp;
13597 tmp = triple_to_lattice(state, scc, *dexpr);
13598 *vexpr = (tmp->val)? tmp->val : tmp->def;
13601 if (scratch->op == OP_BRANCH) {
13602 scratch->next = lnode->def->next;
13604 /* Recompute the value */
13605 #warning "FIXME see if simplify does anything bad"
13606 /* So far it looks like only the strength reduction
13607 * optimization are things I need to worry about.
13609 simplify(state, scratch);
13610 /* Cleanup my value */
13611 if (scratch->use) {
13612 internal_error(state, lnode->def, "scratch used?");
13614 if ((scratch->prev != scratch) ||
13615 ((scratch->next != scratch) &&
13616 ((lnode->def->op != OP_BRANCH) ||
13617 (scratch->next != lnode->def->next)))) {
13618 internal_error(state, lnode->def, "scratch in list?");
13620 /* undo any uses... */
13621 count = TRIPLE_SIZE(scratch->sizes);
13622 for(i = 0; i < count; i++) {
13623 vexpr = &scratch->param[i];
13625 unuse_triple(*vexpr, scratch);
13628 if (!is_const(scratch)) {
13629 for(i = 0; i < count; i++) {
13630 dexpr = &lnode->def->param[i];
13631 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13632 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13634 struct lattice_node *tmp;
13635 tmp = triple_to_lattice(state, scc, *dexpr);
13643 (lnode->val->op == lnode->def->op) &&
13644 (memcmp(lnode->val->param, lnode->def->param,
13645 count * sizeof(lnode->val->param[0])) == 0) &&
13646 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13647 lnode->val = lnode->def;
13649 /* Find the cases that are always lattice lo */
13651 triple_is_def(state, lnode->val) &&
13652 !triple_is_pure(state, lnode->val)) {
13656 (lnode->val->op == OP_SDECL) &&
13657 (lnode->val != lnode->def)) {
13658 internal_error(state, lnode->def, "bad sdecl");
13660 /* See if the lattice value has changed */
13661 changed = lval_changed(state, old, lnode);
13662 if (lnode->val != scratch) {
13668 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13669 struct lattice_node *lnode)
13671 struct lattice_node *cond;
13674 struct flow_edge *fedge;
13675 fprintf(stderr, "branch: %d (",
13678 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13679 fprintf(stderr, " %d", fedge->dst->block->vertex);
13681 fprintf(stderr, " )");
13682 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13683 fprintf(stderr, " <- %d",
13684 RHS(lnode->def, 0)->id);
13686 fprintf(stderr, "\n");
13689 if (lnode->def->op != OP_BRANCH) {
13690 internal_error(state, lnode->def, "not branch");
13692 /* This only applies to conditional branches */
13693 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13696 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13697 if (cond->val && !is_const(cond->val)) {
13698 #warning "FIXME do I need to do something here?"
13699 warning(state, cond->def, "condition not constant?");
13702 if (cond->val == 0) {
13703 scc_add_fedge(state, scc, cond->fblock->out);
13704 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13706 else if (cond->val->u.cval) {
13707 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13710 scc_add_fedge(state, scc, cond->fblock->out);
13715 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13716 struct lattice_node *lnode)
13720 changed = compute_lnode_val(state, scc, lnode);
13723 struct triple **expr;
13724 fprintf(stderr, "expr: %3d %10s (",
13725 lnode->def->id, tops(lnode->def->op));
13726 expr = triple_rhs(state, lnode->def, 0);
13727 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13729 fprintf(stderr, " %d", (*expr)->id);
13732 fprintf(stderr, " ) -> %s\n",
13733 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13736 if (lnode->def->op == OP_BRANCH) {
13737 scc_visit_branch(state, scc, lnode);
13740 else if (changed) {
13741 struct ssa_edge *sedge;
13742 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13743 scc_add_sedge(state, scc, sedge);
13748 static void scc_writeback_values(
13749 struct compile_state *state, struct scc_state *scc)
13751 struct triple *first, *ins;
13752 first = RHS(state->main_function, 0);
13755 struct lattice_node *lnode;
13756 lnode = triple_to_lattice(state, scc, ins);
13758 ins->id = lnode->old_id;
13760 if (lnode->val && !is_const(lnode->val)) {
13761 warning(state, lnode->def,
13762 "lattice node still high?");
13765 if (lnode->val && (lnode->val != ins)) {
13766 /* See if it something I know how to write back */
13767 switch(lnode->val->op) {
13769 mkconst(state, ins, lnode->val->u.cval);
13772 mkaddr_const(state, ins,
13773 MISC(lnode->val, 0), lnode->val->u.cval);
13776 /* By default don't copy the changes,
13777 * recompute them in place instead.
13779 simplify(state, ins);
13782 if (is_const(lnode->val) &&
13783 !constants_equal(state, lnode->val, ins)) {
13784 internal_error(state, 0, "constants not equal");
13786 /* Free the lattice nodes */
13791 } while(ins != first);
13794 static void scc_transform(struct compile_state *state)
13796 struct scc_state scc;
13798 initialize_scc_state(state, &scc);
13800 while(scc.flow_work_list || scc.ssa_work_list) {
13801 struct flow_edge *fedge;
13802 struct ssa_edge *sedge;
13803 struct flow_edge *fptr;
13804 while((fedge = scc_next_fedge(state, &scc))) {
13805 struct block *block;
13806 struct triple *ptr;
13807 struct flow_block *fblock;
13810 if (fedge->executable) {
13814 internal_error(state, 0, "fedge without dst");
13817 internal_error(state, 0, "fedge without src");
13819 fedge->executable = 1;
13820 fblock = fedge->dst;
13821 block = fblock->block;
13823 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13824 if (fptr->executable) {
13829 fprintf(stderr, "vertex: %d time: %d\n",
13830 block->vertex, time);
13834 for(ptr = block->first; !done; ptr = ptr->next) {
13835 struct lattice_node *lnode;
13836 done = (ptr == block->last);
13837 lnode = &scc.lattice[ptr->id];
13838 if (ptr->op == OP_PHI) {
13839 scc_visit_phi(state, &scc, lnode);
13841 else if (time == 1) {
13842 scc_visit_expr(state, &scc, lnode);
13845 if (fblock->out && !fblock->out->out_next) {
13846 scc_add_fedge(state, &scc, fblock->out);
13849 while((sedge = scc_next_sedge(state, &scc))) {
13850 struct lattice_node *lnode;
13851 struct flow_block *fblock;
13852 lnode = sedge->dst;
13853 fblock = lnode->fblock;
13855 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
13856 sedge - scc.ssa_edges,
13857 sedge->src->def->id,
13858 sedge->dst->def->id);
13860 if (lnode->def->op == OP_PHI) {
13861 scc_visit_phi(state, &scc, lnode);
13864 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13865 if (fptr->executable) {
13870 scc_visit_expr(state, &scc, lnode);
13876 scc_writeback_values(state, &scc);
13877 free_scc_state(state, &scc);
13881 static void transform_to_arch_instructions(struct compile_state *state)
13883 struct triple *ins, *first;
13884 first = RHS(state->main_function, 0);
13887 ins = transform_to_arch_instruction(state, ins);
13888 } while(ins != first);
13891 #if DEBUG_CONSISTENCY
13892 static void verify_uses(struct compile_state *state)
13894 struct triple *first, *ins;
13895 struct triple_set *set;
13896 first = RHS(state->main_function, 0);
13899 struct triple **expr;
13900 expr = triple_rhs(state, ins, 0);
13901 for(; expr; expr = triple_rhs(state, ins, expr)) {
13902 for(set = *expr?(*expr)->use:0; set; set = set->next) {
13903 if (set->member == ins) {
13908 internal_error(state, ins, "rhs not used");
13911 expr = triple_lhs(state, ins, 0);
13912 for(; expr; expr = triple_lhs(state, ins, expr)) {
13913 for(set = *expr?(*expr)->use:0; set; set = set->next) {
13914 if (set->member == ins) {
13919 internal_error(state, ins, "lhs not used");
13923 } while(ins != first);
13926 static void verify_blocks(struct compile_state *state)
13928 struct triple *ins;
13929 struct block *block;
13930 block = state->first_block;
13935 for(ins = block->first; ins != block->last->next; ins = ins->next) {
13936 if (!triple_stores_block(state, ins)) {
13939 if (ins->u.block != block) {
13940 internal_error(state, ins, "inconsitent block specified");
13943 if (!triple_stores_block(state, block->last->next)) {
13944 internal_error(state, block->last->next,
13945 "cannot find next block");
13947 block = block->last->next->u.block;
13949 internal_error(state, block->last->next,
13952 } while(block != state->first_block);
13955 static void verify_domination(struct compile_state *state)
13957 struct triple *first, *ins;
13958 struct triple_set *set;
13959 if (!state->first_block) {
13963 first = RHS(state->main_function, 0);
13966 for(set = ins->use; set; set = set->next) {
13967 struct triple **expr;
13968 if (set->member->op == OP_PHI) {
13971 /* See if the use is on the righ hand side */
13972 expr = triple_rhs(state, set->member, 0);
13973 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
13974 if (*expr == ins) {
13979 !tdominates(state, ins, set->member)) {
13980 internal_error(state, set->member,
13981 "non dominated rhs use?");
13985 } while(ins != first);
13988 static void verify_piece(struct compile_state *state)
13990 struct triple *first, *ins;
13991 first = RHS(state->main_function, 0);
13994 struct triple *ptr;
13996 lhs = TRIPLE_LHS(ins->sizes);
13997 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14000 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14001 if (ptr != LHS(ins, i)) {
14002 internal_error(state, ins, "malformed lhs on %s",
14005 if (ptr->op != OP_PIECE) {
14006 internal_error(state, ins, "bad lhs op %s at %d on %s",
14007 tops(ptr->op), i, tops(ins->op));
14009 if (ptr->u.cval != i) {
14010 internal_error(state, ins, "bad u.cval of %d %d expected",
14015 } while(ins != first);
14017 static void verify_ins_colors(struct compile_state *state)
14019 struct triple *first, *ins;
14021 first = RHS(state->main_function, 0);
14025 } while(ins != first);
14027 static void verify_consistency(struct compile_state *state)
14029 verify_uses(state);
14030 verify_blocks(state);
14031 verify_domination(state);
14032 verify_piece(state);
14033 verify_ins_colors(state);
14036 #define verify_consistency(state) do {} while(0)
14037 #endif /* DEBUG_USES */
14039 static void optimize(struct compile_state *state)
14041 if (state->debug & DEBUG_TRIPLES) {
14042 print_triples(state);
14044 /* Replace structures with simpler data types */
14045 flatten_structures(state);
14046 if (state->debug & DEBUG_TRIPLES) {
14047 print_triples(state);
14049 verify_consistency(state);
14050 /* Analize the intermediate code */
14051 setup_basic_blocks(state);
14052 analyze_idominators(state);
14053 analyze_ipdominators(state);
14054 /* Transform the code to ssa form */
14055 transform_to_ssa_form(state);
14056 verify_consistency(state);
14057 if (state->debug & DEBUG_CODE_ELIMINATION) {
14058 fprintf(stdout, "After transform_to_ssa_form\n");
14059 print_blocks(state, stdout);
14061 /* Do strength reduction and simple constant optimizations */
14062 if (state->optimize >= 1) {
14063 simplify_all(state);
14065 verify_consistency(state);
14066 /* Propogate constants throughout the code */
14067 if (state->optimize >= 2) {
14068 #warning "FIXME fix scc_transform"
14069 scc_transform(state);
14070 transform_from_ssa_form(state);
14071 free_basic_blocks(state);
14072 setup_basic_blocks(state);
14073 analyze_idominators(state);
14074 analyze_ipdominators(state);
14075 transform_to_ssa_form(state);
14077 verify_consistency(state);
14078 #warning "WISHLIST implement single use constants (least possible register pressure)"
14079 #warning "WISHLIST implement induction variable elimination"
14080 /* Select architecture instructions and an initial partial
14081 * coloring based on architecture constraints.
14083 transform_to_arch_instructions(state);
14084 verify_consistency(state);
14085 if (state->debug & DEBUG_ARCH_CODE) {
14086 printf("After transform_to_arch_instructions\n");
14087 print_blocks(state, stdout);
14088 print_control_flow(state);
14090 eliminate_inefectual_code(state);
14091 verify_consistency(state);
14092 if (state->debug & DEBUG_CODE_ELIMINATION) {
14093 printf("After eliminate_inefectual_code\n");
14094 print_blocks(state, stdout);
14095 print_control_flow(state);
14097 verify_consistency(state);
14098 /* Color all of the variables to see if they will fit in registers */
14099 insert_copies_to_phi(state);
14100 if (state->debug & DEBUG_INSERTED_COPIES) {
14101 printf("After insert_copies_to_phi\n");
14102 print_blocks(state, stdout);
14103 print_control_flow(state);
14105 verify_consistency(state);
14106 insert_mandatory_copies(state);
14107 if (state->debug & DEBUG_INSERTED_COPIES) {
14108 printf("After insert_mandatory_copies\n");
14109 print_blocks(state, stdout);
14110 print_control_flow(state);
14112 verify_consistency(state);
14113 allocate_registers(state);
14114 verify_consistency(state);
14115 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14116 print_blocks(state, stdout);
14118 if (state->debug & DEBUG_CONTROL_FLOW) {
14119 print_control_flow(state);
14121 /* Remove the optimization information.
14122 * This is more to check for memory consistency than to free memory.
14124 free_basic_blocks(state);
14127 static void print_op_asm(struct compile_state *state,
14128 struct triple *ins, FILE *fp)
14130 struct asm_info *info;
14132 unsigned lhs, rhs, i;
14133 info = ins->u.ainfo;
14134 lhs = TRIPLE_LHS(ins->sizes);
14135 rhs = TRIPLE_RHS(ins->sizes);
14136 /* Don't count the clobbers in lhs */
14137 for(i = 0; i < lhs; i++) {
14138 if (LHS(ins, i)->type == &void_type) {
14144 for(ptr = info->str; *ptr; ptr++) {
14146 unsigned long param;
14147 struct triple *piece;
14157 param = strtoul(ptr, &next, 10);
14159 error(state, ins, "Invalid asm template");
14161 if (param >= (lhs + rhs)) {
14162 error(state, ins, "Invalid param %%%u in asm template",
14165 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14167 arch_reg_str(ID_REG(piece->id)));
14174 /* Only use the low x86 byte registers. This allows me
14175 * allocate the entire register when a byte register is used.
14177 #define X86_4_8BIT_GPRS 1
14179 /* Recognized x86 cpu variants */
14187 #define CPU_DEFAULT CPU_I386
14189 /* The x86 register classes */
14190 #define REGC_FLAGS 0
14191 #define REGC_GPR8 1
14192 #define REGC_GPR16 2
14193 #define REGC_GPR32 3
14194 #define REGC_GPR64 4
14197 #define REGC_GPR32_8 7
14198 #define REGC_GPR16_8 8
14199 #define REGC_IMM32 9
14200 #define REGC_IMM16 10
14201 #define REGC_IMM8 11
14202 #define LAST_REGC REGC_IMM8
14203 #if LAST_REGC >= MAX_REGC
14204 #error "MAX_REGC is to low"
14207 /* Register class masks */
14208 #define REGCM_FLAGS (1 << REGC_FLAGS)
14209 #define REGCM_GPR8 (1 << REGC_GPR8)
14210 #define REGCM_GPR16 (1 << REGC_GPR16)
14211 #define REGCM_GPR32 (1 << REGC_GPR32)
14212 #define REGCM_GPR64 (1 << REGC_GPR64)
14213 #define REGCM_MMX (1 << REGC_MMX)
14214 #define REGCM_XMM (1 << REGC_XMM)
14215 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14216 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14217 #define REGCM_IMM32 (1 << REGC_IMM32)
14218 #define REGCM_IMM16 (1 << REGC_IMM16)
14219 #define REGCM_IMM8 (1 << REGC_IMM8)
14220 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14222 /* The x86 registers */
14223 #define REG_EFLAGS 2
14224 #define REGC_FLAGS_FIRST REG_EFLAGS
14225 #define REGC_FLAGS_LAST REG_EFLAGS
14234 #define REGC_GPR8_FIRST REG_AL
14235 #if X86_4_8BIT_GPRS
14236 #define REGC_GPR8_LAST REG_DL
14238 #define REGC_GPR8_LAST REG_DH
14248 #define REGC_GPR16_FIRST REG_AX
14249 #define REGC_GPR16_LAST REG_SP
14258 #define REGC_GPR32_FIRST REG_EAX
14259 #define REGC_GPR32_LAST REG_ESP
14260 #define REG_EDXEAX 27
14261 #define REGC_GPR64_FIRST REG_EDXEAX
14262 #define REGC_GPR64_LAST REG_EDXEAX
14263 #define REG_MMX0 28
14264 #define REG_MMX1 29
14265 #define REG_MMX2 30
14266 #define REG_MMX3 31
14267 #define REG_MMX4 32
14268 #define REG_MMX5 33
14269 #define REG_MMX6 34
14270 #define REG_MMX7 35
14271 #define REGC_MMX_FIRST REG_MMX0
14272 #define REGC_MMX_LAST REG_MMX7
14273 #define REG_XMM0 36
14274 #define REG_XMM1 37
14275 #define REG_XMM2 38
14276 #define REG_XMM3 39
14277 #define REG_XMM4 40
14278 #define REG_XMM5 41
14279 #define REG_XMM6 42
14280 #define REG_XMM7 43
14281 #define REGC_XMM_FIRST REG_XMM0
14282 #define REGC_XMM_LAST REG_XMM7
14283 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14284 #define LAST_REG REG_XMM7
14286 #define REGC_GPR32_8_FIRST REG_EAX
14287 #define REGC_GPR32_8_LAST REG_EDX
14288 #define REGC_GPR16_8_FIRST REG_AX
14289 #define REGC_GPR16_8_LAST REG_DX
14291 #define REGC_IMM8_FIRST -1
14292 #define REGC_IMM8_LAST -1
14293 #define REGC_IMM16_FIRST -2
14294 #define REGC_IMM16_LAST -1
14295 #define REGC_IMM32_FIRST -4
14296 #define REGC_IMM32_LAST -1
14298 #if LAST_REG >= MAX_REGISTERS
14299 #error "MAX_REGISTERS to low"
14303 static unsigned regc_size[LAST_REGC +1] = {
14304 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
14305 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
14306 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
14307 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
14308 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
14309 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
14310 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
14311 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14312 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14318 static const struct {
14320 } regcm_bound[LAST_REGC + 1] = {
14321 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
14322 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
14323 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
14324 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
14325 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
14326 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
14327 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
14328 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14329 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14330 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
14331 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
14332 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
14335 static int arch_encode_cpu(const char *cpu)
14341 { "i386", CPU_I386 },
14349 for(ptr = cpus; ptr->name; ptr++) {
14350 if (strcmp(ptr->name, cpu) == 0) {
14357 static unsigned arch_regc_size(struct compile_state *state, int class)
14359 if ((class < 0) || (class > LAST_REGC)) {
14362 return regc_size[class];
14364 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14366 /* See if two register classes may have overlapping registers */
14367 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14368 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14370 /* Special case for the immediates */
14371 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14372 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14373 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14374 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
14377 return (regcm1 & regcm2) ||
14378 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14381 static void arch_reg_equivs(
14382 struct compile_state *state, unsigned *equiv, int reg)
14384 if ((reg < 0) || (reg > LAST_REG)) {
14385 internal_error(state, 0, "invalid register");
14390 #if X86_4_8BIT_GPRS
14394 *equiv++ = REG_EAX;
14395 *equiv++ = REG_EDXEAX;
14398 #if X86_4_8BIT_GPRS
14402 *equiv++ = REG_EAX;
14403 *equiv++ = REG_EDXEAX;
14406 #if X86_4_8BIT_GPRS
14410 *equiv++ = REG_EBX;
14414 #if X86_4_8BIT_GPRS
14418 *equiv++ = REG_EBX;
14421 #if X86_4_8BIT_GPRS
14425 *equiv++ = REG_ECX;
14429 #if X86_4_8BIT_GPRS
14433 *equiv++ = REG_ECX;
14436 #if X86_4_8BIT_GPRS
14440 *equiv++ = REG_EDX;
14441 *equiv++ = REG_EDXEAX;
14444 #if X86_4_8BIT_GPRS
14448 *equiv++ = REG_EDX;
14449 *equiv++ = REG_EDXEAX;
14454 *equiv++ = REG_EAX;
14455 *equiv++ = REG_EDXEAX;
14460 *equiv++ = REG_EBX;
14465 *equiv++ = REG_ECX;
14470 *equiv++ = REG_EDX;
14471 *equiv++ = REG_EDXEAX;
14474 *equiv++ = REG_ESI;
14477 *equiv++ = REG_EDI;
14480 *equiv++ = REG_EBP;
14483 *equiv++ = REG_ESP;
14489 *equiv++ = REG_EDXEAX;
14505 *equiv++ = REG_EDXEAX;
14526 *equiv++ = REG_EAX;
14527 *equiv++ = REG_EDX;
14530 *equiv++ = REG_UNSET;
14533 static unsigned arch_avail_mask(struct compile_state *state)
14535 unsigned avail_mask;
14536 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14537 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14538 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14539 switch(state->cpu) {
14542 avail_mask |= REGCM_MMX;
14546 avail_mask |= REGCM_MMX | REGCM_XMM;
14550 /* Don't enable 8 bit values until I can force both operands
14551 * to be 8bits simultaneously.
14553 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14558 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14560 unsigned mask, result;
14563 result &= arch_avail_mask(state);
14565 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14566 if ((result & mask) == 0) {
14569 if (class > LAST_REGC) {
14572 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14573 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14574 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14575 result |= (1 << class2);
14582 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14587 for(class = 0; class <= LAST_REGC; class++) {
14588 if ((reg >= regcm_bound[class].first) &&
14589 (reg <= regcm_bound[class].last)) {
14590 mask |= (1 << class);
14594 internal_error(state, 0, "reg %d not in any class", reg);
14599 static struct reg_info arch_reg_constraint(
14600 struct compile_state *state, struct type *type, const char *constraint)
14602 static const struct {
14606 } constraints[] = {
14607 { 'r', REGCM_GPR32, REG_UNSET },
14608 { 'g', REGCM_GPR32, REG_UNSET },
14609 { 'p', REGCM_GPR32, REG_UNSET },
14610 { 'q', REGCM_GPR8, REG_UNSET },
14611 { 'Q', REGCM_GPR32_8, REG_UNSET },
14612 { 'x', REGCM_XMM, REG_UNSET },
14613 { 'y', REGCM_MMX, REG_UNSET },
14614 { 'a', REGCM_GPR32, REG_EAX },
14615 { 'b', REGCM_GPR32, REG_EBX },
14616 { 'c', REGCM_GPR32, REG_ECX },
14617 { 'd', REGCM_GPR32, REG_EDX },
14618 { 'D', REGCM_GPR32, REG_EDI },
14619 { 'S', REGCM_GPR32, REG_ESI },
14620 { '\0', 0, REG_UNSET },
14622 unsigned int regcm;
14623 unsigned int mask, reg;
14624 struct reg_info result;
14626 regcm = arch_type_to_regcm(state, type);
14629 for(ptr = constraint; *ptr; ptr++) {
14634 for(i = 0; constraints[i].class != '\0'; i++) {
14635 if (constraints[i].class == *ptr) {
14639 if (constraints[i].class == '\0') {
14640 error(state, 0, "invalid register constraint ``%c''", *ptr);
14643 if ((constraints[i].mask & regcm) == 0) {
14644 error(state, 0, "invalid register class %c specified",
14647 mask |= constraints[i].mask;
14648 if (constraints[i].reg != REG_UNSET) {
14649 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14650 error(state, 0, "Only one register may be specified");
14652 reg = constraints[i].reg;
14656 result.regcm = mask;
14660 static struct reg_info arch_reg_clobber(
14661 struct compile_state *state, const char *clobber)
14663 struct reg_info result;
14664 if (strcmp(clobber, "memory") == 0) {
14665 result.reg = REG_UNSET;
14668 else if (strcmp(clobber, "%eax") == 0) {
14669 result.reg = REG_EAX;
14670 result.regcm = REGCM_GPR32;
14672 else if (strcmp(clobber, "%ebx") == 0) {
14673 result.reg = REG_EBX;
14674 result.regcm = REGCM_GPR32;
14676 else if (strcmp(clobber, "%ecx") == 0) {
14677 result.reg = REG_ECX;
14678 result.regcm = REGCM_GPR32;
14680 else if (strcmp(clobber, "%edx") == 0) {
14681 result.reg = REG_EDX;
14682 result.regcm = REGCM_GPR32;
14684 else if (strcmp(clobber, "%esi") == 0) {
14685 result.reg = REG_ESI;
14686 result.regcm = REGCM_GPR32;
14688 else if (strcmp(clobber, "%edi") == 0) {
14689 result.reg = REG_EDI;
14690 result.regcm = REGCM_GPR32;
14692 else if (strcmp(clobber, "%ebp") == 0) {
14693 result.reg = REG_EBP;
14694 result.regcm = REGCM_GPR32;
14696 else if (strcmp(clobber, "%esp") == 0) {
14697 result.reg = REG_ESP;
14698 result.regcm = REGCM_GPR32;
14700 else if (strcmp(clobber, "cc") == 0) {
14701 result.reg = REG_EFLAGS;
14702 result.regcm = REGCM_FLAGS;
14704 else if ((strncmp(clobber, "xmm", 3) == 0) &&
14705 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14706 result.reg = REG_XMM0 + octdigval(clobber[3]);
14707 result.regcm = REGCM_XMM;
14709 else if ((strncmp(clobber, "mmx", 3) == 0) &&
14710 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14711 result.reg = REG_MMX0 + octdigval(clobber[3]);
14712 result.regcm = REGCM_MMX;
14715 error(state, 0, "Invalid register clobber");
14716 result.reg = REG_UNSET;
14722 static int do_select_reg(struct compile_state *state,
14723 char *used, int reg, unsigned classes)
14729 mask = arch_reg_regcm(state, reg);
14730 return (classes & mask) ? reg : REG_UNSET;
14733 static int arch_select_free_register(
14734 struct compile_state *state, char *used, int classes)
14736 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14737 * other types of registers.
14741 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14742 reg = do_select_reg(state, used, i, classes);
14744 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14745 reg = do_select_reg(state, used, i, classes);
14747 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14748 reg = do_select_reg(state, used, i, classes);
14750 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14751 reg = do_select_reg(state, used, i, classes);
14753 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14754 reg = do_select_reg(state, used, i, classes);
14756 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14757 reg = do_select_reg(state, used, i, classes);
14759 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14760 reg = do_select_reg(state, used, i, classes);
14766 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
14768 #warning "FIXME force types smaller (if legal) before I get here"
14769 unsigned avail_mask;
14772 avail_mask = arch_avail_mask(state);
14773 switch(type->type & TYPE_MASK) {
14780 mask = REGCM_GPR8 |
14781 REGCM_GPR16 | REGCM_GPR16_8 |
14782 REGCM_GPR32 | REGCM_GPR32_8 |
14784 REGCM_MMX | REGCM_XMM |
14785 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14789 mask = REGCM_GPR16 | REGCM_GPR16_8 |
14790 REGCM_GPR32 | REGCM_GPR32_8 |
14792 REGCM_MMX | REGCM_XMM |
14793 REGCM_IMM32 | REGCM_IMM16;
14800 mask = REGCM_GPR32 | REGCM_GPR32_8 |
14801 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
14805 internal_error(state, 0, "no register class for type");
14808 mask &= avail_mask;
14812 static int is_imm32(struct triple *imm)
14814 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
14815 (imm->op == OP_ADDRCONST);
14818 static int is_imm16(struct triple *imm)
14820 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
14822 static int is_imm8(struct triple *imm)
14824 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
14827 static int get_imm32(struct triple *ins, struct triple **expr)
14829 struct triple *imm;
14831 while(imm->op == OP_COPY) {
14834 if (!is_imm32(imm)) {
14837 unuse_triple(*expr, ins);
14838 use_triple(imm, ins);
14843 static int get_imm8(struct triple *ins, struct triple **expr)
14845 struct triple *imm;
14847 while(imm->op == OP_COPY) {
14850 if (!is_imm8(imm)) {
14853 unuse_triple(*expr, ins);
14854 use_triple(imm, ins);
14859 #define TEMPLATE_NOP 0
14860 #define TEMPLATE_INTCONST8 1
14861 #define TEMPLATE_INTCONST32 2
14862 #define TEMPLATE_COPY_REG 3
14863 #define TEMPLATE_COPY_IMM32 4
14864 #define TEMPLATE_COPY_IMM16 5
14865 #define TEMPLATE_COPY_IMM8 6
14866 #define TEMPLATE_PHI 7
14867 #define TEMPLATE_STORE8 8
14868 #define TEMPLATE_STORE16 9
14869 #define TEMPLATE_STORE32 10
14870 #define TEMPLATE_LOAD8 11
14871 #define TEMPLATE_LOAD16 12
14872 #define TEMPLATE_LOAD32 13
14873 #define TEMPLATE_BINARY_REG 14
14874 #define TEMPLATE_BINARY_IMM 15
14875 #define TEMPLATE_SL_CL 16
14876 #define TEMPLATE_SL_IMM 17
14877 #define TEMPLATE_UNARY 18
14878 #define TEMPLATE_CMP_REG 19
14879 #define TEMPLATE_CMP_IMM 20
14880 #define TEMPLATE_TEST 21
14881 #define TEMPLATE_SET 22
14882 #define TEMPLATE_JMP 23
14883 #define TEMPLATE_INB_DX 24
14884 #define TEMPLATE_INB_IMM 25
14885 #define TEMPLATE_INW_DX 26
14886 #define TEMPLATE_INW_IMM 27
14887 #define TEMPLATE_INL_DX 28
14888 #define TEMPLATE_INL_IMM 29
14889 #define TEMPLATE_OUTB_DX 30
14890 #define TEMPLATE_OUTB_IMM 31
14891 #define TEMPLATE_OUTW_DX 32
14892 #define TEMPLATE_OUTW_IMM 33
14893 #define TEMPLATE_OUTL_DX 34
14894 #define TEMPLATE_OUTL_IMM 35
14895 #define TEMPLATE_BSF 36
14896 #define TEMPLATE_RDMSR 37
14897 #define TEMPLATE_WRMSR 38
14898 #define LAST_TEMPLATE TEMPLATE_WRMSR
14899 #if LAST_TEMPLATE >= MAX_TEMPLATES
14900 #error "MAX_TEMPLATES to low"
14903 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
14904 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
14906 static struct ins_template templates[] = {
14907 [TEMPLATE_NOP] = {},
14908 [TEMPLATE_INTCONST8] = {
14909 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14911 [TEMPLATE_INTCONST32] = {
14912 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14914 [TEMPLATE_COPY_REG] = {
14915 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14916 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
14918 [TEMPLATE_COPY_IMM32] = {
14919 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
14920 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14922 [TEMPLATE_COPY_IMM16] = {
14923 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
14924 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
14926 [TEMPLATE_COPY_IMM8] = {
14927 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14928 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14931 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
14933 [ 0] = { REG_VIRT0, COPY_REGCM },
14934 [ 1] = { REG_VIRT0, COPY_REGCM },
14935 [ 2] = { REG_VIRT0, COPY_REGCM },
14936 [ 3] = { REG_VIRT0, COPY_REGCM },
14937 [ 4] = { REG_VIRT0, COPY_REGCM },
14938 [ 5] = { REG_VIRT0, COPY_REGCM },
14939 [ 6] = { REG_VIRT0, COPY_REGCM },
14940 [ 7] = { REG_VIRT0, COPY_REGCM },
14941 [ 8] = { REG_VIRT0, COPY_REGCM },
14942 [ 9] = { REG_VIRT0, COPY_REGCM },
14943 [10] = { REG_VIRT0, COPY_REGCM },
14944 [11] = { REG_VIRT0, COPY_REGCM },
14945 [12] = { REG_VIRT0, COPY_REGCM },
14946 [13] = { REG_VIRT0, COPY_REGCM },
14947 [14] = { REG_VIRT0, COPY_REGCM },
14948 [15] = { REG_VIRT0, COPY_REGCM },
14950 [TEMPLATE_STORE8] = {
14951 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14952 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14954 [TEMPLATE_STORE16] = {
14955 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14956 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14958 [TEMPLATE_STORE32] = {
14959 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14960 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14962 [TEMPLATE_LOAD8] = {
14963 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14964 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14966 [TEMPLATE_LOAD16] = {
14967 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14968 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14970 [TEMPLATE_LOAD32] = {
14971 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14972 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14974 [TEMPLATE_BINARY_REG] = {
14975 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14977 [0] = { REG_VIRT0, REGCM_GPR32 },
14978 [1] = { REG_UNSET, REGCM_GPR32 },
14981 [TEMPLATE_BINARY_IMM] = {
14982 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14984 [0] = { REG_VIRT0, REGCM_GPR32 },
14985 [1] = { REG_UNNEEDED, REGCM_IMM32 },
14988 [TEMPLATE_SL_CL] = {
14989 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14991 [0] = { REG_VIRT0, REGCM_GPR32 },
14992 [1] = { REG_CL, REGCM_GPR8 },
14995 [TEMPLATE_SL_IMM] = {
14996 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14998 [0] = { REG_VIRT0, REGCM_GPR32 },
14999 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15002 [TEMPLATE_UNARY] = {
15003 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15004 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15006 [TEMPLATE_CMP_REG] = {
15007 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15009 [0] = { REG_UNSET, REGCM_GPR32 },
15010 [1] = { REG_UNSET, REGCM_GPR32 },
15013 [TEMPLATE_CMP_IMM] = {
15014 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15016 [0] = { REG_UNSET, REGCM_GPR32 },
15017 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15020 [TEMPLATE_TEST] = {
15021 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15022 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15025 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15026 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15029 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15031 [TEMPLATE_INB_DX] = {
15032 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15033 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15035 [TEMPLATE_INB_IMM] = {
15036 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15037 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15039 [TEMPLATE_INW_DX] = {
15040 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15041 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15043 [TEMPLATE_INW_IMM] = {
15044 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15045 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15047 [TEMPLATE_INL_DX] = {
15048 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15049 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15051 [TEMPLATE_INL_IMM] = {
15052 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15053 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15055 [TEMPLATE_OUTB_DX] = {
15057 [0] = { REG_AL, REGCM_GPR8 },
15058 [1] = { REG_DX, REGCM_GPR16 },
15061 [TEMPLATE_OUTB_IMM] = {
15063 [0] = { REG_AL, REGCM_GPR8 },
15064 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15067 [TEMPLATE_OUTW_DX] = {
15069 [0] = { REG_AX, REGCM_GPR16 },
15070 [1] = { REG_DX, REGCM_GPR16 },
15073 [TEMPLATE_OUTW_IMM] = {
15075 [0] = { REG_AX, REGCM_GPR16 },
15076 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15079 [TEMPLATE_OUTL_DX] = {
15081 [0] = { REG_EAX, REGCM_GPR32 },
15082 [1] = { REG_DX, REGCM_GPR16 },
15085 [TEMPLATE_OUTL_IMM] = {
15087 [0] = { REG_EAX, REGCM_GPR32 },
15088 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15092 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15093 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15095 [TEMPLATE_RDMSR] = {
15097 [0] = { REG_EAX, REGCM_GPR32 },
15098 [1] = { REG_EDX, REGCM_GPR32 },
15100 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15102 [TEMPLATE_WRMSR] = {
15104 [0] = { REG_ECX, REGCM_GPR32 },
15105 [1] = { REG_EAX, REGCM_GPR32 },
15106 [2] = { REG_EDX, REGCM_GPR32 },
15111 static void fixup_branches(struct compile_state *state,
15112 struct triple *cmp, struct triple *use, int jmp_op)
15114 struct triple_set *entry, *next;
15115 for(entry = use->use; entry; entry = next) {
15116 next = entry->next;
15117 if (entry->member->op == OP_COPY) {
15118 fixup_branches(state, cmp, entry->member, jmp_op);
15120 else if (entry->member->op == OP_BRANCH) {
15121 struct triple *branch, *test;
15122 struct triple *left, *right;
15124 left = RHS(cmp, 0);
15125 if (TRIPLE_RHS(cmp->sizes) > 1) {
15126 right = RHS(cmp, 1);
15128 branch = entry->member;
15129 test = pre_triple(state, branch,
15130 cmp->op, cmp->type, left, right);
15131 test->template_id = TEMPLATE_TEST;
15132 if (cmp->op == OP_CMP) {
15133 test->template_id = TEMPLATE_CMP_REG;
15134 if (get_imm32(test, &RHS(test, 1))) {
15135 test->template_id = TEMPLATE_CMP_IMM;
15138 use_triple(RHS(test, 0), test);
15139 use_triple(RHS(test, 1), test);
15140 unuse_triple(RHS(branch, 0), branch);
15141 RHS(branch, 0) = test;
15142 branch->op = jmp_op;
15143 branch->template_id = TEMPLATE_JMP;
15144 use_triple(RHS(branch, 0), branch);
15149 static void bool_cmp(struct compile_state *state,
15150 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15152 struct triple_set *entry, *next;
15153 struct triple *set;
15155 /* Put a barrier up before the cmp which preceeds the
15156 * copy instruction. If a set actually occurs this gives
15157 * us a chance to move variables in registers out of the way.
15160 /* Modify the comparison operator */
15162 ins->template_id = TEMPLATE_TEST;
15163 if (cmp_op == OP_CMP) {
15164 ins->template_id = TEMPLATE_CMP_REG;
15165 if (get_imm32(ins, &RHS(ins, 1))) {
15166 ins->template_id = TEMPLATE_CMP_IMM;
15169 /* Generate the instruction sequence that will transform the
15170 * result of the comparison into a logical value.
15172 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15173 use_triple(ins, set);
15174 set->template_id = TEMPLATE_SET;
15176 for(entry = ins->use; entry; entry = next) {
15177 next = entry->next;
15178 if (entry->member == set) {
15181 replace_rhs_use(state, ins, set, entry->member);
15183 fixup_branches(state, ins, set, jmp_op);
15186 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15188 struct triple *next;
15190 lhs = TRIPLE_LHS(ins->sizes);
15191 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15192 if (next != LHS(ins, i)) {
15193 internal_error(state, ins, "malformed lhs on %s",
15196 if (next->op != OP_PIECE) {
15197 internal_error(state, ins, "bad lhs op %s at %d on %s",
15198 tops(next->op), i, tops(ins->op));
15200 if (next->u.cval != i) {
15201 internal_error(state, ins, "bad u.cval of %d %d expected",
15208 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15210 struct ins_template *template;
15211 struct reg_info result;
15213 if (ins->op == OP_PIECE) {
15214 index = ins->u.cval;
15215 ins = MISC(ins, 0);
15217 zlhs = TRIPLE_LHS(ins->sizes);
15218 if (triple_is_def(state, ins)) {
15221 if (index >= zlhs) {
15222 internal_error(state, ins, "index %d out of range for %s\n",
15223 index, tops(ins->op));
15227 template = &ins->u.ainfo->tmpl;
15230 if (ins->template_id > LAST_TEMPLATE) {
15231 internal_error(state, ins, "bad template number %d",
15234 template = &templates[ins->template_id];
15237 result = template->lhs[index];
15238 result.regcm = arch_regcm_normalize(state, result.regcm);
15239 if (result.reg != REG_UNNEEDED) {
15240 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15242 if (result.regcm == 0) {
15243 internal_error(state, ins, "lhs %d regcm == 0", index);
15248 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15250 struct reg_info result;
15251 struct ins_template *template;
15252 if ((index > TRIPLE_RHS(ins->sizes)) ||
15253 (ins->op == OP_PIECE)) {
15254 internal_error(state, ins, "index %d out of range for %s\n",
15255 index, tops(ins->op));
15259 template = &ins->u.ainfo->tmpl;
15262 if (ins->template_id > LAST_TEMPLATE) {
15263 internal_error(state, ins, "bad template number %d",
15266 template = &templates[ins->template_id];
15269 result = template->rhs[index];
15270 result.regcm = arch_regcm_normalize(state, result.regcm);
15271 if (result.regcm == 0) {
15272 internal_error(state, ins, "rhs %d regcm == 0", index);
15277 static struct triple *transform_to_arch_instruction(
15278 struct compile_state *state, struct triple *ins)
15280 /* Transform from generic 3 address instructions
15281 * to archtecture specific instructions.
15282 * And apply architecture specific constrains to instructions.
15283 * Copies are inserted to preserve the register flexibility
15284 * of 3 address instructions.
15286 struct triple *next;
15290 ins->template_id = TEMPLATE_INTCONST32;
15291 if (ins->u.cval < 256) {
15292 ins->template_id = TEMPLATE_INTCONST8;
15296 ins->template_id = TEMPLATE_INTCONST32;
15302 ins->template_id = TEMPLATE_NOP;
15305 ins->template_id = TEMPLATE_COPY_REG;
15306 if (is_imm8(RHS(ins, 0))) {
15307 ins->template_id = TEMPLATE_COPY_IMM8;
15309 else if (is_imm16(RHS(ins, 0))) {
15310 ins->template_id = TEMPLATE_COPY_IMM16;
15312 else if (is_imm32(RHS(ins, 0))) {
15313 ins->template_id = TEMPLATE_COPY_IMM32;
15315 else if (is_const(RHS(ins, 0))) {
15316 internal_error(state, ins, "bad constant passed to copy");
15320 ins->template_id = TEMPLATE_PHI;
15323 switch(ins->type->type & TYPE_MASK) {
15324 case TYPE_CHAR: case TYPE_UCHAR:
15325 ins->template_id = TEMPLATE_STORE8;
15327 case TYPE_SHORT: case TYPE_USHORT:
15328 ins->template_id = TEMPLATE_STORE16;
15330 case TYPE_INT: case TYPE_UINT:
15331 case TYPE_LONG: case TYPE_ULONG:
15333 ins->template_id = TEMPLATE_STORE32;
15336 internal_error(state, ins, "unknown type in store");
15341 switch(ins->type->type & TYPE_MASK) {
15342 case TYPE_CHAR: case TYPE_UCHAR:
15343 ins->template_id = TEMPLATE_LOAD8;
15347 ins->template_id = TEMPLATE_LOAD16;
15354 ins->template_id = TEMPLATE_LOAD32;
15357 internal_error(state, ins, "unknown type in load");
15367 ins->template_id = TEMPLATE_BINARY_REG;
15368 if (get_imm32(ins, &RHS(ins, 1))) {
15369 ins->template_id = TEMPLATE_BINARY_IMM;
15375 ins->template_id = TEMPLATE_SL_CL;
15376 if (get_imm8(ins, &RHS(ins, 1))) {
15377 ins->template_id = TEMPLATE_SL_IMM;
15382 ins->template_id = TEMPLATE_UNARY;
15385 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
15388 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15391 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15394 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15397 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15400 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15403 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15406 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15409 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15412 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15415 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15418 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15421 if (TRIPLE_RHS(ins->sizes) > 0) {
15422 internal_error(state, ins, "bad branch test");
15425 ins->template_id = TEMPLATE_NOP;
15431 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15432 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15433 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15435 if (get_imm8(ins, &RHS(ins, 0))) {
15436 ins->template_id += 1;
15443 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15444 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15445 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15447 if (get_imm8(ins, &RHS(ins, 1))) {
15448 ins->template_id += 1;
15453 ins->template_id = TEMPLATE_BSF;
15456 ins->template_id = TEMPLATE_RDMSR;
15457 next = after_lhs(state, ins);
15460 ins->template_id = TEMPLATE_WRMSR;
15463 ins->template_id = TEMPLATE_NOP;
15466 ins->template_id = TEMPLATE_NOP;
15467 next = after_lhs(state, ins);
15469 /* Already transformed instructions */
15471 ins->template_id = TEMPLATE_TEST;
15474 ins->template_id = TEMPLATE_CMP_REG;
15475 if (get_imm32(ins, &RHS(ins, 1))) {
15476 ins->template_id = TEMPLATE_CMP_IMM;
15479 case OP_JMP_EQ: case OP_JMP_NOTEQ:
15480 case OP_JMP_SLESS: case OP_JMP_ULESS:
15481 case OP_JMP_SMORE: case OP_JMP_UMORE:
15482 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15483 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15484 ins->template_id = TEMPLATE_JMP;
15486 case OP_SET_EQ: case OP_SET_NOTEQ:
15487 case OP_SET_SLESS: case OP_SET_ULESS:
15488 case OP_SET_SMORE: case OP_SET_UMORE:
15489 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15490 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15491 ins->template_id = TEMPLATE_SET;
15493 /* Unhandled instructions */
15496 internal_error(state, ins, "unhandled ins: %d %s\n",
15497 ins->op, tops(ins->op));
15503 static void generate_local_labels(struct compile_state *state)
15505 struct triple *first, *label;
15508 first = RHS(state->main_function, 0);
15511 if ((label->op == OP_LABEL) ||
15512 (label->op == OP_SDECL)) {
15514 label->u.cval = ++label_counter;
15520 label = label->next;
15521 } while(label != first);
15524 static int check_reg(struct compile_state *state,
15525 struct triple *triple, int classes)
15529 reg = ID_REG(triple->id);
15530 if (reg == REG_UNSET) {
15531 internal_error(state, triple, "register not set");
15533 mask = arch_reg_regcm(state, reg);
15534 if (!(classes & mask)) {
15535 internal_error(state, triple, "reg %d in wrong class",
15541 static const char *arch_reg_str(int reg)
15543 static const char *regs[] = {
15547 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15548 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15549 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15551 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15552 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
15553 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15555 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15562 static const char *reg(struct compile_state *state, struct triple *triple,
15566 reg = check_reg(state, triple, classes);
15567 return arch_reg_str(reg);
15570 const char *type_suffix(struct compile_state *state, struct type *type)
15572 const char *suffix;
15573 switch(size_of(state, type)) {
15574 case 1: suffix = "b"; break;
15575 case 2: suffix = "w"; break;
15576 case 4: suffix = "l"; break;
15578 internal_error(state, 0, "unknown suffix");
15585 static void print_const_val(
15586 struct compile_state *state, struct triple *ins, FILE *fp)
15590 fprintf(fp, " $%ld ",
15591 (long_t)(ins->u.cval));
15594 fprintf(fp, " $L%s%lu+%lu ",
15595 state->label_prefix,
15596 MISC(ins, 0)->u.cval,
15600 internal_error(state, ins, "unknown constant type");
15605 static void print_binary_op(struct compile_state *state,
15606 const char *op, struct triple *ins, FILE *fp)
15609 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15610 if (RHS(ins, 0)->id != ins->id) {
15611 internal_error(state, ins, "invalid register assignment");
15613 if (is_const(RHS(ins, 1))) {
15614 fprintf(fp, "\t%s ", op);
15615 print_const_val(state, RHS(ins, 1), fp);
15616 fprintf(fp, ", %s\n",
15617 reg(state, RHS(ins, 0), mask));
15620 unsigned lmask, rmask;
15622 lreg = check_reg(state, RHS(ins, 0), mask);
15623 rreg = check_reg(state, RHS(ins, 1), mask);
15624 lmask = arch_reg_regcm(state, lreg);
15625 rmask = arch_reg_regcm(state, rreg);
15626 mask = lmask & rmask;
15627 fprintf(fp, "\t%s %s, %s\n",
15629 reg(state, RHS(ins, 1), mask),
15630 reg(state, RHS(ins, 0), mask));
15633 static void print_unary_op(struct compile_state *state,
15634 const char *op, struct triple *ins, FILE *fp)
15637 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15638 fprintf(fp, "\t%s %s\n",
15640 reg(state, RHS(ins, 0), mask));
15643 static void print_op_shift(struct compile_state *state,
15644 const char *op, struct triple *ins, FILE *fp)
15647 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15648 if (RHS(ins, 0)->id != ins->id) {
15649 internal_error(state, ins, "invalid register assignment");
15651 if (is_const(RHS(ins, 1))) {
15652 fprintf(fp, "\t%s ", op);
15653 print_const_val(state, RHS(ins, 1), fp);
15654 fprintf(fp, ", %s\n",
15655 reg(state, RHS(ins, 0), mask));
15658 fprintf(fp, "\t%s %s, %s\n",
15660 reg(state, RHS(ins, 1), REGCM_GPR8),
15661 reg(state, RHS(ins, 0), mask));
15665 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15672 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15673 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15674 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15676 internal_error(state, ins, "not an in operation");
15680 dreg = check_reg(state, ins, mask);
15681 if (!reg_is_reg(state, dreg, REG_EAX)) {
15682 internal_error(state, ins, "dst != %%eax");
15684 if (is_const(RHS(ins, 0))) {
15685 fprintf(fp, "\t%s ", op);
15686 print_const_val(state, RHS(ins, 0), fp);
15687 fprintf(fp, ", %s\n",
15688 reg(state, ins, mask));
15692 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15693 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15694 internal_error(state, ins, "src != %%dx");
15696 fprintf(fp, "\t%s %s, %s\n",
15698 reg(state, RHS(ins, 0), REGCM_GPR16),
15699 reg(state, ins, mask));
15703 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15710 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15711 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15712 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15714 internal_error(state, ins, "not an out operation");
15718 lreg = check_reg(state, RHS(ins, 0), mask);
15719 if (!reg_is_reg(state, lreg, REG_EAX)) {
15720 internal_error(state, ins, "src != %%eax");
15722 if (is_const(RHS(ins, 1))) {
15723 fprintf(fp, "\t%s %s,",
15724 op, reg(state, RHS(ins, 0), mask));
15725 print_const_val(state, RHS(ins, 1), fp);
15730 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15731 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15732 internal_error(state, ins, "dst != %%dx");
15734 fprintf(fp, "\t%s %s, %s\n",
15736 reg(state, RHS(ins, 0), mask),
15737 reg(state, RHS(ins, 1), REGCM_GPR16));
15741 static void print_op_move(struct compile_state *state,
15742 struct triple *ins, FILE *fp)
15744 /* op_move is complex because there are many types
15745 * of registers we can move between.
15746 * Because OP_COPY will be introduced in arbitrary locations
15747 * OP_COPY must not affect flags.
15749 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15750 struct triple *dst, *src;
15751 if (ins->op == OP_COPY) {
15755 else if (ins->op == OP_WRITE) {
15760 internal_error(state, ins, "unknown move operation");
15763 if (!is_const(src)) {
15764 int src_reg, dst_reg;
15765 int src_regcm, dst_regcm;
15766 src_reg = ID_REG(src->id);
15767 dst_reg = ID_REG(dst->id);
15768 src_regcm = arch_reg_regcm(state, src_reg);
15769 dst_regcm = arch_reg_regcm(state, dst_reg);
15770 /* If the class is the same just move the register */
15771 if (src_regcm & dst_regcm &
15772 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15773 if ((src_reg != dst_reg) || !omit_copy) {
15774 fprintf(fp, "\tmov %s, %s\n",
15775 reg(state, src, src_regcm),
15776 reg(state, dst, dst_regcm));
15779 /* Move 32bit to 16bit */
15780 else if ((src_regcm & REGCM_GPR32) &&
15781 (dst_regcm & REGCM_GPR16)) {
15782 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15783 if ((src_reg != dst_reg) || !omit_copy) {
15784 fprintf(fp, "\tmovw %s, %s\n",
15785 arch_reg_str(src_reg),
15786 arch_reg_str(dst_reg));
15789 /* Move 32bit to 8bit */
15790 else if ((src_regcm & REGCM_GPR32_8) &&
15791 (dst_regcm & REGCM_GPR8))
15793 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15794 if ((src_reg != dst_reg) || !omit_copy) {
15795 fprintf(fp, "\tmovb %s, %s\n",
15796 arch_reg_str(src_reg),
15797 arch_reg_str(dst_reg));
15800 /* Move 16bit to 8bit */
15801 else if ((src_regcm & REGCM_GPR16_8) &&
15802 (dst_regcm & REGCM_GPR8))
15804 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
15805 if ((src_reg != dst_reg) || !omit_copy) {
15806 fprintf(fp, "\tmovb %s, %s\n",
15807 arch_reg_str(src_reg),
15808 arch_reg_str(dst_reg));
15811 /* Move 8/16bit to 16/32bit */
15812 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
15813 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
15815 op = is_signed(src->type)? "movsx": "movzx";
15816 fprintf(fp, "\t%s %s, %s\n",
15818 reg(state, src, src_regcm),
15819 reg(state, dst, dst_regcm));
15821 /* Move between sse registers */
15822 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
15823 if ((src_reg != dst_reg) || !omit_copy) {
15824 fprintf(fp, "\tmovdqa %s, %s\n",
15825 reg(state, src, src_regcm),
15826 reg(state, dst, dst_regcm));
15829 /* Move between mmx registers or mmx & sse registers */
15830 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15831 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15832 if ((src_reg != dst_reg) || !omit_copy) {
15833 fprintf(fp, "\tmovq %s, %s\n",
15834 reg(state, src, src_regcm),
15835 reg(state, dst, dst_regcm));
15838 /* Move between 32bit gprs & mmx/sse registers */
15839 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
15840 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
15841 fprintf(fp, "\tmovd %s, %s\n",
15842 reg(state, src, src_regcm),
15843 reg(state, dst, dst_regcm));
15845 #if X86_4_8BIT_GPRS
15846 /* Move from 8bit gprs to mmx/sse registers */
15847 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
15848 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15851 op = is_signed(src->type)? "movsx":"movzx";
15852 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15853 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
15855 reg(state, src, src_regcm),
15856 arch_reg_str(mid_reg),
15857 arch_reg_str(mid_reg),
15858 reg(state, dst, dst_regcm));
15860 /* Move from mmx/sse registers and 8bit gprs */
15861 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15862 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
15864 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15865 fprintf(fp, "\tmovd %s, %s\n",
15866 reg(state, src, src_regcm),
15867 arch_reg_str(mid_reg));
15869 /* Move from 32bit gprs to 16bit gprs */
15870 else if ((src_regcm & REGCM_GPR32) &&
15871 (dst_regcm & REGCM_GPR16)) {
15872 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
15873 if ((src_reg != dst_reg) || !omit_copy) {
15874 fprintf(fp, "\tmov %s, %s\n",
15875 arch_reg_str(src_reg),
15876 arch_reg_str(dst_reg));
15879 /* Move from 32bit gprs to 8bit gprs */
15880 else if ((src_regcm & REGCM_GPR32) &&
15881 (dst_regcm & REGCM_GPR8)) {
15882 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15883 if ((src_reg != dst_reg) || !omit_copy) {
15884 fprintf(fp, "\tmov %s, %s\n",
15885 arch_reg_str(src_reg),
15886 arch_reg_str(dst_reg));
15889 /* Move from 16bit gprs to 8bit gprs */
15890 else if ((src_regcm & REGCM_GPR16) &&
15891 (dst_regcm & REGCM_GPR8)) {
15892 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
15893 if ((src_reg != dst_reg) || !omit_copy) {
15894 fprintf(fp, "\tmov %s, %s\n",
15895 arch_reg_str(src_reg),
15896 arch_reg_str(dst_reg));
15899 #endif /* X86_4_8BIT_GPRS */
15901 internal_error(state, ins, "unknown copy type");
15905 fprintf(fp, "\tmov ");
15906 print_const_val(state, src, fp);
15907 fprintf(fp, ", %s\n",
15908 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
15912 static void print_op_load(struct compile_state *state,
15913 struct triple *ins, FILE *fp)
15915 struct triple *dst, *src;
15918 if (is_const(src) || is_const(dst)) {
15919 internal_error(state, ins, "unknown load operation");
15921 fprintf(fp, "\tmov (%s), %s\n",
15922 reg(state, src, REGCM_GPR32),
15923 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
15927 static void print_op_store(struct compile_state *state,
15928 struct triple *ins, FILE *fp)
15930 struct triple *dst, *src;
15933 if (is_const(src) && (src->op == OP_INTCONST)) {
15935 value = (long_t)(src->u.cval);
15936 fprintf(fp, "\tmov%s $%ld, (%s)\n",
15937 type_suffix(state, src->type),
15939 reg(state, dst, REGCM_GPR32));
15941 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
15942 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
15943 type_suffix(state, src->type),
15944 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15948 if (is_const(src) || is_const(dst)) {
15949 internal_error(state, ins, "unknown store operation");
15951 fprintf(fp, "\tmov%s %s, (%s)\n",
15952 type_suffix(state, src->type),
15953 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15954 reg(state, dst, REGCM_GPR32));
15960 static void print_op_smul(struct compile_state *state,
15961 struct triple *ins, FILE *fp)
15963 if (!is_const(RHS(ins, 1))) {
15964 fprintf(fp, "\timul %s, %s\n",
15965 reg(state, RHS(ins, 1), REGCM_GPR32),
15966 reg(state, RHS(ins, 0), REGCM_GPR32));
15969 fprintf(fp, "\timul ");
15970 print_const_val(state, RHS(ins, 1), fp);
15971 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
15975 static void print_op_cmp(struct compile_state *state,
15976 struct triple *ins, FILE *fp)
15980 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15981 dreg = check_reg(state, ins, REGCM_FLAGS);
15982 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
15983 internal_error(state, ins, "bad dest register for cmp");
15985 if (is_const(RHS(ins, 1))) {
15986 fprintf(fp, "\tcmp ");
15987 print_const_val(state, RHS(ins, 1), fp);
15988 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
15991 unsigned lmask, rmask;
15993 lreg = check_reg(state, RHS(ins, 0), mask);
15994 rreg = check_reg(state, RHS(ins, 1), mask);
15995 lmask = arch_reg_regcm(state, lreg);
15996 rmask = arch_reg_regcm(state, rreg);
15997 mask = lmask & rmask;
15998 fprintf(fp, "\tcmp %s, %s\n",
15999 reg(state, RHS(ins, 1), mask),
16000 reg(state, RHS(ins, 0), mask));
16004 static void print_op_test(struct compile_state *state,
16005 struct triple *ins, FILE *fp)
16008 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16009 fprintf(fp, "\ttest %s, %s\n",
16010 reg(state, RHS(ins, 0), mask),
16011 reg(state, RHS(ins, 0), mask));
16014 static void print_op_branch(struct compile_state *state,
16015 struct triple *branch, FILE *fp)
16017 const char *bop = "j";
16018 if (branch->op == OP_JMP) {
16019 if (TRIPLE_RHS(branch->sizes) != 0) {
16020 internal_error(state, branch, "jmp with condition?");
16025 struct triple *ptr;
16026 if (TRIPLE_RHS(branch->sizes) != 1) {
16027 internal_error(state, branch, "jmpcc without condition?");
16029 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16030 if ((RHS(branch, 0)->op != OP_CMP) &&
16031 (RHS(branch, 0)->op != OP_TEST)) {
16032 internal_error(state, branch, "bad branch test");
16034 #warning "FIXME I have observed instructions between the test and branch instructions"
16035 ptr = RHS(branch, 0);
16036 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16037 if (ptr->op != OP_COPY) {
16038 internal_error(state, branch, "branch does not follow test");
16041 switch(branch->op) {
16042 case OP_JMP_EQ: bop = "jz"; break;
16043 case OP_JMP_NOTEQ: bop = "jnz"; break;
16044 case OP_JMP_SLESS: bop = "jl"; break;
16045 case OP_JMP_ULESS: bop = "jb"; break;
16046 case OP_JMP_SMORE: bop = "jg"; break;
16047 case OP_JMP_UMORE: bop = "ja"; break;
16048 case OP_JMP_SLESSEQ: bop = "jle"; break;
16049 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16050 case OP_JMP_SMOREEQ: bop = "jge"; break;
16051 case OP_JMP_UMOREEQ: bop = "jae"; break;
16053 internal_error(state, branch, "Invalid branch op");
16058 fprintf(fp, "\t%s L%s%lu\n",
16060 state->label_prefix,
16061 TARG(branch, 0)->u.cval);
16064 static void print_op_set(struct compile_state *state,
16065 struct triple *set, FILE *fp)
16067 const char *sop = "set";
16068 if (TRIPLE_RHS(set->sizes) != 1) {
16069 internal_error(state, set, "setcc without condition?");
16071 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16072 if ((RHS(set, 0)->op != OP_CMP) &&
16073 (RHS(set, 0)->op != OP_TEST)) {
16074 internal_error(state, set, "bad set test");
16076 if (RHS(set, 0)->next != set) {
16077 internal_error(state, set, "set does not follow test");
16080 case OP_SET_EQ: sop = "setz"; break;
16081 case OP_SET_NOTEQ: sop = "setnz"; break;
16082 case OP_SET_SLESS: sop = "setl"; break;
16083 case OP_SET_ULESS: sop = "setb"; break;
16084 case OP_SET_SMORE: sop = "setg"; break;
16085 case OP_SET_UMORE: sop = "seta"; break;
16086 case OP_SET_SLESSEQ: sop = "setle"; break;
16087 case OP_SET_ULESSEQ: sop = "setbe"; break;
16088 case OP_SET_SMOREEQ: sop = "setge"; break;
16089 case OP_SET_UMOREEQ: sop = "setae"; break;
16091 internal_error(state, set, "Invalid set op");
16094 fprintf(fp, "\t%s %s\n",
16095 sop, reg(state, set, REGCM_GPR8));
16098 static void print_op_bit_scan(struct compile_state *state,
16099 struct triple *ins, FILE *fp)
16103 case OP_BSF: op = "bsf"; break;
16104 case OP_BSR: op = "bsr"; break;
16106 internal_error(state, ins, "unknown bit scan");
16116 reg(state, RHS(ins, 0), REGCM_GPR32),
16117 reg(state, ins, REGCM_GPR32),
16118 reg(state, ins, REGCM_GPR32));
16121 static void print_const(struct compile_state *state,
16122 struct triple *ins, FILE *fp)
16126 switch(ins->type->type & TYPE_MASK) {
16129 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16133 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16139 fprintf(fp, ".int %lu\n", ins->u.cval);
16142 internal_error(state, ins, "Unknown constant type");
16147 unsigned char *blob;
16149 size = size_of(state, ins->type);
16150 blob = ins->u.blob;
16151 for(i = 0; i < size; i++) {
16152 fprintf(fp, ".byte 0x%02x\n",
16158 internal_error(state, ins, "Unknown constant type");
16163 #define TEXT_SECTION ".rom.text"
16164 #define DATA_SECTION ".rom.data"
16166 static void print_sdecl(struct compile_state *state,
16167 struct triple *ins, FILE *fp)
16169 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16170 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16171 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16172 print_const(state, MISC(ins, 0), fp);
16173 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16177 static void print_instruction(struct compile_state *state,
16178 struct triple *ins, FILE *fp)
16180 /* Assumption: after I have exted the register allocator
16181 * everything is in a valid register.
16185 print_op_asm(state, ins, fp);
16187 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16188 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16189 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16190 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16191 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16192 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16193 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16194 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16195 case OP_POS: break;
16196 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16197 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16201 /* Don't generate anything here for constants */
16203 /* Don't generate anything for variable declarations. */
16206 print_sdecl(state, ins, fp);
16210 print_op_move(state, ins, fp);
16213 print_op_load(state, ins, fp);
16216 print_op_store(state, ins, fp);
16219 print_op_smul(state, ins, fp);
16221 case OP_CMP: print_op_cmp(state, ins, fp); break;
16222 case OP_TEST: print_op_test(state, ins, fp); break;
16224 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16225 case OP_JMP_SLESS: case OP_JMP_ULESS:
16226 case OP_JMP_SMORE: case OP_JMP_UMORE:
16227 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16228 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16229 print_op_branch(state, ins, fp);
16231 case OP_SET_EQ: case OP_SET_NOTEQ:
16232 case OP_SET_SLESS: case OP_SET_ULESS:
16233 case OP_SET_SMORE: case OP_SET_UMORE:
16234 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16235 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16236 print_op_set(state, ins, fp);
16238 case OP_INB: case OP_INW: case OP_INL:
16239 print_op_in(state, ins, fp);
16241 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16242 print_op_out(state, ins, fp);
16246 print_op_bit_scan(state, ins, fp);
16249 after_lhs(state, ins);
16250 fprintf(fp, "\trdmsr\n");
16253 fprintf(fp, "\twrmsr\n");
16256 fprintf(fp, "\thlt\n");
16262 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16264 /* Ignore OP_PIECE */
16267 /* Operations I am not yet certain how to handle */
16269 case OP_SDIV: case OP_UDIV:
16270 case OP_SMOD: case OP_UMOD:
16271 /* Operations that should never get here */
16272 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16273 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16274 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16276 internal_error(state, ins, "unknown op: %d %s",
16277 ins->op, tops(ins->op));
16282 static void print_instructions(struct compile_state *state)
16284 struct triple *first, *ins;
16285 int print_location;
16288 const char *last_filename;
16290 print_location = 1;
16294 fp = state->output;
16295 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16296 first = RHS(state->main_function, 0);
16299 if (print_location &&
16300 ((last_filename != ins->filename) ||
16301 (last_line != ins->line) ||
16302 (last_col != ins->col))) {
16303 fprintf(fp, "\t/* %s:%d */\n",
16304 ins->filename, ins->line);
16305 last_filename = ins->filename;
16306 last_line = ins->line;
16307 last_col = ins->col;
16310 print_instruction(state, ins, fp);
16312 } while(ins != first);
16315 static void generate_code(struct compile_state *state)
16317 generate_local_labels(state);
16318 print_instructions(state);
16322 static void print_tokens(struct compile_state *state)
16325 tk = &state->token[0];
16330 next_token(state, 0);
16332 loc(stdout, state, 0);
16333 printf("%s <- `%s'\n",
16335 tk->ident ? tk->ident->name :
16336 tk->str_len ? tk->val.str : "");
16338 } while(tk->tok != TOK_EOF);
16341 static void compile(const char *filename, const char *ofilename,
16342 int cpu, int debug, int opt, const char *label_prefix)
16345 struct compile_state state;
16346 memset(&state, 0, sizeof(state));
16348 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16349 memset(&state.token[i], 0, sizeof(state.token[i]));
16350 state.token[i].tok = -1;
16352 /* Remember the debug settings */
16354 state.debug = debug;
16355 state.optimize = opt;
16356 /* Remember the output filename */
16357 state.ofilename = ofilename;
16358 state.output = fopen(state.ofilename, "w");
16359 if (!state.output) {
16360 error(&state, 0, "Cannot open output file %s\n",
16363 /* Remember the label prefix */
16364 state.label_prefix = label_prefix;
16365 /* Prep the preprocessor */
16366 state.if_depth = 0;
16367 state.if_value = 0;
16368 /* register the C keywords */
16369 register_keywords(&state);
16370 /* register the keywords the macro preprocessor knows */
16371 register_macro_keywords(&state);
16372 /* Memorize where some special keywords are. */
16373 state.i_continue = lookup(&state, "continue", 8);
16374 state.i_break = lookup(&state, "break", 5);
16375 /* Enter the globl definition scope */
16376 start_scope(&state);
16377 register_builtins(&state);
16378 compile_file(&state, filename, 1);
16380 print_tokens(&state);
16383 /* Exit the global definition scope */
16386 /* Now that basic compilation has happened
16387 * optimize the intermediate code
16391 generate_code(&state);
16393 fprintf(stderr, "done\n");
16397 static void version(void)
16399 printf("romcc " VERSION " released " RELEASE_DATE "\n");
16402 static void usage(void)
16406 "Usage: romcc <source>.c\n"
16407 "Compile a C source file without using ram\n"
16411 static void arg_error(char *fmt, ...)
16414 va_start(args, fmt);
16415 vfprintf(stderr, fmt, args);
16421 int main(int argc, char **argv)
16423 const char *filename;
16424 const char *ofilename;
16425 const char *label_prefix;
16432 ofilename = "auto.inc";
16436 while((argc > 1) && (argc != last_argc)) {
16438 if (strncmp(argv[1], "--debug=", 8) == 0) {
16439 debug = atoi(argv[1] + 8);
16443 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16444 label_prefix= argv[1] + 15;
16448 else if ((strcmp(argv[1],"-O") == 0) ||
16449 (strcmp(argv[1], "-O1") == 0)) {
16454 else if (strcmp(argv[1],"-O2") == 0) {
16459 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16460 ofilename = argv[2];
16464 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16465 cpu = arch_encode_cpu(argv[1] + 6);
16466 if (cpu == BAD_CPU) {
16467 arg_error("Invalid cpu specified: %s\n",
16475 arg_error("Wrong argument count %d\n", argc);
16477 filename = argv[1];
16478 compile(filename, ofilename, cpu, debug, optimize, label_prefix);