15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
18 #define X86_4_8BIT_GPRS 1
20 #warning "FIXME static constant variables"
21 #warning "FIXME enable pointers"
22 #warning "FIXME enable string constants"
24 /* Control flow graph of a loop without goto.
35 * |\ GGG HHH | continue;
63 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
67 * [] == DFlocal(X) U DF(X)
70 * Dominator graph of the same nodes.
74 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
76 * CCC CCC: [ ] ( BBB, JJJ )
78 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
80 * FFF FFF: [ ] ( BBB )
82 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
87 * BBB and JJJ are definitely the dominance frontier.
88 * Where do I place phi functions and how do I make that decision.
91 static void die(char *fmt, ...)
96 vfprintf(stderr, fmt, args);
103 #define MALLOC_STRONG_DEBUG
104 static void *xmalloc(size_t size, const char *name)
109 die("Cannot malloc %ld bytes to hold %s: %s\n",
110 size + 0UL, name, strerror(errno));
115 static void *xcmalloc(size_t size, const char *name)
118 buf = xmalloc(size, name);
119 memset(buf, 0, size);
123 static void xfree(const void *ptr)
128 static char *xstrdup(const char *str)
133 new = xmalloc(len + 1, "xstrdup string");
134 memcpy(new, str, len);
139 static void xchdir(const char *path)
141 if (chdir(path) != 0) {
142 die("chdir to %s failed: %s\n",
143 path, strerror(errno));
147 static int exists(const char *dirname, const char *filename)
151 if (access(filename, O_RDONLY) < 0) {
152 if ((errno != EACCES) && (errno != EROFS)) {
160 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
164 off_t size, progress;
173 fd = open(filename, O_RDONLY);
175 die("Cannot open '%s' : %s\n",
176 filename, strerror(errno));
178 result = fstat(fd, &stats);
180 die("Cannot stat: %s: %s\n",
181 filename, strerror(errno));
183 size = stats.st_size;
185 buf = xmalloc(size +2, filename);
186 buf[size] = '\n'; /* Make certain the file is newline terminated */
187 buf[size+1] = '\0'; /* Null terminate the file for good measure */
189 while(progress < size) {
190 result = read(fd, buf + progress, size - progress);
192 if ((errno == EINTR) || (errno == EAGAIN))
194 die("read on %s of %ld bytes failed: %s\n",
195 filename, (size - progress)+ 0UL, strerror(errno));
201 die("Close of %s failed: %s\n",
202 filename, strerror(errno));
207 /* Long on the destination platform */
208 typedef unsigned long ulong_t;
212 struct file_state *prev;
213 const char *basename;
224 struct hash_entry *ident;
232 /* I have two classes of types:
234 * Logical types. (The type the C standard says the operation is of)
236 * The operational types are:
251 * No memory is useable by the compiler.
252 * There is no floating point support.
253 * All operations take place in general purpose registers.
254 * There is one type of general purpose register.
255 * Unsigned longs are stored in that general purpose register.
258 /* Operations on general purpose registers.
275 #define OP_POS 14 /* Dummy positive operator don't use it */
285 #define OP_SLESSEQ 26
286 #define OP_ULESSEQ 27
287 #define OP_SMOREEQ 28
288 #define OP_UMOREEQ 29
290 #define OP_LFALSE 30 /* Test if the expression is logically false */
291 #define OP_LTRUE 31 /* Test if the expression is logcially true */
298 #define OP_MIN_CONST 50
299 #define OP_MAX_CONST 59
300 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
301 #define OP_INTCONST 50
302 #define OP_BLOBCONST 51
303 /* For OP_BLOBCONST ->type holds the layout and size
304 * information. u.blob holds a pointer to the raw binary
305 * data for the constant initializer.
307 #define OP_ADDRCONST 52
308 /* For OP_ADDRCONST ->type holds the type.
309 * RHS(0) holds the reference to the static variable.
310 * ->u.cval holds an offset from that value.
314 /* OP_WRITE moves one pseudo register to another.
315 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
316 * RHS(0) holds the psuedo to move.
320 /* OP_READ reads the value of a variable and makes
321 * it available for the pseudo operation.
322 * Useful for things like def-use chains.
323 * RHS(0) holds points to the triple to read from.
326 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
329 /* OP_PIECE returns one piece of a instruction that returns a structure.
330 * RHS(0) is the instruction
331 * u.cval is the LHS piece of the instruction to return.
335 /* OP_DEREF generates an lvalue from a pointer.
336 * RHS(0) holds the pointer value.
337 * OP_DEREF serves as a place holder to indicate all necessary
338 * checks have been done to indicate a value is an lvalue.
341 /* OP_DOT references a submember of a structure lvalue.
342 * RHS(0) holds the lvalue.
343 * ->u.field holds the name of the field we want.
345 * Not seen outside of expressions.
348 /* OP_VAL returns the value of a subexpression of the current expression.
349 * Useful for operators that have side effects.
350 * RHS(0) holds the expression.
351 * MISC(0) holds the subexpression of RHS(0) that is the
352 * value of the expression.
354 * Not seen outside of expressions.
357 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
358 * Not seen outside of expressions.
361 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
362 * Not seen outside of expressions.
365 /* OP_CODE performas a C ? : operation.
366 * RHS(0) holds the test.
367 * RHS(1) holds the expression to evaluate if the test returns true.
368 * RHS(2) holds the expression to evaluate if the test returns false.
369 * Not seen outside of expressions.
372 /* OP_COMMA performacs a C comma operation.
373 * That is RHS(0) is evaluated, then RHS(1)
374 * and the value of RHS(1) is returned.
375 * Not seen outside of expressions.
379 /* OP_CALL performs a procedure call.
380 * MISC(0) holds a pointer to the OP_LIST of a function
381 * RHS(x) holds argument x of a function
383 * Currently not seen outside of expressions.
385 #define OP_VAL_VEC 74
386 /* OP_VAL_VEC is an array of triples that are either variable
387 * or values for a structure or an array.
388 * RHS(x) holds element x of the vector.
389 * triple->type->elements holds the size of the vector.
394 /* OP_LIST Holds a list of statements, and a result value.
395 * RHS(0) holds the list of statements.
396 * MISC(0) holds the value of the statements.
399 #define OP_BRANCH 81 /* branch */
400 /* For branch instructions
401 * TARG(0) holds the branch target.
402 * RHS(0) if present holds the branch condition.
403 * ->next holds where to branch to if the branch is not taken.
404 * The branch target can only be a decl...
408 /* OP_LABEL is a triple that establishes an target for branches.
409 * ->use is the list of all branches that use this label.
413 /* OP_DECL is a triple that establishes an lvalue for assignments.
414 * ->use is a list of statements that use the variable.
418 /* OP_VAR is a triple that establishes a variable of static
420 * ->use is a list of statements that use the variable.
421 * MISC(0) holds the initializer expression.
426 /* OP_PHI is a triple used in SSA form code.
427 * It is used when multiple code paths merge and a variable needs
428 * a single assignment from any of those code paths.
429 * The operation is a cross between OP_DECL and OP_WRITE, which
430 * is what OP_PHI is geneared from.
432 * RHS(x) points to the value from code path x
433 * The number of RHS entries is the number of control paths into the block
434 * in which OP_PHI resides. The elements of the array point to point
435 * to the variables OP_PHI is derived from.
437 * MISC(0) holds a pointer to the orginal OP_DECL node.
440 /* Architecture specific instructions */
443 #define OP_SET_EQ 102
444 #define OP_SET_NOTEQ 103
445 #define OP_SET_SLESS 104
446 #define OP_SET_ULESS 105
447 #define OP_SET_SMORE 106
448 #define OP_SET_UMORE 107
449 #define OP_SET_SLESSEQ 108
450 #define OP_SET_ULESSEQ 109
451 #define OP_SET_SMOREEQ 110
452 #define OP_SET_UMOREEQ 111
455 #define OP_JMP_EQ 113
456 #define OP_JMP_NOTEQ 114
457 #define OP_JMP_SLESS 115
458 #define OP_JMP_ULESS 116
459 #define OP_JMP_SMORE 117
460 #define OP_JMP_UMORE 118
461 #define OP_JMP_SLESSEQ 119
462 #define OP_JMP_ULESSEQ 120
463 #define OP_JMP_SMOREEQ 121
464 #define OP_JMP_UMOREEQ 122
466 /* Builtin operators that it is just simpler to use the compiler for */
484 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
486 unsigned char lhs, rhs, misc, targ;
489 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
497 static const struct op_info table_ops[] = {
498 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF, "smul"),
499 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF, "umul"),
500 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF, "sdiv"),
501 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF, "udiv"),
502 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF, "smod"),
503 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF, "umod"),
504 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF, "add"),
505 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF, "sub"),
506 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF, "sl"),
507 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF, "usr"),
508 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF, "ssr"),
509 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF, "and"),
510 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF, "xor"),
511 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF, "or"),
512 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF, "pos"),
513 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF, "neg"),
514 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF, "invert"),
516 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF, "eq"),
517 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "noteq"),
518 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF, "sless"),
519 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF, "uless"),
520 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF, "smore"),
521 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF, "umore"),
522 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "slesseq"),
523 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "ulesseq"),
524 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "smoreeq"),
525 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "umoreeq"),
526 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF, "lfalse"),
527 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF, "ltrue"),
529 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF, "load"),
530 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE, "store"),
532 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE, "noop"),
534 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE, "intconst"),
535 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
536 [OP_ADDRCONST ] = OP( 0, 1, 0, 0, PURE, "addrconst"),
538 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE, "write"),
539 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF, "read"),
540 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF, "copy"),
541 [OP_PIECE ] = OP( 0, 1, 0, 0, PURE | DEF, "piece"),
542 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF, "deref"),
543 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF, "dot"),
545 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF, "val"),
546 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF, "land"),
547 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF, "lor"),
548 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF, "cond"),
549 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF, "comma"),
550 /* Call is special most it can stand in for anything so it depends on context */
551 [OP_CALL ] = OP(-1, -1, 1, 0, 0, "call"),
552 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
553 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0, "valvec"),
555 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
556 /* The number of targets for OP_BRANCH depends on context */
557 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE, "branch"),
558 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE, "label"),
559 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE, "adecl"),
560 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE, "sdecl"),
561 /* The number of RHS elements of OP_PHI depend upon context */
562 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF, "phi"),
564 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF, "cmp"),
565 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF, "test"),
566 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF, "set_eq"),
567 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF, "set_noteq"),
568 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF, "set_sless"),
569 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF, "set_uless"),
570 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF, "set_smore"),
571 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF, "set_umore"),
572 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_slesseq"),
573 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_ulesseq"),
574 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_smoreq"),
575 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_umoreq"),
576 [OP_JMP ] = OP( 0, 0, 0, 1, PURE, "jmp"),
577 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE, "jmp_eq"),
578 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE, "jmp_noteq"),
579 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE, "jmp_sless"),
580 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE, "jmp_uless"),
581 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE, "jmp_smore"),
582 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE, "jmp_umore"),
583 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE, "jmp_slesseq"),
584 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE, "jmp_ulesseq"),
585 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE, "jmp_smoreq"),
586 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE, "jmp_umoreq"),
588 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inb"),
589 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inw"),
590 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inl"),
591 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE, "__outb"),
592 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE, "__outw"),
593 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE, "__outl"),
594 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF, "__bsf"),
595 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF, "__bsr"),
596 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE, "__rdmsr"),
597 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE, "__wrmsr"),
598 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE, "__hlt"),
601 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
603 static const char *tops(int index)
605 static const char unknown[] = "unknown op";
609 if (index > OP_MAX) {
612 return table_ops[index].name;
618 struct triple_set *next;
619 struct triple *member;
628 struct triple *next, *prev;
629 struct triple_set *use;
632 unsigned short sizes;
633 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
634 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
635 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
636 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
637 #define TRIPLE_SIZE(SIZES) \
638 ((((SIZES) >> 0) & 0x0f) + \
639 (((SIZES) >> 4) & 0x0f) + \
640 (((SIZES) >> 8) & 0x0f) + \
641 (((SIZES) >> 12) & 0x0f))
642 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
643 ((((LHS) & 0x0f) << 0) | \
644 (((RHS) & 0x0f) << 4) | \
645 (((MISC) & 0x0f) << 8) | \
646 (((TARG) & 0x0f) << 12))
647 #define TRIPLE_LHS_OFF(SIZES) (0)
648 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
649 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
650 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
651 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
652 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
653 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
654 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
655 unsigned id; /* A scratch value and finally the register */
656 #define TRIPLE_FLAG_FLATTENED 1
657 const char *filename;
664 struct hash_entry *field;
666 struct triple *param[2];
670 struct block_set *next;
671 struct block *member;
674 struct block *work_next;
675 struct block *left, *right;
676 struct triple *first, *last;
678 struct block_set *use;
679 struct block_set *idominates;
680 struct block_set *domfrontier;
682 struct block_set *ipdominates;
683 struct block_set *ipdomfrontier;
691 struct hash_entry *ident;
698 struct hash_entry *ident;
704 struct hash_entry *next;
708 struct macro *sym_define;
709 struct symbol *sym_label;
710 struct symbol *sym_struct;
711 struct symbol *sym_ident;
714 #define HASH_TABLE_SIZE 2048
716 struct compile_state {
718 struct file_state *file;
719 struct token token[4];
720 struct hash_entry *hash_table[HASH_TABLE_SIZE];
721 struct hash_entry *i_continue;
722 struct hash_entry *i_break;
724 int if_depth, if_value;
726 struct file_state *macro_file;
727 struct triple *main_function;
728 struct block *first_block, *last_block;
734 /* visibility global/local */
735 /* static/auto duration */
736 /* typedef, register, inline */
738 #define STOR_MASK 0x000f
740 #define STOR_GLOBAL 0x0001
742 #define STOR_PERM 0x0002
743 /* Storage specifiers */
744 #define STOR_AUTO 0x0000
745 #define STOR_STATIC 0x0002
746 #define STOR_EXTERN 0x0003
747 #define STOR_REGISTER 0x0004
748 #define STOR_TYPEDEF 0x0008
749 #define STOR_INLINE 0x000c
752 #define QUAL_MASK 0x0070
753 #define QUAL_NONE 0x0000
754 #define QUAL_CONST 0x0010
755 #define QUAL_VOLATILE 0x0020
756 #define QUAL_RESTRICT 0x0040
759 #define TYPE_MASK 0x1f00
760 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
761 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
762 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
763 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
764 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
765 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
766 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
767 #define TYPE_DEFAULT 0x0000
768 #define TYPE_VOID 0x0100
769 #define TYPE_CHAR 0x0200
770 #define TYPE_UCHAR 0x0300
771 #define TYPE_SHORT 0x0400
772 #define TYPE_USHORT 0x0500
773 #define TYPE_INT 0x0600
774 #define TYPE_UINT 0x0700
775 #define TYPE_LONG 0x0800
776 #define TYPE_ULONG 0x0900
777 #define TYPE_LLONG 0x0a00 /* long long */
778 #define TYPE_ULLONG 0x0b00
779 #define TYPE_FLOAT 0x0c00
780 #define TYPE_DOUBLE 0x0d00
781 #define TYPE_LDOUBLE 0x0e00 /* long double */
782 #define TYPE_STRUCT 0x1000
783 #define TYPE_ENUM 0x1100
784 #define TYPE_POINTER 0x1200
786 * type->left holds the type pointed to.
788 #define TYPE_FUNCTION 0x1300
789 /* For TYPE_FUNCTION:
790 * type->left holds the return type.
791 * type->right holds the...
793 #define TYPE_PRODUCT 0x1400
794 /* TYPE_PRODUCT is a basic building block when defining structures
795 * type->left holds the type that appears first in memory.
796 * type->right holds the type that appears next in memory.
798 #define TYPE_OVERLAP 0x1500
799 /* TYPE_OVERLAP is a basic building block when defining unions
800 * type->left and type->right holds to types that overlap
801 * each other in memory.
803 #define TYPE_ARRAY 0x1600
804 /* TYPE_ARRAY is a basic building block when definitng arrays.
805 * type->left holds the type we are an array of.
806 * type-> holds the number of elements.
809 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
813 struct type *left, *right;
815 struct hash_entry *field_ident;
816 struct hash_entry *type_ident;
819 #define MAX_REGISTERS 75
820 #define MAX_REG_EQUIVS 16
824 /* Provision for 8 register classes */
825 #define REGC_MASK ((1 << MAX_REGC) - 1)
826 #define ID_REG_CLASSES(ID) ((ID) & REGC_MASK)
827 #define ID_REG(ID) ((ID) >> MAX_REGC)
828 #define MK_REG_ID(REG, CLASSES) (((REG) << MAX_REGC) | ((CLASSES) & REGC_MASK))
830 static unsigned alloc_virtual_reg(void)
832 static unsigned virtual_reg = MAX_REGISTERS;
837 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
838 static void arch_reg_equivs(
839 struct compile_state *state, unsigned *equiv, int reg);
840 static int arch_select_free_register(
841 struct compile_state *state, char *used, int classes);
842 static unsigned arch_regc_size(struct compile_state *state, int class);
843 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
844 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
845 static const char *arch_reg_str(int reg);
847 #define DEBUG_ABORT_ON_ERROR 0x0001
848 #define DEBUG_INTERMEDIATE_CODE 0x0002
849 #define DEBUG_CONTROL_FLOW 0x0004
850 #define DEBUG_BASIC_BLOCKS 0x0008
851 #define DEBUG_FDOMINATORS 0x0010
852 #define DEBUG_RDOMINATORS 0x0020
853 #define DEBUG_TRIPLES 0x0040
854 #define DEBUG_INTERFERENCE 0x0080
855 #define DEBUG_ARCH_CODE 0x0100
856 #define DEBUG_CODE_ELIMINATION 0x0200
858 #define GLOBAL_SCOPE_DEPTH 1
860 static void compile_file(struct compile_state *old_state, char *filename, int local);
862 static int get_col(struct file_state *file)
866 ptr = file->line_start;
868 for(col = 0; ptr < end; ptr++) {
873 col = (col & ~7) + 8;
879 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
883 fprintf(fp, "%s:%d.%d: ",
884 triple->filename, triple->line, triple->col);
890 col = get_col(state->file);
891 fprintf(fp, "%s:%d.%d: ",
892 state->file->basename, state->file->line, col);
895 static void __internal_error(struct compile_state *state, struct triple *ptr,
900 loc(stderr, state, ptr);
901 fprintf(stderr, "Internal compiler error: ");
902 vfprintf(stderr, fmt, args);
903 fprintf(stderr, "\n");
909 static void __internal_warning(struct compile_state *state, struct triple *ptr,
914 loc(stderr, state, ptr);
915 fprintf(stderr, "Internal compiler warning: ");
916 vfprintf(stderr, fmt, args);
917 fprintf(stderr, "\n");
923 static void __error(struct compile_state *state, struct triple *ptr,
928 loc(stderr, state, ptr);
929 vfprintf(stderr, fmt, args);
931 fprintf(stderr, "\n");
932 if (state->debug & DEBUG_ABORT_ON_ERROR) {
938 static void __warning(struct compile_state *state, struct triple *ptr,
943 loc(stderr, state, ptr);
944 fprintf(stderr, "warning: ");
945 vfprintf(stderr, fmt, args);
946 fprintf(stderr, "\n");
950 #if DEBUG_ERROR_MESSAGES
951 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
952 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
953 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
954 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
956 # define internal_error __internal_error
957 # define internal_warning __internal_warning
958 # define error __error
959 # define warning __warning
961 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
964 static void valid_op(struct compile_state *state, int op)
966 char *fmt = "invalid op: %d";
968 internal_error(state, 0, fmt, op);
971 internal_error(state, 0, fmt, op);
975 static void valid_ins(struct compile_state *state, struct triple *ptr)
977 valid_op(state, ptr->op);
980 static void process_trigraphs(struct compile_state *state)
982 char *src, *dest, *end;
983 struct file_state *file;
985 src = dest = file->buf;
986 end = file->buf + file->size;
987 while((end - src) >= 3) {
988 if ((src[0] == '?') && (src[1] == '?')) {
991 case '=': c = '#'; break;
992 case '/': c = '\\'; break;
993 case '\'': c = '^'; break;
994 case '(': c = '['; break;
995 case ')': c = ']'; break;
996 case '!': c = '!'; break;
997 case '<': c = '{'; break;
998 case '>': c = '}'; break;
999 case '-': c = '~'; break;
1016 file->size = dest - file->buf;
1019 static void splice_lines(struct compile_state *state)
1021 char *src, *dest, *end;
1022 struct file_state *file;
1024 src = dest = file->buf;
1025 end = file->buf + file->size;
1026 while((end - src) >= 2) {
1027 if ((src[0] == '\\') && (src[1] == '\n')) {
1037 file->size = dest - file->buf;
1040 static struct type void_type;
1041 static void use_triple(struct triple *used, struct triple *user)
1043 struct triple_set **ptr, *new;
1050 if ((*ptr)->member == user) {
1053 ptr = &(*ptr)->next;
1055 /* Append new to the head of the list,
1056 * copy_func and rename_block_variables
1059 new = xcmalloc(sizeof(*new), "triple_set");
1061 new->next = used->use;
1065 static void unuse_triple(struct triple *used, struct triple *unuser)
1067 struct triple_set *use, **ptr;
1071 if (use->member == unuser) {
1081 static void push_triple(struct triple *used, struct triple *user)
1083 struct triple_set *new;
1088 /* Append new to the head of the list,
1089 * it's the only sensible behavoir for a stack.
1091 new = xcmalloc(sizeof(*new), "triple_set");
1093 new->next = used->use;
1097 static void pop_triple(struct triple *used, struct triple *unuser)
1099 struct triple_set *use, **ptr;
1103 if (use->member == unuser) {
1106 /* Only free one occurance from the stack */
1116 /* The zero triple is used as a place holder when we are removing pointers
1117 * from a triple. Having allows certain sanity checks to pass even
1118 * when the original triple that was pointed to is gone.
1120 static struct triple zero_triple = {
1121 .next = &zero_triple,
1122 .prev = &zero_triple,
1125 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1126 .id = -1, /* An invalid id */
1127 .u = { .cval = 0, },
1128 .filename = __FILE__,
1131 .param { [0] = 0, [1] = 0, },
1135 static unsigned short triple_sizes(struct compile_state *state,
1136 int op, struct type *type, int rhs_wanted)
1138 int lhs, rhs, misc, targ;
1139 valid_op(state, op);
1140 lhs = table_ops[op].lhs;
1141 rhs = table_ops[op].rhs;
1142 misc = table_ops[op].misc;
1143 targ = table_ops[op].targ;
1146 if (op == OP_CALL) {
1149 param = type->right;
1150 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1152 param = param->right;
1154 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1158 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1159 lhs = type->left->elements;
1162 else if (op == OP_VAL_VEC) {
1163 rhs = type->elements;
1165 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1168 if ((rhs < 0) || (rhs > MAX_RHS)) {
1169 internal_error(state, 0, "bad rhs");
1171 if ((lhs < 0) || (lhs > MAX_LHS)) {
1172 internal_error(state, 0, "bad lhs");
1174 if ((misc < 0) || (misc > MAX_MISC)) {
1175 internal_error(state, 0, "bad misc");
1177 if ((targ < 0) || (targ > MAX_TARG)) {
1178 internal_error(state, 0, "bad targs");
1180 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1183 static struct triple *alloc_triple(struct compile_state *state,
1184 int op, struct type *type, int rhs,
1185 const char *filename, int line, int col)
1187 size_t size, sizes, extra_count, min_count;
1189 sizes = triple_sizes(state, op, type, rhs);
1191 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1192 extra_count = TRIPLE_SIZE(sizes);
1193 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1195 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1196 ret = xcmalloc(size, "tripple");
1202 ret->filename = filename;
1208 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1212 src_rhs = TRIPLE_RHS(src->sizes);
1213 dup = alloc_triple(state, src->op, src->type, src_rhs,
1214 src->filename, src->line, src->col);
1215 memcpy(dup, src, sizeof(*src));
1216 memcpy(dup->param, src->param, src_rhs * sizeof(src->param[0]));
1220 static struct triple *new_triple(struct compile_state *state,
1221 int op, struct type *type, int rhs)
1224 const char *filename;
1230 filename = state->file->basename;
1231 line = state->file->line;
1232 col = get_col(state->file);
1234 ret = alloc_triple(state, op, type, rhs,
1235 filename, line, col);
1239 static struct triple *build_triple(struct compile_state *state,
1240 int op, struct type *type, struct triple *left, struct triple *right,
1241 const char *filename, int line, int col)
1245 ret = alloc_triple(state, op, type, -1, filename, line, col);
1246 count = TRIPLE_SIZE(ret->sizes);
1248 ret->param[0] = left;
1251 ret->param[1] = right;
1256 static struct triple *triple(struct compile_state *state,
1257 int op, struct type *type, struct triple *left, struct triple *right)
1261 ret = new_triple(state, op, type, -1);
1262 count = TRIPLE_SIZE(ret->sizes);
1264 ret->param[0] = left;
1267 ret->param[1] = right;
1272 static struct triple *branch(struct compile_state *state,
1273 struct triple *targ, struct triple *test)
1276 ret = new_triple(state, OP_BRANCH, &void_type, test?1:0);
1280 TARG(ret, 0) = targ;
1281 /* record the branch target was used */
1282 if (!targ || (targ->op != OP_LABEL)) {
1283 internal_error(state, 0, "branch not to label");
1284 use_triple(targ, ret);
1290 static void insert_triple(struct compile_state *state,
1291 struct triple *first, struct triple *ptr)
1294 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1295 internal_error(state, ptr, "expression already used");
1298 ptr->prev = first->prev;
1299 ptr->prev->next = ptr;
1300 ptr->next->prev = ptr;
1301 if ((ptr->prev->op == OP_BRANCH) &&
1302 TRIPLE_RHS(ptr->prev->sizes)) {
1303 unuse_triple(first, ptr->prev);
1304 use_triple(ptr, ptr->prev);
1309 static struct triple *pre_triple(struct compile_state *state,
1310 struct triple *base,
1311 int op, struct type *type, struct triple *left, struct triple *right)
1313 /* Careful this assumes it can do the easy thing to get the block */
1315 ret = build_triple(state, op, type, left, right,
1316 base->filename, base->line, base->col);
1317 ret->u.block = base->u.block;
1318 insert_triple(state, base, ret);
1322 static struct triple *post_triple(struct compile_state *state,
1323 struct triple *base,
1324 int op, struct type *type, struct triple *left, struct triple *right)
1326 /* Careful this assumes it can do the easy thing to get the block */
1328 ret = build_triple(state, op, type, left, right,
1329 base->filename, base->line, base->col);
1330 ret->u.block = base->u.block;
1331 insert_triple(state, base->next, ret);
1335 static struct triple *label(struct compile_state *state)
1337 /* Labels don't get a type */
1338 struct triple *result;
1339 result = triple(state, OP_LABEL, &void_type, 0, 0);
1343 static void display_triple(FILE *fp, struct triple *ins)
1345 if (ins->op == OP_INTCONST) {
1346 fprintf(fp, "(%p) %3d %-10s 0x%08lx @ %s:%d.%d\n",
1347 ins, ID_REG(ins->id), tops(ins->op), ins->u.cval,
1348 ins->filename, ins->line, ins->col);
1350 else if (ins->op == OP_SDECL) {
1351 fprintf(fp, "(%p) %3d %-10s %-10p @ %s:%d.%d\n",
1352 ins, ID_REG(ins->id), tops(ins->op), MISC(ins, 0),
1353 ins->filename, ins->line, ins->col);
1355 print_ins(state, MISC(ins, 0));
1360 fprintf(fp, "(%p) %3d %-10s",
1361 ins, ID_REG(ins->id), tops(ins->op));
1362 count = TRIPLE_SIZE(ins->sizes);
1363 for(i = 0; i < count; i++) {
1364 fprintf(fp, " %-10p", ins->param[i]);
1369 fprintf(fp, " @ %s:%d.%d\n",
1370 ins->filename, ins->line, ins->col);
1375 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1377 /* Does the triple have no side effects.
1378 * I.e. Rexecuting the triple with the same arguments
1379 * gives the same value.
1382 valid_ins(state, ins);
1383 pure = PURE_BITS(table_ops[ins->op].flags);
1384 if ((pure != PURE) && (pure != IMPURE)) {
1385 internal_error(state, 0, "Purity of %s not known\n",
1388 return pure == PURE;
1391 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1393 /* This function is used to determine which triples need
1397 valid_ins(state, ins);
1398 is_branch = (table_ops[ins->op].targ != 0);
1402 static int triple_is_def(struct compile_state *state, struct triple *ins)
1404 /* This function is used to determine which triples need
1408 valid_ins(state, ins);
1409 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1413 static struct triple **triple_iter(struct compile_state *state,
1414 size_t count, struct triple **vector,
1415 struct triple *ins, struct triple **last)
1417 struct triple **ret;
1423 else if ((last >= vector) && (last < (vector + count - 1))) {
1431 static struct triple **triple_lhs(struct compile_state *state,
1432 struct triple *ins, struct triple **last)
1434 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1438 static struct triple **triple_rhs(struct compile_state *state,
1439 struct triple *ins, struct triple **last)
1441 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1445 static struct triple **triple_misc(struct compile_state *state,
1446 struct triple *ins, struct triple **last)
1448 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1451 static struct triple **triple_targ(struct compile_state *state,
1452 struct triple *ins, struct triple **last)
1454 return triple_iter(state, TRIPLE_TARG(ins->sizes), &TARG(ins,0),
1458 static void free_triple(struct compile_state *state, struct triple *ptr)
1461 size = sizeof(*ptr) - sizeof(ptr->param) +
1462 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1463 ptr->prev->next = ptr->next;
1464 ptr->next->prev = ptr->prev;
1466 internal_error(state, ptr, "ptr->use != 0");
1468 memset(ptr, -1, size);
1472 static void release_triple(struct compile_state *state, struct triple *ptr)
1474 struct triple_set *set, *next;
1475 struct triple **expr;
1476 /* Remove ptr from use chains where it is the user */
1477 expr = triple_rhs(state, ptr, 0);
1478 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1480 unuse_triple(*expr, ptr);
1483 expr = triple_lhs(state, ptr, 0);
1484 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1486 unuse_triple(*expr, ptr);
1489 expr = triple_targ(state, ptr, 0);
1490 for(; expr; expr = triple_targ(state, ptr, expr)) {
1492 unuse_triple(*expr, ptr);
1495 /* Reomve ptr from use chains where it is used */
1496 for(set = ptr->use; set; set = next) {
1498 expr = triple_rhs(state, set->member, 0);
1499 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1501 *expr = &zero_triple;
1504 expr = triple_lhs(state, set->member, 0);
1505 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1507 *expr = &zero_triple;
1510 expr = triple_targ(state, set->member, 0);
1511 for(; expr; expr = triple_targ(state, set->member, expr)) {
1513 *expr = &zero_triple;
1516 unuse_triple(ptr, set->member);
1518 free_triple(state, ptr);
1521 static void print_triple(struct compile_state *state, struct triple *ptr);
1523 #define TOK_UNKNOWN 0
1526 #define TOK_LBRACE 3
1527 #define TOK_RBRACE 4
1531 #define TOK_LBRACKET 8
1532 #define TOK_RBRACKET 9
1533 #define TOK_LPAREN 10
1534 #define TOK_RPAREN 11
1539 #define TOK_TIMESEQ 16
1540 #define TOK_DIVEQ 17
1541 #define TOK_MODEQ 18
1542 #define TOK_PLUSEQ 19
1543 #define TOK_MINUSEQ 20
1546 #define TOK_ANDEQ 23
1547 #define TOK_XOREQ 24
1550 #define TOK_NOTEQ 27
1551 #define TOK_QUEST 28
1552 #define TOK_LOGOR 29
1553 #define TOK_LOGAND 30
1557 #define TOK_LESSEQ 34
1558 #define TOK_MOREEQ 35
1562 #define TOK_MINUS 39
1565 #define TOK_PLUSPLUS 42
1566 #define TOK_MINUSMINUS 43
1568 #define TOK_ARROW 45
1570 #define TOK_TILDE 47
1571 #define TOK_LIT_STRING 48
1572 #define TOK_LIT_CHAR 49
1573 #define TOK_LIT_INT 50
1574 #define TOK_LIT_FLOAT 51
1575 #define TOK_MACRO 52
1576 #define TOK_CONCATENATE 53
1578 #define TOK_IDENT 54
1579 #define TOK_STRUCT_NAME 55
1580 #define TOK_ENUM_CONST 56
1581 #define TOK_TYPE_NAME 57
1584 #define TOK_BREAK 59
1587 #define TOK_CONST 62
1588 #define TOK_CONTINUE 63
1589 #define TOK_DEFAULT 64
1591 #define TOK_DOUBLE 66
1594 #define TOK_EXTERN 69
1595 #define TOK_FLOAT 70
1599 #define TOK_INLINE 74
1602 #define TOK_REGISTER 77
1603 #define TOK_RESTRICT 78
1604 #define TOK_RETURN 79
1605 #define TOK_SHORT 80
1606 #define TOK_SIGNED 81
1607 #define TOK_SIZEOF 82
1608 #define TOK_STATIC 83
1609 #define TOK_STRUCT 84
1610 #define TOK_SWITCH 85
1611 #define TOK_TYPEDEF 86
1612 #define TOK_UNION 87
1613 #define TOK_UNSIGNED 88
1615 #define TOK_VOLATILE 90
1616 #define TOK_WHILE 91
1618 #define TOK_ATTRIBUTE 93
1619 #define TOK_ALIGNOF 94
1620 #define TOK_FIRST_KEYWORD TOK_AUTO
1621 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1623 #define TOK_DEFINE 100
1624 #define TOK_UNDEF 101
1625 #define TOK_INCLUDE 102
1626 #define TOK_LINE 103
1627 #define TOK_ERROR 104
1628 #define TOK_WARNING 105
1629 #define TOK_PRAGMA 106
1630 #define TOK_IFDEF 107
1631 #define TOK_IFNDEF 108
1632 #define TOK_ELIF 109
1633 #define TOK_ENDIF 110
1635 #define TOK_FIRST_MACRO TOK_DEFINE
1636 #define TOK_LAST_MACRO TOK_ENDIF
1640 static const char *tokens[] = {
1641 [TOK_UNKNOWN ] = "unknown",
1642 [TOK_SPACE ] = ":space:",
1644 [TOK_LBRACE ] = "{",
1645 [TOK_RBRACE ] = "}",
1649 [TOK_LBRACKET ] = "[",
1650 [TOK_RBRACKET ] = "]",
1651 [TOK_LPAREN ] = "(",
1652 [TOK_RPAREN ] = ")",
1654 [TOK_DOTS ] = "...",
1657 [TOK_TIMESEQ ] = "*=",
1658 [TOK_DIVEQ ] = "/=",
1659 [TOK_MODEQ ] = "%=",
1660 [TOK_PLUSEQ ] = "+=",
1661 [TOK_MINUSEQ ] = "-=",
1662 [TOK_SLEQ ] = "<<=",
1663 [TOK_SREQ ] = ">>=",
1664 [TOK_ANDEQ ] = "&=",
1665 [TOK_XOREQ ] = "^=",
1668 [TOK_NOTEQ ] = "!=",
1670 [TOK_LOGOR ] = "||",
1671 [TOK_LOGAND ] = "&&",
1675 [TOK_LESSEQ ] = "<=",
1676 [TOK_MOREEQ ] = ">=",
1683 [TOK_PLUSPLUS ] = "++",
1684 [TOK_MINUSMINUS ] = "--",
1686 [TOK_ARROW ] = "->",
1689 [TOK_LIT_STRING ] = ":string:",
1690 [TOK_IDENT ] = ":ident:",
1691 [TOK_TYPE_NAME ] = ":typename:",
1692 [TOK_LIT_CHAR ] = ":char:",
1693 [TOK_LIT_INT ] = ":integer:",
1694 [TOK_LIT_FLOAT ] = ":float:",
1696 [TOK_CONCATENATE ] = "##",
1698 [TOK_AUTO ] = "auto",
1699 [TOK_BREAK ] = "break",
1700 [TOK_CASE ] = "case",
1701 [TOK_CHAR ] = "char",
1702 [TOK_CONST ] = "const",
1703 [TOK_CONTINUE ] = "continue",
1704 [TOK_DEFAULT ] = "default",
1706 [TOK_DOUBLE ] = "double",
1707 [TOK_ELSE ] = "else",
1708 [TOK_ENUM ] = "enum",
1709 [TOK_EXTERN ] = "extern",
1710 [TOK_FLOAT ] = "float",
1712 [TOK_GOTO ] = "goto",
1714 [TOK_INLINE ] = "inline",
1716 [TOK_LONG ] = "long",
1717 [TOK_REGISTER ] = "register",
1718 [TOK_RESTRICT ] = "restrict",
1719 [TOK_RETURN ] = "return",
1720 [TOK_SHORT ] = "short",
1721 [TOK_SIGNED ] = "signed",
1722 [TOK_SIZEOF ] = "sizeof",
1723 [TOK_STATIC ] = "static",
1724 [TOK_STRUCT ] = "struct",
1725 [TOK_SWITCH ] = "switch",
1726 [TOK_TYPEDEF ] = "typedef",
1727 [TOK_UNION ] = "union",
1728 [TOK_UNSIGNED ] = "unsigned",
1729 [TOK_VOID ] = "void",
1730 [TOK_VOLATILE ] = "volatile",
1731 [TOK_WHILE ] = "while",
1733 [TOK_ATTRIBUTE ] = "__attribute__",
1734 [TOK_ALIGNOF ] = "__alignof__",
1736 [TOK_DEFINE ] = "define",
1737 [TOK_UNDEF ] = "undef",
1738 [TOK_INCLUDE ] = "include",
1739 [TOK_LINE ] = "line",
1740 [TOK_ERROR ] = "error",
1741 [TOK_WARNING ] = "warning",
1742 [TOK_PRAGMA ] = "pragma",
1743 [TOK_IFDEF ] = "ifdef",
1744 [TOK_IFNDEF ] = "ifndef",
1745 [TOK_ELIF ] = "elif",
1746 [TOK_ENDIF ] = "endif",
1751 static unsigned int hash(const char *str, int str_len)
1755 end = str + str_len;
1757 for(; str < end; str++) {
1758 hash = (hash *263) + *str;
1760 hash = hash & (HASH_TABLE_SIZE -1);
1764 static struct hash_entry *lookup(
1765 struct compile_state *state, const char *name, int name_len)
1767 struct hash_entry *entry;
1769 index = hash(name, name_len);
1770 entry = state->hash_table[index];
1772 ((entry->name_len != name_len) ||
1773 (memcmp(entry->name, name, name_len) != 0))) {
1774 entry = entry->next;
1778 /* Get a private copy of the name */
1779 new_name = xmalloc(name_len + 1, "hash_name");
1780 memcpy(new_name, name, name_len);
1781 new_name[name_len] = '\0';
1783 /* Create a new hash entry */
1784 entry = xcmalloc(sizeof(*entry), "hash_entry");
1785 entry->next = state->hash_table[index];
1786 entry->name = new_name;
1787 entry->name_len = name_len;
1789 /* Place the new entry in the hash table */
1790 state->hash_table[index] = entry;
1795 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1797 struct hash_entry *entry;
1799 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1800 (entry->tok == TOK_ENUM_CONST) ||
1801 ((entry->tok >= TOK_FIRST_KEYWORD) &&
1802 (entry->tok <= TOK_LAST_KEYWORD)))) {
1803 tk->tok = entry->tok;
1807 static void ident_to_macro(struct compile_state *state, struct token *tk)
1809 struct hash_entry *entry;
1812 (entry->tok >= TOK_FIRST_MACRO) &&
1813 (entry->tok <= TOK_LAST_MACRO)) {
1814 tk->tok = entry->tok;
1818 static void hash_keyword(
1819 struct compile_state *state, const char *keyword, int tok)
1821 struct hash_entry *entry;
1822 entry = lookup(state, keyword, strlen(keyword));
1823 if (entry && entry->tok != TOK_UNKNOWN) {
1824 die("keyword %s already hashed", keyword);
1830 struct compile_state *state, struct hash_entry *ident,
1831 struct symbol **chain, struct triple *def, struct type *type)
1834 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
1835 error(state, 0, "%s already defined", ident->name);
1837 sym = xcmalloc(sizeof(*sym), "symbol");
1841 sym->scope_depth = state->scope_depth;
1846 static void start_scope(struct compile_state *state)
1848 state->scope_depth++;
1851 static void end_scope_syms(struct symbol **chain, int depth)
1853 struct symbol *sym, *next;
1855 while(sym && (sym->scope_depth == depth)) {
1863 static void end_scope(struct compile_state *state)
1867 /* Walk through the hash table and remove all symbols
1868 * in the current scope.
1870 depth = state->scope_depth;
1871 for(i = 0; i < HASH_TABLE_SIZE; i++) {
1872 struct hash_entry *entry;
1873 entry = state->hash_table[i];
1875 end_scope_syms(&entry->sym_label, depth);
1876 end_scope_syms(&entry->sym_struct, depth);
1877 end_scope_syms(&entry->sym_ident, depth);
1878 entry = entry->next;
1881 state->scope_depth = depth - 1;
1884 static void register_keywords(struct compile_state *state)
1886 hash_keyword(state, "auto", TOK_AUTO);
1887 hash_keyword(state, "break", TOK_BREAK);
1888 hash_keyword(state, "case", TOK_CASE);
1889 hash_keyword(state, "char", TOK_CHAR);
1890 hash_keyword(state, "const", TOK_CONST);
1891 hash_keyword(state, "continue", TOK_CONTINUE);
1892 hash_keyword(state, "default", TOK_DEFAULT);
1893 hash_keyword(state, "do", TOK_DO);
1894 hash_keyword(state, "double", TOK_DOUBLE);
1895 hash_keyword(state, "else", TOK_ELSE);
1896 hash_keyword(state, "enum", TOK_ENUM);
1897 hash_keyword(state, "extern", TOK_EXTERN);
1898 hash_keyword(state, "float", TOK_FLOAT);
1899 hash_keyword(state, "for", TOK_FOR);
1900 hash_keyword(state, "goto", TOK_GOTO);
1901 hash_keyword(state, "if", TOK_IF);
1902 hash_keyword(state, "inline", TOK_INLINE);
1903 hash_keyword(state, "int", TOK_INT);
1904 hash_keyword(state, "long", TOK_LONG);
1905 hash_keyword(state, "register", TOK_REGISTER);
1906 hash_keyword(state, "restrict", TOK_RESTRICT);
1907 hash_keyword(state, "return", TOK_RETURN);
1908 hash_keyword(state, "short", TOK_SHORT);
1909 hash_keyword(state, "signed", TOK_SIGNED);
1910 hash_keyword(state, "sizeof", TOK_SIZEOF);
1911 hash_keyword(state, "static", TOK_STATIC);
1912 hash_keyword(state, "struct", TOK_STRUCT);
1913 hash_keyword(state, "switch", TOK_SWITCH);
1914 hash_keyword(state, "typedef", TOK_TYPEDEF);
1915 hash_keyword(state, "union", TOK_UNION);
1916 hash_keyword(state, "unsigned", TOK_UNSIGNED);
1917 hash_keyword(state, "void", TOK_VOID);
1918 hash_keyword(state, "volatile", TOK_VOLATILE);
1919 hash_keyword(state, "while", TOK_WHILE);
1920 hash_keyword(state, "asm", TOK_ASM);
1921 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
1922 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
1925 static void register_macro_keywords(struct compile_state *state)
1927 hash_keyword(state, "define", TOK_DEFINE);
1928 hash_keyword(state, "undef", TOK_UNDEF);
1929 hash_keyword(state, "include", TOK_INCLUDE);
1930 hash_keyword(state, "line", TOK_LINE);
1931 hash_keyword(state, "error", TOK_ERROR);
1932 hash_keyword(state, "warning", TOK_WARNING);
1933 hash_keyword(state, "pragma", TOK_PRAGMA);
1934 hash_keyword(state, "ifdef", TOK_IFDEF);
1935 hash_keyword(state, "ifndef", TOK_IFNDEF);
1936 hash_keyword(state, "elif", TOK_ELIF);
1937 hash_keyword(state, "endif", TOK_ENDIF);
1940 static int spacep(int c)
1956 static int digitp(int c)
1960 case '0': case '1': case '2': case '3': case '4':
1961 case '5': case '6': case '7': case '8': case '9':
1968 static int hexdigitp(int c)
1972 case '0': case '1': case '2': case '3': case '4':
1973 case '5': case '6': case '7': case '8': case '9':
1974 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1975 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1981 static int hexdigval(int c)
1984 if ((c >= '0') && (c <= '9')) {
1987 else if ((c >= 'A') && (c <= 'F')) {
1988 val = 10 + (c - 'A');
1990 else if ((c >= 'a') && (c <= 'f')) {
1991 val = 10 + (c - 'a');
1996 static int octdigitp(int c)
2000 case '0': case '1': case '2': case '3':
2001 case '4': case '5': case '6': case '7':
2007 static int octdigval(int c)
2010 if ((c >= '0') && (c <= '7')) {
2016 static int letterp(int c)
2020 case 'a': case 'b': case 'c': case 'd': case 'e':
2021 case 'f': case 'g': case 'h': case 'i': case 'j':
2022 case 'k': case 'l': case 'm': case 'n': case 'o':
2023 case 'p': case 'q': case 'r': case 's': case 't':
2024 case 'u': case 'v': case 'w': case 'x': case 'y':
2026 case 'A': case 'B': case 'C': case 'D': case 'E':
2027 case 'F': case 'G': case 'H': case 'I': case 'J':
2028 case 'K': case 'L': case 'M': case 'N': case 'O':
2029 case 'P': case 'Q': case 'R': case 'S': case 'T':
2030 case 'U': case 'V': case 'W': case 'X': case 'Y':
2039 static int char_value(struct compile_state *state,
2040 const signed char **strp, const signed char *end)
2042 const signed char *str;
2046 if ((c == '\\') && (str < end)) {
2048 case 'n': c = '\n'; str++; break;
2049 case 't': c = '\t'; str++; break;
2050 case 'v': c = '\v'; str++; break;
2051 case 'b': c = '\b'; str++; break;
2052 case 'r': c = '\r'; str++; break;
2053 case 'f': c = '\f'; str++; break;
2054 case 'a': c = '\a'; str++; break;
2055 case '\\': c = '\\'; str++; break;
2056 case '?': c = '?'; str++; break;
2057 case '\'': c = '\''; str++; break;
2058 case '"': c = '"'; break;
2062 while((str < end) && hexdigitp(*str)) {
2064 c += hexdigval(*str);
2068 case '0': case '1': case '2': case '3':
2069 case '4': case '5': case '6': case '7':
2071 while((str < end) && octdigitp(*str)) {
2073 c += octdigval(*str);
2078 error(state, 0, "Invalid character constant");
2086 static char *after_digits(char *ptr, char *end)
2088 while((ptr < end) && digitp(*ptr)) {
2094 static char *after_octdigits(char *ptr, char *end)
2096 while((ptr < end) && octdigitp(*ptr)) {
2102 static char *after_hexdigits(char *ptr, char *end)
2104 while((ptr < end) && hexdigitp(*ptr)) {
2110 static void save_string(struct compile_state *state,
2111 struct token *tk, char *start, char *end, const char *id)
2115 /* Create a private copy of the string */
2116 str_len = end - start + 1;
2117 str = xmalloc(str_len + 1, id);
2118 memcpy(str, start, str_len);
2119 str[str_len] = '\0';
2121 /* Store the copy in the token */
2123 tk->str_len = str_len;
2125 static void next_token(struct compile_state *state, int index)
2127 struct file_state *file;
2135 tk = &state->token[index];
2138 token = tokp = file->pos;
2139 end = file->buf + file->size;
2146 if ((tokp + 1) < end) {
2150 if ((tokp + 2) < end) {
2154 if ((tokp + 3) < end) {
2162 else if (spacep(c)) {
2164 while ((tokp < end) && spacep(c)) {
2167 file->line_start = tokp + 1;
2176 else if ((c == '/') && (c1 == '/')) {
2178 for(tokp += 2; tokp < end; tokp++) {
2182 file->line_start = tokp +1;
2188 else if ((c == '/') && (c1 == '*')) {
2192 line_start = file->line_start;
2193 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2197 line_start = tokp +1;
2199 else if ((c == '*') && (tokp[1] == '/')) {
2205 if (tok == TOK_UNKNOWN) {
2206 error(state, 0, "unterminated comment");
2209 file->line_start = line_start;
2211 /* string constants */
2212 else if ((c == '"') ||
2213 ((c == 'L') && (c1 == '"'))) {
2218 line_start = file->line_start;
2224 for(tokp += 1; tokp < end; tokp++) {
2228 line_start = tokp + 1;
2230 else if ((c == '\\') && (tokp +1 < end)) {
2233 else if (c == '"') {
2234 tok = TOK_LIT_STRING;
2238 if (tok == TOK_UNKNOWN) {
2239 error(state, 0, "unterminated string constant");
2241 if (line != file->line) {
2242 warning(state, 0, "multiline string constant");
2245 file->line_start = line_start;
2247 /* Save the string value */
2248 save_string(state, tk, token, tokp, "literal string");
2250 /* character constants */
2251 else if ((c == '\'') ||
2252 ((c == 'L') && (c1 == '\''))) {
2257 line_start = file->line_start;
2263 for(tokp += 1; tokp < end; tokp++) {
2267 line_start = tokp + 1;
2269 else if ((c == '\\') && (tokp +1 < end)) {
2272 else if (c == '\'') {
2277 if (tok == TOK_UNKNOWN) {
2278 error(state, 0, "unterminated character constant");
2280 if (line != file->line) {
2281 warning(state, 0, "multiline character constant");
2284 file->line_start = line_start;
2286 /* Save the character value */
2287 save_string(state, tk, token, tokp, "literal character");
2289 /* integer and floating constants
2295 * Floating constants
2296 * {digits}.{digits}[Ee][+-]?{digits}
2298 * {digits}[Ee][+-]?{digits}
2299 * .{digits}[Ee][+-]?{digits}
2303 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2308 next = after_digits(tokp, end);
2313 if (next[0] == '.') {
2314 new = after_digits(next, end);
2315 is_float = (new != next);
2318 if ((next[0] == 'e') || (next[0] == 'E')) {
2319 if (((next + 1) < end) &&
2320 ((next[1] == '+') || (next[1] == '-'))) {
2323 new = after_digits(next, end);
2324 is_float = (new != next);
2328 tok = TOK_LIT_FLOAT;
2329 if ((next < end) && (
2338 if (!is_float && digitp(c)) {
2340 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2341 next = after_hexdigits(tokp + 2, end);
2343 else if (c == '0') {
2344 next = after_octdigits(tokp, end);
2347 next = after_digits(tokp, end);
2349 /* crazy integer suffixes */
2351 ((next[0] == 'u') || (next[0] == 'U'))) {
2354 ((next[0] == 'l') || (next[0] == 'L'))) {
2358 else if ((next < end) &&
2359 ((next[0] == 'l') || (next[0] == 'L'))) {
2362 ((next[0] == 'u') || (next[0] == 'U'))) {
2369 /* Save the integer/floating point value */
2370 save_string(state, tk, token, tokp, "literal number");
2373 else if (letterp(c)) {
2375 for(tokp += 1; tokp < end; tokp++) {
2377 if (!letterp(c) && !digitp(c)) {
2382 tk->ident = lookup(state, token, tokp +1 - token);
2384 /* C99 alternate macro characters */
2385 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2387 tok = TOK_CONCATENATE;
2389 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2390 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2391 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2392 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2393 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2394 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2395 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2396 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2397 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2398 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2399 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2400 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2401 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2402 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2403 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2404 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2405 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2406 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2407 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2408 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2409 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2410 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2411 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2412 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2413 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2414 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2415 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2416 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2417 else if (c == ';') { tok = TOK_SEMI; }
2418 else if (c == '{') { tok = TOK_LBRACE; }
2419 else if (c == '}') { tok = TOK_RBRACE; }
2420 else if (c == ',') { tok = TOK_COMMA; }
2421 else if (c == '=') { tok = TOK_EQ; }
2422 else if (c == ':') { tok = TOK_COLON; }
2423 else if (c == '[') { tok = TOK_LBRACKET; }
2424 else if (c == ']') { tok = TOK_RBRACKET; }
2425 else if (c == '(') { tok = TOK_LPAREN; }
2426 else if (c == ')') { tok = TOK_RPAREN; }
2427 else if (c == '*') { tok = TOK_STAR; }
2428 else if (c == '>') { tok = TOK_MORE; }
2429 else if (c == '<') { tok = TOK_LESS; }
2430 else if (c == '?') { tok = TOK_QUEST; }
2431 else if (c == '|') { tok = TOK_OR; }
2432 else if (c == '&') { tok = TOK_AND; }
2433 else if (c == '^') { tok = TOK_XOR; }
2434 else if (c == '+') { tok = TOK_PLUS; }
2435 else if (c == '-') { tok = TOK_MINUS; }
2436 else if (c == '/') { tok = TOK_DIV; }
2437 else if (c == '%') { tok = TOK_MOD; }
2438 else if (c == '!') { tok = TOK_BANG; }
2439 else if (c == '.') { tok = TOK_DOT; }
2440 else if (c == '~') { tok = TOK_TILDE; }
2441 else if (c == '#') { tok = TOK_MACRO; }
2442 if (tok == TOK_MACRO) {
2443 /* Only match preprocessor directives at the start of a line */
2445 for(ptr = file->line_start; spacep(*ptr); ptr++)
2451 if (tok == TOK_UNKNOWN) {
2452 error(state, 0, "unknown token");
2455 file->pos = tokp + 1;
2457 if (tok == TOK_IDENT) {
2458 ident_to_keyword(state, tk);
2460 /* Don't return space tokens. */
2461 if (tok == TOK_SPACE) {
2466 static void compile_macro(struct compile_state *state, struct token *tk)
2468 struct file_state *file;
2469 struct hash_entry *ident;
2471 file = xmalloc(sizeof(*file), "file_state");
2472 file->basename = xstrdup(tk->ident->name);
2473 file->dirname = xstrdup("");
2474 file->size = ident->sym_define->buf_len;
2475 file->buf = xmalloc(file->size +2, file->basename);
2476 memcpy(file->buf, ident->sym_define->buf, file->size);
2477 file->buf[file->size] = '\n';
2478 file->buf[file->size + 1] = '\0';
2479 file->pos = file->buf;
2480 file->line_start = file->pos;
2482 file->prev = state->file;
2487 static int mpeek(struct compile_state *state, int index)
2491 tk = &state->token[index + 1];
2492 if (tk->tok == -1) {
2493 next_token(state, index + 1);
2497 if ((tk->tok == TOK_EOF) &&
2498 (state->file != state->macro_file) &&
2499 (state->file->prev)) {
2500 struct file_state *file = state->file;
2501 state->file = file->prev;
2502 /* file->basename is used keep it */
2503 xfree(file->dirname);
2506 next_token(state, index + 1);
2509 else if (tk->ident && tk->ident->sym_define) {
2510 compile_macro(state, tk);
2511 next_token(state, index + 1);
2515 /* Don't show the token on the next line */
2516 if (state->macro_line < state->macro_file->line) {
2519 return state->token[index +1].tok;
2522 static void meat(struct compile_state *state, int index, int tok)
2526 next_tok = mpeek(state, index);
2527 if (next_tok != tok) {
2528 const char *name1, *name2;
2529 name1 = tokens[next_tok];
2531 if (next_tok == TOK_IDENT) {
2532 name2 = state->token[index + 1].ident->name;
2534 error(state, 0, "found %s %s expected %s",
2535 name1, name2, tokens[tok]);
2537 /* Free the old token value */
2538 if (state->token[index].str_len) {
2539 memset((void *)(state->token[index].val.str), -1,
2540 state->token[index].str_len);
2541 xfree(state->token[index].val.str);
2543 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2544 state->token[i] = state->token[i + 1];
2546 memset(&state->token[i], 0, sizeof(state->token[i]));
2547 state->token[i].tok = -1;
2550 static long_t mcexpr(struct compile_state *state, int index);
2552 static long_t mprimary_expr(struct compile_state *state, int index)
2556 tok = mpeek(state, index);
2557 while(state->token[index + 1].ident &&
2558 state->token[index + 1].ident->sym_define) {
2559 meat(state, index, tok);
2560 compile_macro(state, &state->token[index]);
2561 tok = mpeek(state, index);
2565 meat(state, index, TOK_LPAREN);
2566 val = mcexpr(state, index);
2567 meat(state, index, TOK_RPAREN);
2572 meat(state, index, TOK_LIT_INT);
2574 val = strtol(state->token[index].val.str, &end, 0);
2575 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2576 (errno == ERANGE)) {
2577 error(state, 0, "Integer constant to large");
2582 meat(state, index, TOK_LIT_INT);
2587 static long_t munary_expr(struct compile_state *state, int index)
2590 switch(mpeek(state, index)) {
2592 meat(state, index, TOK_PLUS);
2593 val = munary_expr(state, index);
2597 meat(state, index, TOK_MINUS);
2598 val = munary_expr(state, index);
2602 meat(state, index, TOK_BANG);
2603 val = munary_expr(state, index);
2607 meat(state, index, TOK_BANG);
2608 val = munary_expr(state, index);
2612 val = mprimary_expr(state, index);
2618 static long_t mmul_expr(struct compile_state *state, int index)
2622 val = munary_expr(state, index);
2626 switch(mpeek(state, index)) {
2628 meat(state, index, TOK_STAR);
2629 right = munary_expr(state, index);
2633 meat(state, index, TOK_DIV);
2634 right = munary_expr(state, index);
2638 meat(state, index, TOK_MOD);
2639 right = munary_expr(state, index);
2651 static long_t madd_expr(struct compile_state *state, int index)
2655 val = mmul_expr(state, index);
2659 switch(mpeek(state, index)) {
2661 meat(state, index, TOK_PLUS);
2662 right = mmul_expr(state, index);
2666 meat(state, index, TOK_MINUS);
2667 right = mmul_expr(state, index);
2679 static long_t mshift_expr(struct compile_state *state, int index)
2683 val = madd_expr(state, index);
2687 switch(mpeek(state, index)) {
2689 meat(state, index, TOK_SL);
2690 right = madd_expr(state, index);
2694 meat(state, index, TOK_SR);
2695 right = madd_expr(state, index);
2707 static long_t mrel_expr(struct compile_state *state, int index)
2711 val = mshift_expr(state, index);
2715 switch(mpeek(state, index)) {
2717 meat(state, index, TOK_LESS);
2718 right = mshift_expr(state, index);
2722 meat(state, index, TOK_MORE);
2723 right = mshift_expr(state, index);
2727 meat(state, index, TOK_LESSEQ);
2728 right = mshift_expr(state, index);
2732 meat(state, index, TOK_MOREEQ);
2733 right = mshift_expr(state, index);
2744 static long_t meq_expr(struct compile_state *state, int index)
2748 val = mrel_expr(state, index);
2752 switch(mpeek(state, index)) {
2754 meat(state, index, TOK_EQEQ);
2755 right = mrel_expr(state, index);
2759 meat(state, index, TOK_NOTEQ);
2760 right = mrel_expr(state, index);
2771 static long_t mand_expr(struct compile_state *state, int index)
2774 val = meq_expr(state, index);
2775 if (mpeek(state, index) == TOK_AND) {
2777 meat(state, index, TOK_AND);
2778 right = meq_expr(state, index);
2784 static long_t mxor_expr(struct compile_state *state, int index)
2787 val = mand_expr(state, index);
2788 if (mpeek(state, index) == TOK_XOR) {
2790 meat(state, index, TOK_XOR);
2791 right = mand_expr(state, index);
2797 static long_t mor_expr(struct compile_state *state, int index)
2800 val = mxor_expr(state, index);
2801 if (mpeek(state, index) == TOK_OR) {
2803 meat(state, index, TOK_OR);
2804 right = mxor_expr(state, index);
2810 static long_t mland_expr(struct compile_state *state, int index)
2813 val = mor_expr(state, index);
2814 if (mpeek(state, index) == TOK_LOGAND) {
2816 meat(state, index, TOK_LOGAND);
2817 right = mor_expr(state, index);
2822 static long_t mlor_expr(struct compile_state *state, int index)
2825 val = mland_expr(state, index);
2826 if (mpeek(state, index) == TOK_LOGOR) {
2828 meat(state, index, TOK_LOGOR);
2829 right = mland_expr(state, index);
2835 static long_t mcexpr(struct compile_state *state, int index)
2837 return mlor_expr(state, index);
2839 static void preprocess(struct compile_state *state, int index)
2841 /* Doing much more with the preprocessor would require
2842 * a parser and a major restructuring.
2843 * Postpone that for later.
2845 struct file_state *file;
2851 tk = &state->token[index];
2852 state->macro_line = line = file->line;
2853 state->macro_file = file;
2855 next_token(state, index);
2856 ident_to_macro(state, tk);
2857 if (tk->tok == TOK_IDENT) {
2858 error(state, 0, "undefined preprocessing directive `%s'",
2865 if (state->if_value < 0) {
2868 warning(state, 0, "Ignoring preprocessor directive: %s",
2872 error(state, 0, "#elif not supported");
2873 #warning "FIXME multiple #elif and #else in an #if do not work properly"
2874 if (state->if_depth == 0) {
2875 error(state, 0, "#elif without #if");
2877 /* If the #if was taken the #elif just disables the following code */
2878 if (state->if_value >= 0) {
2879 state->if_value = - state->if_value;
2881 /* If the previous #if was not taken see if the #elif enables the
2884 else if ((state->if_value < 0) &&
2885 (state->if_depth == - state->if_value))
2887 if (mcexpr(state, index) != 0) {
2888 state->if_value = state->if_depth;
2891 state->if_value = - state->if_depth;
2897 if (state->if_value < 0) {
2900 if (mcexpr(state, index) != 0) {
2901 state->if_value = state->if_depth;
2904 state->if_value = - state->if_depth;
2909 if (state->if_value < 0) {
2912 next_token(state, index);
2913 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2914 error(state, 0, "Invalid macro name");
2916 if (tk->ident->sym_define == 0) {
2917 state->if_value = state->if_depth;
2920 state->if_value = - state->if_depth;
2925 if (state->if_value < 0) {
2928 next_token(state, index);
2929 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2930 error(state, 0, "Invalid macro name");
2932 if (tk->ident->sym_define != 0) {
2933 state->if_value = state->if_depth;
2936 state->if_value = - state->if_depth;
2940 if (state->if_depth == 0) {
2941 error(state, 0, "#else without #if");
2943 if ((state->if_value >= 0) ||
2944 ((state->if_value < 0) &&
2945 (state->if_depth == -state->if_value)))
2947 state->if_value = - state->if_value;
2951 if (state->if_depth == 0) {
2952 error(state, 0, "#endif without #if");
2954 if ((state->if_value >= 0) ||
2955 ((state->if_value < 0) &&
2956 (state->if_depth == -state->if_value)))
2958 state->if_value = state->if_depth - 1;
2964 struct hash_entry *ident;
2965 struct macro *macro;
2968 if (state->if_value < 0) /* quit early when #if'd out */
2971 meat(state, index, TOK_IDENT);
2975 if (*file->pos == '(') {
2976 #warning "FIXME macros with arguments not supported"
2977 error(state, 0, "Macros with arguments not supported");
2980 /* Find the end of the line to get an estimate of
2981 * the macro's length.
2983 for(ptr = file->pos; *ptr != '\n'; ptr++)
2986 if (ident->sym_define != 0) {
2987 error(state, 0, "macro %s already defined\n", ident->name);
2989 macro = xmalloc(sizeof(*macro), "macro");
2990 macro->ident = ident;
2991 macro->buf_len = ptr - file->pos +1;
2992 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
2994 memcpy(macro->buf, file->pos, macro->buf_len);
2995 macro->buf[macro->buf_len] = '\n';
2996 macro->buf[macro->buf_len +1] = '\0';
2998 ident->sym_define = macro;
3005 /* Find the end of the line */
3006 for(end = file->pos; *end != '\n'; end++)
3008 len = (end - file->pos);
3009 if (state->if_value >= 0) {
3010 error(state, 0, "%*.*s", len, len, file->pos);
3019 /* Find the end of the line */
3020 for(end = file->pos; *end != '\n'; end++)
3022 len = (end - file->pos);
3023 if (state->if_value >= 0) {
3024 warning(state, 0, "%*.*s", len, len, file->pos);
3036 next_token(state, index);
3037 if (tk->tok == TOK_LIT_STRING) {
3040 name = xmalloc(tk->str_len, "include");
3041 token = tk->val.str +1;
3042 name_len = tk->str_len -2;
3043 if (*token == '"') {
3047 memcpy(name, token, name_len);
3048 name[name_len] = '\0';
3051 else if (tk->tok == TOK_LESS) {
3054 for(end = start; *end != '\n'; end++) {
3060 error(state, 0, "Unterminated included directive");
3062 name = xmalloc(end - start + 1, "include");
3063 memcpy(name, start, end - start);
3064 name[end - start] = '\0';
3069 error(state, 0, "Invalid include directive");
3071 /* Error if there are any characters after the include */
3072 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3073 if (!isspace(*ptr)) {
3074 error(state, 0, "garbage after include directive");
3077 if (state->if_value >= 0) {
3078 compile_file(state, name, local);
3081 next_token(state, index);
3085 /* Ignore # without a following ident */
3086 if (tk->tok == TOK_IDENT) {
3087 error(state, 0, "Invalid preprocessor directive: %s",
3092 /* Consume the rest of the macro line */
3094 tok = mpeek(state, index);
3095 meat(state, index, tok);
3096 } while(tok != TOK_EOF);
3100 static void token(struct compile_state *state, int index)
3102 struct file_state *file;
3106 tk = &state->token[index];
3107 next_token(state, index);
3111 if (tk->tok == TOK_EOF && file->prev) {
3112 state->file = file->prev;
3113 /* file->basename is used keep it */
3114 xfree(file->dirname);
3117 next_token(state, index);
3120 else if (tk->tok == TOK_MACRO) {
3121 preprocess(state, index);
3124 else if (tk->ident && tk->ident->sym_define) {
3125 compile_macro(state, tk);
3126 next_token(state, index);
3129 else if (state->if_value < 0) {
3130 next_token(state, index);
3136 static int peek(struct compile_state *state)
3138 if (state->token[1].tok == -1) {
3141 return state->token[1].tok;
3144 static int peek2(struct compile_state *state)
3146 if (state->token[1].tok == -1) {
3149 if (state->token[2].tok == -1) {
3152 return state->token[2].tok;
3155 static void eat(struct compile_state *state, int tok)
3159 next_tok = peek(state);
3160 if (next_tok != tok) {
3161 const char *name1, *name2;
3162 name1 = tokens[next_tok];
3164 if (next_tok == TOK_IDENT) {
3165 name2 = state->token[1].ident->name;
3167 error(state, 0, "\tfound %s %s expected %s",
3168 name1, name2 ,tokens[tok]);
3170 /* Free the old token value */
3171 if (state->token[0].str_len) {
3172 xfree((void *)(state->token[0].val.str));
3174 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3175 state->token[i] = state->token[i + 1];
3177 memset(&state->token[i], 0, sizeof(state->token[i]));
3178 state->token[i].tok = -1;
3181 #warning "FIXME do not hardcode the include paths"
3182 static char *include_paths[] = {
3183 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3184 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3185 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3189 static void compile_file(struct compile_state *state, char *filename, int local)
3192 char *subdir, *base;
3194 struct file_state *file;
3196 file = xmalloc(sizeof(*file), "file_state");
3198 base = strrchr(filename, '/');
3201 subdir_len = base - filename;
3208 basename = xmalloc(strlen(base) +1, "basename");
3209 strcpy(basename, base);
3210 file->basename = basename;
3212 if (getcwd(cwd, sizeof(cwd)) == 0) {
3213 die("cwd buffer to small");
3216 if (subdir[0] == '/') {
3217 file->dirname = xmalloc(subdir_len + 1, "dirname");
3218 memcpy(file->dirname, subdir, subdir_len);
3219 file->dirname[subdir_len] = '\0';
3225 /* Find the appropriate directory... */
3227 if (!state->file && exists(cwd, filename)) {
3230 if (local && state->file && exists(state->file->dirname, filename)) {
3231 dir = state->file->dirname;
3233 for(path = include_paths; !dir && *path; path++) {
3234 if (exists(*path, filename)) {
3239 error(state, 0, "Cannot find `%s'\n", filename);
3241 dirlen = strlen(dir);
3242 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3243 memcpy(file->dirname, dir, dirlen);
3244 file->dirname[dirlen] = '/';
3245 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3246 file->dirname[dirlen + 1 + subdir_len] = '\0';
3248 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3251 file->pos = file->buf;
3252 file->line_start = file->pos;
3255 file->prev = state->file;
3258 process_trigraphs(state);
3259 splice_lines(state);
3262 /* Type helper functions */
3264 static struct type *new_type(
3265 unsigned int type, struct type *left, struct type *right)
3267 struct type *result;
3268 result = xmalloc(sizeof(*result), "type");
3269 result->type = type;
3270 result->left = left;
3271 result->right = right;
3272 result->field_ident = 0;
3273 result->type_ident = 0;
3277 static struct type *clone_type(unsigned int specifiers, struct type *old)
3279 struct type *result;
3280 result = xmalloc(sizeof(*result), "type");
3281 memcpy(result, old, sizeof(*result));
3282 result->type &= TYPE_MASK;
3283 result->type |= specifiers;
3287 #define SIZEOF_SHORT 2
3288 #define SIZEOF_INT 4
3289 #define SIZEOF_LONG (sizeof(long_t))
3291 #define ALIGNOF_SHORT 2
3292 #define ALIGNOF_INT 4
3293 #define ALIGNOF_LONG (sizeof(long_t))
3295 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3296 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3297 static inline ulong_t mask_uint(ulong_t x)
3299 if (SIZEOF_INT < SIZEOF_LONG) {
3300 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3305 #define MASK_UINT(X) (mask_uint(X))
3306 #define MASK_ULONG(X) (X)
3308 static struct type void_type = { .type = TYPE_VOID };
3309 static struct type char_type = { .type = TYPE_CHAR };
3310 static struct type uchar_type = { .type = TYPE_UCHAR };
3311 static struct type short_type = { .type = TYPE_SHORT };
3312 static struct type ushort_type = { .type = TYPE_USHORT };
3313 static struct type int_type = { .type = TYPE_INT };
3314 static struct type uint_type = { .type = TYPE_UINT };
3315 static struct type long_type = { .type = TYPE_LONG };
3316 static struct type ulong_type = { .type = TYPE_ULONG };
3318 static struct triple *variable(struct compile_state *state, struct type *type)
3320 struct triple *result;
3321 if ((type->type & STOR_MASK) != STOR_PERM) {
3322 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3323 result = triple(state, OP_ADECL, type, 0, 0);
3326 struct triple **vector;
3328 result = new_triple(state, OP_VAL_VEC, type, -1);
3329 vector = &result->param[0];
3333 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3334 vector[index] = variable(state, field->left);
3335 field = field->right;
3338 vector[index] = variable(state, field);
3342 result = triple(state, OP_SDECL, type, 0, 0);
3347 static void stor_of(FILE *fp, struct type *type)
3349 switch(type->type & STOR_MASK) {
3351 fprintf(fp, "auto ");
3354 fprintf(fp, "static ");
3357 fprintf(fp, "extern ");
3360 fprintf(fp, "register ");
3363 fprintf(fp, "typedef ");
3366 fprintf(fp, "inline ");
3370 static void qual_of(FILE *fp, struct type *type)
3372 if (type->type & QUAL_CONST) {
3373 fprintf(fp, " const");
3375 if (type->type & QUAL_VOLATILE) {
3376 fprintf(fp, " volatile");
3378 if (type->type & QUAL_RESTRICT) {
3379 fprintf(fp, " restrict");
3383 static void name_of(FILE *fp, struct type *type)
3386 switch(type->type & TYPE_MASK) {
3388 fprintf(fp, "void");
3392 fprintf(fp, "signed char");
3396 fprintf(fp, "unsigned char");
3400 fprintf(fp, "signed short");
3404 fprintf(fp, "unsigned short");
3408 fprintf(fp, "signed int");
3412 fprintf(fp, "unsigned int");
3416 fprintf(fp, "signed long");
3420 fprintf(fp, "unsigned long");
3424 name_of(fp, type->left);
3430 name_of(fp, type->left);
3432 name_of(fp, type->right);
3435 fprintf(fp, "enum %s", type->type_ident->name);
3439 fprintf(fp, "struct %s", type->type_ident->name);
3444 name_of(fp, type->left);
3445 fprintf(fp, " (*)(");
3446 name_of(fp, type->right);
3451 name_of(fp, type->left);
3452 fprintf(fp, " [%ld]", type->elements);
3455 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3460 static size_t align_of(struct compile_state *state, struct type *type)
3464 switch(type->type & TYPE_MASK) {
3474 align = ALIGNOF_SHORT;
3479 align = ALIGNOF_INT;
3484 align = ALIGNOF_LONG;
3489 size_t left_align, right_align;
3490 left_align = align_of(state, type->left);
3491 right_align = align_of(state, type->right);
3492 align = (left_align >= right_align) ? left_align : right_align;
3496 align = align_of(state, type->left);
3499 align = align_of(state, type->left);
3502 error(state, 0, "alignof not yet defined for type\n");
3508 static size_t size_of(struct compile_state *state, struct type *type)
3512 switch(type->type & TYPE_MASK) {
3522 size = SIZEOF_SHORT;
3537 size = size_of(state, type->left);
3538 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3540 align = align_of(state, type->left);
3541 pad = align - (size % align);
3542 size = size + pad + size_of(state, type->left);
3544 align = align_of(state, type->right);
3545 pad = align - (size % align);
3546 size = size + pad + sizeof(type->right);
3551 size_t size_left, size_right;
3552 size_left = size_of(state, type->left);
3553 size_right = size_of(state, type->right);
3554 size = (size_left >= size_right)? size_left : size_right;
3558 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3559 internal_error(state, 0, "Invalid array type");
3561 size = size_of(state, type->left) * type->elements;
3565 size = size_of(state, type->left);
3568 error(state, 0, "sizeof not yet defined for type\n");
3574 static size_t field_offset(struct compile_state *state,
3575 struct type *type, struct hash_entry *field)
3577 size_t size, align, pad;
3578 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3579 internal_error(state, 0, "field_offset only works on structures");
3583 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3584 if (type->left->field_ident == field) {
3587 size += size_of(state, type->left);
3589 align = align_of(state, type->left);
3590 pad = align - (size % align);
3593 if (type->field_ident != field) {
3594 internal_error(state, 0, "field_offset: member %s not present",
3600 static struct type *field_type(struct compile_state *state,
3601 struct type *type, struct hash_entry *field)
3603 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3604 internal_error(state, 0, "field_type only works on structures");
3607 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3608 if (type->left->field_ident == field) {
3614 if (type->field_ident != field) {
3615 internal_error(state, 0, "field_type: member %s not present",
3621 static struct triple *struct_field(struct compile_state *state,
3622 struct triple *decl, struct hash_entry *field)
3624 struct triple **vector;
3628 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3631 if (decl->op != OP_VAL_VEC) {
3632 internal_error(state, 0, "Invalid struct variable");
3635 internal_error(state, 0, "Missing structure field");
3638 vector = &RHS(decl, 0);
3640 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3641 if (type->left->field_ident == field) {
3648 if (type->field_ident != field) {
3649 internal_error(state, 0, "field %s not found?", field->name);
3651 return vector[index];
3654 static void arrays_complete(struct compile_state *state, struct type *type)
3656 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3657 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3658 error(state, 0, "array size not specified");
3660 arrays_complete(state, type->left);
3664 static unsigned int do_integral_promotion(unsigned int type)
3667 if (TYPE_INTEGER(type) &&
3668 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3674 static unsigned int do_arithmetic_conversion(
3675 unsigned int left, unsigned int right)
3679 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3680 return TYPE_LDOUBLE;
3682 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3685 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3688 left = do_integral_promotion(left);
3689 right = do_integral_promotion(right);
3690 /* If both operands have the same size done */
3691 if (left == right) {
3694 /* If both operands have the same signedness pick the larger */
3695 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3696 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3698 /* If the signed type can hold everything use it */
3699 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3702 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3705 /* Convert to the unsigned type with the same rank as the signed type */
3706 else if (TYPE_SIGNED(left)) {
3707 return TYPE_MKUNSIGNED(left);
3710 return TYPE_MKUNSIGNED(right);
3714 /* see if two types are the same except for qualifiers */
3715 static int equiv_types(struct type *left, struct type *right)
3718 /* Error if the basic types do not match */
3719 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3722 type = left->type & TYPE_MASK;
3723 /* if the basic types match and it is an arithmetic type we are done */
3724 if (TYPE_ARITHMETIC(type)) {
3727 /* If it is a pointer type recurse and keep testing */
3728 if (type == TYPE_POINTER) {
3729 return equiv_types(left->left, right->left);
3731 else if (type == TYPE_ARRAY) {
3732 return (left->elements == right->elements) &&
3733 equiv_types(left->left, right->left);
3735 /* test for struct/union equality */
3736 else if (type == TYPE_STRUCT) {
3737 return left->type_ident == right->type_ident;
3739 /* Test for equivalent functions */
3740 else if (type == TYPE_FUNCTION) {
3741 return equiv_types(left->left, right->left) &&
3742 equiv_types(left->right, right->right);
3744 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3745 else if (type == TYPE_PRODUCT) {
3746 return equiv_types(left->left, right->left) &&
3747 equiv_types(left->right, right->right);
3749 /* We should see TYPE_OVERLAP */
3755 static int equiv_ptrs(struct type *left, struct type *right)
3757 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3758 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3761 return equiv_types(left->left, right->left);
3764 static struct type *compatible_types(struct type *left, struct type *right)
3766 struct type *result;
3767 unsigned int type, qual_type;
3768 /* Error if the basic types do not match */
3769 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3772 type = left->type & TYPE_MASK;
3773 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3775 /* if the basic types match and it is an arithmetic type we are done */
3776 if (TYPE_ARITHMETIC(type)) {
3777 result = new_type(qual_type, 0, 0);
3779 /* If it is a pointer type recurse and keep testing */
3780 else if (type == TYPE_POINTER) {
3781 result = compatible_types(left->left, right->left);
3783 result = new_type(qual_type, result, 0);
3786 /* test for struct/union equality */
3787 else if (type == TYPE_STRUCT) {
3788 if (left->type_ident == right->type_ident) {
3792 /* Test for equivalent functions */
3793 else if (type == TYPE_FUNCTION) {
3794 struct type *lf, *rf;
3795 lf = compatible_types(left->left, right->left);
3796 rf = compatible_types(left->right, right->right);
3798 result = new_type(qual_type, lf, rf);
3801 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3802 else if (type == TYPE_PRODUCT) {
3803 struct type *lf, *rf;
3804 lf = compatible_types(left->left, right->left);
3805 rf = compatible_types(left->right, right->right);
3807 result = new_type(qual_type, lf, rf);
3811 /* Nothing else is compatible */
3816 static struct type *compatible_ptrs(struct type *left, struct type *right)
3818 struct type *result;
3819 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3820 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3823 result = compatible_types(left->left, right->left);
3825 unsigned int qual_type;
3826 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3827 result = new_type(qual_type, result, 0);
3832 static struct triple *integral_promotion(
3833 struct compile_state *state, struct triple *def)
3837 /* As all operations are carried out in registers
3838 * the values are converted on load I just convert
3839 * logical type of the operand.
3841 if (TYPE_INTEGER(type->type)) {
3842 unsigned int int_type;
3843 int_type = type->type & ~TYPE_MASK;
3844 int_type |= do_integral_promotion(type->type);
3845 if (int_type != type->type) {
3846 def->type = new_type(int_type, 0, 0);
3853 static void arithmetic(struct compile_state *state, struct triple *def)
3855 if (!TYPE_ARITHMETIC(def->type->type)) {
3856 error(state, def, "arithmetic type expexted");
3860 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
3862 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
3863 error(state, def, "pointer or arithmetic type expected");
3867 static int is_integral(struct triple *ins)
3869 return TYPE_INTEGER(ins->type->type);
3872 static void integral(struct compile_state *state, struct triple *def)
3874 if (!is_integral(def)) {
3875 error(state, 0, "integral type expected");
3880 static void bool(struct compile_state *state, struct triple *def)
3882 if (!TYPE_ARITHMETIC(def->type->type) &&
3883 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
3884 error(state, 0, "arithmetic or pointer type expected");
3888 static int is_signed(struct type *type)
3890 return !!TYPE_SIGNED(type->type);
3893 /* Is this value located in a register otherwise it must be in memory */
3894 static int is_in_reg(struct compile_state *state, struct triple *def)
3897 if (def->op == OP_ADECL) {
3900 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
3903 else if (def->op == OP_VAL_VEC) {
3904 in_reg = is_in_reg(state, RHS(def, 0));
3906 else if (def->op == OP_DOT) {
3907 in_reg = is_in_reg(state, RHS(def, 0));
3910 internal_error(state, 0, "unknown expr storage location");
3916 /* Is this a stable variable location otherwise it must be a temporary */
3917 static int is_stable(struct compile_state *state, struct triple *def)
3924 if ((def->op == OP_ADECL) ||
3925 (def->op == OP_SDECL) ||
3926 (def->op == OP_DEREF) ||
3927 (def->op == OP_BLOBCONST)) {
3930 else if (def->op == OP_DOT) {
3931 ret = is_stable(state, RHS(def, 0));
3933 else if (def->op == OP_VAL_VEC) {
3934 struct triple **vector;
3937 vector = &RHS(def, 0);
3938 for(i = 0; i < def->type->elements; i++) {
3939 if (!is_stable(state, vector[i])) {
3948 static int is_lvalue(struct compile_state *state, struct triple *def)
3955 if (!is_stable(state, def)) {
3958 if (def->type->type & QUAL_CONST) {
3961 else if (def->op == OP_DOT) {
3962 ret = is_lvalue(state, RHS(def, 0));
3967 static void lvalue(struct compile_state *state, struct triple *def)
3970 internal_error(state, def, "nothing where lvalue expected?");
3972 if (!is_lvalue(state, def)) {
3973 error(state, def, "lvalue expected");
3977 static int is_pointer(struct triple *def)
3979 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
3982 static void pointer(struct compile_state *state, struct triple *def)
3984 if (!is_pointer(def)) {
3985 error(state, def, "pointer expected");
3989 static struct triple *int_const(
3990 struct compile_state *state, struct type *type, ulong_t value)
3992 struct triple *result;
3993 switch(type->type & TYPE_MASK) {
3995 case TYPE_INT: case TYPE_UINT:
3996 case TYPE_LONG: case TYPE_ULONG:
3999 internal_error(state, 0, "constant for unkown type");
4001 result = triple(state, OP_INTCONST, type, 0, 0);
4002 result->u.cval = value;
4007 static struct triple *do_mk_addr_expr(struct compile_state *state,
4008 struct triple *expr, struct type *type, ulong_t offset)
4010 struct triple *result;
4011 lvalue(state, expr);
4014 if (expr->op == OP_ADECL) {
4015 error(state, expr, "address of auto variables not supported");
4017 else if (expr->op == OP_SDECL) {
4018 result = triple(state, OP_ADDRCONST, type, expr, 0);
4019 result->u.cval = offset;
4021 else if (expr->op == OP_DEREF) {
4022 result = triple(state, OP_ADD, type,
4024 int_const(state, &ulong_type, offset));
4029 static struct triple *mk_addr_expr(
4030 struct compile_state *state, struct triple *expr, ulong_t offset)
4035 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4038 return do_mk_addr_expr(state, expr, type, offset);
4041 static struct triple *mk_deref_expr(
4042 struct compile_state *state, struct triple *expr)
4044 struct type *base_type;
4045 pointer(state, expr);
4046 base_type = expr->type->left;
4047 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4049 "Only pointer and arithmetic values can be dereferenced");
4051 return triple(state, OP_DEREF, base_type, expr, 0);
4054 static struct triple *deref_field(
4055 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4057 struct triple *result;
4058 struct type *type, *member;
4060 internal_error(state, 0, "No field passed to deref_field");
4064 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4065 error(state, 0, "request for member %s in something not a struct or union",
4068 member = type->left;
4069 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070 if (member->left->field_ident == field) {
4071 member = member->left;
4074 member = member->right;
4076 if (member->field_ident != field) {
4077 error(state, 0, "%s is not a member", field->name);
4079 if ((type->type & STOR_MASK) == STOR_PERM) {
4080 /* Do the pointer arithmetic to get a deref the field */
4082 offset = field_offset(state, type, field);
4083 result = do_mk_addr_expr(state, expr, member, offset);
4084 result = mk_deref_expr(state, result);
4087 /* Find the variable for the field I want. */
4088 result = triple(state, OP_DOT,
4089 field_type(state, type, field), expr, 0);
4090 result->u.field = field;
4095 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4101 if (!is_stable(state, def)) {
4104 /* Tranform an array to a pointer to the first element */
4105 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4106 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4109 TYPE_POINTER | (def->type->type & QUAL_MASK),
4110 def->type->left, 0);
4111 return triple(state, OP_ADDRCONST, type, def, 0);
4113 if (is_in_reg(state, def)) {
4118 return triple(state, op, def->type, def, 0);
4121 static void write_compatible(struct compile_state *state,
4122 struct type *dest, struct type *rval)
4125 /* Both operands have arithmetic type */
4126 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4129 /* One operand is a pointer and the other is a pointer to void */
4130 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4131 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4132 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4133 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4136 /* If both types are the same without qualifiers we are good */
4137 else if (equiv_ptrs(dest, rval)) {
4140 /* test for struct/union equality */
4141 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4142 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4143 (dest->type_ident == rval->type_ident)) {
4147 error(state, 0, "Incompatible types in assignment");
4151 static struct triple *write_expr(
4152 struct compile_state *state, struct triple *dest, struct triple *rval)
4159 internal_error(state, 0, "missing rval");
4162 if (rval->op == OP_LIST) {
4163 internal_error(state, 0, "expression of type OP_LIST?");
4165 if (!is_lvalue(state, dest)) {
4166 internal_error(state, 0, "writing to a non lvalue?");
4169 write_compatible(state, dest->type, rval->type);
4171 /* Now figure out which assignment operator to use */
4173 if (is_in_reg(state, dest)) {
4178 def = triple(state, op, dest->type, dest, rval);
4182 static struct triple *init_expr(
4183 struct compile_state *state, struct triple *dest, struct triple *rval)
4189 internal_error(state, 0, "missing rval");
4191 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4192 rval = read_expr(state, rval);
4193 def = write_expr(state, dest, rval);
4196 /* Fill in the array size if necessary */
4197 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4198 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4199 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4200 dest->type->elements = rval->type->elements;
4203 if (!equiv_types(dest->type, rval->type)) {
4204 error(state, 0, "Incompatible types in inializer");
4206 MISC(dest, 0) = rval;
4211 struct type *arithmetic_result(
4212 struct compile_state *state, struct triple *left, struct triple *right)
4215 /* Sanity checks to ensure I am working with arithmetic types */
4216 arithmetic(state, left);
4217 arithmetic(state, right);
4219 do_arithmetic_conversion(
4221 right->type->type), 0, 0);
4225 struct type *ptr_arithmetic_result(
4226 struct compile_state *state, struct triple *left, struct triple *right)
4229 /* Sanity checks to ensure I am working with the proper types */
4230 ptr_arithmetic(state, left);
4231 arithmetic(state, right);
4232 if (TYPE_ARITHMETIC(left->type->type) &&
4233 TYPE_ARITHMETIC(right->type->type)) {
4234 type = arithmetic_result(state, left, right);
4236 else if (TYPE_PTR(left->type->type)) {
4240 internal_error(state, 0, "huh?");
4247 /* boolean helper function */
4249 static struct triple *ltrue_expr(struct compile_state *state,
4250 struct triple *expr)
4253 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4254 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4255 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4256 /* If the expression is already boolean do nothing */
4259 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4265 static struct triple *lfalse_expr(struct compile_state *state,
4266 struct triple *expr)
4268 return triple(state, OP_LFALSE, &int_type, expr, 0);
4271 static struct triple *cond_expr(
4272 struct compile_state *state,
4273 struct triple *test, struct triple *left, struct triple *right)
4276 struct type *result_type;
4277 unsigned int left_type, right_type;
4279 left_type = left->type->type;
4280 right_type = right->type->type;
4282 /* Both operands have arithmetic type */
4283 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4284 result_type = arithmetic_result(state, left, right);
4286 /* Both operands have void type */
4287 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4288 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4289 result_type = &void_type;
4291 /* pointers to the same type... */
4292 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4295 /* Both operands are pointers and left is a pointer to void */
4296 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4297 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4298 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4299 result_type = right->type;
4301 /* Both operands are pointers and right is a pointer to void */
4302 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4303 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4304 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4305 result_type = left->type;
4308 error(state, 0, "Incompatible types in conditional expression");
4310 /* Cleanup and invert the test */
4311 test = lfalse_expr(state, read_expr(state, test));
4312 def = new_triple(state, OP_COND, result_type, 3);
4313 def->param[0] = test;
4314 def->param[1] = left;
4315 def->param[2] = right;
4320 static int expr_depth(struct compile_state *state, struct triple *ins)
4324 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4327 else if (ins->op == OP_DEREF) {
4328 count = expr_depth(state, RHS(ins, 0)) - 1;
4330 else if (ins->op == OP_VAL) {
4331 count = expr_depth(state, RHS(ins, 0)) - 1;
4333 else if (ins->op == OP_COMMA) {
4335 ldepth = expr_depth(state, RHS(ins, 0));
4336 rdepth = expr_depth(state, RHS(ins, 1));
4337 count = (ldepth >= rdepth)? ldepth : rdepth;
4339 else if (ins->op == OP_CALL) {
4340 /* Don't figure the depth of a call just guess it is huge */
4344 struct triple **expr;
4345 expr = triple_rhs(state, ins, 0);
4346 for(;expr; expr = triple_rhs(state, ins, expr)) {
4349 depth = expr_depth(state, *expr);
4350 if (depth > count) {
4359 static struct triple *flatten(
4360 struct compile_state *state, struct triple *first, struct triple *ptr);
4362 static struct triple *flatten_generic(
4363 struct compile_state *state, struct triple *first, struct triple *ptr)
4367 struct triple **ins;
4370 /* Only operations with just a rhs should come here */
4371 rhs = TRIPLE_RHS(ptr->sizes);
4372 lhs = TRIPLE_LHS(ptr->sizes);
4373 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4374 internal_error(state, ptr, "unexpected args for: %d %s",
4375 ptr->op, tops(ptr->op));
4377 /* Find the depth of the rhs elements */
4378 for(i = 0; i < rhs; i++) {
4379 vector[i].ins = &RHS(ptr, i);
4380 vector[i].depth = expr_depth(state, *vector[i].ins);
4382 /* Selection sort the rhs */
4383 for(i = 0; i < rhs; i++) {
4385 for(j = i + 1; j < rhs; j++ ) {
4386 if (vector[j].depth > vector[max].depth) {
4391 struct rhs_vector tmp;
4393 vector[i] = vector[max];
4397 /* Now flatten the rhs elements */
4398 for(i = 0; i < rhs; i++) {
4399 *vector[i].ins = flatten(state, first, *vector[i].ins);
4400 use_triple(*vector[i].ins, ptr);
4403 /* Now flatten the lhs elements */
4404 for(i = 0; i < lhs; i++) {
4405 struct triple **ins = &LHS(ptr, i);
4406 *ins = flatten(state, first, *ins);
4407 use_triple(*ins, ptr);
4412 static struct triple *flatten_land(
4413 struct compile_state *state, struct triple *first, struct triple *ptr)
4415 struct triple *left, *right;
4416 struct triple *val, *test, *jmp, *label1, *end;
4418 /* Find the triples */
4420 right = RHS(ptr, 1);
4422 /* Generate the needed triples */
4425 /* Thread the triples together */
4426 val = flatten(state, first, variable(state, ptr->type));
4427 left = flatten(state, first, write_expr(state, val, left));
4428 test = flatten(state, first,
4429 lfalse_expr(state, read_expr(state, val)));
4430 jmp = flatten(state, first, branch(state, end, test));
4431 label1 = flatten(state, first, label(state));
4432 right = flatten(state, first, write_expr(state, val, right));
4433 TARG(jmp, 0) = flatten(state, first, end);
4435 /* Now give the caller something to chew on */
4436 return read_expr(state, val);
4439 static struct triple *flatten_lor(
4440 struct compile_state *state, struct triple *first, struct triple *ptr)
4442 struct triple *left, *right;
4443 struct triple *val, *jmp, *label1, *end;
4445 /* Find the triples */
4447 right = RHS(ptr, 1);
4449 /* Generate the needed triples */
4452 /* Thread the triples together */
4453 val = flatten(state, first, variable(state, ptr->type));
4454 left = flatten(state, first, write_expr(state, val, left));
4455 jmp = flatten(state, first, branch(state, end, left));
4456 label1 = flatten(state, first, label(state));
4457 right = flatten(state, first, write_expr(state, val, right));
4458 TARG(jmp, 0) = flatten(state, first, end);
4461 /* Now give the caller something to chew on */
4462 return read_expr(state, val);
4465 static struct triple *flatten_cond(
4466 struct compile_state *state, struct triple *first, struct triple *ptr)
4468 struct triple *test, *left, *right;
4469 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4471 /* Find the triples */
4474 right = RHS(ptr, 2);
4476 /* Generate the needed triples */
4478 middle = label(state);
4480 /* Thread the triples together */
4481 val = flatten(state, first, variable(state, ptr->type));
4482 test = flatten(state, first, test);
4483 jmp1 = flatten(state, first, branch(state, middle, test));
4484 label1 = flatten(state, first, label(state));
4485 left = flatten(state, first, left);
4486 mv1 = flatten(state, first, write_expr(state, val, left));
4487 jmp2 = flatten(state, first, branch(state, end, 0));
4488 TARG(jmp1, 0) = flatten(state, first, middle);
4489 right = flatten(state, first, right);
4490 mv2 = flatten(state, first, write_expr(state, val, right));
4491 TARG(jmp2, 0) = flatten(state, first, end);
4493 /* Now give the caller something to chew on */
4494 return read_expr(state, val);
4497 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4499 struct triple *nfunc;
4500 struct triple *nfirst, *ofirst;
4501 struct triple *new, *old;
4504 fprintf(stdout, "\n");
4505 loc(stdout, state, 0);
4506 fprintf(stdout, "\n__________ copy_func _________\n");
4507 print_triple(state, ofunc);
4508 fprintf(stdout, "__________ copy_func _________ done\n\n");
4511 /* Make a new copy of the old function */
4512 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4514 ofirst = old = RHS(ofunc, 0);
4518 old_rhs = TRIPLE_RHS(old->sizes);
4519 new = alloc_triple(state, old->op, old->type, old_rhs,
4520 old->filename, old->line, old->col);
4521 if (IS_CONST_OP(new->op)) {
4522 memcpy(&new->u, &old->u, sizeof(new->u));
4524 #warning "WISHLIST find a way to handle SDECL without a special case..."
4525 /* The problem is that I don't flatten the misc field,
4526 * so I cannot look the value the misc field should have.
4528 else if (new->op == OP_SDECL) {
4529 MISC(new, 0) = MISC(old, 0);
4532 RHS(nfunc, 0) = nfirst = new;
4535 insert_triple(state, nfirst, new);
4537 new->id |= TRIPLE_FLAG_FLATTENED;
4539 /* During the copy remember new as user of old */
4540 use_triple(old, new);
4542 /* Populate the return type if present */
4543 if (old == MISC(ofunc, 0)) {
4544 MISC(nfunc, 0) = new;
4547 } while(old != ofirst);
4549 /* Make a second pass to fix up any unresolved references */
4553 struct triple **oexpr, **nexpr;
4555 /* Lookup where the copy is, to join pointers */
4556 count = TRIPLE_SIZE(old->sizes);
4557 for(i = 0; i < count; i++) {
4558 oexpr = &old->param[i];
4559 nexpr = &new->param[i];
4560 if (!*nexpr && *oexpr && (*oexpr)->use) {
4561 *nexpr = (*oexpr)->use->member;
4562 if (*nexpr == old) {
4563 internal_error(state, 0, "new == old?");
4565 use_triple(*nexpr, new);
4567 if (!*nexpr && *oexpr) {
4568 internal_error(state, 0, "Could not copy %d\n", i);
4573 } while((old != ofirst) && (new != nfirst));
4575 /* Make a third pass to cleanup the extra useses */
4579 unuse_triple(old, new);
4582 } while ((old != ofirst) && (new != nfirst));
4586 static struct triple *flatten_call(
4587 struct compile_state *state, struct triple *first, struct triple *ptr)
4589 /* Inline the function call */
4591 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4592 struct triple *end, *nend;
4595 /* Find the triples */
4596 ofunc = MISC(ptr, 0);
4597 if (ofunc->op != OP_LIST) {
4598 internal_error(state, 0, "improper function");
4600 nfunc = copy_func(state, ofunc);
4601 nfirst = RHS(nfunc, 0)->next;
4602 /* Prepend the parameter reading into the new function list */
4603 ptype = nfunc->type->right;
4604 param = RHS(nfunc, 0)->next;
4605 pvals = TRIPLE_RHS(ptr->sizes);
4606 for(i = 0; i < pvals; i++) {
4610 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4611 atype = ptype->left;
4613 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4614 param = param->next;
4617 flatten(state, nfirst, write_expr(state, param, arg));
4618 ptype = ptype->right;
4619 param = param->next;
4622 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4623 result = read_expr(state, MISC(nfunc,0));
4626 fprintf(stdout, "\n");
4627 loc(stdout, state, 0);
4628 fprintf(stdout, "\n__________ flatten_call _________\n");
4629 print_triple(state, nfunc);
4630 fprintf(stdout, "__________ flatten_call _________ done\n\n");
4633 /* Get rid of the extra triples */
4634 nfirst = RHS(nfunc, 0)->next;
4635 free_triple(state, RHS(nfunc, 0));
4637 free_triple(state, nfunc);
4639 /* Append the new function list onto the return list */
4641 nend = nfirst->prev;
4650 static struct triple *flatten(
4651 struct compile_state *state, struct triple *first, struct triple *ptr)
4653 struct triple *orig_ptr;
4658 /* Only flatten triples once */
4659 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4665 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4666 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4667 use_triple(LHS(ptr, 0), ptr);
4668 use_triple(RHS(ptr, 0), ptr);
4671 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4675 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4676 return MISC(ptr, 0);
4679 ptr = flatten_land(state, first, ptr);
4682 ptr = flatten_lor(state, first, ptr);
4685 ptr = flatten_cond(state, first, ptr);
4688 ptr = flatten_call(state, first, ptr);
4692 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4693 use_triple(RHS(ptr, 0), ptr);
4696 use_triple(TARG(ptr, 0), ptr);
4697 if (TRIPLE_RHS(ptr->sizes)) {
4698 use_triple(RHS(ptr, 0), ptr);
4699 if (ptr->next != ptr) {
4700 use_triple(ptr->next, ptr);
4705 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4706 use_triple(MISC(ptr, 0), ptr);
4709 /* Since OP_DEREF is just a marker delete it when I flatten it */
4711 RHS(orig_ptr, 0) = 0;
4712 free_triple(state, orig_ptr);
4716 struct triple *base;
4718 base = flatten(state, first, base);
4719 if (base->op == OP_VAL_VEC) {
4720 ptr = struct_field(state, base, ptr->u.field);
4728 /* Flatten the easy cases we don't override */
4729 ptr = flatten_generic(state, first, ptr);
4732 } while(ptr && (ptr != orig_ptr));
4734 insert_triple(state, first, ptr);
4735 ptr->id |= TRIPLE_FLAG_FLATTENED;
4740 static void release_expr(struct compile_state *state, struct triple *expr)
4742 struct triple *head;
4743 head = label(state);
4744 flatten(state, head, expr);
4745 while(head->next != head) {
4746 release_triple(state, head->next);
4748 free_triple(state, head);
4751 static int replace_rhs_use(struct compile_state *state,
4752 struct triple *orig, struct triple *new, struct triple *use)
4754 struct triple **expr;
4757 expr = triple_rhs(state, use, 0);
4758 for(;expr; expr = triple_rhs(state, use, expr)) {
4759 if (*expr == orig) {
4765 unuse_triple(orig, use);
4766 use_triple(new, use);
4771 static int replace_lhs_use(struct compile_state *state,
4772 struct triple *orig, struct triple *new, struct triple *use)
4774 struct triple **expr;
4777 expr = triple_lhs(state, use, 0);
4778 for(;expr; expr = triple_lhs(state, use, expr)) {
4779 if (*expr == orig) {
4785 unuse_triple(orig, use);
4786 use_triple(new, use);
4791 static void propogate_use(struct compile_state *state,
4792 struct triple *orig, struct triple *new)
4794 struct triple_set *user, *next;
4795 for(user = orig->use; user; user = next) {
4801 found |= replace_rhs_use(state, orig, new, use);
4802 found |= replace_lhs_use(state, orig, new, use);
4804 internal_error(state, use, "use without use");
4808 internal_error(state, orig, "used after propogate_use");
4814 * ===========================
4817 static struct triple *mk_add_expr(
4818 struct compile_state *state, struct triple *left, struct triple *right)
4820 struct type *result_type;
4821 /* Put pointer operands on the left */
4822 if (is_pointer(right)) {
4828 result_type = ptr_arithmetic_result(state, left, right);
4829 left = read_expr(state, left);
4830 right = read_expr(state, right);
4831 if (is_pointer(left)) {
4832 right = triple(state,
4833 is_signed(right->type)? OP_SMUL : OP_UMUL,
4836 int_const(state, &ulong_type,
4837 size_of(state, left->type->left)));
4839 return triple(state, OP_ADD, result_type, left, right);
4842 static struct triple *mk_sub_expr(
4843 struct compile_state *state, struct triple *left, struct triple *right)
4845 struct type *result_type;
4846 result_type = ptr_arithmetic_result(state, left, right);
4847 left = read_expr(state, left);
4848 right = read_expr(state, right);
4849 if (is_pointer(left)) {
4850 right = triple(state,
4851 is_signed(right->type)? OP_SMUL : OP_UMUL,
4854 int_const(state, &ulong_type,
4855 size_of(state, left->type->left)));
4857 return triple(state, OP_SUB, result_type, left, right);
4860 static struct triple *mk_pre_inc_expr(
4861 struct compile_state *state, struct triple *def)
4865 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
4866 return triple(state, OP_VAL, def->type,
4867 write_expr(state, def, val),
4871 static struct triple *mk_pre_dec_expr(
4872 struct compile_state *state, struct triple *def)
4876 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
4877 return triple(state, OP_VAL, def->type,
4878 write_expr(state, def, val),
4882 static struct triple *mk_post_inc_expr(
4883 struct compile_state *state, struct triple *def)
4887 val = read_expr(state, def);
4888 return triple(state, OP_VAL, def->type,
4889 write_expr(state, def,
4890 mk_add_expr(state, val, int_const(state, &int_type, 1)))
4894 static struct triple *mk_post_dec_expr(
4895 struct compile_state *state, struct triple *def)
4899 val = read_expr(state, def);
4900 return triple(state, OP_VAL, def->type,
4901 write_expr(state, def,
4902 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
4906 static struct triple *mk_subscript_expr(
4907 struct compile_state *state, struct triple *left, struct triple *right)
4909 left = read_expr(state, left);
4910 right = read_expr(state, right);
4911 if (!is_pointer(left) && !is_pointer(right)) {
4912 error(state, left, "subscripted value is not a pointer");
4914 return mk_deref_expr(state, mk_add_expr(state, left, right));
4918 * Compile time evaluation
4919 * ===========================
4921 static int is_const(struct triple *ins)
4923 return IS_CONST_OP(ins->op);
4926 static int constants_equal(struct compile_state *state,
4927 struct triple *left, struct triple *right)
4930 if (!is_const(left) || !is_const(right)) {
4933 else if (left->op != right->op) {
4936 else if (!equiv_types(left->type, right->type)) {
4943 if (left->u.cval == right->u.cval) {
4949 size_t lsize, rsize;
4950 lsize = size_of(state, left->type);
4951 rsize = size_of(state, right->type);
4952 if (lsize != rsize) {
4955 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
4961 if ((RHS(left, 0) == RHS(right, 0)) &&
4962 (left->u.cval == right->u.cval)) {
4967 internal_error(state, left, "uknown constant type");
4974 static int is_zero(struct triple *ins)
4976 return is_const(ins) && (ins->u.cval == 0);
4979 static int is_one(struct triple *ins)
4981 return is_const(ins) && (ins->u.cval == 1);
4984 static long_t bsr(ulong_t value)
4987 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
4998 static long_t bsf(ulong_t value)
5001 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5012 static long_t log2(ulong_t value)
5017 static long_t tlog2(struct triple *ins)
5019 return log2(ins->u.cval);
5022 static int is_pow2(struct triple *ins)
5024 ulong_t value, mask;
5026 if (!is_const(ins)) {
5029 value = ins->u.cval;
5036 return ((value & mask) == value);
5039 static ulong_t read_const(struct compile_state *state,
5040 struct triple *ins, struct triple **expr)
5044 switch(rhs->type->type &TYPE_MASK) {
5056 internal_error(state, rhs, "bad type to read_const\n");
5062 static long_t read_sconst(struct triple *ins, struct triple **expr)
5066 return (long_t)(rhs->u.cval);
5069 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5071 struct triple **expr;
5072 expr = triple_rhs(state, ins, 0);
5073 for(;expr;expr = triple_rhs(state, ins, expr)) {
5075 unuse_triple(*expr, ins);
5081 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5083 struct triple **expr;
5084 expr = triple_lhs(state, ins, 0);
5085 for(;expr;expr = triple_lhs(state, ins, expr)) {
5086 unuse_triple(*expr, ins);
5091 static void check_lhs(struct compile_state *state, struct triple *ins)
5093 struct triple **expr;
5094 expr = triple_lhs(state, ins, 0);
5095 for(;expr;expr = triple_lhs(state, ins, expr)) {
5096 internal_error(state, ins, "unexpected lhs");
5100 static void check_targ(struct compile_state *state, struct triple *ins)
5102 struct triple **expr;
5103 expr = triple_targ(state, ins, 0);
5104 for(;expr;expr = triple_targ(state, ins, expr)) {
5105 internal_error(state, ins, "unexpected targ");
5109 static void wipe_ins(struct compile_state *state, struct triple *ins)
5111 /* Becareful which instructions you replace the wiped
5112 * instruction with, as there are not enough slots
5113 * in all instructions to hold all others.
5115 check_targ(state, ins);
5116 unuse_rhs(state, ins);
5117 unuse_lhs(state, ins);
5120 static void mkcopy(struct compile_state *state,
5121 struct triple *ins, struct triple *rhs)
5123 wipe_ins(state, ins);
5125 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5127 use_triple(RHS(ins, 0), ins);
5130 static void mkconst(struct compile_state *state,
5131 struct triple *ins, ulong_t value)
5133 if (!is_integral(ins) && !is_pointer(ins)) {
5134 internal_error(state, ins, "unknown type to make constant\n");
5136 wipe_ins(state, ins);
5137 ins->op = OP_INTCONST;
5138 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5139 ins->u.cval = value;
5142 static void mkaddr_const(struct compile_state *state,
5143 struct triple *ins, struct triple *sdecl, ulong_t value)
5145 wipe_ins(state, ins);
5146 ins->op = OP_ADDRCONST;
5147 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5148 RHS(ins, 0) = sdecl;
5149 ins->u.cval = value;
5150 use_triple(sdecl, ins);
5153 /* Transform multicomponent variables into simple register variables */
5154 static void flatten_structures(struct compile_state *state)
5156 struct triple *ins, *first;
5157 first = RHS(state->main_function, 0);
5159 /* Pass one expand structure values into valvecs.
5163 struct triple *next;
5165 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5166 if (ins->op == OP_VAL_VEC) {
5169 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5170 struct triple *def, **vector;
5177 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5178 ins->filename, ins->line, ins->col);
5180 vector = &RHS(next, 0);
5181 tptr = next->type->left;
5182 for(i = 0; i < next->type->elements; i++) {
5183 struct triple *sfield;
5186 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5187 mtype = mtype->left;
5189 sfield = deref_field(state, def, mtype->field_ident);
5192 state, op, mtype, sfield, 0);
5193 vector[i]->filename = next->filename;
5194 vector[i]->line = next->line;
5195 vector[i]->col = next->col;
5198 propogate_use(state, ins, next);
5199 flatten(state, ins, next);
5200 free_triple(state, ins);
5202 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5203 struct triple *src, *dst, **vector;
5211 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5212 ins->filename, ins->line, ins->col);
5214 vector = &RHS(next, 0);
5215 tptr = next->type->left;
5216 for(i = 0; i < ins->type->elements; i++) {
5217 struct triple *dfield, *sfield;
5220 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5221 mtype = mtype->left;
5223 sfield = deref_field(state, src, mtype->field_ident);
5224 dfield = deref_field(state, dst, mtype->field_ident);
5226 state, op, mtype, dfield, sfield);
5227 vector[i]->filename = next->filename;
5228 vector[i]->line = next->line;
5229 vector[i]->col = next->col;
5232 propogate_use(state, ins, next);
5233 flatten(state, ins, next);
5234 free_triple(state, ins);
5238 } while(ins != first);
5239 /* Pass two flatten the valvecs.
5243 struct triple *next;
5245 if (ins->op == OP_VAL_VEC) {
5246 release_triple(state, ins);
5249 } while(ins != first);
5250 /* Pass three verify the state and set ->id to 0.
5255 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5256 internal_error(state, 0, "STRUCT_TYPE remains?");
5258 if (ins->op == OP_DOT) {
5259 internal_error(state, 0, "OP_DOT remains?");
5261 if (ins->op == OP_VAL_VEC) {
5262 internal_error(state, 0, "OP_VAL_VEC remains?");
5265 } while(ins != first);
5268 /* For those operations that cannot be simplified */
5269 static void simplify_noop(struct compile_state *state, struct triple *ins)
5274 static void simplify_smul(struct compile_state *state, struct triple *ins)
5276 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5279 RHS(ins, 0) = RHS(ins, 1);
5282 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5284 left = read_sconst(ins, &RHS(ins, 0));
5285 right = read_sconst(ins, &RHS(ins, 1));
5286 mkconst(state, ins, left * right);
5288 else if (is_zero(RHS(ins, 1))) {
5289 mkconst(state, ins, 0);
5291 else if (is_one(RHS(ins, 1))) {
5292 mkcopy(state, ins, RHS(ins, 0));
5294 else if (is_pow2(RHS(ins, 1))) {
5296 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5298 insert_triple(state, ins, val);
5299 unuse_triple(RHS(ins, 1), ins);
5300 use_triple(val, ins);
5305 static void simplify_umul(struct compile_state *state, struct triple *ins)
5307 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5310 RHS(ins, 0) = RHS(ins, 1);
5313 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5314 ulong_t left, right;
5315 left = read_const(state, ins, &RHS(ins, 0));
5316 right = read_const(state, ins, &RHS(ins, 1));
5317 mkconst(state, ins, left * right);
5319 else if (is_zero(RHS(ins, 1))) {
5320 mkconst(state, ins, 0);
5322 else if (is_one(RHS(ins, 1))) {
5323 mkcopy(state, ins, RHS(ins, 0));
5325 else if (is_pow2(RHS(ins, 1))) {
5327 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5329 insert_triple(state, ins, val);
5330 unuse_triple(RHS(ins, 1), ins);
5331 use_triple(val, ins);
5336 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5338 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5340 left = read_sconst(ins, &RHS(ins, 0));
5341 right = read_sconst(ins, &RHS(ins, 1));
5342 mkconst(state, ins, left / right);
5344 else if (is_zero(RHS(ins, 0))) {
5345 mkconst(state, ins, 0);
5347 else if (is_zero(RHS(ins, 1))) {
5348 error(state, ins, "division by zero");
5350 else if (is_one(RHS(ins, 1))) {
5351 mkcopy(state, ins, RHS(ins, 0));
5353 else if (is_pow2(RHS(ins, 1))) {
5355 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5357 insert_triple(state, ins, val);
5358 unuse_triple(RHS(ins, 1), ins);
5359 use_triple(val, ins);
5364 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5366 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5367 ulong_t left, right;
5368 left = read_const(state, ins, &RHS(ins, 0));
5369 right = read_const(state, ins, &RHS(ins, 1));
5370 mkconst(state, ins, left / right);
5372 else if (is_zero(RHS(ins, 0))) {
5373 mkconst(state, ins, 0);
5375 else if (is_zero(RHS(ins, 1))) {
5376 error(state, ins, "division by zero");
5378 else if (is_one(RHS(ins, 1))) {
5379 mkcopy(state, ins, RHS(ins, 0));
5381 else if (is_pow2(RHS(ins, 1))) {
5383 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5385 insert_triple(state, ins, val);
5386 unuse_triple(RHS(ins, 1), ins);
5387 use_triple(val, ins);
5392 static void simplify_smod(struct compile_state *state, struct triple *ins)
5394 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5396 left = read_const(state, ins, &RHS(ins, 0));
5397 right = read_const(state, ins, &RHS(ins, 1));
5398 mkconst(state, ins, left % right);
5400 else if (is_zero(RHS(ins, 0))) {
5401 mkconst(state, ins, 0);
5403 else if (is_zero(RHS(ins, 1))) {
5404 error(state, ins, "division by zero");
5406 else if (is_one(RHS(ins, 1))) {
5407 mkconst(state, ins, 0);
5409 else if (is_pow2(RHS(ins, 1))) {
5411 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5413 insert_triple(state, ins, val);
5414 unuse_triple(RHS(ins, 1), ins);
5415 use_triple(val, ins);
5419 static void simplify_umod(struct compile_state *state, struct triple *ins)
5421 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5422 ulong_t left, right;
5423 left = read_const(state, ins, &RHS(ins, 0));
5424 right = read_const(state, ins, &RHS(ins, 1));
5425 mkconst(state, ins, left % right);
5427 else if (is_zero(RHS(ins, 0))) {
5428 mkconst(state, ins, 0);
5430 else if (is_zero(RHS(ins, 1))) {
5431 error(state, ins, "division by zero");
5433 else if (is_one(RHS(ins, 1))) {
5434 mkconst(state, ins, 0);
5436 else if (is_pow2(RHS(ins, 1))) {
5438 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5440 insert_triple(state, ins, val);
5441 unuse_triple(RHS(ins, 1), ins);
5442 use_triple(val, ins);
5447 static void simplify_add(struct compile_state *state, struct triple *ins)
5449 /* start with the pointer on the left */
5450 if (is_pointer(RHS(ins, 1))) {
5453 RHS(ins, 0) = RHS(ins, 1);
5456 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5457 if (!is_pointer(RHS(ins, 0))) {
5458 ulong_t left, right;
5459 left = read_const(state, ins, &RHS(ins, 0));
5460 right = read_const(state, ins, &RHS(ins, 1));
5461 mkconst(state, ins, left + right);
5463 else /* op == OP_ADDRCONST */ {
5464 struct triple *sdecl;
5465 ulong_t left, right;
5466 sdecl = RHS(RHS(ins, 0), 0);
5467 left = RHS(ins, 0)->u.cval;
5468 right = RHS(ins, 1)->u.cval;
5469 mkaddr_const(state, ins, sdecl, left + right);
5472 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5475 RHS(ins, 1) = RHS(ins, 0);
5480 static void simplify_sub(struct compile_state *state, struct triple *ins)
5482 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5483 if (!is_pointer(RHS(ins, 0))) {
5484 ulong_t left, right;
5485 left = read_const(state, ins, &RHS(ins, 0));
5486 right = read_const(state, ins, &RHS(ins, 1));
5487 mkconst(state, ins, left - right);
5489 else /* op == OP_ADDRCONST */ {
5490 struct triple *sdecl;
5491 ulong_t left, right;
5492 sdecl = RHS(RHS(ins, 0), 0);
5493 left = RHS(ins, 0)->u.cval;
5494 right = RHS(ins, 1)->u.cval;
5495 mkaddr_const(state, ins, sdecl, left - right);
5500 static void simplify_sl(struct compile_state *state, struct triple *ins)
5502 if (is_const(RHS(ins, 1))) {
5504 right = read_const(state, ins, &RHS(ins, 1));
5505 if (right >= (size_of(state, ins->type)*8)) {
5506 warning(state, ins, "left shift count >= width of type");
5509 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5510 ulong_t left, right;
5511 left = read_const(state, ins, &RHS(ins, 0));
5512 right = read_const(state, ins, &RHS(ins, 1));
5513 mkconst(state, ins, left << right);
5517 static void simplify_usr(struct compile_state *state, struct triple *ins)
5519 if (is_const(RHS(ins, 1))) {
5521 right = read_const(state, ins, &RHS(ins, 1));
5522 if (right >= (size_of(state, ins->type)*8)) {
5523 warning(state, ins, "right shift count >= width of type");
5526 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5527 ulong_t left, right;
5528 left = read_const(state, ins, &RHS(ins, 0));
5529 right = read_const(state, ins, &RHS(ins, 1));
5530 mkconst(state, ins, left >> right);
5534 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5536 if (is_const(RHS(ins, 1))) {
5538 right = read_const(state, ins, &RHS(ins, 1));
5539 if (right >= (size_of(state, ins->type)*8)) {
5540 warning(state, ins, "right shift count >= width of type");
5543 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5545 left = read_sconst(ins, &RHS(ins, 0));
5546 right = read_sconst(ins, &RHS(ins, 1));
5547 mkconst(state, ins, left >> right);
5551 static void simplify_and(struct compile_state *state, struct triple *ins)
5553 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5554 ulong_t left, right;
5555 left = read_const(state, ins, &RHS(ins, 0));
5556 right = read_const(state, ins, &RHS(ins, 1));
5557 mkconst(state, ins, left & right);
5561 static void simplify_or(struct compile_state *state, struct triple *ins)
5563 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5564 ulong_t left, right;
5565 left = read_const(state, ins, &RHS(ins, 0));
5566 right = read_const(state, ins, &RHS(ins, 1));
5567 mkconst(state, ins, left | right);
5571 static void simplify_xor(struct compile_state *state, struct triple *ins)
5573 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5574 ulong_t left, right;
5575 left = read_const(state, ins, &RHS(ins, 0));
5576 right = read_const(state, ins, &RHS(ins, 1));
5577 mkconst(state, ins, left ^ right);
5581 static void simplify_pos(struct compile_state *state, struct triple *ins)
5583 if (is_const(RHS(ins, 0))) {
5584 mkconst(state, ins, RHS(ins, 0)->u.cval);
5587 mkcopy(state, ins, RHS(ins, 0));
5591 static void simplify_neg(struct compile_state *state, struct triple *ins)
5593 if (is_const(RHS(ins, 0))) {
5595 left = read_const(state, ins, &RHS(ins, 0));
5596 mkconst(state, ins, -left);
5598 else if (RHS(ins, 0)->op == OP_NEG) {
5599 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5603 static void simplify_invert(struct compile_state *state, struct triple *ins)
5605 if (is_const(RHS(ins, 0))) {
5607 left = read_const(state, ins, &RHS(ins, 0));
5608 mkconst(state, ins, ~left);
5612 static void simplify_eq(struct compile_state *state, struct triple *ins)
5614 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5615 ulong_t left, right;
5616 left = read_const(state, ins, &RHS(ins, 0));
5617 right = read_const(state, ins, &RHS(ins, 1));
5618 mkconst(state, ins, left == right);
5620 else if (RHS(ins, 0) == RHS(ins, 1)) {
5621 mkconst(state, ins, 1);
5625 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5627 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5628 ulong_t left, right;
5629 left = read_const(state, ins, &RHS(ins, 0));
5630 right = read_const(state, ins, &RHS(ins, 1));
5631 mkconst(state, ins, left != right);
5633 else if (RHS(ins, 0) == RHS(ins, 1)) {
5634 mkconst(state, ins, 0);
5638 static void simplify_sless(struct compile_state *state, struct triple *ins)
5640 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5642 left = read_sconst(ins, &RHS(ins, 0));
5643 right = read_sconst(ins, &RHS(ins, 1));
5644 mkconst(state, ins, left < right);
5646 else if (RHS(ins, 0) == RHS(ins, 1)) {
5647 mkconst(state, ins, 0);
5651 static void simplify_uless(struct compile_state *state, struct triple *ins)
5653 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5654 ulong_t left, right;
5655 left = read_const(state, ins, &RHS(ins, 0));
5656 right = read_const(state, ins, &RHS(ins, 1));
5657 mkconst(state, ins, left < right);
5659 else if (is_zero(RHS(ins, 0))) {
5660 mkconst(state, ins, 1);
5662 else if (RHS(ins, 0) == RHS(ins, 1)) {
5663 mkconst(state, ins, 0);
5667 static void simplify_smore(struct compile_state *state, struct triple *ins)
5669 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5671 left = read_sconst(ins, &RHS(ins, 0));
5672 right = read_sconst(ins, &RHS(ins, 1));
5673 mkconst(state, ins, left > right);
5675 else if (RHS(ins, 0) == RHS(ins, 1)) {
5676 mkconst(state, ins, 0);
5680 static void simplify_umore(struct compile_state *state, struct triple *ins)
5682 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5683 ulong_t left, right;
5684 left = read_const(state, ins, &RHS(ins, 0));
5685 right = read_const(state, ins, &RHS(ins, 1));
5686 mkconst(state, ins, left > right);
5688 else if (is_zero(RHS(ins, 1))) {
5689 mkconst(state, ins, 1);
5691 else if (RHS(ins, 0) == RHS(ins, 1)) {
5692 mkconst(state, ins, 0);
5697 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5699 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5701 left = read_sconst(ins, &RHS(ins, 0));
5702 right = read_sconst(ins, &RHS(ins, 1));
5703 mkconst(state, ins, left <= right);
5705 else if (RHS(ins, 0) == RHS(ins, 1)) {
5706 mkconst(state, ins, 1);
5710 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5712 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5713 ulong_t left, right;
5714 left = read_const(state, ins, &RHS(ins, 0));
5715 right = read_const(state, ins, &RHS(ins, 1));
5716 mkconst(state, ins, left <= right);
5718 else if (is_zero(RHS(ins, 0))) {
5719 mkconst(state, ins, 1);
5721 else if (RHS(ins, 0) == RHS(ins, 1)) {
5722 mkconst(state, ins, 1);
5726 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5728 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5730 left = read_sconst(ins, &RHS(ins, 0));
5731 right = read_sconst(ins, &RHS(ins, 1));
5732 mkconst(state, ins, left >= right);
5734 else if (RHS(ins, 0) == RHS(ins, 1)) {
5735 mkconst(state, ins, 1);
5739 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5741 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5742 ulong_t left, right;
5743 left = read_const(state, ins, &RHS(ins, 0));
5744 right = read_const(state, ins, &RHS(ins, 1));
5745 mkconst(state, ins, left >= right);
5747 else if (is_zero(RHS(ins, 1))) {
5748 mkconst(state, ins, 1);
5750 else if (RHS(ins, 0) == RHS(ins, 1)) {
5751 mkconst(state, ins, 1);
5755 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5757 if (is_const(RHS(ins, 0))) {
5759 left = read_const(state, ins, &RHS(ins, 0));
5760 mkconst(state, ins, left == 0);
5762 /* Otherwise if I am the only user... */
5763 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5765 /* Invert a boolean operation */
5766 switch(RHS(ins, 0)->op) {
5767 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
5768 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
5769 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
5770 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
5771 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
5772 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
5773 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
5774 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
5775 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
5776 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
5777 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
5778 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
5784 mkcopy(state, ins, RHS(ins, 0));
5789 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5791 if (is_const(RHS(ins, 0))) {
5793 left = read_const(state, ins, &RHS(ins, 0));
5794 mkconst(state, ins, left != 0);
5796 else switch(RHS(ins, 0)->op) {
5797 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
5798 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
5799 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
5800 mkcopy(state, ins, RHS(ins, 0));
5805 static void simplify_copy(struct compile_state *state, struct triple *ins)
5807 if (is_const(RHS(ins, 0))) {
5808 switch(RHS(ins, 0)->op) {
5812 left = read_const(state, ins, &RHS(ins, 0));
5813 mkconst(state, ins, left);
5818 struct triple *sdecl;
5820 sdecl = RHS(ins, 0);
5821 offset = ins->u.cval;
5822 mkaddr_const(state, ins, sdecl, offset);
5826 internal_error(state, ins, "uknown constant");
5832 static void simplify_branch(struct compile_state *state, struct triple *ins)
5834 struct block *block;
5835 if (ins->op != OP_BRANCH) {
5836 internal_error(state, ins, "not branch");
5838 if (ins->use != 0) {
5839 internal_error(state, ins, "branch use");
5841 #warning "FIXME implement simplify branch."
5842 /* The challenge here with simplify branch is that I need to
5843 * make modifications to the control flow graph as well
5844 * as to the branch instruction itself.
5846 block = ins->u.block;
5848 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
5849 struct triple *targ;
5851 value = read_const(state, ins, &RHS(ins, 0));
5852 unuse_triple(RHS(ins, 0), ins);
5853 targ = TARG(ins, 0);
5854 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
5856 unuse_triple(ins->next, ins);
5857 TARG(ins, 0) = targ;
5860 unuse_triple(targ, ins);
5861 TARG(ins, 0) = ins->next;
5863 #warning "FIXME handle the case of making a branch unconditional"
5865 if (TARG(ins, 0) == ins->next) {
5866 unuse_triple(ins->next, ins);
5867 if (TRIPLE_RHS(ins->sizes)) {
5868 unuse_triple(RHS(ins, 0), ins);
5869 unuse_triple(ins->next, ins);
5871 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5874 internal_error(state, ins, "noop use != 0");
5876 #warning "FIXME handle the case of killing a branch"
5880 static void simplify_phi(struct compile_state *state, struct triple *ins)
5882 struct triple **expr;
5884 expr = triple_rhs(state, ins, 0);
5885 if (!*expr || !is_const(*expr)) {
5888 value = read_const(state, ins, expr);
5889 for(;expr;expr = triple_rhs(state, ins, expr)) {
5890 if (!*expr || !is_const(*expr)) {
5893 if (value != read_const(state, ins, expr)) {
5897 mkconst(state, ins, value);
5901 static void simplify_bsf(struct compile_state *state, struct triple *ins)
5903 if (is_const(RHS(ins, 0))) {
5905 left = read_const(state, ins, &RHS(ins, 0));
5906 mkconst(state, ins, bsf(left));
5910 static void simplify_bsr(struct compile_state *state, struct triple *ins)
5912 if (is_const(RHS(ins, 0))) {
5914 left = read_const(state, ins, &RHS(ins, 0));
5915 mkconst(state, ins, bsr(left));
5920 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
5921 static const simplify_t table_simplify[] = {
5923 #define simplify_smul simplify_noop
5924 #define simplify_umul simplify_noop
5925 #define simplify_sdiv simplify_noop
5926 #define simplify_udiv simplify_noop
5927 #define simplify_smod simplify_noop
5928 #define simplify_umod simplify_noop
5931 #define simplify_add simplify_noop
5932 #define simplify_sub simplify_noop
5935 #define simplify_sl simplify_noop
5936 #define simplify_usr simplify_noop
5937 #define simplify_ssr simplify_noop
5940 #define simplify_and simplify_noop
5941 #define simplify_xor simplify_noop
5942 #define simplify_or simplify_noop
5945 #define simplify_pos simplify_noop
5946 #define simplify_neg simplify_noop
5947 #define simplify_invert simplify_noop
5951 #define simplify_eq simplify_noop
5952 #define simplify_noteq simplify_noop
5955 #define simplify_sless simplify_noop
5956 #define simplify_uless simplify_noop
5957 #define simplify_smore simplify_noop
5958 #define simplify_umore simplify_noop
5961 #define simplify_slesseq simplify_noop
5962 #define simplify_ulesseq simplify_noop
5963 #define simplify_smoreeq simplify_noop
5964 #define simplify_umoreeq simplify_noop
5967 #define simplify_lfalse simplify_noop
5970 #define simplify_ltrue simplify_noop
5974 #define simplify_copy simplify_noop
5978 #define simplify_branch simplify_noop
5982 #define simplify_phi simplify_noop
5986 #define simplify_bsf simplify_noop
5987 #define simplify_bsr simplify_noop
5990 [OP_SMUL ] = simplify_smul,
5991 [OP_UMUL ] = simplify_umul,
5992 [OP_SDIV ] = simplify_sdiv,
5993 [OP_UDIV ] = simplify_udiv,
5994 [OP_SMOD ] = simplify_smod,
5995 [OP_UMOD ] = simplify_umod,
5996 [OP_ADD ] = simplify_add,
5997 [OP_SUB ] = simplify_sub,
5998 [OP_SL ] = simplify_sl,
5999 [OP_USR ] = simplify_usr,
6000 [OP_SSR ] = simplify_ssr,
6001 [OP_AND ] = simplify_and,
6002 [OP_XOR ] = simplify_xor,
6003 [OP_OR ] = simplify_or,
6004 [OP_POS ] = simplify_pos,
6005 [OP_NEG ] = simplify_neg,
6006 [OP_INVERT ] = simplify_invert,
6008 [OP_EQ ] = simplify_eq,
6009 [OP_NOTEQ ] = simplify_noteq,
6010 [OP_SLESS ] = simplify_sless,
6011 [OP_ULESS ] = simplify_uless,
6012 [OP_SMORE ] = simplify_smore,
6013 [OP_UMORE ] = simplify_umore,
6014 [OP_SLESSEQ ] = simplify_slesseq,
6015 [OP_ULESSEQ ] = simplify_ulesseq,
6016 [OP_SMOREEQ ] = simplify_smoreeq,
6017 [OP_UMOREEQ ] = simplify_umoreeq,
6018 [OP_LFALSE ] = simplify_lfalse,
6019 [OP_LTRUE ] = simplify_ltrue,
6021 [OP_LOAD ] = simplify_noop,
6022 [OP_STORE ] = simplify_noop,
6024 [OP_NOOP ] = simplify_noop,
6026 [OP_INTCONST ] = simplify_noop,
6027 [OP_BLOBCONST ] = simplify_noop,
6028 [OP_ADDRCONST ] = simplify_noop,
6030 [OP_WRITE ] = simplify_noop,
6031 [OP_READ ] = simplify_noop,
6032 [OP_COPY ] = simplify_copy,
6033 [OP_PIECE ] = simplify_noop,
6035 [OP_DOT ] = simplify_noop,
6036 [OP_VAL_VEC ] = simplify_noop,
6038 [OP_LIST ] = simplify_noop,
6039 [OP_BRANCH ] = simplify_branch,
6040 [OP_LABEL ] = simplify_noop,
6041 [OP_ADECL ] = simplify_noop,
6042 [OP_SDECL ] = simplify_noop,
6043 [OP_PHI ] = simplify_phi,
6045 [OP_INB ] = simplify_noop,
6046 [OP_INW ] = simplify_noop,
6047 [OP_INL ] = simplify_noop,
6048 [OP_OUTB ] = simplify_noop,
6049 [OP_OUTW ] = simplify_noop,
6050 [OP_OUTL ] = simplify_noop,
6051 [OP_BSF ] = simplify_bsf,
6052 [OP_BSR ] = simplify_bsr,
6053 [OP_RDMSR ] = simplify_noop,
6054 [OP_WRMSR ] = simplify_noop,
6055 [OP_HLT ] = simplify_noop,
6058 static void simplify(struct compile_state *state, struct triple *ins)
6061 simplify_t do_simplify;
6065 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6069 do_simplify = table_simplify[op];
6072 internal_error(state, ins, "cannot simplify op: %d %s\n",
6076 do_simplify(state, ins);
6077 } while(ins->op != op);
6080 static void simplify_all(struct compile_state *state)
6082 struct triple *ins, *first;
6083 first = RHS(state->main_function, 0);
6086 simplify(state, ins);
6088 } while(ins != first);
6093 * ============================
6096 static void register_builtin_function(struct compile_state *state,
6097 const char *name, int op, struct type *rtype, ...)
6099 struct type *ftype, *atype, *param, **next;
6100 struct triple *def, *arg, *result, *work, *last, *first;
6101 struct hash_entry *ident;
6102 struct file_state file;
6108 /* Dummy file state to get debug handling right */
6109 memset(&file, 0, sizeof(file));
6110 file.basename = name;
6112 file.prev = state->file;
6113 state->file = &file;
6115 /* Find the Parameter count */
6116 valid_op(state, op);
6117 parameters = table_ops[op].rhs;
6118 if (parameters < 0 ) {
6119 internal_error(state, 0, "Invalid builtin parameter count");
6122 /* Find the function type */
6123 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6124 next = &ftype->right;
6125 va_start(args, rtype);
6126 for(i = 0; i < parameters; i++) {
6127 atype = va_arg(args, struct type *);
6131 *next = new_type(TYPE_PRODUCT, *next, atype);
6132 next = &((*next)->right);
6140 /* Generate the needed triples */
6141 def = triple(state, OP_LIST, ftype, 0, 0);
6142 first = label(state);
6143 RHS(def, 0) = first;
6145 /* Now string them together */
6146 param = ftype->right;
6147 for(i = 0; i < parameters; i++) {
6148 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6149 atype = param->left;
6153 arg = flatten(state, first, variable(state, atype));
6154 param = param->right;
6157 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6158 result = flatten(state, first, variable(state, rtype));
6160 MISC(def, 0) = result;
6161 work = new_triple(state, op, rtype, parameters);
6162 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6163 RHS(work, i) = read_expr(state, arg);
6165 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6167 /* Populate the LHS with the target registers */
6168 work = flatten(state, first, work);
6169 work->type = &void_type;
6170 param = rtype->left;
6171 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6172 internal_error(state, 0, "Invalid result type");
6174 val = new_triple(state, OP_VAL_VEC, rtype, -1);
6175 for(i = 0; i < rtype->elements; i++) {
6176 struct triple *piece;
6178 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6179 atype = param->left;
6181 if (!TYPE_ARITHMETIC(atype->type) &&
6182 !TYPE_PTR(atype->type)) {
6183 internal_error(state, 0, "Invalid lhs type");
6185 piece = triple(state, OP_PIECE, atype, work, 0);
6187 LHS(work, i) = piece;
6188 RHS(val, i) = piece;
6193 work = write_expr(state, result, work);
6195 work = flatten(state, first, work);
6196 last = flatten(state, first, label(state));
6197 name_len = strlen(name);
6198 ident = lookup(state, name, name_len);
6199 symbol(state, ident, &ident->sym_ident, def, ftype);
6201 state->file = file.prev;
6203 fprintf(stdout, "\n");
6204 loc(stdout, state, 0);
6205 fprintf(stdout, "\n__________ builtin_function _________\n");
6206 print_triple(state, def);
6207 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6211 static struct type *partial_struct(struct compile_state *state,
6212 const char *field_name, struct type *type, struct type *rest)
6214 struct hash_entry *field_ident;
6215 struct type *result;
6218 field_name_len = strlen(field_name);
6219 field_ident = lookup(state, field_name, field_name_len);
6221 result = clone_type(0, type);
6222 result->field_ident = field_ident;
6225 result = new_type(TYPE_PRODUCT, result, rest);
6230 static struct type *register_builtin_type(struct compile_state *state,
6231 const char *name, struct type *type)
6233 struct hash_entry *ident;
6236 name_len = strlen(name);
6237 ident = lookup(state, name, name_len);
6239 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6240 ulong_t elements = 0;
6242 type = new_type(TYPE_STRUCT, type, 0);
6244 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6246 field = field->right;
6249 symbol(state, ident, &ident->sym_struct, 0, type);
6250 type->type_ident = ident;
6251 type->elements = elements;
6253 symbol(state, ident, &ident->sym_ident, 0, type);
6254 ident->tok = TOK_TYPE_NAME;
6259 static void register_builtins(struct compile_state *state)
6261 struct type *msr_type;
6263 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6265 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6267 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6270 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6271 &uchar_type, &ushort_type);
6272 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6273 &ushort_type, &ushort_type);
6274 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6275 &uint_type, &ushort_type);
6277 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6279 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6282 msr_type = register_builtin_type(state, "__builtin_msr_t",
6283 partial_struct(state, "lo", &ulong_type,
6284 partial_struct(state, "hi", &ulong_type, 0)));
6286 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6288 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6289 &ulong_type, &ulong_type, &ulong_type);
6291 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6295 static struct type *declarator(
6296 struct compile_state *state, struct type *type,
6297 struct hash_entry **ident, int need_ident);
6298 static void decl(struct compile_state *state, struct triple *first);
6299 static struct type *specifier_qualifier_list(struct compile_state *state);
6300 static int isdecl_specifier(int tok);
6301 static struct type *decl_specifiers(struct compile_state *state);
6302 static int istype(int tok);
6303 static struct triple *expr(struct compile_state *state);
6304 static struct triple *assignment_expr(struct compile_state *state);
6305 static struct type *type_name(struct compile_state *state);
6306 static void statement(struct compile_state *state, struct triple *fist);
6308 static struct triple *call_expr(
6309 struct compile_state *state, struct triple *func)
6312 struct type *param, *type;
6313 ulong_t pvals, index;
6315 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6316 error(state, 0, "Called object is not a function");
6318 if (func->op != OP_LIST) {
6319 internal_error(state, 0, "improper function");
6321 eat(state, TOK_LPAREN);
6322 /* Find the return type without any specifiers */
6323 type = clone_type(0, func->type->left);
6324 def = new_triple(state, OP_CALL, func->type, -1);
6327 pvals = TRIPLE_RHS(def->sizes);
6328 MISC(def, 0) = func;
6330 param = func->type->right;
6331 for(index = 0; index < pvals; index++) {
6333 struct type *arg_type;
6334 val = read_expr(state, assignment_expr(state));
6336 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6337 arg_type = param->left;
6339 write_compatible(state, arg_type, val->type);
6340 RHS(def, index) = val;
6341 if (index != (pvals - 1)) {
6342 eat(state, TOK_COMMA);
6343 param = param->right;
6346 eat(state, TOK_RPAREN);
6351 static struct triple *character_constant(struct compile_state *state)
6355 const signed char *str, *end;
6358 eat(state, TOK_LIT_CHAR);
6359 tk = &state->token[0];
6360 str = tk->val.str + 1;
6361 str_len = tk->str_len - 2;
6363 error(state, 0, "empty character constant");
6365 end = str + str_len;
6366 c = char_value(state, &str, end);
6368 error(state, 0, "multibyte character constant not supported");
6370 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6374 static struct triple *string_constant(struct compile_state *state)
6379 const signed char *str, *end;
6380 signed char *buf, *ptr;
6384 type = new_type(TYPE_ARRAY, &char_type, 0);
6386 /* The while loop handles string concatenation */
6388 eat(state, TOK_LIT_STRING);
6389 tk = &state->token[0];
6390 str = tk->val.str + 1;
6391 str_len = tk->str_len - 2;
6393 error(state, 0, "negative string constant length");
6395 end = str + str_len;
6397 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6398 memcpy(buf, ptr, type->elements);
6399 ptr = buf + type->elements;
6401 *ptr++ = char_value(state, &str, end);
6403 type->elements = ptr - buf;
6404 } while(peek(state) == TOK_LIT_STRING);
6406 type->elements += 1;
6407 def = triple(state, OP_BLOBCONST, type, 0, 0);
6413 static struct triple *integer_constant(struct compile_state *state)
6422 eat(state, TOK_LIT_INT);
6423 tk = &state->token[0];
6425 decimal = (tk->val.str[0] != '0');
6426 val = strtoul(tk->val.str, &end, 0);
6427 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6428 error(state, 0, "Integer constant to large");
6431 if ((*end == 'u') || (*end == 'U')) {
6435 if ((*end == 'l') || (*end == 'L')) {
6439 if ((*end == 'u') || (*end == 'U')) {
6444 error(state, 0, "Junk at end of integer constant");
6451 if (!decimal && (val > LONG_MAX)) {
6457 if (val > UINT_MAX) {
6463 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6466 else if (!decimal && (val > LONG_MAX)) {
6469 else if (val > INT_MAX) {
6473 def = int_const(state, type, val);
6477 static struct triple *primary_expr(struct compile_state *state)
6485 struct hash_entry *ident;
6486 /* Here ident is either:
6489 * an enumeration constant.
6491 eat(state, TOK_IDENT);
6492 ident = state->token[0].ident;
6493 if (!ident->sym_ident) {
6494 error(state, 0, "%s undeclared", ident->name);
6496 def = ident->sym_ident->def;
6499 case TOK_ENUM_CONST:
6500 /* Here ident is an enumeration constant */
6501 eat(state, TOK_ENUM_CONST);
6506 eat(state, TOK_LPAREN);
6508 eat(state, TOK_RPAREN);
6511 def = integer_constant(state);
6514 eat(state, TOK_LIT_FLOAT);
6515 error(state, 0, "Floating point constants not supported");
6520 def = character_constant(state);
6522 case TOK_LIT_STRING:
6523 def = string_constant(state);
6527 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6532 static struct triple *postfix_expr(struct compile_state *state)
6536 def = primary_expr(state);
6538 struct triple *left;
6542 switch((tok = peek(state))) {
6544 eat(state, TOK_LBRACKET);
6545 def = mk_subscript_expr(state, left, expr(state));
6546 eat(state, TOK_RBRACKET);
6549 def = call_expr(state, def);
6553 struct hash_entry *field;
6554 eat(state, TOK_DOT);
6555 eat(state, TOK_IDENT);
6556 field = state->token[0].ident;
6557 def = deref_field(state, def, field);
6562 struct hash_entry *field;
6563 eat(state, TOK_ARROW);
6564 eat(state, TOK_IDENT);
6565 field = state->token[0].ident;
6566 def = mk_deref_expr(state, read_expr(state, def));
6567 def = deref_field(state, def, field);
6571 eat(state, TOK_PLUSPLUS);
6572 def = mk_post_inc_expr(state, left);
6574 case TOK_MINUSMINUS:
6575 eat(state, TOK_MINUSMINUS);
6576 def = mk_post_dec_expr(state, left);
6586 static struct triple *cast_expr(struct compile_state *state);
6588 static struct triple *unary_expr(struct compile_state *state)
6590 struct triple *def, *right;
6592 switch((tok = peek(state))) {
6594 eat(state, TOK_PLUSPLUS);
6595 def = mk_pre_inc_expr(state, unary_expr(state));
6597 case TOK_MINUSMINUS:
6598 eat(state, TOK_MINUSMINUS);
6599 def = mk_pre_dec_expr(state, unary_expr(state));
6602 eat(state, TOK_AND);
6603 def = mk_addr_expr(state, cast_expr(state), 0);
6606 eat(state, TOK_STAR);
6607 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6610 eat(state, TOK_PLUS);
6611 right = read_expr(state, cast_expr(state));
6612 arithmetic(state, right);
6613 def = integral_promotion(state, right);
6616 eat(state, TOK_MINUS);
6617 right = read_expr(state, cast_expr(state));
6618 arithmetic(state, right);
6619 def = integral_promotion(state, right);
6620 def = triple(state, OP_NEG, def->type, def, 0);
6623 eat(state, TOK_TILDE);
6624 right = read_expr(state, cast_expr(state));
6625 integral(state, right);
6626 def = integral_promotion(state, right);
6627 def = triple(state, OP_INVERT, def->type, def, 0);
6630 eat(state, TOK_BANG);
6631 right = read_expr(state, cast_expr(state));
6633 def = lfalse_expr(state, right);
6639 eat(state, TOK_SIZEOF);
6641 tok2 = peek2(state);
6642 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6643 eat(state, TOK_LPAREN);
6644 type = type_name(state);
6645 eat(state, TOK_RPAREN);
6648 struct triple *expr;
6649 expr = unary_expr(state);
6651 release_expr(state, expr);
6653 def = int_const(state, &ulong_type, size_of(state, type));
6660 eat(state, TOK_ALIGNOF);
6662 tok2 = peek2(state);
6663 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6664 eat(state, TOK_LPAREN);
6665 type = type_name(state);
6666 eat(state, TOK_RPAREN);
6669 struct triple *expr;
6670 expr = unary_expr(state);
6672 release_expr(state, expr);
6674 def = int_const(state, &ulong_type, align_of(state, type));
6678 def = postfix_expr(state);
6684 static struct triple *cast_expr(struct compile_state *state)
6689 tok2 = peek2(state);
6690 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6692 eat(state, TOK_LPAREN);
6693 type = type_name(state);
6694 eat(state, TOK_RPAREN);
6695 def = read_expr(state, cast_expr(state));
6696 def = triple(state, OP_COPY, type, def, 0);
6697 #warning "FIXME do I need an OP_CAST expr to be semantically correct here?"
6700 def = unary_expr(state);
6705 static struct triple *mult_expr(struct compile_state *state)
6709 def = cast_expr(state);
6711 struct triple *left, *right;
6712 struct type *result_type;
6715 switch(tok = (peek(state))) {
6719 left = read_expr(state, def);
6720 arithmetic(state, left);
6724 right = read_expr(state, cast_expr(state));
6725 arithmetic(state, right);
6727 result_type = arithmetic_result(state, left, right);
6728 sign = is_signed(result_type);
6731 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6732 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
6733 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
6735 def = triple(state, op, result_type, left, right);
6745 static struct triple *add_expr(struct compile_state *state)
6749 def = mult_expr(state);
6752 switch( peek(state)) {
6754 eat(state, TOK_PLUS);
6755 def = mk_add_expr(state, def, mult_expr(state));
6758 eat(state, TOK_MINUS);
6759 def = mk_sub_expr(state, def, mult_expr(state));
6769 static struct triple *shift_expr(struct compile_state *state)
6773 def = add_expr(state);
6775 struct triple *left, *right;
6778 switch((tok = peek(state))) {
6781 left = read_expr(state, def);
6782 integral(state, left);
6783 left = integral_promotion(state, left);
6787 right = read_expr(state, add_expr(state));
6788 integral(state, right);
6789 right = integral_promotion(state, right);
6791 op = (tok == TOK_SL)? OP_SL :
6792 is_signed(left->type)? OP_SSR: OP_USR;
6794 def = triple(state, op, left->type, left, right);
6804 static struct triple *relational_expr(struct compile_state *state)
6806 #warning "Extend relational exprs to work on more than arithmetic types"
6809 def = shift_expr(state);
6811 struct triple *left, *right;
6812 struct type *arg_type;
6815 switch((tok = peek(state))) {
6820 left = read_expr(state, def);
6821 arithmetic(state, left);
6825 right = read_expr(state, shift_expr(state));
6826 arithmetic(state, right);
6828 arg_type = arithmetic_result(state, left, right);
6829 sign = is_signed(arg_type);
6832 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
6833 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
6834 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
6835 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
6837 def = triple(state, op, &int_type, left, right);
6847 static struct triple *equality_expr(struct compile_state *state)
6849 #warning "Extend equality exprs to work on more than arithmetic types"
6852 def = relational_expr(state);
6854 struct triple *left, *right;
6857 switch((tok = peek(state))) {
6860 left = read_expr(state, def);
6861 arithmetic(state, left);
6863 right = read_expr(state, relational_expr(state));
6864 arithmetic(state, right);
6865 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
6866 def = triple(state, op, &int_type, left, right);
6876 static struct triple *and_expr(struct compile_state *state)
6879 def = equality_expr(state);
6880 while(peek(state) == TOK_AND) {
6881 struct triple *left, *right;
6882 struct type *result_type;
6883 left = read_expr(state, def);
6884 integral(state, left);
6885 eat(state, TOK_AND);
6886 right = read_expr(state, equality_expr(state));
6887 integral(state, right);
6888 result_type = arithmetic_result(state, left, right);
6889 def = triple(state, OP_AND, result_type, left, right);
6894 static struct triple *xor_expr(struct compile_state *state)
6897 def = and_expr(state);
6898 while(peek(state) == TOK_XOR) {
6899 struct triple *left, *right;
6900 struct type *result_type;
6901 left = read_expr(state, def);
6902 integral(state, left);
6903 eat(state, TOK_XOR);
6904 right = read_expr(state, and_expr(state));
6905 integral(state, right);
6906 result_type = arithmetic_result(state, left, right);
6907 def = triple(state, OP_XOR, result_type, left, right);
6912 static struct triple *or_expr(struct compile_state *state)
6915 def = xor_expr(state);
6916 while(peek(state) == TOK_OR) {
6917 struct triple *left, *right;
6918 struct type *result_type;
6919 left = read_expr(state, def);
6920 integral(state, left);
6922 right = read_expr(state, xor_expr(state));
6923 integral(state, right);
6924 result_type = arithmetic_result(state, left, right);
6925 def = triple(state, OP_OR, result_type, left, right);
6930 static struct triple *land_expr(struct compile_state *state)
6933 def = or_expr(state);
6934 while(peek(state) == TOK_LOGAND) {
6935 struct triple *left, *right;
6936 left = read_expr(state, def);
6938 eat(state, TOK_LOGAND);
6939 right = read_expr(state, or_expr(state));
6942 def = triple(state, OP_LAND, &int_type,
6943 ltrue_expr(state, left),
6944 ltrue_expr(state, right));
6949 static struct triple *lor_expr(struct compile_state *state)
6952 def = land_expr(state);
6953 while(peek(state) == TOK_LOGOR) {
6954 struct triple *left, *right;
6955 left = read_expr(state, def);
6957 eat(state, TOK_LOGOR);
6958 right = read_expr(state, land_expr(state));
6961 def = triple(state, OP_LOR, &int_type,
6962 ltrue_expr(state, left),
6963 ltrue_expr(state, right));
6968 static struct triple *conditional_expr(struct compile_state *state)
6971 def = lor_expr(state);
6972 if (peek(state) == TOK_QUEST) {
6973 struct triple *test, *left, *right;
6975 test = ltrue_expr(state, read_expr(state, def));
6976 eat(state, TOK_QUEST);
6977 left = read_expr(state, expr(state));
6978 eat(state, TOK_COLON);
6979 right = read_expr(state, conditional_expr(state));
6981 def = cond_expr(state, test, left, right);
6986 static struct triple *eval_const_expr(
6987 struct compile_state *state, struct triple *expr)
6990 struct triple *head, *ptr;
6991 head = label(state); /* dummy initial triple */
6992 flatten(state, head, expr);
6993 for(ptr = head->next; ptr != head; ptr = ptr->next) {
6994 simplify(state, ptr);
6996 /* Remove the constant value the tail of the list */
6998 def->prev->next = def->next;
6999 def->next->prev = def->prev;
7000 def->next = def->prev = def;
7001 if (!is_const(def)) {
7002 internal_error(state, 0, "Not a constant expression");
7004 /* Free the intermediate expressions */
7005 while(head->next != head) {
7006 release_triple(state, head->next);
7008 free_triple(state, head);
7012 static struct triple *constant_expr(struct compile_state *state)
7014 return eval_const_expr(state, conditional_expr(state));
7017 static struct triple *assignment_expr(struct compile_state *state)
7019 struct triple *def, *left, *right;
7021 /* The C grammer in K&R shows assignment expressions
7022 * only taking unary expressions as input on their
7023 * left hand side. But specifies the precedence of
7024 * assignemnt as the lowest operator except for comma.
7026 * Allowing conditional expressions on the left hand side
7027 * of an assignement results in a grammar that accepts
7028 * a larger set of statements than standard C. As long
7029 * as the subset of the grammar that is standard C behaves
7030 * correctly this should cause no problems.
7032 * For the extra token strings accepted by the grammar
7033 * none of them should produce a valid lvalue, so they
7034 * should not produce functioning programs.
7036 * GCC has this bug as well, so surprises should be minimal.
7038 def = conditional_expr(state);
7040 switch((tok = peek(state))) {
7042 lvalue(state, left);
7044 def = write_expr(state, left,
7045 read_expr(state, assignment_expr(state)));
7052 lvalue(state, left);
7053 arithmetic(state, left);
7055 right = read_expr(state, assignment_expr(state));
7056 arithmetic(state, right);
7058 sign = is_signed(left->type);
7061 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7062 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7063 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7064 case TOK_PLUSEQ: op = OP_ADD; break;
7065 case TOK_MINUSEQ: op = OP_SUB; break;
7067 def = write_expr(state, left,
7068 triple(state, op, left->type,
7069 read_expr(state, left), right));
7076 lvalue(state, left);
7077 integral(state, left);
7079 right = read_expr(state, assignment_expr(state));
7080 integral(state, right);
7081 right = integral_promotion(state, right);
7082 sign = is_signed(left->type);
7085 case TOK_SLEQ: op = OP_SL; break;
7086 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7087 case TOK_ANDEQ: op = OP_AND; break;
7088 case TOK_XOREQ: op = OP_XOR; break;
7089 case TOK_OREQ: op = OP_OR; break;
7091 def = write_expr(state, left,
7092 triple(state, op, left->type,
7093 read_expr(state, left), right));
7099 static struct triple *expr(struct compile_state *state)
7102 def = assignment_expr(state);
7103 while(peek(state) == TOK_COMMA) {
7104 struct triple *left, *right;
7106 eat(state, TOK_COMMA);
7107 right = assignment_expr(state);
7108 def = triple(state, OP_COMMA, right->type, left, right);
7113 static void expr_statement(struct compile_state *state, struct triple *first)
7115 if (peek(state) != TOK_SEMI) {
7116 flatten(state, first, expr(state));
7118 eat(state, TOK_SEMI);
7121 static void if_statement(struct compile_state *state, struct triple *first)
7123 struct triple *test, *jmp1, *jmp2, *middle, *end;
7125 jmp1 = jmp2 = middle = 0;
7127 eat(state, TOK_LPAREN);
7130 /* Cleanup and invert the test */
7131 test = lfalse_expr(state, read_expr(state, test));
7132 eat(state, TOK_RPAREN);
7133 /* Generate the needed pieces */
7134 middle = label(state);
7135 jmp1 = branch(state, middle, test);
7136 /* Thread the pieces together */
7137 flatten(state, first, test);
7138 flatten(state, first, jmp1);
7139 flatten(state, first, label(state));
7140 statement(state, first);
7141 if (peek(state) == TOK_ELSE) {
7142 eat(state, TOK_ELSE);
7143 /* Generate the rest of the pieces */
7145 jmp2 = branch(state, end, 0);
7146 /* Thread them together */
7147 flatten(state, first, jmp2);
7148 flatten(state, first, middle);
7149 statement(state, first);
7150 flatten(state, first, end);
7153 flatten(state, first, middle);
7157 static void for_statement(struct compile_state *state, struct triple *first)
7159 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7160 struct triple *label1, *label2, *label3;
7161 struct hash_entry *ident;
7163 eat(state, TOK_FOR);
7164 eat(state, TOK_LPAREN);
7165 head = test = tail = jmp1 = jmp2 = 0;
7166 if (peek(state) != TOK_SEMI) {
7169 eat(state, TOK_SEMI);
7170 if (peek(state) != TOK_SEMI) {
7173 test = ltrue_expr(state, read_expr(state, test));
7175 eat(state, TOK_SEMI);
7176 if (peek(state) != TOK_RPAREN) {
7179 eat(state, TOK_RPAREN);
7180 /* Generate the needed pieces */
7181 label1 = label(state);
7182 label2 = label(state);
7183 label3 = label(state);
7185 jmp1 = branch(state, label3, 0);
7186 jmp2 = branch(state, label1, test);
7189 jmp2 = branch(state, label1, 0);
7192 /* Remember where break and continue go */
7194 ident = state->i_break;
7195 symbol(state, ident, &ident->sym_ident, end, end->type);
7196 ident = state->i_continue;
7197 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7198 /* Now include the body */
7199 flatten(state, first, head);
7200 flatten(state, first, jmp1);
7201 flatten(state, first, label1);
7202 statement(state, first);
7203 flatten(state, first, label2);
7204 flatten(state, first, tail);
7205 flatten(state, first, label3);
7206 flatten(state, first, test);
7207 flatten(state, first, jmp2);
7208 flatten(state, first, end);
7209 /* Cleanup the break/continue scope */
7213 static void while_statement(struct compile_state *state, struct triple *first)
7215 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7216 struct hash_entry *ident;
7217 eat(state, TOK_WHILE);
7218 eat(state, TOK_LPAREN);
7221 test = ltrue_expr(state, read_expr(state, test));
7222 eat(state, TOK_RPAREN);
7223 /* Generate the needed pieces */
7224 label1 = label(state);
7225 label2 = label(state);
7226 jmp1 = branch(state, label2, 0);
7227 jmp2 = branch(state, label1, test);
7229 /* Remember where break and continue go */
7231 ident = state->i_break;
7232 symbol(state, ident, &ident->sym_ident, end, end->type);
7233 ident = state->i_continue;
7234 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7235 /* Thread them together */
7236 flatten(state, first, jmp1);
7237 flatten(state, first, label1);
7238 statement(state, first);
7239 flatten(state, first, label2);
7240 flatten(state, first, test);
7241 flatten(state, first, jmp2);
7242 flatten(state, first, end);
7243 /* Cleanup the break/continue scope */
7247 static void do_statement(struct compile_state *state, struct triple *first)
7249 struct triple *label1, *label2, *test, *end;
7250 struct hash_entry *ident;
7252 /* Generate the needed pieces */
7253 label1 = label(state);
7254 label2 = label(state);
7256 /* Remember where break and continue go */
7258 ident = state->i_break;
7259 symbol(state, ident, &ident->sym_ident, end, end->type);
7260 ident = state->i_continue;
7261 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7262 /* Now include the body */
7263 flatten(state, first, label1);
7264 statement(state, first);
7265 /* Cleanup the break/continue scope */
7267 /* Eat the rest of the loop */
7268 eat(state, TOK_WHILE);
7269 eat(state, TOK_LPAREN);
7270 test = read_expr(state, expr(state));
7272 eat(state, TOK_RPAREN);
7273 eat(state, TOK_SEMI);
7274 /* Thread the pieces together */
7275 test = ltrue_expr(state, test);
7276 flatten(state, first, label2);
7277 flatten(state, first, test);
7278 flatten(state, first, branch(state, label1, test));
7279 flatten(state, first, end);
7283 static void return_statement(struct compile_state *state, struct triple *first)
7285 struct triple *jmp, *mv, *dest, *var, *val;
7287 eat(state, TOK_RETURN);
7289 #warning "FIXME implement a more general excess branch elimination"
7291 /* If we have a return value do some more work */
7292 if (peek(state) != TOK_SEMI) {
7293 val = read_expr(state, expr(state));
7295 eat(state, TOK_SEMI);
7297 /* See if this last statement in a function */
7298 last = ((peek(state) == TOK_RBRACE) &&
7299 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7301 /* Find the return variable */
7302 var = MISC(state->main_function, 0);
7303 /* Find the return destination */
7304 dest = RHS(state->main_function, 0)->prev;
7306 /* If needed generate a jump instruction */
7308 jmp = branch(state, dest, 0);
7310 /* If needed generate an assignment instruction */
7312 mv = write_expr(state, var, val);
7314 /* Now put the code together */
7316 flatten(state, first, mv);
7317 flatten(state, first, jmp);
7320 flatten(state, first, jmp);
7324 static void break_statement(struct compile_state *state, struct triple *first)
7326 struct triple *dest;
7327 eat(state, TOK_BREAK);
7328 eat(state, TOK_SEMI);
7329 if (!state->i_break->sym_ident) {
7330 error(state, 0, "break statement not within loop or switch");
7332 dest = state->i_break->sym_ident->def;
7333 flatten(state, first, branch(state, dest, 0));
7336 static void continue_statement(struct compile_state *state, struct triple *first)
7338 struct triple *dest;
7339 eat(state, TOK_CONTINUE);
7340 eat(state, TOK_SEMI);
7341 if (!state->i_continue->sym_ident) {
7342 error(state, 0, "continue statement outside of a loop");
7344 dest = state->i_continue->sym_ident->def;
7345 flatten(state, first, branch(state, dest, 0));
7348 static void goto_statement(struct compile_state *state, struct triple *first)
7351 eat(state, TOK_GOTO);
7352 eat(state, TOK_IDENT);
7353 eat(state, TOK_SEMI);
7354 error(state, 0, "goto is not implemeted");
7358 static void labeled_statement(struct compile_state *state, struct triple *first)
7361 eat(state, TOK_IDENT);
7362 eat(state, TOK_COLON);
7363 statement(state, first);
7364 error(state, 0, "labeled statements are not implemented");
7368 static void switch_statement(struct compile_state *state, struct triple *first)
7371 eat(state, TOK_SWITCH);
7372 eat(state, TOK_LPAREN);
7374 eat(state, TOK_RPAREN);
7375 statement(state, first);
7376 error(state, 0, "switch statements are not implemented");
7380 static void case_statement(struct compile_state *state, struct triple *first)
7383 eat(state, TOK_CASE);
7384 constant_expr(state);
7385 eat(state, TOK_COLON);
7386 statement(state, first);
7387 error(state, 0, "case statements are not implemented");
7391 static void default_statement(struct compile_state *state, struct triple *first)
7394 eat(state, TOK_DEFAULT);
7395 eat(state, TOK_COLON);
7396 statement(state, first);
7397 error(state, 0, "default statements are not implemented");
7401 static void asm_statement(struct compile_state *state, struct triple *first)
7404 error(state, 0, "FIXME finish asm_statement");
7408 static int isdecl(int tok)
7431 case TOK_TYPE_NAME: /* typedef name */
7438 static void compound_statement(struct compile_state *state, struct triple *first)
7440 eat(state, TOK_LBRACE);
7443 /* statement-list opt */
7444 while (peek(state) != TOK_RBRACE) {
7445 statement(state, first);
7448 eat(state, TOK_RBRACE);
7451 static void statement(struct compile_state *state, struct triple *first)
7455 if (tok == TOK_LBRACE) {
7456 compound_statement(state, first);
7458 else if (tok == TOK_IF) {
7459 if_statement(state, first);
7461 else if (tok == TOK_FOR) {
7462 for_statement(state, first);
7464 else if (tok == TOK_WHILE) {
7465 while_statement(state, first);
7467 else if (tok == TOK_DO) {
7468 do_statement(state, first);
7470 else if (tok == TOK_RETURN) {
7471 return_statement(state, first);
7473 else if (tok == TOK_BREAK) {
7474 break_statement(state, first);
7476 else if (tok == TOK_CONTINUE) {
7477 continue_statement(state, first);
7479 else if (tok == TOK_GOTO) {
7480 goto_statement(state, first);
7482 else if (tok == TOK_SWITCH) {
7483 switch_statement(state, first);
7485 else if (tok == TOK_ASM) {
7486 asm_statement(state, first);
7488 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7489 labeled_statement(state, first);
7491 else if (tok == TOK_CASE) {
7492 case_statement(state, first);
7494 else if (tok == TOK_DEFAULT) {
7495 default_statement(state, first);
7497 else if (isdecl(tok)) {
7498 /* This handles C99 intermixing of statements and decls */
7502 expr_statement(state, first);
7506 static struct type *param_decl(struct compile_state *state)
7509 struct hash_entry *ident;
7510 /* Cheat so the declarator will know we are not global */
7513 type = decl_specifiers(state);
7514 type = declarator(state, type, &ident, 0);
7515 type->field_ident = ident;
7520 static struct type *param_type_list(struct compile_state *state, struct type *type)
7522 struct type *ftype, **next;
7523 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7524 next = &ftype->right;
7525 while(peek(state) == TOK_COMMA) {
7526 eat(state, TOK_COMMA);
7527 if (peek(state) == TOK_DOTS) {
7528 eat(state, TOK_DOTS);
7529 error(state, 0, "variadic functions not supported");
7532 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7533 next = &((*next)->right);
7540 static struct type *type_name(struct compile_state *state)
7543 type = specifier_qualifier_list(state);
7544 /* abstract-declarator (may consume no tokens) */
7545 type = declarator(state, type, 0, 0);
7549 static struct type *direct_declarator(
7550 struct compile_state *state, struct type *type,
7551 struct hash_entry **ident, int need_ident)
7556 arrays_complete(state, type);
7557 switch(peek(state)) {
7559 eat(state, TOK_IDENT);
7561 error(state, 0, "Unexpected identifier found");
7563 /* The name of what we are declaring */
7564 *ident = state->token[0].ident;
7567 eat(state, TOK_LPAREN);
7568 outer = declarator(state, type, ident, need_ident);
7569 eat(state, TOK_RPAREN);
7573 error(state, 0, "Identifier expected");
7579 arrays_complete(state, type);
7580 switch(peek(state)) {
7582 eat(state, TOK_LPAREN);
7583 type = param_type_list(state, type);
7584 eat(state, TOK_RPAREN);
7588 unsigned int qualifiers;
7589 struct triple *value;
7591 eat(state, TOK_LBRACKET);
7592 if (peek(state) != TOK_RBRACKET) {
7593 value = constant_expr(state);
7594 integral(state, value);
7596 eat(state, TOK_RBRACKET);
7598 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7599 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7601 type->elements = value->u.cval;
7602 free_triple(state, value);
7604 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7616 arrays_complete(state, type);
7618 for(inner = outer; inner->left; inner = inner->left)
7626 static struct type *declarator(
7627 struct compile_state *state, struct type *type,
7628 struct hash_entry **ident, int need_ident)
7630 while(peek(state) == TOK_STAR) {
7631 eat(state, TOK_STAR);
7632 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7634 type = direct_declarator(state, type, ident, need_ident);
7639 static struct type *typedef_name(
7640 struct compile_state *state, unsigned int specifiers)
7642 struct hash_entry *ident;
7644 eat(state, TOK_TYPE_NAME);
7645 ident = state->token[0].ident;
7646 type = ident->sym_ident->type;
7647 specifiers |= type->type & QUAL_MASK;
7648 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
7649 (type->type & (STOR_MASK | QUAL_MASK))) {
7650 type = clone_type(specifiers, type);
7655 static struct type *enum_specifier(
7656 struct compile_state *state, unsigned int specifiers)
7662 eat(state, TOK_ENUM);
7664 if (tok == TOK_IDENT) {
7665 eat(state, TOK_IDENT);
7667 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
7668 eat(state, TOK_LBRACE);
7670 eat(state, TOK_IDENT);
7671 if (peek(state) == TOK_EQ) {
7673 constant_expr(state);
7675 if (peek(state) == TOK_COMMA) {
7676 eat(state, TOK_COMMA);
7678 } while(peek(state) != TOK_RBRACE);
7679 eat(state, TOK_RBRACE);
7686 static struct type *struct_declarator(
7687 struct compile_state *state, struct type *type, struct hash_entry **ident)
7690 #warning "struct_declarator is complicated because of bitfields, kill them?"
7692 if (tok != TOK_COLON) {
7693 type = declarator(state, type, ident, 1);
7695 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
7696 eat(state, TOK_COLON);
7697 constant_expr(state);
7704 static struct type *struct_or_union_specifier(
7705 struct compile_state *state, unsigned int specifiers)
7707 struct type *struct_type;
7708 struct hash_entry *ident;
7709 unsigned int type_join;
7713 switch(peek(state)) {
7715 eat(state, TOK_STRUCT);
7716 type_join = TYPE_PRODUCT;
7719 eat(state, TOK_UNION);
7720 type_join = TYPE_OVERLAP;
7721 error(state, 0, "unions not yet supported\n");
7724 eat(state, TOK_STRUCT);
7725 type_join = TYPE_PRODUCT;
7729 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
7731 ident = state->token[0].ident;
7733 if (!ident || (peek(state) == TOK_LBRACE)) {
7736 eat(state, TOK_LBRACE);
7738 struct type *base_type;
7741 base_type = specifier_qualifier_list(state);
7742 next = &struct_type;
7745 struct hash_entry *fident;
7747 type = declarator(state, base_type, &fident, 1);
7749 if (peek(state) == TOK_COMMA) {
7751 eat(state, TOK_COMMA);
7753 type = clone_type(0, type);
7754 type->field_ident = fident;
7756 *next = new_type(type_join, *next, type);
7757 next = &((*next)->right);
7762 eat(state, TOK_SEMI);
7763 } while(peek(state) != TOK_RBRACE);
7764 eat(state, TOK_RBRACE);
7765 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
7766 struct_type->type_ident = ident;
7767 struct_type->elements = elements;
7768 symbol(state, ident, &ident->sym_struct, 0, struct_type);
7770 if (ident && ident->sym_struct) {
7771 struct_type = ident->sym_struct->type;
7773 else if (ident && !ident->sym_struct) {
7774 error(state, 0, "struct %s undeclared", ident->name);
7779 static unsigned int storage_class_specifier_opt(struct compile_state *state)
7781 unsigned int specifiers;
7782 switch(peek(state)) {
7784 eat(state, TOK_AUTO);
7785 specifiers = STOR_AUTO;
7788 eat(state, TOK_REGISTER);
7789 specifiers = STOR_REGISTER;
7792 eat(state, TOK_STATIC);
7793 specifiers = STOR_STATIC;
7796 eat(state, TOK_EXTERN);
7797 specifiers = STOR_EXTERN;
7800 eat(state, TOK_TYPEDEF);
7801 specifiers = STOR_TYPEDEF;
7804 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
7805 specifiers = STOR_STATIC;
7808 specifiers = STOR_AUTO;
7814 static unsigned int function_specifier_opt(struct compile_state *state)
7816 /* Ignore the inline keyword */
7817 unsigned int specifiers;
7819 switch(peek(state)) {
7821 eat(state, TOK_INLINE);
7822 specifiers = STOR_INLINE;
7827 static unsigned int type_qualifiers(struct compile_state *state)
7829 unsigned int specifiers;
7832 specifiers = QUAL_NONE;
7834 switch(peek(state)) {
7836 eat(state, TOK_CONST);
7837 specifiers = QUAL_CONST;
7840 eat(state, TOK_VOLATILE);
7841 specifiers = QUAL_VOLATILE;
7844 eat(state, TOK_RESTRICT);
7845 specifiers = QUAL_RESTRICT;
7855 static struct type *type_specifier(
7856 struct compile_state *state, unsigned int spec)
7860 switch(peek(state)) {
7862 eat(state, TOK_VOID);
7863 type = new_type(TYPE_VOID | spec, 0, 0);
7866 eat(state, TOK_CHAR);
7867 type = new_type(TYPE_CHAR | spec, 0, 0);
7870 eat(state, TOK_SHORT);
7871 if (peek(state) == TOK_INT) {
7872 eat(state, TOK_INT);
7874 type = new_type(TYPE_SHORT | spec, 0, 0);
7877 eat(state, TOK_INT);
7878 type = new_type(TYPE_INT | spec, 0, 0);
7881 eat(state, TOK_LONG);
7882 switch(peek(state)) {
7884 eat(state, TOK_LONG);
7885 error(state, 0, "long long not supported");
7888 eat(state, TOK_DOUBLE);
7889 error(state, 0, "long double not supported");
7892 eat(state, TOK_INT);
7893 type = new_type(TYPE_LONG | spec, 0, 0);
7896 type = new_type(TYPE_LONG | spec, 0, 0);
7901 eat(state, TOK_FLOAT);
7902 error(state, 0, "type float not supported");
7905 eat(state, TOK_DOUBLE);
7906 error(state, 0, "type double not supported");
7909 eat(state, TOK_SIGNED);
7910 switch(peek(state)) {
7912 eat(state, TOK_LONG);
7913 switch(peek(state)) {
7915 eat(state, TOK_LONG);
7916 error(state, 0, "type long long not supported");
7919 eat(state, TOK_INT);
7920 type = new_type(TYPE_LONG | spec, 0, 0);
7923 type = new_type(TYPE_LONG | spec, 0, 0);
7928 eat(state, TOK_INT);
7929 type = new_type(TYPE_INT | spec, 0, 0);
7932 eat(state, TOK_SHORT);
7933 type = new_type(TYPE_SHORT | spec, 0, 0);
7936 eat(state, TOK_CHAR);
7937 type = new_type(TYPE_CHAR | spec, 0, 0);
7940 type = new_type(TYPE_INT | spec, 0, 0);
7945 eat(state, TOK_UNSIGNED);
7946 switch(peek(state)) {
7948 eat(state, TOK_LONG);
7949 switch(peek(state)) {
7951 eat(state, TOK_LONG);
7952 error(state, 0, "unsigned long long not supported");
7955 eat(state, TOK_INT);
7956 type = new_type(TYPE_ULONG | spec, 0, 0);
7959 type = new_type(TYPE_ULONG | spec, 0, 0);
7964 eat(state, TOK_INT);
7965 type = new_type(TYPE_UINT | spec, 0, 0);
7968 eat(state, TOK_SHORT);
7969 type = new_type(TYPE_USHORT | spec, 0, 0);
7972 eat(state, TOK_CHAR);
7973 type = new_type(TYPE_UCHAR | spec, 0, 0);
7976 type = new_type(TYPE_UINT | spec, 0, 0);
7980 /* struct or union specifier */
7983 type = struct_or_union_specifier(state, spec);
7985 /* enum-spefifier */
7987 type = enum_specifier(state, spec);
7991 type = typedef_name(state, spec);
7994 error(state, 0, "bad type specifier %s",
7995 tokens[peek(state)]);
8001 static int istype(int tok)
8027 static struct type *specifier_qualifier_list(struct compile_state *state)
8030 unsigned int specifiers = 0;
8032 /* type qualifiers */
8033 specifiers |= type_qualifiers(state);
8035 /* type specifier */
8036 type = type_specifier(state, specifiers);
8041 static int isdecl_specifier(int tok)
8044 /* storage class specifier */
8050 /* type qualifier */
8054 /* type specifiers */
8064 /* struct or union specifier */
8067 /* enum-spefifier */
8071 /* function specifiers */
8079 static struct type *decl_specifiers(struct compile_state *state)
8082 unsigned int specifiers;
8083 /* I am overly restrictive in the arragement of specifiers supported.
8084 * C is overly flexible in this department it makes interpreting
8085 * the parse tree difficult.
8089 /* storage class specifier */
8090 specifiers |= storage_class_specifier_opt(state);
8092 /* function-specifier */
8093 specifiers |= function_specifier_opt(state);
8095 /* type qualifier */
8096 specifiers |= type_qualifiers(state);
8098 /* type specifier */
8099 type = type_specifier(state, specifiers);
8103 static unsigned designator(struct compile_state *state)
8109 switch(peek(state)) {
8112 struct triple *value;
8113 eat(state, TOK_LBRACKET);
8114 value = constant_expr(state);
8115 eat(state, TOK_RBRACKET);
8116 index = value->u.cval;
8120 eat(state, TOK_DOT);
8121 eat(state, TOK_IDENT);
8122 error(state, 0, "Struct Designators not currently supported");
8125 error(state, 0, "Invalid designator");
8128 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8133 static struct triple *initializer(
8134 struct compile_state *state, struct type *type)
8136 struct triple *result;
8137 if (peek(state) != TOK_LBRACE) {
8138 result = assignment_expr(state);
8142 unsigned index, max_index;
8144 max_index = index = 0;
8145 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8146 max_index = type->elements;
8147 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8151 error(state, 0, "Struct initializers not currently supported");
8153 buf = xcmalloc(size_of(state, type), "initializer");
8154 eat(state, TOK_LBRACE);
8156 struct triple *value;
8157 struct type *value_type;
8162 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8163 index = designator(state);
8165 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8166 (index > max_index)) {
8167 error(state, 0, "element beyond bounds");
8170 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8171 value_type = type->left;
8173 value = eval_const_expr(state, initializer(state, value_type));
8174 value_size = size_of(state, value_type);
8175 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8176 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8177 (type->elements <= index)) {
8181 old_size = size_of(state, type);
8182 type->elements = index + 1;
8183 buf = xmalloc(size_of(state, type), "initializer");
8184 memcpy(buf, old_buf, old_size);
8187 if (value->op == OP_BLOBCONST) {
8188 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8190 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8191 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8193 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8194 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8196 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8197 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8200 fprintf(stderr, "%d %d\n",
8201 value->op, value_size);
8202 internal_error(state, 0, "unhandled constant initializer");
8204 if (peek(state) == TOK_COMMA) {
8205 eat(state, TOK_COMMA);
8209 } while(comma && (peek(state) != TOK_RBRACE));
8210 eat(state, TOK_RBRACE);
8211 result = triple(state, OP_BLOBCONST, type, 0, 0);
8212 result->u.blob = buf;
8217 static struct triple *function_definition(
8218 struct compile_state *state, struct type *type)
8220 struct triple *def, *tmp, *first, *end;
8221 struct hash_entry *ident;
8224 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8225 error(state, 0, "Invalid function header");
8228 /* Verify the function type */
8229 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8230 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8231 (type->right->field_ident == 0)) {
8232 error(state, 0, "Invalid function parameters");
8234 param = type->right;
8236 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8238 if (!param->left->field_ident) {
8239 error(state, 0, "No identifier for parameter %d\n", i);
8241 param = param->right;
8244 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8245 error(state, 0, "No identifier for paramter %d\n", i);
8248 /* Get a list of statements for this function. */
8249 def = triple(state, OP_LIST, type, 0, 0);
8251 /* Start a new scope for the passed parameters */
8254 /* Put a label at the very start of a function */
8255 first = label(state);
8256 RHS(def, 0) = first;
8258 /* Put a label at the very end of a function */
8260 flatten(state, first, end);
8262 /* Walk through the parameters and create symbol table entries
8265 param = type->right;
8266 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8267 ident = param->left->field_ident;
8268 tmp = variable(state, param->left);
8269 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8270 flatten(state, end, tmp);
8271 param = param->right;
8273 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8274 /* And don't forget the last parameter */
8275 ident = param->field_ident;
8276 tmp = variable(state, param);
8277 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8278 flatten(state, end, tmp);
8280 /* Add a variable for the return value */
8282 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8283 /* Remove all type qualifiers from the return type */
8284 tmp = variable(state, clone_type(0, type->left));
8285 flatten(state, end, tmp);
8286 /* Remember where the return value is */
8290 /* Remember which function I am compiling.
8291 * Also assume the last defined function is the main function.
8293 state->main_function = def;
8295 /* Now get the actual function definition */
8296 compound_statement(state, end);
8298 /* Remove the parameter scope */
8301 fprintf(stdout, "\n");
8302 loc(stdout, state, 0);
8303 fprintf(stdout, "\n__________ function_definition _________\n");
8304 print_triple(state, def);
8305 fprintf(stdout, "__________ function_definition _________ done\n\n");
8311 static struct triple *do_decl(struct compile_state *state,
8312 struct type *type, struct hash_entry *ident)
8316 /* Clean up the storage types used */
8317 switch (type->type & STOR_MASK) {
8320 /* These are the good types I am aiming for */
8323 type->type &= ~STOR_MASK;
8324 type->type |= STOR_AUTO;
8327 type->type &= ~STOR_MASK;
8328 type->type |= STOR_STATIC;
8332 error(state, 0, "typedef without name");
8334 symbol(state, ident, &ident->sym_ident, 0, type);
8335 ident->tok = TOK_TYPE_NAME;
8339 internal_error(state, 0, "Undefined storage class");
8341 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8342 ((type->type & QUAL_CONST) == 0)) {
8343 error(state, 0, "non const static variables not supported");
8346 def = variable(state, type);
8347 symbol(state, ident, &ident->sym_ident, def, type);
8352 static void decl(struct compile_state *state, struct triple *first)
8354 struct type *base_type, *type;
8355 struct hash_entry *ident;
8358 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8359 base_type = decl_specifiers(state);
8361 type = declarator(state, base_type, &ident, 0);
8362 if (global && ident && (peek(state) == TOK_LBRACE)) {
8364 def = function_definition(state, type);
8365 symbol(state, ident, &ident->sym_ident, def, type);
8369 flatten(state, first, do_decl(state, type, ident));
8370 /* type or variable definition */
8373 if (peek(state) == TOK_EQ) {
8375 error(state, 0, "cannot assign to a type");
8378 flatten(state, first,
8380 ident->sym_ident->def,
8381 initializer(state, type)));
8383 arrays_complete(state, type);
8384 if (peek(state) == TOK_COMMA) {
8385 eat(state, TOK_COMMA);
8387 type = declarator(state, base_type, &ident, 0);
8388 flatten(state, first, do_decl(state, type, ident));
8392 eat(state, TOK_SEMI);
8396 static void decls(struct compile_state *state)
8398 struct triple *list;
8400 list = label(state);
8403 if (tok == TOK_EOF) {
8406 if (tok == TOK_SPACE) {
8407 eat(state, TOK_SPACE);
8410 if (list->next != list) {
8411 error(state, 0, "global variables not supported");
8417 * Data structurs for optimation.
8420 static void do_use_block(
8421 struct block *used, struct block_set **head, struct block *user,
8424 struct block_set **ptr, *new;
8431 if ((*ptr)->member == user) {
8434 ptr = &(*ptr)->next;
8436 new = xcmalloc(sizeof(*new), "block_set");
8447 static void do_unuse_block(
8448 struct block *used, struct block_set **head, struct block *unuser)
8450 struct block_set *use, **ptr;
8454 if (use->member == unuser) {
8456 memset(use, -1, sizeof(*use));
8465 static void use_block(struct block *used, struct block *user)
8467 /* Append new to the head of the list, print_block
8470 do_use_block(used, &used->use, user, 1);
8473 static void unuse_block(struct block *used, struct block *unuser)
8475 do_unuse_block(used, &used->use, unuser);
8479 static void idom_block(struct block *idom, struct block *user)
8481 do_use_block(idom, &idom->idominates, user, 0);
8484 static void unidom_block(struct block *idom, struct block *unuser)
8486 do_unuse_block(idom, &idom->idominates, unuser);
8489 static void domf_block(struct block *block, struct block *domf)
8491 do_use_block(block, &block->domfrontier, domf, 0);
8494 static void undomf_block(struct block *block, struct block *undomf)
8496 do_unuse_block(block, &block->domfrontier, undomf);
8499 static void ipdom_block(struct block *ipdom, struct block *user)
8501 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8504 static void unipdom_block(struct block *ipdom, struct block *unuser)
8506 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8509 static void ipdomf_block(struct block *block, struct block *ipdomf)
8511 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8514 static void unipdomf_block(struct block *block, struct block *unipdomf)
8516 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8521 static int do_walk_triple(struct compile_state *state,
8522 struct triple *ptr, int depth,
8523 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8526 result = cb(state, ptr, depth);
8527 if ((result == 0) && (ptr->op == OP_LIST)) {
8528 struct triple *list;
8532 result = do_walk_triple(state, ptr, depth + 1, cb);
8533 if (ptr->next->prev != ptr) {
8534 internal_error(state, ptr->next, "bad prev");
8538 } while((result == 0) && (ptr != RHS(list, 0)));
8543 static int walk_triple(
8544 struct compile_state *state,
8546 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8548 return do_walk_triple(state, ptr, 0, cb);
8551 static void do_print_prefix(int depth)
8554 for(i = 0; i < depth; i++) {
8559 #define PRINT_LIST 1
8560 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8564 if (op == OP_LIST) {
8569 if ((op == OP_LABEL) && (ins->use)) {
8570 printf("\n%p:\n", ins);
8572 do_print_prefix(depth);
8573 display_triple(stdout, ins);
8575 if ((ins->op == OP_BRANCH) && ins->use) {
8576 internal_error(state, ins, "branch used?");
8580 struct triple_set *user;
8581 for(user = ins->use; user; user = user->next) {
8582 printf("use: %p\n", user->member);
8586 if (triple_is_branch(state, ins)) {
8592 static void print_triple(struct compile_state *state, struct triple *ins)
8594 walk_triple(state, ins, do_print_triple);
8597 static void print_triples(struct compile_state *state)
8599 print_triple(state, state->main_function);
8603 struct block *block;
8605 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8607 if (!block || (cf[block->vertex].block == block)) {
8610 cf[block->vertex].block = block;
8611 find_cf_blocks(cf, block->left);
8612 find_cf_blocks(cf, block->right);
8615 static void print_control_flow(struct compile_state *state)
8617 struct cf_block *cf;
8619 printf("\ncontrol flow\n");
8620 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8621 find_cf_blocks(cf, state->first_block);
8623 for(i = 1; i <= state->last_vertex; i++) {
8624 struct block *block;
8625 block = cf[i].block;
8628 printf("(%p) %d:", block, block->vertex);
8630 printf(" %d", block->left->vertex);
8632 if (block->right && (block->right != block->left)) {
8633 printf(" %d", block->right->vertex);
8642 static struct block *basic_block(struct compile_state *state,
8643 struct triple *first)
8645 struct block *block;
8648 if (first->op != OP_LABEL) {
8649 internal_error(state, 0, "block does not start with a label");
8651 /* See if this basic block has already been setup */
8652 if (first->u.block != 0) {
8653 return first->u.block;
8655 /* Allocate another basic block structure */
8656 state->last_vertex += 1;
8657 block = xcmalloc(sizeof(*block), "block");
8658 block->first = block->last = first;
8659 block->vertex = state->last_vertex;
8662 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
8666 /* If ptr->u is not used remember where the baic block is */
8667 if (!is_const(ptr)) {
8668 ptr->u.block = block;
8670 if (ptr->op == OP_BRANCH) {
8674 } while (ptr != RHS(state->main_function, 0));
8675 if (ptr == RHS(state->main_function, 0))
8678 if (op == OP_LABEL) {
8679 block->left = basic_block(state, ptr);
8681 use_block(block->left, block);
8683 else if (op == OP_BRANCH) {
8685 /* Trace the branch target */
8686 block->right = basic_block(state, TARG(ptr, 0));
8687 use_block(block->right, block);
8688 /* If there is a test trace the branch as well */
8689 if (TRIPLE_RHS(ptr->sizes)) {
8690 block->left = basic_block(state, ptr->next);
8691 use_block(block->left, block);
8695 internal_error(state, 0, "Bad basic block split");
8701 static void walk_blocks(struct compile_state *state,
8702 void (*cb)(struct compile_state *state, struct block *block, void *arg),
8705 struct triple *ptr, *first;
8706 struct block *last_block;
8708 first = RHS(state->main_function, 0);
8711 struct block *block;
8712 if (ptr->op == OP_LABEL) {
8713 block = ptr->u.block;
8714 if (block && (block != last_block)) {
8715 cb(state, block, arg);
8720 } while(ptr != first);
8723 static void print_block(
8724 struct compile_state *state, struct block *block, void *arg)
8728 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
8732 block->left && block->left->use?block->left->use->member : 0,
8734 block->right && block->right->use?block->right->use->member : 0);
8735 if (block->first->op == OP_LABEL) {
8736 printf("%p:\n", block->first);
8738 for(ptr = block->first; ; ptr = ptr->next) {
8739 struct triple_set *user;
8742 if (!IS_CONST_OP(op)) {
8743 if (ptr->u.block != block) {
8744 internal_error(state, ptr,
8745 "Wrong block pointer: %p\n",
8749 if (op == OP_ADECL) {
8750 for(user = ptr->use; user; user = user->next) {
8751 if (!user->member->u.block) {
8752 internal_error(state, user->member,
8753 "Use %p not in a block?\n",
8758 display_triple(stdout, ptr);
8760 /* Sanity checks... */
8761 valid_ins(state, ptr);
8762 for(user = ptr->use; user; user = user->next) {
8765 valid_ins(state, use);
8766 if (!IS_CONST_OP(user->member->op) &&
8767 !user->member->u.block) {
8768 internal_error(state, user->member,
8769 "Use %p not in a block?",
8774 if (ptr == block->last)
8781 static void print_blocks(struct compile_state *state)
8783 printf("--------------- blocks ---------------\n");
8784 walk_blocks(state, print_block, 0);
8787 static void prune_nonblock_triples(struct compile_state *state)
8789 struct block *block;
8790 struct triple *first, *ins;
8791 /* Delete the triples not in a basic block */
8792 first = RHS(state->main_function, 0);
8796 if (ins->op == OP_LABEL) {
8797 block = ins->u.block;
8801 release_triple(state, ins->prev);
8803 } while(ins != first);
8806 static void setup_basic_blocks(struct compile_state *state)
8808 /* Find the basic blocks */
8809 state->last_vertex = 0;
8810 state->first_block = basic_block(state, RHS(state->main_function,0));
8811 /* Delete the triples not in a basic block */
8812 prune_nonblock_triples(state);
8813 /* Find the last basic block */
8814 state->last_block = RHS(state->main_function, 0)->prev->u.block;
8815 if (!state->last_block) {
8816 internal_error(state, 0, "end not used?");
8818 /* Insert an extra unused edge from start to the end
8819 * This helps with reverse control flow calculations.
8821 use_block(state->first_block, state->last_block);
8822 /* If we are debugging print what I have just done */
8823 if (state->debug & DEBUG_BASIC_BLOCKS) {
8824 print_blocks(state);
8825 print_control_flow(state);
8829 static void free_basic_block(struct compile_state *state, struct block *block)
8831 struct block_set *entry, *next;
8832 struct block *child;
8836 if (block->vertex == -1) {
8841 unuse_block(block->left, block);
8844 unuse_block(block->right, block);
8847 unidom_block(block->idom, block);
8851 unipdom_block(block->ipdom, block);
8854 for(entry = block->use; entry; entry = next) {
8856 child = entry->member;
8857 unuse_block(block, child);
8858 if (child->left == block) {
8861 if (child->right == block) {
8865 for(entry = block->idominates; entry; entry = next) {
8867 child = entry->member;
8868 unidom_block(block, child);
8871 for(entry = block->domfrontier; entry; entry = next) {
8873 child = entry->member;
8874 undomf_block(block, child);
8876 for(entry = block->ipdominates; entry; entry = next) {
8878 child = entry->member;
8879 unipdom_block(block, child);
8882 for(entry = block->ipdomfrontier; entry; entry = next) {
8884 child = entry->member;
8885 unipdomf_block(block, child);
8887 if (block->users != 0) {
8888 internal_error(state, 0, "block still has users");
8890 free_basic_block(state, block->left);
8892 free_basic_block(state, block->right);
8894 memset(block, -1, sizeof(*block));
8898 static void free_basic_blocks(struct compile_state *state)
8900 struct triple *first, *ins;
8901 free_basic_block(state, state->first_block);
8902 state->last_vertex = 0;
8903 state->first_block = state->last_block = 0;
8904 first = RHS(state->main_function, 0);
8907 if (!is_const(ins)) {
8911 } while(ins != first);
8916 struct block *block;
8917 struct sdom_block *sdominates;
8918 struct sdom_block *sdom_next;
8919 struct sdom_block *sdom;
8920 struct sdom_block *label;
8921 struct sdom_block *parent;
8922 struct sdom_block *ancestor;
8927 static void unsdom_block(struct sdom_block *block)
8929 struct sdom_block **ptr;
8930 if (!block->sdom_next) {
8933 ptr = &block->sdom->sdominates;
8935 if ((*ptr) == block) {
8936 *ptr = block->sdom_next;
8939 ptr = &(*ptr)->sdom_next;
8943 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
8945 unsdom_block(block);
8947 block->sdom_next = sdom->sdominates;
8948 sdom->sdominates = block;
8953 static int initialize_sdblock(struct sdom_block *sd,
8954 struct block *parent, struct block *block, int vertex)
8956 if (!block || (sd[block->vertex].block == block)) {
8960 /* Renumber the blocks in a convinient fashion */
8961 block->vertex = vertex;
8962 sd[vertex].block = block;
8963 sd[vertex].sdom = &sd[vertex];
8964 sd[vertex].label = &sd[vertex];
8965 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
8966 sd[vertex].ancestor = 0;
8967 sd[vertex].vertex = vertex;
8968 vertex = initialize_sdblock(sd, block, block->left, vertex);
8969 vertex = initialize_sdblock(sd, block, block->right, vertex);
8973 static int initialize_sdpblock(struct sdom_block *sd,
8974 struct block *parent, struct block *block, int vertex)
8976 struct block_set *user;
8977 if (!block || (sd[block->vertex].block == block)) {
8981 /* Renumber the blocks in a convinient fashion */
8982 block->vertex = vertex;
8983 sd[vertex].block = block;
8984 sd[vertex].sdom = &sd[vertex];
8985 sd[vertex].label = &sd[vertex];
8986 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
8987 sd[vertex].ancestor = 0;
8988 sd[vertex].vertex = vertex;
8989 for(user = block->use; user; user = user->next) {
8990 vertex = initialize_sdpblock(sd, block, user->member, vertex);
8995 static void compress_ancestors(struct sdom_block *v)
8997 /* This procedure assumes ancestor(v) != 0 */
8998 /* if (ancestor(ancestor(v)) != 0) {
8999 * compress(ancestor(ancestor(v)));
9000 * if (semi(label(ancestor(v))) < semi(label(v))) {
9001 * label(v) = label(ancestor(v));
9003 * ancestor(v) = ancestor(ancestor(v));
9009 if (v->ancestor->ancestor) {
9010 compress_ancestors(v->ancestor->ancestor);
9011 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9012 v->label = v->ancestor->label;
9014 v->ancestor = v->ancestor->ancestor;
9018 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9022 * for each v <= pred(w) {
9024 * if (semi[u] < semi[w] {
9025 * semi[w] = semi[u];
9028 * add w to bucket(vertex(semi[w]));
9029 * LINK(parent(w), w);
9032 * for each v <= bucket(parent(w)) {
9033 * delete v from bucket(parent(w));
9035 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9038 for(i = state->last_vertex; i >= 2; i--) {
9039 struct sdom_block *v, *parent, *next;
9040 struct block_set *user;
9041 struct block *block;
9042 block = sd[i].block;
9043 parent = sd[i].parent;
9045 for(user = block->use; user; user = user->next) {
9046 struct sdom_block *v, *u;
9047 v = &sd[user->member->vertex];
9048 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9049 if (u->sdom->vertex < sd[i].sdom->vertex) {
9050 sd[i].sdom = u->sdom;
9053 sdom_block(sd[i].sdom, &sd[i]);
9054 sd[i].ancestor = parent;
9056 for(v = parent->sdominates; v; v = next) {
9057 struct sdom_block *u;
9058 next = v->sdom_next;
9060 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9061 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9062 u->block : parent->block;
9067 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9071 * for each v <= pred(w) {
9073 * if (semi[u] < semi[w] {
9074 * semi[w] = semi[u];
9077 * add w to bucket(vertex(semi[w]));
9078 * LINK(parent(w), w);
9081 * for each v <= bucket(parent(w)) {
9082 * delete v from bucket(parent(w));
9084 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9087 for(i = state->last_vertex; i >= 2; i--) {
9088 struct sdom_block *u, *v, *parent, *next;
9089 struct block *block;
9090 block = sd[i].block;
9091 parent = sd[i].parent;
9094 v = &sd[block->left->vertex];
9095 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9096 if (u->sdom->vertex < sd[i].sdom->vertex) {
9097 sd[i].sdom = u->sdom;
9100 if (block->right && (block->right != block->left)) {
9101 v = &sd[block->right->vertex];
9102 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9103 if (u->sdom->vertex < sd[i].sdom->vertex) {
9104 sd[i].sdom = u->sdom;
9107 sdom_block(sd[i].sdom, &sd[i]);
9108 sd[i].ancestor = parent;
9110 for(v = parent->sdominates; v; v = next) {
9111 struct sdom_block *u;
9112 next = v->sdom_next;
9114 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9115 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9116 u->block : parent->block;
9121 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9124 for(i = 2; i <= state->last_vertex; i++) {
9125 struct block *block;
9126 block = sd[i].block;
9127 if (block->idom->vertex != sd[i].sdom->vertex) {
9128 block->idom = block->idom->idom;
9130 idom_block(block->idom, block);
9132 sd[1].block->idom = 0;
9135 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9138 for(i = 2; i <= state->last_vertex; i++) {
9139 struct block *block;
9140 block = sd[i].block;
9141 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9142 block->ipdom = block->ipdom->ipdom;
9144 ipdom_block(block->ipdom, block);
9146 sd[1].block->ipdom = 0;
9150 * Every vertex of a flowgraph G = (V, E, r) except r has
9151 * a unique immediate dominator.
9152 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9153 * rooted at r, called the dominator tree of G, such that
9154 * v dominates w if and only if v is a proper ancestor of w in
9155 * the dominator tree.
9158 * If v and w are vertices of G such that v <= w,
9159 * than any path from v to w must contain a common ancestor
9162 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9163 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9164 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9166 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9167 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9170 * Let w != r and let u be a vertex for which sdom(u) is
9171 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9172 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9174 /* Lemma 5: Let vertices v,w satisfy v -> w.
9175 * Then v -> idom(w) or idom(w) -> idom(v)
9178 static void find_immediate_dominators(struct compile_state *state)
9180 struct sdom_block *sd;
9181 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9182 * vi > w for (1 <= i <= k - 1}
9185 * For any vertex w != r.
9187 * {v|(v,w) <= E and v < w } U
9188 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9191 * Let w != r and let u be a vertex for which sdom(u) is
9192 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9194 * { sdom(w) if sdom(w) = sdom(u),
9196 * { idom(u) otherwise
9198 /* The algorithm consists of the following 4 steps.
9199 * Step 1. Carry out a depth-first search of the problem graph.
9200 * Number the vertices from 1 to N as they are reached during
9201 * the search. Initialize the variables used in succeeding steps.
9202 * Step 2. Compute the semidominators of all vertices by applying
9203 * theorem 4. Carry out the computation vertex by vertex in
9204 * decreasing order by number.
9205 * Step 3. Implicitly define the immediate dominator of each vertex
9206 * by applying Corollary 1.
9207 * Step 4. Explicitly define the immediate dominator of each vertex,
9208 * carrying out the computation vertex by vertex in increasing order
9211 /* Step 1 initialize the basic block information */
9212 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9213 initialize_sdblock(sd, 0, state->first_block, 0);
9219 /* Step 2 compute the semidominators */
9220 /* Step 3 implicitly define the immediate dominator of each vertex */
9221 compute_sdom(state, sd);
9222 /* Step 4 explicitly define the immediate dominator of each vertex */
9223 compute_idom(state, sd);
9227 static void find_post_dominators(struct compile_state *state)
9229 struct sdom_block *sd;
9230 /* Step 1 initialize the basic block information */
9231 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9233 initialize_sdpblock(sd, 0, state->last_block, 0);
9235 /* Step 2 compute the semidominators */
9236 /* Step 3 implicitly define the immediate dominator of each vertex */
9237 compute_spdom(state, sd);
9238 /* Step 4 explicitly define the immediate dominator of each vertex */
9239 compute_ipdom(state, sd);
9245 static void find_block_domf(struct compile_state *state, struct block *block)
9247 struct block *child;
9248 struct block_set *user;
9249 if (block->domfrontier != 0) {
9250 internal_error(state, block->first, "domfrontier present?");
9252 for(user = block->idominates; user; user = user->next) {
9253 child = user->member;
9254 if (child->idom != block) {
9255 internal_error(state, block->first, "bad idom");
9257 find_block_domf(state, child);
9259 if (block->left && block->left->idom != block) {
9260 domf_block(block, block->left);
9262 if (block->right && block->right->idom != block) {
9263 domf_block(block, block->right);
9265 for(user = block->idominates; user; user = user->next) {
9266 struct block_set *frontier;
9267 child = user->member;
9268 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9269 if (frontier->member->idom != block) {
9270 domf_block(block, frontier->member);
9276 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9278 struct block *child;
9279 struct block_set *user;
9280 if (block->ipdomfrontier != 0) {
9281 internal_error(state, block->first, "ipdomfrontier present?");
9283 for(user = block->ipdominates; user; user = user->next) {
9284 child = user->member;
9285 if (child->ipdom != block) {
9286 internal_error(state, block->first, "bad ipdom");
9288 find_block_ipdomf(state, child);
9290 if (block->left && block->left->ipdom != block) {
9291 ipdomf_block(block, block->left);
9293 if (block->right && block->right->ipdom != block) {
9294 ipdomf_block(block, block->right);
9296 for(user = block->idominates; user; user = user->next) {
9297 struct block_set *frontier;
9298 child = user->member;
9299 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9300 if (frontier->member->ipdom != block) {
9301 ipdomf_block(block, frontier->member);
9307 static int print_dominated(
9308 struct compile_state *state, struct block *block, int vertex)
9310 struct block_set *user;
9312 if (!block || (block->vertex != vertex + 1)) {
9317 printf("%d:", block->vertex);
9318 for(user = block->idominates; user; user = user->next) {
9319 printf(" %d", user->member->vertex);
9320 if (user->member->idom != block) {
9321 internal_error(state, user->member->first, "bad idom");
9325 vertex = print_dominated(state, block->left, vertex);
9326 vertex = print_dominated(state, block->right, vertex);
9330 static void print_dominators(struct compile_state *state)
9332 printf("\ndominates\n");
9333 print_dominated(state, state->first_block, 0);
9337 static int print_frontiers(
9338 struct compile_state *state, struct block *block, int vertex)
9340 struct block_set *user;
9342 if (!block || (block->vertex != vertex + 1)) {
9347 printf("%d:", block->vertex);
9348 for(user = block->domfrontier; user; user = user->next) {
9349 printf(" %d", user->member->vertex);
9353 vertex = print_frontiers(state, block->left, vertex);
9354 vertex = print_frontiers(state, block->right, vertex);
9357 static void print_dominance_frontiers(struct compile_state *state)
9359 printf("\ndominance frontiers\n");
9360 print_frontiers(state, state->first_block, 0);
9364 static void analyze_idominators(struct compile_state *state)
9366 /* Find the immediate dominators */
9367 find_immediate_dominators(state);
9368 /* Find the dominance frontiers */
9369 find_block_domf(state, state->first_block);
9370 /* If debuging print the print what I have just found */
9371 if (state->debug & DEBUG_FDOMINATORS) {
9372 print_dominators(state);
9373 print_dominance_frontiers(state);
9374 print_control_flow(state);
9380 static int print_ipdominated(
9381 struct compile_state *state, struct block *block, int vertex)
9383 struct block_set *user;
9385 if (!block || (block->vertex != vertex + 1)) {
9390 printf("%d:", block->vertex);
9391 for(user = block->ipdominates; user; user = user->next) {
9392 printf(" %d", user->member->vertex);
9393 if (user->member->ipdom != block) {
9394 internal_error(state, user->member->first, "bad ipdom");
9398 for(user = block->use; user; user = user->next) {
9399 vertex = print_ipdominated(state, user->member, vertex);
9404 static void print_ipdominators(struct compile_state *state)
9406 printf("\nipdominates\n");
9407 print_ipdominated(state, state->last_block, 0);
9410 static int print_pfrontiers(
9411 struct compile_state *state, struct block *block, int vertex)
9413 struct block_set *user;
9415 if (!block || (block->vertex != vertex + 1)) {
9420 printf("%d:", block->vertex);
9421 for(user = block->ipdomfrontier; user; user = user->next) {
9422 printf(" %d", user->member->vertex);
9425 for(user = block->use; user; user = user->next) {
9426 vertex = print_pfrontiers(state, user->member, vertex);
9430 static void print_ipdominance_frontiers(struct compile_state *state)
9432 printf("\nipdominance frontiers\n");
9433 print_pfrontiers(state, state->last_block, 0);
9437 static void analyze_ipdominators(struct compile_state *state)
9439 /* Find the post dominators */
9440 find_post_dominators(state);
9441 /* Find the control dependencies (post dominance frontiers) */
9442 find_block_ipdomf(state, state->last_block);
9443 /* If debuging print the print what I have just found */
9444 if (state->debug & DEBUG_RDOMINATORS) {
9445 print_ipdominators(state);
9446 print_ipdominance_frontiers(state);
9447 print_control_flow(state);
9452 static void insert_phi_operations(struct compile_state *state)
9455 struct triple *first;
9456 int *has_already, *work;
9457 struct block *work_list, **work_list_tail;
9461 size = sizeof(int) * (state->last_vertex + 1);
9462 has_already = xcmalloc(size, "has_already");
9463 work = xcmalloc(size, "work");
9466 first = RHS(state->main_function, 0);
9467 for(var = first->next; var != first ; var = var->next) {
9468 struct block *block;
9469 struct triple_set *user;
9470 if ((var->op != OP_ADECL) || !var->use) {
9475 work_list_tail = &work_list;
9476 for(user = var->use; user; user = user->next) {
9477 if (user->member->op == OP_READ) {
9480 if (user->member->op != OP_WRITE) {
9481 internal_error(state, user->member,
9482 "bad variable access");
9484 block = user->member->u.block;
9486 warning(state, user->member, "dead code");
9488 work[block->vertex] = iter;
9489 *work_list_tail = block;
9490 block->work_next = 0;
9491 work_list_tail = &block->work_next;
9493 for(block = work_list; block; block = block->work_next) {
9494 struct block_set *df;
9495 for(df = block->domfrontier; df; df = df->next) {
9497 struct block *front;
9501 if (has_already[front->vertex] >= iter) {
9504 /* Count how many edges flow into this block */
9505 in_edges = front->users;
9506 /* Insert a phi function for this variable */
9508 state, OP_PHI, var->type, in_edges,
9509 front->first->filename,
9512 phi->u.block = front;
9514 use_triple(var, phi);
9515 /* Insert the phi functions immediately after the label */
9516 insert_triple(state, front->first->next, phi);
9517 if (front->first == front->last) {
9518 front->last = front->first->next;
9520 has_already[front->vertex] = iter;
9522 /* If necessary plan to visit the basic block */
9523 if (work[front->vertex] >= iter) {
9526 work[front->vertex] = iter;
9527 *work_list_tail = front;
9528 front->work_next = 0;
9529 work_list_tail = &front->work_next;
9541 static void fixup_block_phi_variables(
9542 struct compile_state *state, struct block *parent, struct block *block)
9544 struct block_set *set;
9547 if (!parent || !block)
9549 /* Find the edge I am coming in on */
9551 for(set = block->use; set; set = set->next, edge++) {
9552 if (set->member == parent) {
9557 internal_error(state, 0, "phi input is not on a control predecessor");
9559 for(ptr = block->first; ; ptr = ptr->next) {
9560 if (ptr->op == OP_PHI) {
9561 struct triple *var, *val, **slot;
9563 /* Find the current value of the variable */
9564 val = var->use->member;
9565 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9566 internal_error(state, val, "bad value in phi");
9568 if (edge >= TRIPLE_RHS(ptr->sizes)) {
9569 internal_error(state, ptr, "edges > phi rhs");
9571 slot = &RHS(ptr, edge);
9572 if ((*slot != 0) && (*slot != val)) {
9573 internal_error(state, ptr, "phi already bound on this edge");
9576 use_triple(val, ptr);
9578 if (ptr == block->last) {
9585 static void rename_block_variables(
9586 struct compile_state *state, struct block *block)
9588 struct block_set *user;
9589 struct triple *ptr, *next, *last;
9593 last = block->first;
9595 for(ptr = block->first; !done; ptr = next) {
9597 if (ptr == block->last) {
9601 if (ptr->op == OP_READ) {
9602 struct triple *var, *val;
9604 unuse_triple(var, ptr);
9606 error(state, ptr, "variable used without being set");
9608 /* Find the current value of the variable */
9609 val = var->use->member;
9610 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9611 internal_error(state, val, "bad value in read");
9613 propogate_use(state, ptr, val);
9614 release_triple(state, ptr);
9618 if (ptr->op == OP_WRITE) {
9619 struct triple *var, *val;
9622 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9623 internal_error(state, val, "bad value in write");
9625 propogate_use(state, ptr, val);
9626 unuse_triple(var, ptr);
9627 /* Push OP_WRITE ptr->right onto a stack of variable uses */
9628 push_triple(var, val);
9630 if (ptr->op == OP_PHI) {
9633 /* Push OP_PHI onto a stack of variable uses */
9634 push_triple(var, ptr);
9640 /* Fixup PHI functions in the cf successors */
9641 fixup_block_phi_variables(state, block, block->left);
9642 fixup_block_phi_variables(state, block, block->right);
9643 /* rename variables in the dominated nodes */
9644 for(user = block->idominates; user; user = user->next) {
9645 rename_block_variables(state, user->member);
9647 /* pop the renamed variable stack */
9648 last = block->first;
9650 for(ptr = block->first; !done ; ptr = next) {
9652 if (ptr == block->last) {
9655 if (ptr->op == OP_WRITE) {
9658 /* Pop OP_WRITE ptr->right from the stack of variable uses */
9659 pop_triple(var, RHS(ptr, 0));
9660 release_triple(state, ptr);
9663 if (ptr->op == OP_PHI) {
9666 /* Pop OP_WRITE ptr->right from the stack of variable uses */
9667 pop_triple(var, ptr);
9674 static void prune_block_variables(struct compile_state *state,
9675 struct block *block)
9677 struct block_set *user;
9678 struct triple *next, *last, *ptr;
9680 last = block->first;
9682 for(ptr = block->first; !done; ptr = next) {
9684 if (ptr == block->last) {
9687 if (ptr->op == OP_ADECL) {
9688 struct triple_set *user, *next;
9689 for(user = ptr->use; user; user = next) {
9693 if (use->op != OP_PHI) {
9694 internal_error(state, use, "decl still used");
9696 if (MISC(use, 0) != ptr) {
9697 internal_error(state, use, "bad phi use of decl");
9699 unuse_triple(ptr, use);
9702 release_triple(state, ptr);
9708 for(user = block->idominates; user; user = user->next) {
9709 prune_block_variables(state, user->member);
9713 static void transform_to_ssa_form(struct compile_state *state)
9715 insert_phi_operations(state);
9717 printf("@%s:%d\n", __FILE__, __LINE__);
9718 print_blocks(state);
9720 rename_block_variables(state, state->first_block);
9721 prune_block_variables(state, state->first_block);
9725 static void transform_from_ssa_form(struct compile_state *state)
9727 /* To get out of ssa form we insert moves on the incoming
9728 * edges to blocks containting phi functions.
9730 struct triple *first;
9731 struct triple *phi, *next;
9733 /* Walk all of the operations to find the phi functions */
9734 first = RHS(state->main_function, 0);
9735 for(phi = first->next; phi != first ; phi = next) {
9736 struct block_set *set;
9737 struct block *block;
9738 struct triple **slot;
9739 struct triple *var, *read;
9742 if (phi->op != OP_PHI) {
9745 block = phi->u.block;
9746 slot = &RHS(phi, 0);
9748 /* A variable to replace the phi function */
9749 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
9750 /* A read of the single value that is set into the variable */
9751 read = post_triple(state, var, OP_READ, phi->type, var, 0);
9752 use_triple(var, read);
9754 /* Replaces uses of the phi with variable reads */
9755 propogate_use(state, phi, read);
9757 /* Walk all of the incoming edges/blocks and insert moves.
9759 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9760 struct block *eblock;
9761 struct triple *move;
9763 eblock = set->member;
9765 unuse_triple(val, phi);
9771 move = post_triple(state,
9772 val, OP_WRITE, phi->type, var, val);
9773 use_triple(val, move);
9774 use_triple(var, move);
9776 release_triple(state, phi);
9781 static void insert_copies_to_phi(struct compile_state *state)
9783 /* To get out of ssa form we insert moves on the incoming
9784 * edges to blocks containting phi functions.
9786 struct triple *first;
9789 /* Walk all of the operations to find the phi functions */
9790 first = RHS(state->main_function, 0);
9791 for(phi = first->next; phi != first ; phi = phi->next) {
9792 struct block_set *set;
9793 struct block *block;
9794 struct triple **slot;
9796 if (phi->op != OP_PHI) {
9799 if (ID_REG(phi->id) == REG_UNSET) {
9800 phi->id = MK_REG_ID(alloc_virtual_reg(),
9801 ID_REG_CLASSES(phi->id));
9803 block = phi->u.block;
9804 slot = &RHS(phi, 0);
9805 /* Walk all of the incoming edges/blocks and insert moves.
9807 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9808 struct block *eblock;
9809 struct triple *move;
9812 eblock = set->member;
9819 move = build_triple(state, OP_COPY, phi->type, val, 0,
9820 val->filename, val->line, val->col);
9821 move->u.block = eblock;
9823 use_triple(val, move);
9826 unuse_triple(val, phi);
9827 use_triple(move, phi);
9829 /* Walk through the block backwards to find
9830 * an appropriate location for the OP_COPY.
9832 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
9833 struct triple **expr;
9834 if ((ptr == phi) || (ptr == val)) {
9837 expr = triple_rhs(state, ptr, 0);
9838 for(;expr; expr = triple_rhs(state, ptr, expr)) {
9839 if ((*expr) == phi) {
9845 if (triple_is_branch(state, ptr)) {
9846 internal_error(state, ptr,
9847 "Could not insert write to phi");
9849 insert_triple(state, ptr->next, move);
9850 if (eblock->last == ptr) {
9851 eblock->last = move;
9857 struct triple_reg_set {
9858 struct triple_reg_set *next;
9859 struct triple *member;
9864 struct block *block;
9865 struct triple_reg_set *in;
9866 struct triple_reg_set *out;
9870 static int do_triple_set(struct triple_reg_set **head,
9871 struct triple *member, struct triple *new_member)
9873 struct triple_reg_set **ptr, *new;
9878 if ((*ptr)->member == member) {
9881 ptr = &(*ptr)->next;
9883 new = xcmalloc(sizeof(*new), "triple_set");
9884 new->member = member;
9885 new->new = new_member;
9891 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
9893 struct triple_reg_set *entry, **ptr;
9897 if (entry->member == member) {
9908 static int in_triple(struct reg_block *rb, struct triple *in)
9910 return do_triple_set(&rb->in, in, 0);
9912 static void unin_triple(struct reg_block *rb, struct triple *unin)
9914 do_triple_unset(&rb->in, unin);
9917 static int out_triple(struct reg_block *rb, struct triple *out)
9919 return do_triple_set(&rb->out, out, 0);
9921 static void unout_triple(struct reg_block *rb, struct triple *unout)
9923 do_triple_unset(&rb->out, unout);
9926 static int initialize_regblock(struct reg_block *blocks,
9927 struct block *block, int vertex)
9929 struct block_set *user;
9930 if (!block || (blocks[block->vertex].block == block)) {
9934 /* Renumber the blocks in a convinient fashion */
9935 block->vertex = vertex;
9936 blocks[vertex].block = block;
9937 blocks[vertex].vertex = vertex;
9938 for(user = block->use; user; user = user->next) {
9939 vertex = initialize_regblock(blocks, user->member, vertex);
9944 static int phi_in(struct compile_state *state, struct reg_block *blocks,
9945 struct reg_block *rb, struct block *suc)
9947 /* Read the conditional input set of a successor block
9948 * (i.e. the input to the phi nodes) and place it in the
9949 * current blocks output set.
9951 struct block_set *set;
9956 /* Find the edge I am coming in on */
9957 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
9958 if (set->member == rb->block) {
9963 internal_error(state, 0, "Not coming on a control edge?");
9965 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
9966 struct triple **slot, *expr, *ptr2;
9967 int out_change, done2;
9968 done = (ptr == suc->last);
9969 if (ptr->op != OP_PHI) {
9972 slot = &RHS(ptr, 0);
9974 out_change = out_triple(rb, expr);
9978 /* If we don't define the variable also plast it
9979 * in the current blocks input set.
9981 ptr2 = rb->block->first;
9982 for(done2 = 0; !done2; ptr2 = ptr2->next) {
9986 done2 = (ptr2 == rb->block->last);
9991 change |= in_triple(rb, expr);
9996 static int reg_in(struct compile_state *state, struct reg_block *blocks,
9997 struct reg_block *rb, struct block *suc)
9999 struct triple_reg_set *in_set;
10002 /* Read the input set of a successor block
10003 * and place it in the current blocks output set.
10005 in_set = blocks[suc->vertex].in;
10006 for(; in_set; in_set = in_set->next) {
10007 int out_change, done;
10008 struct triple *first, *last, *ptr;
10009 out_change = out_triple(rb, in_set->member);
10013 /* If we don't define the variable also place it
10014 * in the current blocks input set.
10016 first = rb->block->first;
10017 last = rb->block->last;
10019 for(ptr = first; !done; ptr = ptr->next) {
10020 if (ptr == in_set->member) {
10023 done = (ptr == last);
10028 change |= in_triple(rb, in_set->member);
10030 change |= phi_in(state, blocks, rb, suc);
10035 static int use_in(struct compile_state *state, struct reg_block *rb)
10037 /* Find the variables we use but don't define and add
10038 * it to the current blocks input set.
10040 #warning "FIXME is this O(N^2) algorithm bad?"
10041 struct block *block;
10042 struct triple *ptr;
10047 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10048 struct triple **expr;
10049 done = (ptr == block->first);
10050 /* The variable a phi function uses depends on the
10051 * control flow, and is handled in phi_in, not
10054 if (ptr->op == OP_PHI) {
10057 expr = triple_rhs(state, ptr, 0);
10058 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10059 struct triple *rhs, *test;
10065 /* See if rhs is defined in this block */
10066 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10067 tdone = (test == block->first);
10073 /* If the triple is not a definition skip it. */
10074 if (!triple_is_def(state, ptr)) {
10077 /* If I still have a valid rhs add it to in */
10078 change |= in_triple(rb, rhs);
10084 static struct reg_block *compute_variable_lifetimes(
10085 struct compile_state *state)
10087 struct reg_block *blocks;
10090 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10091 initialize_regblock(blocks, state->last_block, 0);
10095 for(i = 1; i <= state->last_vertex; i++) {
10096 struct reg_block *rb;
10098 /* Add the left successor's input set to in */
10099 if (rb->block->left) {
10100 change |= reg_in(state, blocks, rb, rb->block->left);
10102 /* Add the right successor's input set to in */
10103 if ((rb->block->right) &&
10104 (rb->block->right != rb->block->left)) {
10105 change |= reg_in(state, blocks, rb, rb->block->right);
10107 /* Add use to in... */
10108 change |= use_in(state, rb);
10114 static void free_variable_lifetimes(
10115 struct compile_state *state, struct reg_block *blocks)
10118 /* free in_set && out_set on each block */
10119 for(i = 1; i <= state->last_vertex; i++) {
10120 struct triple_reg_set *entry, *next;
10121 struct reg_block *rb;
10123 for(entry = rb->in; entry ; entry = next) {
10124 next = entry->next;
10125 do_triple_unset(&rb->in, entry->member);
10127 for(entry = rb->out; entry; entry = next) {
10128 next = entry->next;
10129 do_triple_unset(&rb->out, entry->member);
10136 typedef struct triple *(*wvl_cb_t)(
10137 struct compile_state *state,
10138 struct reg_block *blocks, struct triple_reg_set *live,
10139 struct reg_block *rb, struct triple *ins, void *arg);
10141 static void walk_variable_lifetimes(struct compile_state *state,
10142 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10146 for(i = 1; i <= state->last_vertex; i++) {
10147 struct triple_reg_set *live;
10148 struct triple_reg_set *entry, *next;
10149 struct triple *ptr, *prev;
10150 struct reg_block *rb;
10151 struct block *block;
10154 /* Get the blocks */
10158 /* Copy out into live */
10160 for(entry = rb->out; entry; entry = next) {
10161 next = entry->next;
10162 do_triple_set(&live, entry->member, entry->new);
10164 /* Walk through the basic block calculating live */
10165 for(done = 0, ptr = block->last; !done; ptr = prev) {
10166 struct triple **expr;
10169 done = (ptr == block->first);
10171 /* Remove the current definition from live */
10172 do_triple_unset(&live, ptr);
10174 /* If the current instruction was deleted continue */
10175 if (!cb(state, blocks, live, rb, ptr, arg)) {
10176 if (block->last == ptr) {
10177 block->last = prev;
10182 /* Add the current uses to live.
10184 * It is safe to skip phi functions because they do
10185 * not have any block local uses, and the block
10186 * output sets already properly account for what
10187 * control flow depedent uses phi functions do have.
10189 if (ptr->op == OP_PHI) {
10192 expr = triple_rhs(state, ptr, 0);
10193 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10194 /* If the triple is not a definition skip it. */
10195 if (!*expr || !triple_is_def(state, *expr)) {
10198 do_triple_set(&live, *expr, 0);
10200 expr = triple_lhs(state, ptr, 0);
10201 for(;expr; expr = triple_lhs(state, ptr, expr)) {
10202 /* If the triple is not a definition skip it. */
10203 if (!*expr || !triple_is_def(state, *expr)) {
10206 do_triple_set(&live, *expr, 0);
10211 for(entry = live; entry; entry = next) {
10212 next = entry->next;
10213 do_triple_unset(&live, entry->member);
10218 static int count_triples(struct compile_state *state)
10220 struct triple *first, *ins;
10222 first = RHS(state->main_function, 0);
10227 } while (ins != first);
10230 struct dead_triple {
10231 struct triple *triple;
10232 struct dead_triple *work_next;
10233 struct block *block;
10236 #define TRIPLE_FLAG_ALIVE 1
10240 static void awaken(
10241 struct compile_state *state,
10242 struct dead_triple *dtriple, struct triple **expr,
10243 struct dead_triple ***work_list_tail)
10245 struct triple *triple;
10246 struct dead_triple *dt;
10254 if (triple->id <= 0) {
10255 internal_error(state, triple, "bad triple id: %d",
10258 if (triple->op == OP_NOOP) {
10259 internal_warning(state, triple, "awakening noop?");
10262 dt = &dtriple[triple->id];
10263 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10264 dt->flags |= TRIPLE_FLAG_ALIVE;
10265 if (!dt->work_next) {
10266 **work_list_tail = dt;
10267 *work_list_tail = &dt->work_next;
10272 static void eliminate_inefectual_code(struct compile_state *state)
10274 struct block *block;
10275 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10277 struct triple *first, *ins;
10279 /* Setup the work list */
10281 work_list_tail = &work_list;
10283 first = RHS(state->main_function, 0);
10285 /* Count how many triples I have */
10286 triples = count_triples(state);
10288 /* Now put then in an array and mark all of the triples dead */
10289 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
10295 if (ins->op == OP_LABEL) {
10296 block = ins->u.block;
10298 dtriple[i].triple = ins;
10299 dtriple[i].block = block;
10300 dtriple[i].flags = 0;
10301 dtriple[i].color = ins->id;
10303 /* See if it is an operation we always keep */
10304 #warning "FIXME handle the case of killing a branch instruction"
10305 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
10306 awaken(state, dtriple, &ins, &work_list_tail);
10310 } while(ins != first);
10312 struct dead_triple *dt;
10313 struct block_set *user;
10314 struct triple **expr;
10316 work_list = dt->work_next;
10318 work_list_tail = &work_list;
10320 /* Wake up the data depencencies of this triple */
10323 expr = triple_rhs(state, dt->triple, expr);
10324 awaken(state, dtriple, expr, &work_list_tail);
10327 expr = triple_lhs(state, dt->triple, expr);
10328 awaken(state, dtriple, expr, &work_list_tail);
10330 /* Wake up the forward control dependencies */
10332 expr = triple_targ(state, dt->triple, expr);
10333 awaken(state, dtriple, expr, &work_list_tail);
10335 /* Wake up the reverse control dependencies of this triple */
10336 for(user = dt->block->ipdomfrontier; user; user = user->next) {
10337 awaken(state, dtriple, &user->member->last, &work_list_tail);
10340 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
10341 if ((dt->triple->op == OP_NOOP) &&
10342 (dt->flags & TRIPLE_FLAG_ALIVE)) {
10343 internal_error(state, dt->triple, "noop effective?");
10345 dt->triple->id = dt->color; /* Restore the color */
10346 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10347 #warning "FIXME handle the case of killing a basic block"
10348 if (dt->block->first == dt->triple) {
10351 if (dt->block->last == dt->triple) {
10352 dt->block->last = dt->triple->prev;
10354 release_triple(state, dt->triple);
10361 struct live_range_edge;
10362 struct live_range {
10363 struct live_range_edge *edges;
10364 struct triple *def;
10368 struct live_range *group_next, **group_prev;
10371 struct live_range_edge {
10372 struct live_range_edge *next;
10373 struct live_range *node;
10376 #define LRE_HASH_SIZE 2048
10378 struct lre_hash *next;
10379 struct live_range *left;
10380 struct live_range *right;
10385 struct lre_hash *hash[LRE_HASH_SIZE];
10386 struct reg_block *blocks;
10387 struct live_range *lr;
10388 struct live_range *low, **low_tail;
10389 struct live_range *high, **high_tail;
10394 static unsigned regc_max_size(struct compile_state *state, int classes)
10399 for(i = 0; i < MAX_REGC; i++) {
10400 if (classes & (1 << i)) {
10402 size = arch_regc_size(state, i);
10403 if (size > max_size) {
10411 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
10413 unsigned equivs[MAX_REG_EQUIVS];
10415 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
10416 internal_error(state, 0, "invalid register");
10418 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
10419 internal_error(state, 0, "invalid register");
10421 arch_reg_equivs(state, equivs, reg1);
10422 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10423 if (equivs[i] == reg2) {
10430 static void reg_fill_used(struct compile_state *state, char *used, int reg)
10432 unsigned equivs[MAX_REG_EQUIVS];
10434 arch_reg_equivs(state, equivs, reg);
10435 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10436 used[equivs[i]] = 1;
10441 static unsigned int hash_live_edge(
10442 struct live_range *left, struct live_range *right)
10444 unsigned int hash, val;
10445 unsigned long lval, rval;
10446 lval = ((unsigned long)left)/sizeof(struct live_range);
10447 rval = ((unsigned long)right)/sizeof(struct live_range);
10452 hash = (hash *263) + val;
10457 hash = (hash *263) + val;
10459 hash = hash & (LRE_HASH_SIZE - 1);
10463 static struct lre_hash **lre_probe(struct reg_state *rstate,
10464 struct live_range *left, struct live_range *right)
10466 struct lre_hash **ptr;
10467 unsigned int index;
10468 /* Ensure left <= right */
10469 if (left > right) {
10470 struct live_range *tmp;
10475 index = hash_live_edge(left, right);
10477 ptr = &rstate->hash[index];
10478 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
10479 ptr = &(*ptr)->next;
10484 static int interfere(struct reg_state *rstate,
10485 struct live_range *left, struct live_range *right)
10487 struct lre_hash **ptr;
10488 ptr = lre_probe(rstate, left, right);
10489 return ptr && *ptr;
10492 static void add_live_edge(struct reg_state *rstate,
10493 struct live_range *left, struct live_range *right)
10495 /* FIXME the memory allocation overhead is noticeable here... */
10496 struct lre_hash **ptr, *new_hash;
10497 struct live_range_edge *edge;
10499 if (left == right) {
10502 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
10505 /* Ensure left <= right */
10506 if (left > right) {
10507 struct live_range *tmp;
10512 ptr = lre_probe(rstate, left, right);
10516 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
10517 new_hash->next = *ptr;
10518 new_hash->left = left;
10519 new_hash->right = right;
10522 edge = xmalloc(sizeof(*edge), "live_range_edge");
10523 edge->next = left->edges;
10524 edge->node = right;
10525 left->edges = edge;
10528 edge = xmalloc(sizeof(*edge), "live_range_edge");
10529 edge->next = right->edges;
10531 right->edges = edge;
10532 right->degree += 1;
10535 static void remove_live_edge(struct reg_state *rstate,
10536 struct live_range *left, struct live_range *right)
10538 struct live_range_edge *edge, **ptr;
10539 struct lre_hash **hptr, *entry;
10540 hptr = lre_probe(rstate, left, right);
10541 if (!hptr || !*hptr) {
10545 *hptr = entry->next;
10548 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
10550 if (edge->node == right) {
10552 memset(edge, 0, sizeof(*edge));
10557 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
10559 if (edge->node == left) {
10561 memset(edge, 0, sizeof(*edge));
10568 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
10570 struct live_range_edge *edge, *next;
10571 for(edge = range->edges; edge; edge = next) {
10573 remove_live_edge(rstate, range, edge->node);
10578 /* Interference graph...
10580 * new(n) --- Return a graph with n nodes but no edges.
10581 * add(g,x,y) --- Return a graph including g with an between x and y
10582 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
10583 * x and y in the graph g
10584 * degree(g, x) --- Return the degree of the node x in the graph g
10585 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
10587 * Implement with a hash table && a set of adjcency vectors.
10588 * The hash table supports constant time implementations of add and interfere.
10589 * The adjacency vectors support an efficient implementation of neighbors.
10593 * +---------------------------------------------------+
10594 * | +--------------+ |
10596 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
10598 * -- In simplify implment optimistic coloring... (No backtracking)
10599 * -- Implement Rematerialization it is the only form of spilling we can perform
10600 * Essentially this means dropping a constant from a register because
10601 * we can regenerate it later.
10603 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
10604 * coalesce at phi points...
10605 * --- Bias coloring if at all possible do the coalesing a compile time.
10610 static void different_colored(
10611 struct compile_state *state, struct reg_state *rstate,
10612 struct triple *parent, struct triple *ins)
10614 struct live_range *lr;
10615 struct triple **expr;
10616 lr = &rstate->lr[ins->id];
10617 expr = triple_rhs(state, ins, 0);
10618 for(;expr; expr = triple_rhs(state, ins, expr)) {
10619 struct live_range *lr2;
10620 if (!*expr || (*expr == parent) || (*expr == ins)) {
10623 lr2 = &rstate->lr[(*expr)->id];
10624 if (lr->color == lr2->color) {
10625 internal_error(state, ins, "live range too big");
10630 static void initialize_live_ranges(
10631 struct compile_state *state, struct reg_state *rstate)
10633 struct triple *ins, *first;
10637 first = RHS(state->main_function, 0);
10638 /* First count how many live ranges I will need.
10640 rstate->ranges = count_triples(state);
10641 size = sizeof(rstate->lr[0]) * (rstate->ranges + 1);
10642 rstate->lr = xcmalloc(size, "live_range");
10643 /* Setup the dummy live range */
10644 rstate->lr[0].classes = 0;
10645 rstate->lr[0].color = REG_UNSET;
10646 rstate->lr[0].def = 0;
10650 unsigned color, classes;
10651 /* Find the architecture specific color information */
10652 color = ID_REG(ins->id);
10653 classes = ID_REG_CLASSES(ins->id);
10654 if ((color != REG_UNSET) && (color < MAX_REGISTERS)) {
10655 classes = arch_reg_regcm(state, color);
10658 /* If the triple is a variable definition give it a live range. */
10659 if (triple_is_def(state, ins)) {
10662 rstate->lr[i].def = ins;
10663 rstate->lr[i].color = color;
10664 rstate->lr[i].classes = classes;
10665 rstate->lr[i].degree = 0;
10667 internal_error(state, ins,
10668 "live range without a class");
10671 /* Otherwise give the triple the dummy live range. */
10676 } while(ins != first);
10677 rstate->ranges = i;
10678 /* Make a second pass to handle achitecture specific register
10683 struct live_range *lr;
10684 lr = &rstate->lr[ins->id];
10685 if (lr->color != REG_UNSET) {
10686 struct triple **expr;
10687 /* This assumes the virtual register is only
10688 * used by one input operation.
10690 expr = triple_rhs(state, ins, 0);
10691 for(;expr; expr = triple_rhs(state, ins, expr)) {
10692 struct live_range *lr2;
10693 if (!*expr || (ins == *expr)) {
10696 lr2 = &rstate->lr[(*expr)->id];
10697 if (lr->color == lr2->color) {
10698 different_colored(state, rstate,
10700 (*expr)->id = ins->id;
10706 } while(ins != first);
10708 /* Make a third pass and forget the virtual registers */
10709 for(i = 1; i <= rstate->ranges; i++) {
10710 if (rstate->lr[i].color >= MAX_REGISTERS) {
10711 rstate->lr[i].color = REG_UNSET;
10716 static struct triple *graph_ins(
10717 struct compile_state *state,
10718 struct reg_block *blocks, struct triple_reg_set *live,
10719 struct reg_block *rb, struct triple *ins, void *arg)
10721 struct reg_state *rstate = arg;
10722 struct live_range *def;
10723 struct triple_reg_set *entry;
10725 /* If the triple does not start a live range
10726 * we do not have a definition to add to
10727 * the interference graph.
10729 if (ins->id <= 0) {
10732 def = &rstate->lr[ins->id];
10734 /* Create an edge between ins and everything that is
10735 * alive, unless the live_range cannot share
10736 * a physical register with ins.
10738 for(entry = live; entry; entry = entry->next) {
10739 struct live_range *lr;
10740 lr= &rstate->lr[entry->member->id];
10741 if (!arch_regcm_intersect(def->classes, lr->classes)) {
10744 add_live_edge(rstate, def, lr);
10750 static struct triple *print_interference_ins(
10751 struct compile_state *state,
10752 struct reg_block *blocks, struct triple_reg_set *live,
10753 struct reg_block *rb, struct triple *ins, void *arg)
10755 struct reg_state *rstate = arg;
10756 struct live_range *lr;
10758 lr = &rstate->lr[ins->id];
10759 display_triple(stdout, ins);
10761 struct triple_reg_set *entry;
10763 for(entry = live; entry; entry = entry->next) {
10764 printf(" %-10p", entry->member);
10769 struct live_range_edge *entry;
10771 for(entry = lr->edges; entry; entry = entry->next) {
10772 printf(" %-10p", entry->node->def);
10776 if (triple_is_branch(state, ins)) {
10782 #if DEBUG_COLOR_GRAPH > 1
10783 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
10784 #define cgdebug_flush() fflush(stdout)
10785 #elif DEBUG_COLOR_GRAPH == 1
10786 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
10787 #define cgdebug_flush() fflush(stderr)
10789 #define cgdebug_printf(...)
10790 #define cgdebug_flush()
10793 static void select_free_color(struct compile_state *state,
10794 struct reg_state *rstate, struct live_range *range)
10796 struct triple_set *entry;
10797 struct live_range *phi;
10798 struct live_range_edge *edge;
10799 char used[MAX_REGISTERS];
10800 struct triple **expr;
10802 /* If a color is already assigned don't change it */
10803 if (range->color != REG_UNSET) {
10806 /* Instead of doing just the trivial color select here I try
10807 * a few extra things because a good color selection will help reduce
10811 /* Find the registers currently in use */
10812 memset(used, 0, sizeof(used));
10813 for(edge = range->edges; edge; edge = edge->next) {
10814 if (edge->node->color == REG_UNSET) {
10817 reg_fill_used(state, used, edge->node->color);
10819 #if DEBUG_COLOR_GRAPH > 1
10823 for(edge = range->edges; edge; edge = edge->next) {
10826 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
10827 tops(range->def->op), i,
10828 range->def->filename, range->def->line, range->def->col);
10829 for(i = 0; i < MAX_REGISTERS; i++) {
10831 cgdebug_printf("used: %s\n",
10838 /* If I feed into an expression reuse it's color.
10839 * This should help remove copies in the case of 2 register instructions
10840 * and phi functions.
10843 entry = range->def->use;
10844 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
10845 struct live_range *lr;
10846 lr = &rstate->lr[entry->member->id];
10847 if (entry->member->id == 0) {
10850 if (!phi && (lr->def->op == OP_PHI) &&
10851 !interfere(rstate, range, lr)) {
10854 if ((lr->color == REG_UNSET) ||
10855 ((lr->classes & range->classes) == 0) ||
10856 (used[lr->color])) {
10859 if (interfere(rstate, range, lr)) {
10862 range->color = lr->color;
10864 /* If I feed into a phi function reuse it's color of the color
10865 * of something else that feeds into the phi function.
10868 if (phi->color != REG_UNSET) {
10869 if (used[phi->color]) {
10870 range->color = phi->color;
10874 expr = triple_rhs(state, phi->def, 0);
10875 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
10876 struct live_range *lr;
10880 lr = &rstate->lr[(*expr)->id];
10881 if ((lr->color == REG_UNSET) ||
10882 ((lr->classes & range->classes) == 0) ||
10883 (used[lr->color])) {
10886 if (interfere(rstate, range, lr)) {
10889 range->color = lr->color;
10893 /* If I don't interfere with a rhs node reuse it's color */
10894 if (range->color == REG_UNSET) {
10895 expr = triple_rhs(state, range->def, 0);
10896 for(; expr; expr = triple_rhs(state, range->def, expr)) {
10897 struct live_range *lr;
10901 lr = &rstate->lr[(*expr)->id];
10902 if ((lr->color == -1) ||
10903 ((lr->classes & range->classes) == 0) ||
10904 (used[lr->color])) {
10907 if (interfere(rstate, range, lr)) {
10910 range->color = lr->color;
10914 /* If I have not opportunitically picked a useful color
10915 * pick the first color that is free.
10917 if (range->color == REG_UNSET) {
10919 arch_select_free_register(state, used, range->classes);
10921 if (range->color == REG_UNSET) {
10923 for(edge = range->edges; edge; edge = edge->next) {
10924 if (edge->node->color == REG_UNSET) {
10927 warning(state, edge->node->def, "reg %s",
10928 arch_reg_str(edge->node->color));
10930 warning(state, range->def, "classes: %x",
10932 for(i = 0; i < MAX_REGISTERS; i++) {
10934 warning(state, range->def, "used: %s",
10938 #if DEBUG_COLOR_GRAPH < 2
10939 error(state, range->def, "too few registers");
10941 internal_error(state, range->def, "too few registers");
10944 range->classes = arch_reg_regcm(state, range->color);
10948 static void color_graph(struct compile_state *state, struct reg_state *rstate)
10950 struct live_range_edge *edge;
10951 struct live_range *range;
10953 cgdebug_printf("Lo: ");
10954 range = rstate->low;
10955 if (*range->group_prev != range) {
10956 internal_error(state, 0, "lo: *prev != range?");
10958 *range->group_prev = range->group_next;
10959 if (range->group_next) {
10960 range->group_next->group_prev = range->group_prev;
10962 if (&range->group_next == rstate->low_tail) {
10963 rstate->low_tail = range->group_prev;
10965 if (rstate->low == range) {
10966 internal_error(state, 0, "low: next != prev?");
10969 else if (rstate->high) {
10970 cgdebug_printf("Hi: ");
10971 range = rstate->high;
10972 if (*range->group_prev != range) {
10973 internal_error(state, 0, "hi: *prev != range?");
10975 *range->group_prev = range->group_next;
10976 if (range->group_next) {
10977 range->group_next->group_prev = range->group_prev;
10979 if (&range->group_next == rstate->high_tail) {
10980 rstate->high_tail = range->group_prev;
10982 if (rstate->high == range) {
10983 internal_error(state, 0, "high: next != prev?");
10989 cgdebug_printf(" %d\n", range - rstate->lr);
10990 range->group_prev = 0;
10991 for(edge = range->edges; edge; edge = edge->next) {
10992 struct live_range *node;
10994 /* Move nodes from the high to the low list */
10995 if (node->group_prev && (node->color == REG_UNSET) &&
10996 (node->degree == regc_max_size(state, node->classes))) {
10997 if (*node->group_prev != node) {
10998 internal_error(state, 0, "move: *prev != node?");
11000 *node->group_prev = node->group_next;
11001 if (node->group_next) {
11002 node->group_next->group_prev = node->group_prev;
11004 if (&node->group_next == rstate->high_tail) {
11005 rstate->high_tail = node->group_prev;
11007 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
11008 node->group_prev = rstate->low_tail;
11009 node->group_next = 0;
11010 *rstate->low_tail = node;
11011 rstate->low_tail = &node->group_next;
11012 if (*node->group_prev != node) {
11013 internal_error(state, 0, "move2: *prev != node?");
11018 color_graph(state, rstate);
11019 cgdebug_printf("Coloring %d @%s:%d.%d:",
11020 range - rstate->lr,
11021 range->def->filename, range->def->line, range->def->col);
11023 select_free_color(state, rstate, range);
11024 if (range->color == -1) {
11025 internal_error(state, range->def, "select_free_color did not?");
11027 cgdebug_printf(" %s\n", arch_reg_str(range->color));
11030 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
11032 struct live_range *lr;
11033 struct live_range_edge *edge;
11034 struct triple *ins, *first;
11035 char used[MAX_REGISTERS];
11036 first = RHS(state->main_function, 0);
11039 if (triple_is_def(state, ins)) {
11040 if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11041 internal_error(state, ins,
11042 "triple without a live range");
11044 lr = &rstate->lr[ins->id];
11045 if (lr->color == REG_UNSET) {
11046 internal_error(state, ins,
11047 "triple without a color");
11049 /* Find the registers used by the edges */
11050 memset(used, 0, sizeof(used));
11051 for(edge = lr->edges; edge; edge = edge->next) {
11052 if (edge->node->color == REG_UNSET) {
11053 internal_error(state, 0,
11054 "live range without a color");
11056 reg_fill_used(state, used, edge->node->color);
11058 if (used[lr->color]) {
11059 internal_error(state, ins,
11060 "triple with already used color");
11064 } while(ins != first);
11067 static void color_triples(struct compile_state *state, struct reg_state *rstate)
11069 struct live_range *lr;
11070 struct triple *first, *ins;
11071 first = RHS(state->main_function, 0);
11074 if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11075 internal_error(state, ins,
11076 "triple without a live range");
11078 lr = &rstate->lr[ins->id];
11079 ins->id = MK_REG_ID(lr->color, 0);
11081 } while (ins != first);
11084 static void print_interference_block(
11085 struct compile_state *state, struct block *block, void *arg)
11088 struct reg_state *rstate = arg;
11089 struct reg_block *rb;
11090 struct triple *ptr;
11093 rb = &rstate->blocks[block->vertex];
11095 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
11099 block->left && block->left->use?block->left->use->member : 0,
11101 block->right && block->right->use?block->right->use->member : 0);
11103 struct triple_reg_set *in_set;
11105 for(in_set = rb->in; in_set; in_set = in_set->next) {
11106 printf(" %-10p", in_set->member);
11111 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11112 done = (ptr == block->last);
11113 if (ptr->op == OP_PHI) {
11120 for(edge = 0; edge < block->users; edge++) {
11121 printf(" in(%d):", edge);
11122 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11123 struct triple **slot;
11124 done = (ptr == block->last);
11125 if (ptr->op != OP_PHI) {
11128 slot = &RHS(ptr, 0);
11129 printf(" %-10p", slot[edge]);
11134 if (block->first->op == OP_LABEL) {
11135 printf("%p:\n", block->first);
11137 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11138 struct triple_set *user;
11139 struct live_range *lr;
11143 done = (ptr == block->last);
11144 lr = &rstate->lr[ptr->id];
11146 if (!IS_CONST_OP(op)) {
11147 if (ptr->u.block != block) {
11148 internal_error(state, ptr,
11149 "Wrong block pointer: %p",
11153 if (op == OP_ADECL) {
11154 for(user = ptr->use; user; user = user->next) {
11155 struct live_range *lr;
11156 lr = &rstate->lr[user->member->id];
11157 if (!user->member->u.block) {
11158 internal_error(state, user->member,
11159 "Use %p not in a block?",
11166 ptr->id = MK_REG_ID(lr->color, 0);
11167 display_triple(stdout, ptr);
11170 if (lr->edges > 0) {
11171 struct live_range_edge *edge;
11173 for(edge = lr->edges; edge; edge = edge->next) {
11174 printf(" %-10p", edge->node->def);
11178 /* Do a bunch of sanity checks */
11179 valid_ins(state, ptr);
11180 if ((ptr->id < 0) || (ptr->id > rstate->ranges)) {
11181 internal_error(state, ptr, "Invalid triple id: %d",
11184 for(user = ptr->use; user; user = user->next) {
11185 struct triple *use;
11186 struct live_range *ulr;
11187 use = user->member;
11188 valid_ins(state, use);
11189 if ((use->id < 0) || (use->id > rstate->ranges)) {
11190 internal_error(state, use, "Invalid triple id: %d",
11193 ulr = &rstate->lr[user->member->id];
11194 if (!IS_CONST_OP(user->member->op) &&
11195 !user->member->u.block) {
11196 internal_error(state, user->member,
11197 "Use %p not in a block?",
11203 struct triple_reg_set *out_set;
11205 for(out_set = rb->out; out_set; out_set = out_set->next) {
11206 printf(" %-10p", out_set->member);
11213 static struct live_range *merge_sort_lr(
11214 struct live_range *first, struct live_range *last)
11216 struct live_range *mid, *join, **join_tail, *pick;
11218 size = (last - first) + 1;
11220 mid = first + size/2;
11221 first = merge_sort_lr(first, mid -1);
11222 mid = merge_sort_lr(mid, last);
11226 /* merge the two lists */
11227 while(first && mid) {
11228 if (first->degree <= mid->degree) {
11230 first = first->group_next;
11232 first->group_prev = 0;
11237 mid = mid->group_next;
11239 mid->group_prev = 0;
11242 pick->group_next = 0;
11243 pick->group_prev = join_tail;
11245 join_tail = &pick->group_next;
11247 /* Splice the remaining list */
11248 pick = (first)? first : mid;
11250 pick->group_prev = join_tail;
11261 static void allocate_registers(struct compile_state *state)
11263 struct reg_state rstate;
11264 struct live_range **point, **next;
11267 /* Clear out the reg_state */
11268 memset(&rstate, 0, sizeof(rstate));
11270 /* Compute the variable lifetimes */
11271 rstate.blocks = compute_variable_lifetimes(state);
11273 /* Allocate and initialize the live ranges */
11274 initialize_live_ranges(state, &rstate);
11276 /* Compute the interference graph */
11277 walk_variable_lifetimes(
11278 state, rstate.blocks, graph_ins, &rstate);
11280 /* Display the interference graph if desired */
11281 if (state->debug & DEBUG_INTERFERENCE) {
11282 printf("\nlive variables by block\n");
11283 walk_blocks(state, print_interference_block, &rstate);
11284 printf("\nlive variables by instruction\n");
11285 walk_variable_lifetimes(
11286 state, rstate.blocks,
11287 print_interference_ins, &rstate);
11290 /* Do not perform coalescing! It is a neat idea but it limits what
11291 * we can do later. It has no benefits that decrease register pressure.
11292 * It only decreases instruction count.
11294 * It might be worth testing this reducing the number of
11295 * live_ragnes as opposed to splitting them seems to help.
11298 /* Build the groups low and high. But with the nodes
11299 * first sorted by degree order.
11301 rstate.low_tail = &rstate.low;
11302 rstate.high_tail = &rstate.high;
11303 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
11305 rstate.high->group_prev = &rstate.high;
11307 for(point = &rstate.high; *point; point = &(*point)->group_next)
11309 rstate.high_tail = point;
11310 /* Walk through the high list and move everything that needs
11313 for(point = &rstate.high; *point; point = next) {
11314 struct live_range *range;
11315 next = &(*point)->group_next;
11318 /* If it has a low degree or it already has a color
11319 * place the node in low.
11321 if ((range->degree < regc_max_size(state, range->classes)) ||
11322 (range->color != REG_UNSET)) {
11323 cgdebug_printf("Lo: %5d degree %5d%s\n",
11324 range - rstate.lr, range->degree,
11325 (range->color != REG_UNSET) ? " (colored)": "");
11326 *range->group_prev = range->group_next;
11327 if (range->group_next) {
11328 range->group_next->group_prev = range->group_prev;
11330 if (&range->group_next == rstate.high_tail) {
11331 rstate.high_tail = range->group_prev;
11333 range->group_prev = rstate.low_tail;
11334 range->group_next = 0;
11335 *rstate.low_tail = range;
11336 rstate.low_tail = &range->group_next;
11340 cgdebug_printf("hi: %5d degree %5d%s\n",
11341 range - rstate.lr, range->degree,
11342 (range->color != REG_UNSET) ? " (colored)": "");
11346 /* Color the live_ranges */
11347 color_graph(state, &rstate);
11349 /* Verify the graph was properly colored */
11350 verify_colors(state, &rstate);
11352 /* Move the colors from the graph to the triples */
11353 color_triples(state, &rstate);
11355 /* Free the edges on each node */
11356 for(i = 1; i <= rstate.ranges; i++) {
11357 remove_live_edges(&rstate, &rstate.lr[i]);
11361 /* Free the variable lifetime information */
11362 free_variable_lifetimes(state, rstate.blocks);
11366 /* Sparce Conditional Constant Propogation
11367 * =========================================
11371 struct lattice_node {
11372 struct triple *def;
11373 struct ssa_edge *out;
11374 struct flow_block *fblock;
11375 struct triple *val;
11376 /* lattice high val && !is_const(val)
11377 * lattice const is_const(val)
11378 * lattice low val == 0
11382 struct lattice_node *src;
11383 struct lattice_node *dst;
11384 struct ssa_edge *work_next;
11385 struct ssa_edge *work_prev;
11386 struct ssa_edge *out_next;
11389 struct flow_block *src;
11390 struct flow_block *dst;
11391 struct flow_edge *work_next;
11392 struct flow_edge *work_prev;
11393 struct flow_edge *in_next;
11394 struct flow_edge *out_next;
11397 struct flow_block {
11398 struct block *block;
11399 struct flow_edge *in;
11400 struct flow_edge *out;
11401 struct flow_edge left, right;
11406 struct lattice_node *lattice;
11407 struct ssa_edge *ssa_edges;
11408 struct flow_block *flow_blocks;
11409 struct flow_edge *flow_work_list;
11410 struct ssa_edge *ssa_work_list;
11414 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
11415 struct flow_edge *fedge)
11417 if (!scc->flow_work_list) {
11418 scc->flow_work_list = fedge;
11419 fedge->work_next = fedge->work_prev = fedge;
11422 struct flow_edge *ftail;
11423 ftail = scc->flow_work_list->work_prev;
11424 fedge->work_next = ftail->work_next;
11425 fedge->work_prev = ftail;
11426 fedge->work_next->work_prev = fedge;
11427 fedge->work_prev->work_next = fedge;
11431 static struct flow_edge *scc_next_fedge(
11432 struct compile_state *state, struct scc_state *scc)
11434 struct flow_edge *fedge;
11435 fedge = scc->flow_work_list;
11437 fedge->work_next->work_prev = fedge->work_prev;
11438 fedge->work_prev->work_next = fedge->work_next;
11439 if (fedge->work_next != fedge) {
11440 scc->flow_work_list = fedge->work_next;
11442 scc->flow_work_list = 0;
11448 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
11449 struct ssa_edge *sedge)
11451 if (!scc->ssa_work_list) {
11452 scc->ssa_work_list = sedge;
11453 sedge->work_next = sedge->work_prev = sedge;
11456 struct ssa_edge *stail;
11457 stail = scc->ssa_work_list->work_prev;
11458 sedge->work_next = stail->work_next;
11459 sedge->work_prev = stail;
11460 sedge->work_next->work_prev = sedge;
11461 sedge->work_prev->work_next = sedge;
11465 static struct ssa_edge *scc_next_sedge(
11466 struct compile_state *state, struct scc_state *scc)
11468 struct ssa_edge *sedge;
11469 sedge = scc->ssa_work_list;
11471 sedge->work_next->work_prev = sedge->work_prev;
11472 sedge->work_prev->work_next = sedge->work_next;
11473 if (sedge->work_next != sedge) {
11474 scc->ssa_work_list = sedge->work_next;
11476 scc->ssa_work_list = 0;
11482 static void initialize_scc_state(
11483 struct compile_state *state, struct scc_state *scc)
11485 int ins_count, ssa_edge_count;
11486 int ins_index, ssa_edge_index, fblock_index;
11487 struct triple *first, *ins;
11488 struct block *block;
11489 struct flow_block *fblock;
11491 memset(scc, 0, sizeof(*scc));
11493 /* Inialize pass zero find out how much memory we need */
11494 first = RHS(state->main_function, 0);
11496 ins_count = ssa_edge_count = 0;
11498 struct triple_set *edge;
11500 for(edge = ins->use; edge; edge = edge->next) {
11504 } while(ins != first);
11506 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
11507 ins_count, ssa_edge_count, state->last_vertex);
11509 scc->ins_count = ins_count;
11511 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
11513 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
11515 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
11518 /* Initialize pass one collect up the nodes */
11521 ins_index = ssa_edge_index = fblock_index = 0;
11525 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11526 block = ins->u.block;
11528 internal_error(state, ins, "label without block");
11531 block->vertex = fblock_index;
11532 fblock = &scc->flow_blocks[fblock_index];
11533 fblock->block = block;
11536 struct lattice_node *lnode;
11538 ins->id = ins_index;
11539 lnode = &scc->lattice[ins_index];
11542 lnode->fblock = fblock;
11543 lnode->val = ins; /* LATTICE HIGH */
11546 } while(ins != first);
11547 /* Initialize pass two collect up the edges */
11552 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11553 struct flow_edge *fedge, **ftail;
11554 struct block_set *bedge;
11555 block = ins->u.block;
11556 fblock = &scc->flow_blocks[block->vertex];
11559 ftail = &fblock->out;
11561 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
11562 if (fblock->left.dst->block != block->left) {
11563 internal_error(state, 0, "block mismatch");
11565 fblock->left.out_next = 0;
11566 *ftail = &fblock->left;
11567 ftail = &fblock->left.out_next;
11569 if (block->right) {
11570 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
11571 if (fblock->right.dst->block != block->right) {
11572 internal_error(state, 0, "block mismatch");
11574 fblock->right.out_next = 0;
11575 *ftail = &fblock->right;
11576 ftail = &fblock->right.out_next;
11578 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
11579 fedge->src = fblock;
11580 fedge->work_next = fedge->work_prev = fedge;
11581 fedge->executable = 0;
11583 ftail = &fblock->in;
11584 for(bedge = block->use; bedge; bedge = bedge->next) {
11585 struct block *src_block;
11586 struct flow_block *sfblock;
11587 struct flow_edge *sfedge;
11588 src_block = bedge->member;
11589 sfblock = &scc->flow_blocks[src_block->vertex];
11591 if (src_block->left == block) {
11592 sfedge = &sfblock->left;
11594 sfedge = &sfblock->right;
11597 ftail = &sfedge->in_next;
11598 sfedge->in_next = 0;
11602 struct triple_set *edge;
11603 struct ssa_edge **stail;
11604 struct lattice_node *lnode;
11605 lnode = &scc->lattice[ins->id];
11607 stail = &lnode->out;
11608 for(edge = ins->use; edge; edge = edge->next) {
11609 struct ssa_edge *sedge;
11610 ssa_edge_index += 1;
11611 sedge = &scc->ssa_edges[ssa_edge_index];
11613 stail = &sedge->out_next;
11614 sedge->src = lnode;
11615 sedge->dst = &scc->lattice[edge->member->id];
11616 sedge->work_next = sedge->work_prev = sedge;
11617 sedge->out_next = 0;
11621 } while(ins != first);
11622 /* Setup a dummy block 0 as a node above the start node */
11624 struct flow_block *fblock, *dst;
11625 struct flow_edge *fedge;
11626 fblock = &scc->flow_blocks[0];
11629 fblock->out = &fblock->left;
11630 dst = &scc->flow_blocks[state->first_block->vertex];
11631 fedge = &fblock->left;
11632 fedge->src = fblock;
11634 fedge->work_next = fedge;
11635 fedge->work_prev = fedge;
11636 fedge->in_next = fedge->dst->in;
11637 fedge->out_next = 0;
11638 fedge->executable = 0;
11639 fedge->dst->in = fedge;
11641 /* Initialize the work lists */
11642 scc->flow_work_list = 0;
11643 scc->ssa_work_list = 0;
11644 scc_add_fedge(state, scc, fedge);
11647 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
11648 ins_index, ssa_edge_index, fblock_index);
11653 static void free_scc_state(
11654 struct compile_state *state, struct scc_state *scc)
11657 for(i = 0; i < scc->ins_count; i++) {
11658 if (scc->lattice[i].val &&
11659 (scc->lattice[i].val != scc->lattice[i].def)) {
11660 xfree(scc->lattice[i].val);
11663 xfree(scc->flow_blocks);
11664 xfree(scc->ssa_edges);
11665 xfree(scc->lattice);
11669 static struct lattice_node *triple_to_lattice(
11670 struct compile_state *state, struct scc_state *scc, struct triple *ins)
11672 if (ins->id <= 0) {
11673 internal_error(state, ins, "bad id");
11675 return &scc->lattice[ins->id];
11678 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
11679 struct lattice_node *lnode)
11681 struct lattice_node *tmp;
11682 struct triple **slot;
11683 struct flow_edge *fedge;
11685 if (lnode->def->op != OP_PHI) {
11686 internal_error(state, lnode->def, "not phi");
11688 /* default to lattice high */
11689 lnode->val = lnode->def;
11690 slot = &RHS(lnode->def, 0);
11692 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
11693 if (!fedge->executable) {
11696 if (!slot[index]) {
11697 internal_error(state, lnode->def, "no phi value");
11699 tmp = triple_to_lattice(state, scc, slot[index]);
11700 /* meet(X, lattice low) = lattice low */
11704 /* meet(X, lattice high) = X */
11705 else if (!tmp->val) {
11706 lnode->val = lnode->val;
11708 /* meet(lattice high, X) = X */
11709 else if (!is_const(lnode->val)) {
11710 lnode->val = tmp->val;
11712 /* meet(const, const) = const or lattice low */
11713 else if (!constants_equal(state, lnode->val, tmp->val)) {
11720 /* Do I need to update any work lists here? */
11722 fprintf(stderr, "phi: %d -> %s\n",
11724 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11728 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
11729 struct lattice_node *lnode)
11732 struct triple *old, *scratch;
11733 struct triple **dexpr, **vexpr;
11736 if (lnode->def->op != OP_STORE) {
11737 check_lhs(state, lnode->def);
11740 /* Store the original value */
11742 old = dup_triple(state, lnode->val);
11743 if (lnode->val != lnode->def) {
11751 /* Reinitialize the value */
11752 lnode->val = scratch = dup_triple(state, lnode->def);
11753 scratch->next = scratch;
11754 scratch->prev = scratch;
11757 count = TRIPLE_SIZE(scratch->sizes);
11758 for(i = 0; i < count; i++) {
11759 struct lattice_node *tmp;
11760 dexpr = &lnode->def->param[i];
11761 vexpr = &scratch->param[i];
11764 tmp = triple_to_lattice(state, scc, *dexpr);
11765 *vexpr = (tmp->val)? tmp->val : tmp->def;
11768 if (scratch->op == OP_BRANCH) {
11769 scratch->next = lnode->def->next;
11771 /* Recompute the value */
11772 #warning "FIXME see if simplify does anything bad"
11773 /* So far it looks like only the strength reduction
11774 * optimization are things I need to worry about.
11776 simplify(state, scratch);
11777 /* Cleanup my value */
11778 if (scratch->use) {
11779 internal_error(state, lnode->def, "scratch used?");
11781 if ((scratch->prev != scratch) ||
11782 ((scratch->next != scratch) &&
11783 ((lnode->def->op != OP_BRANCH) ||
11784 (scratch->next != lnode->def->next)))) {
11785 internal_error(state, lnode->def, "scratch in list?");
11787 /* undo any uses... */
11788 count = TRIPLE_SIZE(scratch->sizes);
11789 for(i = 0; i < count; i++) {
11790 vexpr = &scratch->param[i];
11792 unuse_triple(*vexpr, scratch);
11795 if (!is_const(scratch)) {
11796 for(i = 0; i < count; i++) {
11797 dexpr = &lnode->def->param[i];
11799 struct lattice_node *tmp;
11800 tmp = triple_to_lattice(state, scc, *dexpr);
11808 (lnode->val->op == lnode->def->op) &&
11809 (memcmp(lnode->val->param, lnode->def->param,
11810 count * sizeof(lnode->val->param[0])) == 0) &&
11811 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
11812 lnode->val = lnode->def;
11814 /* Find the cases that are always lattice lo */
11816 triple_is_def(state, lnode->val) &&
11817 !triple_is_pure(state, lnode->val)) {
11822 (lnode->val->op == OP_SDECL) &&
11823 (lnode->val != lnode->def)) {
11824 internal_error(state, lnode->def, "bad sdecl");
11827 /* See if the lattice value has changed */
11829 if (!old && !lnode->val) {
11832 if (changed && lnode->val && !is_const(lnode->val)) {
11836 lnode->val && old &&
11837 (lnode->val->op == old->op) &&
11838 (memcmp(lnode->val->param, old->param,
11839 count * sizeof(lnode->val->param[0])) == 0) &&
11840 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
11846 if (lnode->val != scratch) {
11852 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
11853 struct lattice_node *lnode)
11855 struct lattice_node *cond;
11858 struct flow_edge *fedge;
11859 fprintf(stderr, "branch: %d (",
11862 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
11863 fprintf(stderr, " %d", fedge->dst->block->vertex);
11865 fprintf(stderr, " )");
11866 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
11867 fprintf(stderr, " <- %d",
11868 RHS(lnode->def)->id);
11870 fprintf(stderr, "\n");
11873 if (lnode->def->op != OP_BRANCH) {
11874 internal_error(state, lnode->def, "not branch");
11876 /* This only applies to conditional branches */
11877 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
11880 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
11881 if (cond->val && !is_const(cond->val)) {
11882 #warning "FIXME do I need to do something here?"
11883 warning(state, cond->def, "condition not constant?");
11886 if (cond->val == 0) {
11887 scc_add_fedge(state, scc, cond->fblock->out);
11888 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11890 else if (cond->val->u.cval) {
11891 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11894 scc_add_fedge(state, scc, cond->fblock->out);
11899 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
11900 struct lattice_node *lnode)
11904 changed = compute_lnode_val(state, scc, lnode);
11907 struct triple **expr;
11908 fprintf(stderr, "expr: %3d %10s (",
11909 lnode->def->id, tops(lnode->def->op));
11910 expr = triple_rhs(state, lnode->def, 0);
11911 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
11913 fprintf(stderr, " %d", (*expr)->id);
11916 fprintf(stderr, " ) -> %s\n",
11917 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11920 if (lnode->def->op == OP_BRANCH) {
11921 scc_visit_branch(state, scc, lnode);
11924 else if (changed) {
11925 struct ssa_edge *sedge;
11926 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
11927 scc_add_sedge(state, scc, sedge);
11932 static void scc_writeback_values(
11933 struct compile_state *state, struct scc_state *scc)
11935 struct triple *first, *ins;
11936 first = RHS(state->main_function, 0);
11939 struct lattice_node *lnode;
11940 lnode = triple_to_lattice(state, scc, ins);
11942 if (lnode->val && !is_const(lnode->val)) {
11943 warning(state, lnode->def,
11944 "lattice node still high?");
11947 if (lnode->val && (lnode->val != ins)) {
11948 /* See if it something I know how to write back */
11949 switch(lnode->val->op) {
11951 mkconst(state, ins, lnode->val->u.cval);
11954 mkaddr_const(state, ins,
11955 RHS(lnode->val, 0), lnode->val->u.cval);
11958 /* By default don't copy the changes,
11959 * recompute them in place instead.
11961 simplify(state, ins);
11966 } while(ins != first);
11969 static void scc_transform(struct compile_state *state)
11971 struct scc_state scc;
11973 initialize_scc_state(state, &scc);
11975 while(scc.flow_work_list || scc.ssa_work_list) {
11976 struct flow_edge *fedge;
11977 struct ssa_edge *sedge;
11978 struct flow_edge *fptr;
11979 while((fedge = scc_next_fedge(state, &scc))) {
11980 struct block *block;
11981 struct triple *ptr;
11982 struct flow_block *fblock;
11985 if (fedge->executable) {
11989 internal_error(state, 0, "fedge without dst");
11992 internal_error(state, 0, "fedge without src");
11994 fedge->executable = 1;
11995 fblock = fedge->dst;
11996 block = fblock->block;
11998 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11999 if (fptr->executable) {
12004 fprintf(stderr, "vertex: %d time: %d\n",
12005 block->vertex, time);
12009 for(ptr = block->first; !done; ptr = ptr->next) {
12010 struct lattice_node *lnode;
12011 done = (ptr == block->last);
12012 lnode = &scc.lattice[ptr->id];
12013 if (ptr->op == OP_PHI) {
12014 scc_visit_phi(state, &scc, lnode);
12016 else if (time == 1) {
12017 scc_visit_expr(state, &scc, lnode);
12020 if (fblock->out && !fblock->out->out_next) {
12021 scc_add_fedge(state, &scc, fblock->out);
12024 while((sedge = scc_next_sedge(state, &scc))) {
12025 struct lattice_node *lnode;
12026 struct flow_block *fblock;
12027 lnode = sedge->dst;
12028 fblock = lnode->fblock;
12030 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
12031 sedge - scc.ssa_edges,
12032 sedge->src->def->id,
12033 sedge->dst->def->id);
12035 if (lnode->def->op == OP_PHI) {
12036 scc_visit_phi(state, &scc, lnode);
12039 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
12040 if (fptr->executable) {
12045 scc_visit_expr(state, &scc, lnode);
12051 scc_writeback_values(state, &scc);
12052 free_scc_state(state, &scc);
12056 static void transform_to_arch_instructions(struct compile_state *state);
12059 static void optimize(struct compile_state *state)
12061 if (state->debug & DEBUG_TRIPLES) {
12062 print_triples(state);
12064 /* Replace structures with simpler data types */
12065 flatten_structures(state);
12066 if (state->debug & DEBUG_TRIPLES) {
12067 print_triples(state);
12069 /* Analize the intermediate code */
12070 setup_basic_blocks(state);
12071 analyze_idominators(state);
12072 analyze_ipdominators(state);
12073 /* Transform the code to ssa form */
12074 transform_to_ssa_form(state);
12075 /* Do strength reduction and simple constant optimizations */
12076 if (state->optimize >= 1) {
12077 simplify_all(state);
12079 /* Propogate constants throughout the code */
12080 if (state->optimize >= 2) {
12081 scc_transform(state);
12082 transform_from_ssa_form(state);
12083 free_basic_blocks(state);
12084 setup_basic_blocks(state);
12085 analyze_idominators(state);
12086 analyze_ipdominators(state);
12087 transform_to_ssa_form(state);
12090 #warning "WISHLIST implement single use constants (least possible register pressure)"
12091 #warning "WISHLIST implement induction variable elimination"
12092 #warning "WISHLIST implement strength reduction"
12093 /* Select architecture instructions and an initial partial
12094 * coloring based on architecture constraints.
12096 transform_to_arch_instructions(state);
12097 if (state->debug & DEBUG_ARCH_CODE) {
12098 printf("After transform_to_arch_instructions\n");
12099 print_blocks(state);
12100 print_control_flow(state);
12102 eliminate_inefectual_code(state);
12103 if (state->debug & DEBUG_CODE_ELIMINATION) {
12104 printf("After eliminate_inefectual_code\n");
12105 print_blocks(state);
12106 print_control_flow(state);
12108 /* Color all of the variables to see if they will fit in registers */
12109 insert_copies_to_phi(state);
12110 allocate_registers(state);
12111 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
12112 print_blocks(state);
12114 if (state->debug & DEBUG_CONTROL_FLOW) {
12115 print_control_flow(state);
12117 /* Remove the optimization information.
12118 * This is more to check for memory consistency than to free memory.
12120 free_basic_blocks(state);
12123 /* The x86 register classes */
12124 #define REGC_FLAGS 0
12125 #define REGC_GPR8 1
12126 #define REGC_GPR16 2
12127 #define REGC_GPR32 3
12128 #define REGC_GPR64 4
12131 #define REGC_GPR32_8 7
12132 #define REGC_GPR16_8 8
12133 #define LAST_REGC REGC_GPR16_8
12134 #if LAST_REGC >= MAX_REGC
12135 #error "MAX_REGC is to low"
12138 /* Register class masks */
12139 #define REGCM_FLAGS (1 << REGC_FLAGS)
12140 #define REGCM_GPR8 (1 << REGC_GPR8)
12141 #define REGCM_GPR16 (1 << REGC_GPR16)
12142 #define REGCM_GPR32 (1 << REGC_GPR32)
12143 #define REGCM_GPR64 (1 << REGC_GPR64)
12144 #define REGCM_MMX (1 << REGC_MMX)
12145 #define REGCM_XMM (1 << REGC_XMM)
12146 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
12147 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
12149 /* The x86 registers */
12150 #define REG_EFLAGS 1
12151 #define REGC_FLAGS_FIRST REG_EFLAGS
12152 #define REGC_FLAGS_LAST REG_EFLAGS
12161 #define REGC_GPR8_FIRST REG_AL
12162 #if X86_4_8BIT_GPRS
12163 #define REGC_GPR8_LAST REG_DL
12165 #define REGC_GPR8_LAST REG_DH
12175 #define REGC_GPR16_FIRST REG_AX
12176 #define REGC_GPR16_LAST REG_SP
12185 #define REGC_GPR32_FIRST REG_EAX
12186 #define REGC_GPR32_LAST REG_ESP
12187 #define REG_EDXEAX 26
12188 #define REGC_GPR64_FIRST REG_EDXEAX
12189 #define REGC_GPR64_LAST REG_EDXEAX
12190 #define REG_MMX0 27
12191 #define REG_MMX1 28
12192 #define REG_MMX2 29
12193 #define REG_MMX3 30
12194 #define REG_MMX4 31
12195 #define REG_MMX5 32
12196 #define REG_MMX6 33
12197 #define REG_MMX7 34
12198 #define REGC_MMX_FIRST REG_MMX0
12199 #define REGC_MMX_LAST REG_MMX7
12200 #define REG_XMM0 35
12201 #define REG_XMM1 36
12202 #define REG_XMM2 37
12203 #define REG_XMM3 38
12204 #define REG_XMM4 39
12205 #define REG_XMM5 40
12206 #define REG_XMM6 41
12207 #define REG_XMM7 42
12208 #define REGC_XMM_FIRST REG_XMM0
12209 #define REGC_XMM_LAST REG_XMM7
12210 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
12211 #define LAST_REG REG_XMM7
12213 #define REGC_GPR32_8_FIRST REG_EAX
12214 #define REGC_GPR32_8_LAST REG_EDX
12215 #define REGC_GPR16_8_FIRST REG_AX
12216 #define REGC_GPR16_8_LAST REG_DX
12218 #if LAST_REG >= MAX_REGISTERS
12219 #error "MAX_REGISTERS to low"
12222 static unsigned arch_regc_size(struct compile_state *state, int class)
12224 static unsigned regc_size[LAST_REGC +1] = {
12225 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
12226 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
12227 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
12228 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
12229 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
12230 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
12231 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
12232 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
12233 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
12235 if ((class < 0) || (class > LAST_REGC)) {
12238 return regc_size[class];
12240 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
12242 /* See if two register classes may have overlapping registers */
12243 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12244 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
12246 return (regcm1 & regcm2) ||
12247 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
12250 static void arch_reg_equivs(
12251 struct compile_state *state, unsigned *equiv, int reg)
12253 if ((reg < 0) || (reg > LAST_REG)) {
12254 internal_error(state, 0, "invalid register");
12261 *equiv++ = REG_EAX;
12262 *equiv++ = REG_EDXEAX;
12267 *equiv++ = REG_EBX;
12272 *equiv++ = REG_ECX;
12277 *equiv++ = REG_EDX;
12278 *equiv++ = REG_EDXEAX;
12283 *equiv++ = REG_EAX;
12284 *equiv++ = REG_EDXEAX;
12289 *equiv++ = REG_EBX;
12294 *equiv++ = REG_ECX;
12299 *equiv++ = REG_EDX;
12300 *equiv++ = REG_EDXEAX;
12303 *equiv++ = REG_ESI;
12306 *equiv++ = REG_EDI;
12309 *equiv++ = REG_EBP;
12312 *equiv++ = REG_ESP;
12318 *equiv++ = REG_EDXEAX;
12334 *equiv++ = REG_EDXEAX;
12355 *equiv++ = REG_EAX;
12356 *equiv++ = REG_EDX;
12359 *equiv++ = REG_UNSET;
12363 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
12365 static const struct {
12367 } bound[LAST_REGC + 1] = {
12368 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
12369 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
12370 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
12371 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
12372 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
12373 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
12374 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
12375 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
12376 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
12381 for(class = 0; class <= LAST_REGC; class++) {
12382 if ((reg >= bound[class].first) &&
12383 (reg <= bound[class].last)) {
12384 mask |= (1 << class);
12388 internal_error(state, 0, "reg %d not in any class", reg);
12393 static int do_select_reg(struct compile_state *state,
12394 char *used, int reg, unsigned classes)
12400 mask = arch_reg_regcm(state, reg);
12401 return (classes & mask) ? reg : REG_UNSET;
12404 static int arch_select_free_register(
12405 struct compile_state *state, char *used, int classes)
12407 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
12408 * other types of registers.
12412 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
12413 reg = do_select_reg(state, used, i, classes);
12415 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
12416 reg = do_select_reg(state, used, i, classes);
12418 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
12419 reg = do_select_reg(state, used, i, classes);
12421 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
12422 reg = do_select_reg(state, used, i, classes);
12424 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
12425 reg = do_select_reg(state, used, i, classes);
12427 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
12428 reg = do_select_reg(state, used, i, classes);
12430 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
12431 reg = do_select_reg(state, used, i, classes);
12436 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
12438 #warning "FIXME force types smaller (if legal) before I get here"
12441 unsigned avail_mask;
12443 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12444 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64;
12446 /* Don't enable 8 bit values until I can force both operands
12447 * to be 8bits simultaneously.
12449 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
12452 avail_mask |= REGCM_MMX;
12455 avail_mask |= REGCM_XMM;
12458 switch(type->type & TYPE_MASK) {
12465 mask = REGCM_GPR8 |
12466 REGCM_GPR16_8 | REGCM_GPR16 |
12467 REGCM_GPR32 | REGCM_GPR32_8 |
12469 REGCM_MMX | REGCM_XMM;
12473 mask = REGCM_GPR16 | REGCM_GPR16_8 |
12474 REGCM_GPR32 | REGCM_GPR32_8 |
12476 REGCM_MMX | REGCM_XMM;
12483 mask = REGCM_GPR32 | REGCM_GPR32_8 |
12484 REGCM_GPR64 | REGCM_MMX | REGCM_XMM;
12487 internal_error(state, 0, "no register class for type");
12490 mask &= avail_mask;
12494 static void get_imm32(struct triple *ins, struct triple **expr)
12496 struct triple *imm;
12497 if ((*expr)->op != OP_COPY) {
12500 imm = RHS((*expr), 0);
12501 while(imm->op == OP_COPY) {
12504 if (imm->op != OP_INTCONST) {
12508 unuse_triple(*expr, ins);
12509 use_triple(*expr, ins);
12512 static void get_imm8(struct triple *ins, struct triple **expr)
12514 struct triple *imm;
12515 if ((*expr)->op != OP_COPY) {
12518 imm = RHS((*expr), 0);
12519 while(imm->op == OP_COPY) {
12522 if (imm->op != OP_INTCONST) {
12525 /* For imm8 only a sufficienlty small constant can be used */
12526 if (imm->u.cval > 0xff) {
12530 unuse_triple(*expr, ins);
12531 use_triple(*expr, ins);
12534 static struct triple *pre_copy(struct compile_state *state,
12535 struct triple *ins, struct triple **expr,
12536 unsigned reg, unsigned mask)
12538 /* Carefully insert enough operations so that I can
12539 * enter any operation with a GPR32.
12542 /* See if I can directly reach the result from a GPR32 */
12543 if (mask & (REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)) {
12544 in = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12546 /* If it is a byte value force a earlier copy to a GPR32_8 */
12547 else if (mask & REGCM_GPR8) {
12548 struct triple *tmp;
12549 tmp = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12550 tmp->filename = ins->filename;
12551 tmp->line = ins->line;
12552 tmp->col = ins->col;
12553 tmp->u.block = ins->u.block;
12554 tmp->id = MK_REG_ID(REG_UNSET, REGCM_GPR32_8 | REGCM_GPR16_8);
12555 use_triple(RHS(tmp, 0), tmp);
12556 insert_triple(state, ins, tmp);
12558 in = triple(state, OP_COPY, tmp->type, tmp, 0);
12561 internal_error(state, ins, "bad copy type");
12564 in->filename = ins->filename;
12565 in->line = ins->line;
12566 in->col = ins->col;
12567 in->u.block = ins->u.block;
12568 in->id = MK_REG_ID(reg, mask);
12569 unuse_triple(*expr, ins);
12571 use_triple(RHS(in, 0), in);
12572 use_triple(in, ins);
12573 insert_triple(state, ins, in);
12577 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
12579 struct triple_set *entry, *next;
12580 struct triple *out, *label;
12581 struct block *block;
12583 while(label->op != OP_LABEL) {
12584 label = label->prev;
12586 block = label->u.block;
12587 out = triple(state, OP_COPY, ins->type, ins, 0);
12588 out->filename = ins->filename;
12589 out->line = ins->line;
12590 out->col = ins->col;
12591 out->u.block = block;
12592 out->id = MK_REG_ID(REG_UNSET,
12593 arch_type_to_regcm(state, ins->type));
12594 use_triple(ins, out);
12595 insert_triple(state, ins->next, out);
12596 if (block->last == ins) {
12599 /* Get the users of ins to use out instead */
12600 for(entry = ins->use; entry; entry = next) {
12601 next = entry->next;
12602 if (entry->member == out) {
12605 replace_rhs_use(state, ins, out, entry->member);
12610 static void fixup_branches(struct compile_state *state,
12611 struct triple *cmp, struct triple *use, int jmp_op)
12613 struct triple_set *entry, *next;
12614 for(entry = use->use; entry; entry = next) {
12615 next = entry->next;
12616 if (entry->member->op == OP_COPY) {
12617 fixup_branches(state, cmp, entry->member, jmp_op);
12619 else if (entry->member->op == OP_BRANCH) {
12620 struct triple *branch, *test;
12621 struct triple *left, *right;
12623 left = RHS(cmp, 0);
12624 if (TRIPLE_RHS(cmp->sizes) > 1) {
12625 right = RHS(cmp, 1);
12627 branch = entry->member;
12628 test = pre_triple(state, branch,
12629 cmp->op, cmp->type, left, right);
12630 test->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12631 unuse_triple(RHS(branch, 0), branch);
12632 RHS(branch, 0) = test;
12633 branch->op = jmp_op;
12634 use_triple(RHS(branch, 0), branch);
12639 static void bool_cmp(struct compile_state *state,
12640 struct triple *ins, int cmp_op, int jmp_op, int set_op)
12642 struct block *block;
12643 struct triple_set *entry, *next;
12644 struct triple *set, *tmp1, *tmp2;
12646 #warning "WISHLIST implement an expression simplifier to reduce the use of set?"
12648 block = ins->u.block;
12650 /* Put a barrier up before the cmp which preceeds the
12651 * copy instruction. If a set actually occurs this gives
12652 * us a chance to move variables in registers out of the way.
12655 /* Modify the comparison operator */
12657 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12658 if (cmp_op == OP_CMP) {
12659 get_imm32(ins, &RHS(ins, 1));
12661 /* Generate the instruction sequence that will transform the
12662 * result of the comparison into a logical value.
12664 tmp1 = triple(state, set_op, ins->type, ins, 0);
12665 tmp1->filename = ins->filename;
12666 tmp1->line = ins->line;
12667 tmp1->col = ins->col;
12668 tmp1->u.block = block;
12669 tmp1->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12670 use_triple(ins, tmp1);
12671 insert_triple(state, ins->next, tmp1);
12673 tmp2 = triple(state, OP_COPY, ins->type, tmp1, 0);
12674 tmp2->filename = ins->filename;
12675 tmp2->line = ins->line;
12676 tmp2->col = ins->col;
12677 tmp2->u.block = block;
12678 tmp2->id = MK_REG_ID(REG_UNSET,
12679 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR16 | REGCM_GPR16_8 | REGCM_GPR8);
12680 use_triple(tmp1, tmp2);
12681 insert_triple(state, tmp1->next, tmp2);
12683 if (block->last == ins) {
12684 block->last = tmp2;
12688 for(entry = ins->use; entry; entry = next) {
12689 next = entry->next;
12690 if (entry->member == tmp1) {
12693 replace_rhs_use(state, ins, set, entry->member);
12695 fixup_branches(state, ins, set, jmp_op);
12698 static void verify_lhs(struct compile_state *state, struct triple *ins)
12700 struct triple *next;
12702 lhs = TRIPLE_LHS(ins->sizes);
12703 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
12704 if (next != LHS(ins, i)) {
12705 internal_error(state, ins, "malformed lhs on %s",
12711 static void transform_to_arch_instructions(struct compile_state *state)
12713 /* Transform from generic 3 address instructions
12714 * to archtecture specific instructions.
12715 * And apply architecture specific constrains to instructions.
12716 * Copies are inserted to preserve the register flexibility
12717 * of 3 address instructions.
12719 struct triple *ins, *first, *next;
12720 struct triple *in, *in2;
12721 first = RHS(state->main_function, 0);
12725 ins->id = MK_REG_ID(REG_UNSET, arch_type_to_regcm(state, ins->type));
12730 post_copy(state, ins);
12738 /* instructions that can be used as is */
12746 switch(ins->type->type & TYPE_MASK) {
12747 case TYPE_CHAR: case TYPE_UCHAR:
12750 case TYPE_SHORT: case TYPE_USHORT:
12751 mask = REGCM_GPR16;
12753 case TYPE_INT: case TYPE_UINT:
12754 case TYPE_LONG: case TYPE_ULONG:
12756 mask = REGCM_GPR32;
12759 internal_error(state, ins, "unknown type in store");
12763 in = pre_copy(state, ins, &RHS(ins, 0), REG_UNSET, mask);
12767 switch(ins->type->type & TYPE_MASK) {
12768 case TYPE_CHAR: case TYPE_UCHAR:
12769 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12773 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR16);
12780 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32);
12783 internal_error(state, ins, "unknown type in load");
12792 get_imm32(ins, &RHS(ins, 1));
12793 in = pre_copy(state, ins, &RHS(ins, 0),
12794 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12800 get_imm8(ins, &RHS(ins, 1));
12801 in = pre_copy(state, ins, &RHS(ins, 0),
12802 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12804 if (!is_const(RHS(ins, 1))) {
12805 in2 = pre_copy(state, ins, &RHS(ins, 1),
12806 REG_CL, REGCM_GPR8);
12811 in = pre_copy(state, ins, &RHS(ins, 0),
12812 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12816 get_imm32(ins, &RHS(ins, 1));
12817 in = pre_copy(state, ins, &RHS(ins, 0),
12818 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12820 if (!is_const(RHS(ins, 1))) {
12821 in2 = pre_copy(state, ins, &RHS(ins, 1),
12822 REG_UNSET, REGCM_GPR32);
12826 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
12829 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12832 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
12835 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
12838 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
12841 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
12844 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
12847 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
12850 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
12853 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
12856 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12859 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
12862 if (TRIPLE_RHS(ins->sizes) > 0) {
12863 internal_error(state, ins, "bad branch test");
12871 get_imm8(ins, &RHS(ins, 0));
12873 case OP_INB: ins->id = MK_REG_ID(REG_AL, REGCM_GPR8); break;
12874 case OP_INW: ins->id = MK_REG_ID(REG_AX, REGCM_GPR16); break;
12875 case OP_INL: ins->id = MK_REG_ID(REG_EAX, REGCM_GPR32); break;
12877 if (!is_const(RHS(ins, 0))) {
12878 in = pre_copy(state, ins, &RHS(ins, 0),
12879 REG_DX, REGCM_GPR16);
12881 post_copy(state, ins);
12887 unsigned reg, mask;
12888 get_imm8(ins, &RHS(ins, 1));
12890 case OP_OUTB: reg = REG_AL; mask = REGCM_GPR8; break;
12891 case OP_OUTW: reg = REG_AX; mask = REGCM_GPR16; break;
12892 case OP_OUTL: reg = REG_EAX; mask = REGCM_GPR32; break;
12893 default: reg = REG_UNSET; mask = 0; break;
12895 in = pre_copy(state, ins, &RHS(ins, 0), reg, mask);
12896 if (!is_const(RHS(ins, 1))) {
12897 in2 = pre_copy(state, ins, &RHS(ins, 1),
12898 REG_DX, REGCM_GPR16);
12904 in = pre_copy(state, ins, &RHS(ins, 0),
12905 REG_UNSET, REGCM_GPR32);
12906 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32 | REGCM_GPR32_8);
12909 in = pre_copy(state, ins, &RHS(ins, 0),
12910 REG_ECX, REGCM_GPR32);
12911 verify_lhs(state, ins);
12912 LHS(ins,0)->id = MK_REG_ID(REG_EAX, REGCM_GPR32);
12913 LHS(ins,1)->id = MK_REG_ID(REG_EDX, REGCM_GPR32);
12914 next = ins->next->next->next;
12917 pre_copy(state, ins, &RHS(ins, 0), REG_ECX, REGCM_GPR32);
12918 pre_copy(state, ins, &RHS(ins, 1), REG_EAX, REGCM_GPR32);
12919 pre_copy(state, ins, &RHS(ins, 2), REG_EDX, REGCM_GPR32);
12923 /* Already transformed instructions */
12926 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12928 case OP_JMP_EQ: case OP_JMP_NOTEQ:
12929 case OP_JMP_SLESS: case OP_JMP_ULESS:
12930 case OP_JMP_SMORE: case OP_JMP_UMORE:
12931 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
12932 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
12933 case OP_SET_EQ: case OP_SET_NOTEQ:
12934 case OP_SET_SLESS: case OP_SET_ULESS:
12935 case OP_SET_SMORE: case OP_SET_UMORE:
12936 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
12937 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
12939 /* Unhandled instructions */
12942 internal_error(state, ins, "unhandled ins: %d %s\n",
12943 ins->op, tops(ins->op));
12947 } while(ins != first);
12950 static void generate_local_labels(struct compile_state *state)
12952 struct triple *first, *label;
12955 first = RHS(state->main_function, 0);
12958 if ((label->op == OP_LABEL) ||
12959 (label->op == OP_SDECL)) {
12961 label->u.cval = ++label_counter;
12967 label = label->next;
12968 } while(label != first);
12971 static int check_reg(struct compile_state *state,
12972 struct triple *triple, int classes)
12976 reg = ID_REG(triple->id);
12977 if (reg == REG_UNSET) {
12978 internal_error(state, triple, "register not set");
12980 if (ID_REG_CLASSES(triple->id)) {
12981 internal_error(state, triple, "class specifier present");
12983 mask = arch_reg_regcm(state, reg);
12984 if (!(classes & mask)) {
12985 internal_error(state, triple, "reg %d in wrong class",
12991 static const char *arch_reg_str(int reg)
12993 static const char *regs[] = {
12996 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
12997 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
12998 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
13000 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
13001 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
13002 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
13004 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
13010 static const char *reg(struct compile_state *state, struct triple *triple,
13014 reg = check_reg(state, triple, classes);
13015 return arch_reg_str(reg);
13018 const char *type_suffix(struct compile_state *state, struct type *type)
13020 const char *suffix;
13021 switch(size_of(state, type)) {
13022 case 1: suffix = "b"; break;
13023 case 2: suffix = "w"; break;
13024 case 4: suffix = "l"; break;
13026 internal_error(state, 0, "unknown suffix");
13033 static void print_binary_op(struct compile_state *state,
13034 const char *op, struct triple *ins, FILE *fp)
13037 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13038 if (RHS(ins, 0)->id != ins->id) {
13039 internal_error(state, ins, "invalid register assignment");
13041 if (is_const(RHS(ins, 1))) {
13042 fprintf(fp, "\t%s $%lu, %s\n",
13044 RHS(ins, 1)->u.cval,
13045 reg(state, RHS(ins, 0), mask));
13049 unsigned lmask, rmask;
13051 lreg = check_reg(state, RHS(ins, 0), mask);
13052 rreg = check_reg(state, RHS(ins, 1), mask);
13053 lmask = arch_reg_regcm(state, lreg);
13054 rmask = arch_reg_regcm(state, rreg);
13055 mask = lmask & rmask;
13056 fprintf(fp, "\t%s %s, %s\n",
13058 reg(state, RHS(ins, 1), mask),
13059 reg(state, RHS(ins, 0), mask));
13062 static void print_unary_op(struct compile_state *state,
13063 const char *op, struct triple *ins, FILE *fp)
13066 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13067 fprintf(fp, "\t%s %s\n",
13069 reg(state, RHS(ins, 0), mask));
13072 static void print_op_shift(struct compile_state *state,
13073 const char *op, struct triple *ins, FILE *fp)
13076 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13077 if (RHS(ins, 0)->id != ins->id) {
13078 internal_error(state, ins, "invalid register assignment");
13080 if (is_const(RHS(ins, 1))) {
13081 fprintf(fp, "\t%s $%lu, %s\n",
13083 RHS(ins, 1)->u.cval,
13084 reg(state, RHS(ins, 0), mask));
13088 fprintf(fp, "\t%s %s, %s\n",
13090 reg(state, RHS(ins, 1), REGCM_GPR8),
13091 reg(state, RHS(ins, 0), mask));
13095 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
13102 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
13103 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
13104 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
13106 internal_error(state, ins, "not an in operation");
13110 dreg = check_reg(state, ins, mask);
13111 if (!reg_is_reg(state, dreg, REG_EAX)) {
13112 internal_error(state, ins, "dst != %%eax");
13114 if (is_const(RHS(ins, 0))) {
13115 fprintf(fp, "\t%s $%lu, %s\n",
13116 op, RHS(ins, 0)->u.cval,
13117 reg(state, ins, mask));
13121 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
13122 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13123 internal_error(state, ins, "src != %%dx");
13125 fprintf(fp, "\t%s %s, %s\n",
13127 reg(state, RHS(ins, 0), REGCM_GPR16),
13128 reg(state, ins, mask));
13132 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
13139 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
13140 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
13141 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
13143 internal_error(state, ins, "not an out operation");
13147 lreg = check_reg(state, RHS(ins, 0), mask);
13148 if (!reg_is_reg(state, lreg, REG_EAX)) {
13149 internal_error(state, ins, "src != %%eax");
13151 if (is_const(RHS(ins, 1))) {
13152 fprintf(fp, "\t%s %s, $%lu\n",
13153 op, reg(state, RHS(ins, 0), mask),
13154 RHS(ins, 1)->u.cval);
13158 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
13159 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13160 internal_error(state, ins, "dst != %%dx");
13162 fprintf(fp, "\t%s %s, %s\n",
13164 reg(state, RHS(ins, 0), mask),
13165 reg(state, RHS(ins, 1), REGCM_GPR16));
13169 static void print_op_move(struct compile_state *state,
13170 struct triple *ins, FILE *fp)
13172 /* op_move is complex because there are many types
13173 * of registers we can move between.
13175 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
13176 struct triple *dst, *src;
13177 if (ins->op == OP_COPY) {
13181 else if (ins->op == OP_WRITE) {
13186 internal_error(state, ins, "unknown move operation");
13189 if (!is_const(src)) {
13190 int src_reg, dst_reg;
13191 int src_regcm, dst_regcm;
13192 src_reg = ID_REG(src->id);
13193 dst_reg = ID_REG(dst->id);
13194 src_regcm = arch_reg_regcm(state, src_reg);
13195 dst_regcm = arch_reg_regcm(state, dst_reg);
13196 /* If the class is the same just move the register */
13197 if (src_regcm & dst_regcm &
13198 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
13199 if ((src_reg != dst_reg) || !omit_copy) {
13200 fprintf(fp, "\tmov %s, %s\n",
13201 reg(state, src, src_regcm),
13202 reg(state, dst, dst_regcm));
13205 /* Move 32bit to 16bit */
13206 else if ((src_regcm & REGCM_GPR32) &&
13207 (dst_regcm & REGCM_GPR16)) {
13208 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
13209 if ((src_reg != dst_reg) || !omit_copy) {
13210 fprintf(fp, "\tmovw %s, %s\n",
13211 arch_reg_str(src_reg),
13212 arch_reg_str(dst_reg));
13215 /* Move 32bit to 8bit */
13216 else if ((src_regcm & REGCM_GPR32_8) &&
13217 (dst_regcm & REGCM_GPR8))
13219 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
13220 if ((src_reg != dst_reg) || !omit_copy) {
13221 fprintf(fp, "\tmovb %s, %s\n",
13222 arch_reg_str(src_reg),
13223 arch_reg_str(dst_reg));
13226 /* Move 16bit to 8bit */
13227 else if ((src_regcm & REGCM_GPR16_8) &&
13228 (dst_regcm & REGCM_GPR8))
13230 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
13231 if ((src_reg != dst_reg) || !omit_copy) {
13232 fprintf(fp, "\tmovb %s, %s\n",
13233 arch_reg_str(src_reg),
13234 arch_reg_str(dst_reg));
13237 /* Move 8/16bit to 16/32bit */
13238 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
13239 (dst_regcm & (REGC_GPR16 | REGCM_GPR32))) {
13241 op = is_signed(src->type)? "movsx": "movzx";
13242 fprintf(fp, "\t%s %s, %s\n",
13244 reg(state, src, src_regcm),
13245 reg(state, dst, dst_regcm));
13247 /* Move between sse registers */
13248 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
13249 if ((src_reg != dst_reg) || !omit_copy) {
13250 fprintf(fp, "\tmovdqa %s %s\n",
13251 reg(state, src, src_regcm),
13252 reg(state, dst, dst_regcm));
13255 /* Move between mmx registers or mmx & sse registers */
13256 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
13257 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
13258 if ((src_reg != dst_reg) || !omit_copy) {
13259 fprintf(fp, "\tmovq %s %s\n",
13260 reg(state, src, src_regcm),
13261 reg(state, dst, dst_regcm));
13264 /* Move between 32bit gprs & mmx/sse registers */
13265 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
13266 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
13267 fprintf(fp, "\tmovd %s, %s\n",
13268 reg(state, src, src_regcm),
13269 reg(state, dst, dst_regcm));
13272 internal_error(state, ins, "unknown copy type");
13275 else switch(src->op) {
13279 value = (long_t)(src->u.cval);
13280 fprintf(fp, "\tmov $%ld, %s\n",
13282 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
13286 fprintf(fp, "\tmov $L%lu+%lu, %s\n",
13287 RHS(src, 0)->u.cval,
13289 reg(state, dst, REGCM_GPR32));
13292 internal_error(state, ins, "uknown copy operation");
13296 static void print_op_load(struct compile_state *state,
13297 struct triple *ins, FILE *fp)
13299 struct triple *dst, *src;
13302 if (is_const(src) || is_const(dst)) {
13303 internal_error(state, ins, "unknown load operation");
13305 fprintf(fp, "\tmov (%s), %s\n",
13306 reg(state, src, REGCM_GPR32),
13307 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
13311 static void print_op_store(struct compile_state *state,
13312 struct triple *ins, FILE *fp)
13314 struct triple *dst, *src;
13317 if (is_const(src) && (src->op == OP_INTCONST)) {
13319 value = (long_t)(src->u.cval);
13320 fprintf(fp, "\tmov%s $%ld, (%s)\n",
13321 type_suffix(state, src->type),
13323 reg(state, dst, REGCM_GPR32));
13325 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
13326 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
13327 type_suffix(state, src->type),
13328 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13332 if (is_const(src) || is_const(dst)) {
13333 internal_error(state, ins, "unknown store operation");
13335 fprintf(fp, "\tmov%s %s, (%s)\n",
13336 type_suffix(state, src->type),
13337 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13338 reg(state, dst, REGCM_GPR32));
13344 static void print_op_smul(struct compile_state *state,
13345 struct triple *ins, FILE *fp)
13347 if (!is_const(RHS(ins, 1))) {
13348 fprintf(fp, "\timul %s, %s\n",
13349 reg(state, RHS(ins, 1), REGCM_GPR32),
13350 reg(state, RHS(ins, 0), REGCM_GPR32));
13353 fprintf(fp, "\timul $%ld, %s\n",
13354 RHS(ins, 1)->u.cval,
13355 reg(state, RHS(ins, 0), REGCM_GPR32));
13359 static void print_op_cmp(struct compile_state *state,
13360 struct triple *ins, FILE *fp)
13364 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13365 dreg = check_reg(state, ins, REGCM_FLAGS);
13366 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
13367 internal_error(state, ins, "bad dest register for cmp");
13369 if (is_const(RHS(ins, 1))) {
13370 fprintf(fp, "\tcmp $%lu, %s\n",
13371 RHS(ins, 1)->u.cval,
13372 reg(state, RHS(ins, 0), mask));
13375 unsigned lmask, rmask;
13377 lreg = check_reg(state, RHS(ins, 0), mask);
13378 rreg = check_reg(state, RHS(ins, 1), mask);
13379 lmask = arch_reg_regcm(state, lreg);
13380 rmask = arch_reg_regcm(state, rreg);
13381 mask = lmask & rmask;
13382 fprintf(fp, "\tcmp %s, %s\n",
13383 reg(state, RHS(ins, 1), mask),
13384 reg(state, RHS(ins, 0), mask));
13388 static void print_op_test(struct compile_state *state,
13389 struct triple *ins, FILE *fp)
13392 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13393 fprintf(fp, "\ttest %s, %s\n",
13394 reg(state, RHS(ins, 0), mask),
13395 reg(state, RHS(ins, 0), mask));
13398 static void print_op_branch(struct compile_state *state,
13399 struct triple *branch, FILE *fp)
13401 const char *bop = "j";
13402 if (branch->op == OP_JMP) {
13403 if (TRIPLE_RHS(branch->sizes) != 0) {
13404 internal_error(state, branch, "jmp with condition?");
13409 if (TRIPLE_RHS(branch->sizes) != 1) {
13410 internal_error(state, branch, "jmpcc without condition?");
13412 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
13413 if ((RHS(branch, 0)->op != OP_CMP) &&
13414 (RHS(branch, 0)->op != OP_TEST)) {
13415 internal_error(state, branch, "bad branch test");
13417 #warning "FIXME I have observed instructions between the test and branch instructions"
13418 if (RHS(branch, 0)->next != branch) {
13419 internal_error(state, branch, "branch does not follow test");
13421 switch(branch->op) {
13422 case OP_JMP_EQ: bop = "jz"; break;
13423 case OP_JMP_NOTEQ: bop = "jnz"; break;
13424 case OP_JMP_SLESS: bop = "jl"; break;
13425 case OP_JMP_ULESS: bop = "jb"; break;
13426 case OP_JMP_SMORE: bop = "jg"; break;
13427 case OP_JMP_UMORE: bop = "ja"; break;
13428 case OP_JMP_SLESSEQ: bop = "jle"; break;
13429 case OP_JMP_ULESSEQ: bop = "jbe"; break;
13430 case OP_JMP_SMOREEQ: bop = "jge"; break;
13431 case OP_JMP_UMOREEQ: bop = "jae"; break;
13433 internal_error(state, branch, "Invalid branch op");
13438 fprintf(fp, "\t%s L%lu\n",
13439 bop, TARG(branch, 0)->u.cval);
13442 static void print_op_set(struct compile_state *state,
13443 struct triple *set, FILE *fp)
13445 const char *sop = "set";
13446 if (TRIPLE_RHS(set->sizes) != 1) {
13447 internal_error(state, set, "setcc without condition?");
13449 check_reg(state, RHS(set, 0), REGCM_FLAGS);
13450 if ((RHS(set, 0)->op != OP_CMP) &&
13451 (RHS(set, 0)->op != OP_TEST)) {
13452 internal_error(state, set, "bad set test");
13454 if (RHS(set, 0)->next != set) {
13455 internal_error(state, set, "set does not follow test");
13458 case OP_SET_EQ: sop = "setz"; break;
13459 case OP_SET_NOTEQ: sop = "setnz"; break;
13460 case OP_SET_SLESS: sop = "setl"; break;
13461 case OP_SET_ULESS: sop = "setb"; break;
13462 case OP_SET_SMORE: sop = "setg"; break;
13463 case OP_SET_UMORE: sop = "seta"; break;
13464 case OP_SET_SLESSEQ: sop = "setle"; break;
13465 case OP_SET_ULESSEQ: sop = "setbe"; break;
13466 case OP_SET_SMOREEQ: sop = "setge"; break;
13467 case OP_SET_UMOREEQ: sop = "setae"; break;
13469 internal_error(state, set, "Invalid set op");
13472 fprintf(fp, "\t%s %s\n",
13473 sop, reg(state, set, REGCM_GPR8));
13476 static void print_op_bit_scan(struct compile_state *state,
13477 struct triple *ins, FILE *fp)
13481 case OP_BSF: op = "bsf"; break;
13482 case OP_BSR: op = "bsr"; break;
13484 internal_error(state, ins, "unknown bit scan");
13494 reg(state, RHS(ins, 0), REGCM_GPR32),
13495 reg(state, ins, REGCM_GPR32),
13496 reg(state, ins, REGCM_GPR32));
13499 static void print_const(struct compile_state *state,
13500 struct triple *ins, FILE *fp)
13504 switch(ins->type->type & TYPE_MASK) {
13507 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
13511 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
13517 fprintf(fp, ".int %lu\n", ins->u.cval);
13520 internal_error(state, ins, "Unknown constant type");
13525 unsigned char *blob;
13527 size = size_of(state, ins->type);
13528 blob = ins->u.blob;
13529 for(i = 0; i < size; i++) {
13530 fprintf(fp, ".byte 0x%02x\n",
13537 fprintf(fp, ".int $L%lu+%lu",
13543 internal_error(state, ins, "Unknown constant type");
13548 static void print_sdecl(struct compile_state *state,
13549 struct triple *ins, FILE *fp)
13551 fprintf(fp, ".section \".rom.data\"\n");
13552 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
13553 fprintf(fp, "L%lu:\n", ins->u.cval);
13554 print_const(state, MISC(ins, 0), fp);
13555 fprintf(fp, ".section \".rom.text\"\n");
13559 static void print_instruction(struct compile_state *state,
13560 struct triple *ins, FILE *fp)
13562 /* Assumption: after I have exted the register allocator
13563 * everything is in a valid register.
13566 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
13567 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
13568 case OP_AND: print_binary_op(state, "and", ins, fp); break;
13569 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
13570 case OP_OR: print_binary_op(state, "or", ins, fp); break;
13571 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
13572 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
13573 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
13574 case OP_POS: break;
13575 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
13576 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
13579 /* Don't generate anything here for constants */
13581 /* Don't generate anything for variable declarations. */
13584 print_sdecl(state, ins, fp);
13588 print_op_move(state, ins, fp);
13591 print_op_load(state, ins, fp);
13594 print_op_store(state, ins, fp);
13597 print_op_smul(state, ins, fp);
13599 case OP_CMP: print_op_cmp(state, ins, fp); break;
13600 case OP_TEST: print_op_test(state, ins, fp); break;
13602 case OP_JMP_EQ: case OP_JMP_NOTEQ:
13603 case OP_JMP_SLESS: case OP_JMP_ULESS:
13604 case OP_JMP_SMORE: case OP_JMP_UMORE:
13605 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
13606 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
13607 print_op_branch(state, ins, fp);
13609 case OP_SET_EQ: case OP_SET_NOTEQ:
13610 case OP_SET_SLESS: case OP_SET_ULESS:
13611 case OP_SET_SMORE: case OP_SET_UMORE:
13612 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
13613 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
13614 print_op_set(state, ins, fp);
13616 case OP_INB: case OP_INW: case OP_INL:
13617 print_op_in(state, ins, fp);
13619 case OP_OUTB: case OP_OUTW: case OP_OUTL:
13620 print_op_out(state, ins, fp);
13624 print_op_bit_scan(state, ins, fp);
13627 verify_lhs(state, ins);
13628 fprintf(fp, "\trdmsr\n");
13631 fprintf(fp, "\twrmsr\n");
13634 fprintf(fp, "\thlt\n");
13640 fprintf(fp, "L%lu:\n", ins->u.cval);
13642 /* Ignore OP_PIECE */
13645 /* Operations I am not yet certain how to handle */
13647 case OP_SDIV: case OP_UDIV:
13648 case OP_SMOD: case OP_UMOD:
13649 /* Operations that should never get here */
13650 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
13651 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
13652 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
13654 internal_error(state, ins, "unknown op: %d %s",
13655 ins->op, tops(ins->op));
13660 static void print_instructions(struct compile_state *state)
13662 struct triple *first, *ins;
13663 int print_location;
13666 const char *last_filename;
13668 print_location = 1;
13673 fprintf(fp, ".section \".rom.text\"\n");
13674 first = RHS(state->main_function, 0);
13677 if (print_location &&
13678 ((last_filename != ins->filename) ||
13679 (last_line != ins->line) ||
13680 (last_col != ins->col))) {
13681 fprintf(fp, "\t/* %s:%d */\n",
13682 ins->filename, ins->line);
13683 last_filename = ins->filename;
13684 last_line = ins->line;
13685 last_col = ins->col;
13688 print_instruction(state, ins, fp);
13690 } while(ins != first);
13693 static void generate_code(struct compile_state *state)
13695 generate_local_labels(state);
13696 print_instructions(state);
13700 static void print_tokens(struct compile_state *state)
13703 tk = &state->token[0];
13708 next_token(state, 0);
13710 loc(stdout, state, 0);
13711 printf("%s <- `%s'\n",
13713 tk->ident ? tk->ident->name :
13714 tk->str_len ? tk->val.str : "");
13716 } while(tk->tok != TOK_EOF);
13719 static void compile(char *filename, int debug, int opt)
13722 struct compile_state state;
13723 memset(&state, 0, sizeof(state));
13725 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
13726 memset(&state.token[i], 0, sizeof(state.token[i]));
13727 state.token[i].tok = -1;
13729 /* Remember the debug settings */
13730 state.debug = debug;
13731 state.optimize = opt;
13732 /* Prep the preprocessor */
13733 state.if_depth = 0;
13734 state.if_value = 0;
13735 /* register the C keywords */
13736 register_keywords(&state);
13737 /* register the keywords the macro preprocessor knows */
13738 register_macro_keywords(&state);
13739 /* Memorize where some special keywords are. */
13740 state.i_continue = lookup(&state, "continue", 8);
13741 state.i_break = lookup(&state, "break", 5);
13742 /* Enter the globl definition scope */
13743 start_scope(&state);
13744 register_builtins(&state);
13745 compile_file(&state, filename, 1);
13747 print_tokens(&state);
13750 /* Exit the global definition scope */
13753 /* Now that basic compilation has happened
13754 * optimize the intermediate code
13757 generate_code(&state);
13759 fprintf(stderr, "done\n");
13763 static void version(void)
13765 printf("romcc " VERSION " released " RELEASE_DATE "\n");
13768 static void usage(void)
13772 "Usage: romcc <source>.c\n"
13773 "Compile a C source file without using ram\n"
13777 static void arg_error(char *fmt, ...)
13780 va_start(args, fmt);
13781 vfprintf(stderr, fmt, args);
13787 int main(int argc, char **argv)
13796 while((argc > 1) && (argc != last_argc)) {
13798 if (strncmp(argv[1], "--debug=", 8) == 0) {
13799 debug = atoi(argv[1] + 8);
13803 else if ((strcmp(argv[1],"-O") == 0) ||
13804 (strcmp(argv[1], "-O1") == 0)) {
13809 else if (strcmp(argv[1],"-O2") == 0) {
13816 arg_error("Wrong argument count %d\n", argc);
13818 filename = argv[1];
13819 compile(filename, debug, optimize);