- Minor mod to reset16.inc to work with newer binutils hopefully this works with...
[coreboot.git] / util / romcc / romcc.c
1 #include <stdarg.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <limits.h>
13
14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
16 #define DEBUG_SCC 0
17 #define DEBUG_CONSISTENCY 1
18
19 #warning "FIXME boundary cases with small types in larger registers"
20 #warning "FIXME give clear error messages about unused variables"
21
22 /*  Control flow graph of a loop without goto.
23  * 
24  *        AAA
25  *   +---/
26  *  /
27  * / +--->CCC
28  * | |    / \
29  * | |  DDD EEE    break;
30  * | |    \    \
31  * | |    FFF   \
32  *  \|    / \    \
33  *   |\ GGG HHH   |   continue;
34  *   | \  \   |   |
35  *   |  \ III |  /
36  *   |   \ | /  / 
37  *   |    vvv  /  
38  *   +----BBB /   
39  *         | /
40  *         vv
41  *        JJJ
42  *
43  * 
44  *             AAA
45  *     +-----+  |  +----+
46  *     |      \ | /     |
47  *     |       BBB  +-+ |
48  *     |       / \ /  | |
49  *     |     CCC JJJ / /
50  *     |     / \    / / 
51  *     |   DDD EEE / /  
52  *     |    |   +-/ /
53  *     |   FFF     /    
54  *     |   / \    /     
55  *     | GGG HHH /      
56  *     |  |   +-/
57  *     | III
58  *     +--+ 
59  *
60  * 
61  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
62  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
63  *
64  *
65  * [] == DFlocal(X) U DF(X)
66  * () == DFup(X)
67  *
68  * Dominator graph of the same nodes.
69  *
70  *           AAA     AAA: [ ] ()
71  *          /   \
72  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
73  *         |
74  *        CCC        CCC: [ ] ( BBB, JJJ )
75  *        / \
76  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
77  *      |
78  *     FFF           FFF: [ ] ( BBB )
79  *     / \         
80  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
81  *   |
82  *  III              III: [ BBB ] ()
83  *
84  *
85  * BBB and JJJ are definitely the dominance frontier.
86  * Where do I place phi functions and how do I make that decision.
87  *   
88  */
89 static void die(char *fmt, ...)
90 {
91         va_list args;
92
93         va_start(args, fmt);
94         vfprintf(stderr, fmt, args);
95         va_end(args);
96         fflush(stdout);
97         fflush(stderr);
98         exit(1);
99 }
100
101 #define MALLOC_STRONG_DEBUG
102 static void *xmalloc(size_t size, const char *name)
103 {
104         void *buf;
105         buf = malloc(size);
106         if (!buf) {
107                 die("Cannot malloc %ld bytes to hold %s: %s\n",
108                         size + 0UL, name, strerror(errno));
109         }
110         return buf;
111 }
112
113 static void *xcmalloc(size_t size, const char *name)
114 {
115         void *buf;
116         buf = xmalloc(size, name);
117         memset(buf, 0, size);
118         return buf;
119 }
120
121 static void xfree(const void *ptr)
122 {
123         free((void *)ptr);
124 }
125
126 static char *xstrdup(const char *str)
127 {
128         char *new;
129         int len;
130         len = strlen(str);
131         new = xmalloc(len + 1, "xstrdup string");
132         memcpy(new, str, len);
133         new[len] = '\0';
134         return new;
135 }
136
137 static void xchdir(const char *path)
138 {
139         if (chdir(path) != 0) {
140                 die("chdir to %s failed: %s\n",
141                         path, strerror(errno));
142         }
143 }
144
145 static int exists(const char *dirname, const char *filename)
146 {
147         int does_exist = 1;
148         xchdir(dirname);
149         if (access(filename, O_RDONLY) < 0) {
150                 if ((errno != EACCES) && (errno != EROFS)) {
151                         does_exist = 0;
152                 }
153         }
154         return does_exist;
155 }
156
157
158 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
159 {
160         int fd;
161         char *buf;
162         off_t size, progress;
163         ssize_t result;
164         struct stat stats;
165         
166         if (!filename) {
167                 *r_size = 0;
168                 return 0;
169         }
170         xchdir(dirname);
171         fd = open(filename, O_RDONLY);
172         if (fd < 0) {
173                 die("Cannot open '%s' : %s\n",
174                         filename, strerror(errno));
175         }
176         result = fstat(fd, &stats);
177         if (result < 0) {
178                 die("Cannot stat: %s: %s\n",
179                         filename, strerror(errno));
180         }
181         size = stats.st_size;
182         *r_size = size +1;
183         buf = xmalloc(size +2, filename);
184         buf[size] = '\n'; /* Make certain the file is newline terminated */
185         buf[size+1] = '\0'; /* Null terminate the file for good measure */
186         progress = 0;
187         while(progress < size) {
188                 result = read(fd, buf + progress, size - progress);
189                 if (result < 0) {
190                         if ((errno == EINTR) || (errno == EAGAIN))
191                                 continue;
192                         die("read on %s of %ld bytes failed: %s\n",
193                                 filename, (size - progress)+ 0UL, strerror(errno));
194                 }
195                 progress += result;
196         }
197         result = close(fd);
198         if (result < 0) {
199                 die("Close of %s failed: %s\n",
200                         filename, strerror(errno));
201         }
202         return buf;
203 }
204
205 /* Long on the destination platform */
206 typedef unsigned long ulong_t;
207 typedef long long_t;
208
209 struct file_state {
210         struct file_state *prev;
211         const char *basename;
212         char *dirname;
213         char *buf;
214         off_t size;
215         char *pos;
216         int line;
217         char *line_start;
218 };
219 struct hash_entry;
220 struct token {
221         int tok;
222         struct hash_entry *ident;
223         int str_len;
224         union {
225                 ulong_t integer;
226                 const char *str;
227         } val;
228 };
229
230 /* I have two classes of types:
231  * Operational types.
232  * Logical types.  (The type the C standard says the operation is of)
233  *
234  * The operational types are:
235  * chars
236  * shorts
237  * ints
238  * longs
239  *
240  * floats
241  * doubles
242  * long doubles
243  *
244  * pointer
245  */
246
247
248 /* Machine model.
249  * No memory is useable by the compiler.
250  * There is no floating point support.
251  * All operations take place in general purpose registers.
252  * There is one type of general purpose register.
253  * Unsigned longs are stored in that general purpose register.
254  */
255
256 /* Operations on general purpose registers.
257  */
258
259 #define OP_SMUL       0
260 #define OP_UMUL       1
261 #define OP_SDIV       2
262 #define OP_UDIV       3
263 #define OP_SMOD       4
264 #define OP_UMOD       5
265 #define OP_ADD        6
266 #define OP_SUB        7
267 #define OP_SL         8
268 #define OP_USR        9
269 #define OP_SSR       10 
270 #define OP_AND       11 
271 #define OP_XOR       12
272 #define OP_OR        13
273 #define OP_POS       14 /* Dummy positive operator don't use it */
274 #define OP_NEG       15
275 #define OP_INVERT    16
276                      
277 #define OP_EQ        20
278 #define OP_NOTEQ     21
279 #define OP_SLESS     22
280 #define OP_ULESS     23
281 #define OP_SMORE     24
282 #define OP_UMORE     25
283 #define OP_SLESSEQ   26
284 #define OP_ULESSEQ   27
285 #define OP_SMOREEQ   28
286 #define OP_UMOREEQ   29
287                      
288 #define OP_LFALSE    30  /* Test if the expression is logically false */
289 #define OP_LTRUE     31  /* Test if the expression is logcially true */
290
291 #define OP_LOAD      32
292 #define OP_STORE     33
293
294 #define OP_NOOP      34
295
296 #define OP_MIN_CONST 50
297 #define OP_MAX_CONST 59
298 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
299 #define OP_INTCONST  50
300 #define OP_BLOBCONST 51
301 /* For OP_BLOBCONST ->type holds the layout and size
302  * information.  u.blob holds a pointer to the raw binary
303  * data for the constant initializer.
304  */
305 #define OP_ADDRCONST 52
306 /* For OP_ADDRCONST ->type holds the type.
307  * MISC(0) holds the reference to the static variable.
308  * ->u.cval holds an offset from that value.
309  */
310
311 #define OP_WRITE     60 
312 /* OP_WRITE moves one pseudo register to another.
313  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
314  * RHS(0) holds the psuedo to move.
315  */
316
317 #define OP_READ      61
318 /* OP_READ reads the value of a variable and makes
319  * it available for the pseudo operation.
320  * Useful for things like def-use chains.
321  * RHS(0) holds points to the triple to read from.
322  */
323 #define OP_COPY      62
324 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
325  */
326 #define OP_PIECE     63
327 /* OP_PIECE returns one piece of a instruction that returns a structure.
328  * MISC(0) is the instruction
329  * u.cval is the LHS piece of the instruction to return.
330  */
331 #define OP_ASM       64
332 /* OP_ASM holds a sequence of assembly instructions, the result
333  * of a C asm directive.
334  * RHS(x) holds input value x to the assembly sequence.
335  * LHS(x) holds the output value x from the assembly sequence.
336  * u.blob holds the string of assembly instructions.
337  */
338
339 #define OP_DEREF     65
340 /* OP_DEREF generates an lvalue from a pointer.
341  * RHS(0) holds the pointer value.
342  * OP_DEREF serves as a place holder to indicate all necessary
343  * checks have been done to indicate a value is an lvalue.
344  */
345 #define OP_DOT       66
346 /* OP_DOT references a submember of a structure lvalue.
347  * RHS(0) holds the lvalue.
348  * ->u.field holds the name of the field we want.
349  *
350  * Not seen outside of expressions.
351  */
352 #define OP_VAL       67
353 /* OP_VAL returns the value of a subexpression of the current expression.
354  * Useful for operators that have side effects.
355  * RHS(0) holds the expression.
356  * MISC(0) holds the subexpression of RHS(0) that is the
357  * value of the expression.
358  *
359  * Not seen outside of expressions.
360  */
361 #define OP_LAND      68
362 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
363  * Not seen outside of expressions.
364  */
365 #define OP_LOR       69
366 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
367  * Not seen outside of expressions.
368  */
369 #define OP_COND      70
370 /* OP_CODE performas a C ? : operation. 
371  * RHS(0) holds the test.
372  * RHS(1) holds the expression to evaluate if the test returns true.
373  * RHS(2) holds the expression to evaluate if the test returns false.
374  * Not seen outside of expressions.
375  */
376 #define OP_COMMA     71
377 /* OP_COMMA performacs a C comma operation.
378  * That is RHS(0) is evaluated, then RHS(1)
379  * and the value of RHS(1) is returned.
380  * Not seen outside of expressions.
381  */
382
383 #define OP_CALL      72
384 /* OP_CALL performs a procedure call. 
385  * MISC(0) holds a pointer to the OP_LIST of a function
386  * RHS(x) holds argument x of a function
387  * 
388  * Currently not seen outside of expressions.
389  */
390 #define OP_VAL_VEC   74
391 /* OP_VAL_VEC is an array of triples that are either variable
392  * or values for a structure or an array.
393  * RHS(x) holds element x of the vector.
394  * triple->type->elements holds the size of the vector.
395  */
396
397 /* statements */
398 #define OP_LIST      80
399 /* OP_LIST Holds a list of statements, and a result value.
400  * RHS(0) holds the list of statements.
401  * MISC(0) holds the value of the statements.
402  */
403
404 #define OP_BRANCH    81 /* branch */
405 /* For branch instructions
406  * TARG(0) holds the branch target.
407  * RHS(0) if present holds the branch condition.
408  * ->next holds where to branch to if the branch is not taken.
409  * The branch target can only be a decl...
410  */
411
412 #define OP_LABEL     83
413 /* OP_LABEL is a triple that establishes an target for branches.
414  * ->use is the list of all branches that use this label.
415  */
416
417 #define OP_ADECL     84 
418 /* OP_DECL is a triple that establishes an lvalue for assignments.
419  * ->use is a list of statements that use the variable.
420  */
421
422 #define OP_SDECL     85
423 /* OP_SDECL is a triple that establishes a variable of static
424  * storage duration.
425  * ->use is a list of statements that use the variable.
426  * MISC(0) holds the initializer expression.
427  */
428
429
430 #define OP_PHI       86
431 /* OP_PHI is a triple used in SSA form code.  
432  * It is used when multiple code paths merge and a variable needs
433  * a single assignment from any of those code paths.
434  * The operation is a cross between OP_DECL and OP_WRITE, which
435  * is what OP_PHI is geneared from.
436  * 
437  * RHS(x) points to the value from code path x
438  * The number of RHS entries is the number of control paths into the block
439  * in which OP_PHI resides.  The elements of the array point to point
440  * to the variables OP_PHI is derived from.
441  *
442  * MISC(0) holds a pointer to the orginal OP_DECL node.
443  */
444
445 /* Architecture specific instructions */
446 #define OP_CMP         100
447 #define OP_TEST        101
448 #define OP_SET_EQ      102
449 #define OP_SET_NOTEQ   103
450 #define OP_SET_SLESS   104
451 #define OP_SET_ULESS   105
452 #define OP_SET_SMORE   106
453 #define OP_SET_UMORE   107
454 #define OP_SET_SLESSEQ 108
455 #define OP_SET_ULESSEQ 109
456 #define OP_SET_SMOREEQ 110
457 #define OP_SET_UMOREEQ 111
458
459 #define OP_JMP         112
460 #define OP_JMP_EQ      113
461 #define OP_JMP_NOTEQ   114
462 #define OP_JMP_SLESS   115
463 #define OP_JMP_ULESS   116
464 #define OP_JMP_SMORE   117
465 #define OP_JMP_UMORE   118
466 #define OP_JMP_SLESSEQ 119
467 #define OP_JMP_ULESSEQ 120
468 #define OP_JMP_SMOREEQ 121
469 #define OP_JMP_UMOREEQ 122
470
471 /* Builtin operators that it is just simpler to use the compiler for */
472 #define OP_INB         130
473 #define OP_INW         131
474 #define OP_INL         132
475 #define OP_OUTB        133
476 #define OP_OUTW        134
477 #define OP_OUTL        135
478 #define OP_BSF         136
479 #define OP_BSR         137
480 #define OP_RDMSR       138
481 #define OP_WRMSR       139
482 #define OP_HLT         140
483
484 struct op_info {
485         const char *name;
486         unsigned flags;
487 #define PURE   1
488 #define IMPURE 2
489 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
490 #define DEF    4
491 #define BLOCK  8 /* Triple stores the current block */
492         unsigned char lhs, rhs, misc, targ;
493 };
494
495 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
496         .name = (NAME), \
497         .flags = (FLAGS), \
498         .lhs = (LHS), \
499         .rhs = (RHS), \
500         .misc = (MISC), \
501         .targ = (TARG), \
502          }
503 static const struct op_info table_ops[] = {
504 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
505 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
506 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
507 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
508 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
509 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
510 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
511 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
512 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
513 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
514 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
515 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
516 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
517 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
518 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
519 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
520 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
521
522 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
523 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
524 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
525 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
526 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
527 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
528 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
529 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
530 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
531 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
532 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
533 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
534
535 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
536 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE | BLOCK , "store"),
537
538 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
539
540 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
541 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
542 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
543
544 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE | BLOCK, "write"),
545 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
546 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
547 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
548 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
549 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
550 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
551
552 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
553 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
554 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
555 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
556 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
557 /* Call is special most it can stand in for anything so it depends on context */
558 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
559 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
560 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
561
562 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
563 /* The number of targets for OP_BRANCH depends on context */
564 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
565 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
566 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
567 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
568 /* The number of RHS elements of OP_PHI depend upon context */
569 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
570
571 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
572 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
573 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
574 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
575 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
576 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
577 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
578 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
579 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
580 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
581 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
582 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
583 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
584 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
585 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
586 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
587 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
588 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
589 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
590 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
591 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
592 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
593 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
594
595 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
596 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
597 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
598 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
599 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
600 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
601 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
602 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
603 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
604 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
605 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
606 };
607 #undef OP
608 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
609
610 static const char *tops(int index) 
611 {
612         static const char unknown[] = "unknown op";
613         if (index < 0) {
614                 return unknown;
615         }
616         if (index > OP_MAX) {
617                 return unknown;
618         }
619         return table_ops[index].name;
620 }
621
622 struct asm_info;
623 struct triple;
624 struct block;
625 struct triple_set {
626         struct triple_set *next;
627         struct triple *member;
628 };
629
630 #define MAX_LHS  15
631 #define MAX_RHS  15
632 #define MAX_MISC 15
633 #define MAX_TARG 15
634
635 struct triple {
636         struct triple *next, *prev;
637         struct triple_set *use;
638         struct type *type;
639         unsigned char op;
640         unsigned char template_id;
641         unsigned short sizes;
642 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
643 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
644 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
645 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
646 #define TRIPLE_SIZE(SIZES) \
647         ((((SIZES) >> 0) & 0x0f) + \
648         (((SIZES) >>  4) & 0x0f) + \
649         (((SIZES) >>  8) & 0x0f) + \
650         (((SIZES) >> 12) & 0x0f))
651 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
652         ((((LHS) & 0x0f) <<  0) | \
653         (((RHS) & 0x0f)  <<  4) | \
654         (((MISC) & 0x0f) <<  8) | \
655         (((TARG) & 0x0f) << 12))
656 #define TRIPLE_LHS_OFF(SIZES)  (0)
657 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
658 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
659 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
660 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
661 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
662 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
663 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
664         unsigned id; /* A scratch value and finally the register */
665 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
666 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
667 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
668         const char *filename;
669         int line;
670         int col;
671         union {
672                 ulong_t cval;
673                 struct block  *block;
674                 void *blob;
675                 struct hash_entry *field;
676                 struct asm_info *ainfo;
677         } u;
678         struct triple *param[2];
679 };
680
681 struct reg_info {
682         unsigned reg;
683         unsigned regcm;
684 };
685 struct ins_template {
686         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
687 };
688
689 struct asm_info {
690         struct ins_template tmpl;
691         char *str;
692 };
693
694 struct block_set {
695         struct block_set *next;
696         struct block *member;
697 };
698 struct block {
699         struct block *work_next;
700         struct block *left, *right;
701         struct triple *first, *last;
702         int users;
703         struct block_set *use;
704         struct block_set *idominates;
705         struct block_set *domfrontier;
706         struct block *idom;
707         struct block_set *ipdominates;
708         struct block_set *ipdomfrontier;
709         struct block *ipdom;
710         int vertex;
711         
712 };
713
714 struct symbol {
715         struct symbol *next;
716         struct hash_entry *ident;
717         struct triple *def;
718         struct type *type;
719         int scope_depth;
720 };
721
722 struct macro {
723         struct hash_entry *ident;
724         char *buf;
725         int buf_len;
726 };
727
728 struct hash_entry {
729         struct hash_entry *next;
730         const char *name;
731         int name_len;
732         int tok;
733         struct macro *sym_define;
734         struct symbol *sym_label;
735         struct symbol *sym_struct;
736         struct symbol *sym_ident;
737 };
738
739 #define HASH_TABLE_SIZE 2048
740
741 struct compile_state {
742         const char *label_prefix;
743         const char *ofilename;
744         FILE *output;
745         struct triple *vars;
746         struct file_state *file;
747         struct token token[4];
748         struct hash_entry *hash_table[HASH_TABLE_SIZE];
749         struct hash_entry *i_continue;
750         struct hash_entry *i_break;
751         int scope_depth;
752         int if_depth, if_value;
753         int macro_line;
754         struct file_state *macro_file;
755         struct triple *main_function;
756         struct block *first_block, *last_block;
757         int last_vertex;
758         int cpu;
759         int debug;
760         int optimize;
761 };
762
763 /* visibility global/local */
764 /* static/auto duration */
765 /* typedef, register, inline */
766 #define STOR_SHIFT         0
767 #define STOR_MASK     0x000f
768 /* Visibility */
769 #define STOR_GLOBAL   0x0001
770 /* Duration */
771 #define STOR_PERM     0x0002
772 /* Storage specifiers */
773 #define STOR_AUTO     0x0000
774 #define STOR_STATIC   0x0002
775 #define STOR_EXTERN   0x0003
776 #define STOR_REGISTER 0x0004
777 #define STOR_TYPEDEF  0x0008
778 #define STOR_INLINE   0x000c
779
780 #define QUAL_SHIFT         4
781 #define QUAL_MASK     0x0070
782 #define QUAL_NONE     0x0000
783 #define QUAL_CONST    0x0010
784 #define QUAL_VOLATILE 0x0020
785 #define QUAL_RESTRICT 0x0040
786
787 #define TYPE_SHIFT         8
788 #define TYPE_MASK     0x1f00
789 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
790 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
791 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
792 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
793 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
794 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
795 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
796 #define TYPE_DEFAULT  0x0000
797 #define TYPE_VOID     0x0100
798 #define TYPE_CHAR     0x0200
799 #define TYPE_UCHAR    0x0300
800 #define TYPE_SHORT    0x0400
801 #define TYPE_USHORT   0x0500
802 #define TYPE_INT      0x0600
803 #define TYPE_UINT     0x0700
804 #define TYPE_LONG     0x0800
805 #define TYPE_ULONG    0x0900
806 #define TYPE_LLONG    0x0a00 /* long long */
807 #define TYPE_ULLONG   0x0b00
808 #define TYPE_FLOAT    0x0c00
809 #define TYPE_DOUBLE   0x0d00
810 #define TYPE_LDOUBLE  0x0e00 /* long double */
811 #define TYPE_STRUCT   0x1000
812 #define TYPE_ENUM     0x1100
813 #define TYPE_POINTER  0x1200 
814 /* For TYPE_POINTER:
815  * type->left holds the type pointed to.
816  */
817 #define TYPE_FUNCTION 0x1300 
818 /* For TYPE_FUNCTION:
819  * type->left holds the return type.
820  * type->right holds the...
821  */
822 #define TYPE_PRODUCT  0x1400
823 /* TYPE_PRODUCT is a basic building block when defining structures
824  * type->left holds the type that appears first in memory.
825  * type->right holds the type that appears next in memory.
826  */
827 #define TYPE_OVERLAP  0x1500
828 /* TYPE_OVERLAP is a basic building block when defining unions
829  * type->left and type->right holds to types that overlap
830  * each other in memory.
831  */
832 #define TYPE_ARRAY    0x1600
833 /* TYPE_ARRAY is a basic building block when definitng arrays.
834  * type->left holds the type we are an array of.
835  * type-> holds the number of elements.
836  */
837
838 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
839
840 struct type {
841         unsigned int type;
842         struct type *left, *right;
843         ulong_t elements;
844         struct hash_entry *field_ident;
845         struct hash_entry *type_ident;
846 };
847
848 #define MAX_REGISTERS      75
849 #define MAX_REG_EQUIVS     16
850 #if 1
851 #define REGISTER_BITS      16
852 #else
853 #define REGISTER_BITS      28
854 #endif
855 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
856 #define TEMPLATE_BITS      6
857 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
858 #define MAX_REGC           12
859 #define REG_UNSET          0
860 #define REG_UNNEEDED       1
861 #define REG_VIRT0          (MAX_REGISTERS + 0)
862 #define REG_VIRT1          (MAX_REGISTERS + 1)
863 #define REG_VIRT2          (MAX_REGISTERS + 2)
864 #define REG_VIRT3          (MAX_REGISTERS + 3)
865 #define REG_VIRT4          (MAX_REGISTERS + 4)
866 #define REG_VIRT5          (MAX_REGISTERS + 5)
867 #define REG_VIRT6          (MAX_REGISTERS + 5)
868 #define REG_VIRT7          (MAX_REGISTERS + 5)
869 #define REG_VIRT8          (MAX_REGISTERS + 5)
870 #define REG_VIRT9          (MAX_REGISTERS + 5)
871
872 /* Provision for 8 register classes */
873 #if 1
874 #define REG_SHIFT  0
875 #define REGC_SHIFT REGISTER_BITS
876 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
877 #define REG_MASK (MAX_VIRT_REGISTERS -1)
878 #define ID_REG(ID)              ((ID) & REG_MASK)
879 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
880 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
881 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
882 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
883                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
884 #else
885 #define REG_MASK (MAX_VIRT_REGISTERS -1)
886 #define ID_REG(ID)              ((ID) & REG_MASK)
887 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
888 #endif
889
890 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
891 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
892 static void arch_reg_equivs(
893         struct compile_state *state, unsigned *equiv, int reg);
894 static int arch_select_free_register(
895         struct compile_state *state, char *used, int classes);
896 static unsigned arch_regc_size(struct compile_state *state, int class);
897 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
898 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
899 static const char *arch_reg_str(int reg);
900 static struct reg_info arch_reg_constraint(
901         struct compile_state *state, struct type *type, const char *constraint);
902 static struct reg_info arch_reg_clobber(
903         struct compile_state *state, const char *clobber);
904 static struct reg_info arch_reg_lhs(struct compile_state *state, 
905         struct triple *ins, int index);
906 static struct reg_info arch_reg_rhs(struct compile_state *state, 
907         struct triple *ins, int index);
908 static struct triple *transform_to_arch_instruction(
909         struct compile_state *state, struct triple *ins);
910
911
912
913 #define DEBUG_ABORT_ON_ERROR    0x0001
914 #define DEBUG_INTERMEDIATE_CODE 0x0002
915 #define DEBUG_CONTROL_FLOW      0x0004
916 #define DEBUG_BASIC_BLOCKS      0x0008
917 #define DEBUG_FDOMINATORS       0x0010
918 #define DEBUG_RDOMINATORS       0x0020
919 #define DEBUG_TRIPLES           0x0040
920 #define DEBUG_INTERFERENCE      0x0080
921 #define DEBUG_ARCH_CODE         0x0100
922 #define DEBUG_CODE_ELIMINATION  0x0200
923 #define DEBUG_INSERTED_COPIES   0x0400
924
925 #define GLOBAL_SCOPE_DEPTH 1
926
927 static void compile_file(struct compile_state *old_state, const char *filename, int local);
928
929 static void do_cleanup(struct compile_state *state)
930 {
931         if (state->output) {
932                 fclose(state->output);
933                 unlink(state->ofilename);
934         }
935 }
936
937 static int get_col(struct file_state *file)
938 {
939         int col;
940         char *ptr, *end;
941         ptr = file->line_start;
942         end = file->pos;
943         for(col = 0; ptr < end; ptr++) {
944                 if (*ptr != '\t') {
945                         col++;
946                 } 
947                 else {
948                         col = (col & ~7) + 8;
949                 }
950         }
951         return col;
952 }
953
954 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
955 {
956         int col;
957         if (triple) {
958                 fprintf(fp, "%s:%d.%d: ", 
959                         triple->filename, triple->line, triple->col);
960                 return;
961         }
962         if (!state->file) {
963                 return;
964         }
965         col = get_col(state->file);
966         fprintf(fp, "%s:%d.%d: ", 
967                 state->file->basename, state->file->line, col);
968 }
969
970 static void __internal_error(struct compile_state *state, struct triple *ptr, 
971         char *fmt, ...)
972 {
973         va_list args;
974         va_start(args, fmt);
975         loc(stderr, state, ptr);
976         if (ptr) {
977                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
978         }
979         fprintf(stderr, "Internal compiler error: ");
980         vfprintf(stderr, fmt, args);
981         fprintf(stderr, "\n");
982         va_end(args);
983         do_cleanup(state);
984         abort();
985 }
986
987
988 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
989         char *fmt, ...)
990 {
991         va_list args;
992         va_start(args, fmt);
993         loc(stderr, state, ptr);
994         fprintf(stderr, "Internal compiler warning: ");
995         vfprintf(stderr, fmt, args);
996         fprintf(stderr, "\n");
997         va_end(args);
998 }
999
1000
1001
1002 static void __error(struct compile_state *state, struct triple *ptr, 
1003         char *fmt, ...)
1004 {
1005         va_list args;
1006         va_start(args, fmt);
1007         loc(stderr, state, ptr);
1008         vfprintf(stderr, fmt, args);
1009         va_end(args);
1010         fprintf(stderr, "\n");
1011         do_cleanup(state);
1012         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1013                 abort();
1014         }
1015         exit(1);
1016 }
1017
1018 static void __warning(struct compile_state *state, struct triple *ptr, 
1019         char *fmt, ...)
1020 {
1021         va_list args;
1022         va_start(args, fmt);
1023         loc(stderr, state, ptr);
1024         fprintf(stderr, "warning: "); 
1025         vfprintf(stderr, fmt, args);
1026         fprintf(stderr, "\n");
1027         va_end(args);
1028 }
1029
1030 #if DEBUG_ERROR_MESSAGES 
1031 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1032 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1033 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1034 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1035 #else
1036 #  define internal_error __internal_error
1037 #  define internal_warning __internal_warning
1038 #  define error __error
1039 #  define warning __warning
1040 #endif
1041 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1042
1043 static void valid_op(struct compile_state *state, int op)
1044 {
1045         char *fmt = "invalid op: %d";
1046         if (op >= OP_MAX) {
1047                 internal_error(state, 0, fmt, op);
1048         }
1049         if (op < 0) {
1050                 internal_error(state, 0, fmt, op);
1051         }
1052 }
1053
1054 static void valid_ins(struct compile_state *state, struct triple *ptr)
1055 {
1056         valid_op(state, ptr->op);
1057 }
1058
1059 static void process_trigraphs(struct compile_state *state)
1060 {
1061         char *src, *dest, *end;
1062         struct file_state *file;
1063         file = state->file;
1064         src = dest = file->buf;
1065         end = file->buf + file->size;
1066         while((end - src) >= 3) {
1067                 if ((src[0] == '?') && (src[1] == '?')) {
1068                         int c = -1;
1069                         switch(src[2]) {
1070                         case '=': c = '#'; break;
1071                         case '/': c = '\\'; break;
1072                         case '\'': c = '^'; break;
1073                         case '(': c = '['; break;
1074                         case ')': c = ']'; break;
1075                         case '!': c = '!'; break;
1076                         case '<': c = '{'; break;
1077                         case '>': c = '}'; break;
1078                         case '-': c = '~'; break;
1079                         }
1080                         if (c != -1) {
1081                                 *dest++ = c;
1082                                 src += 3;
1083                         }
1084                         else {
1085                                 *dest++ = *src++;
1086                         }
1087                 }
1088                 else {
1089                         *dest++ = *src++;
1090                 }
1091         }
1092         while(src != end) {
1093                 *dest++ = *src++;
1094         }
1095         file->size = dest - file->buf;
1096 }
1097
1098 static void splice_lines(struct compile_state *state)
1099 {
1100         char *src, *dest, *end;
1101         struct file_state *file;
1102         file = state->file;
1103         src = dest = file->buf;
1104         end = file->buf + file->size;
1105         while((end - src) >= 2) {
1106                 if ((src[0] == '\\') && (src[1] == '\n')) {
1107                         src += 2;
1108                 }
1109                 else {
1110                         *dest++ = *src++;
1111                 }
1112         }
1113         while(src != end) {
1114                 *dest++ = *src++;
1115         }
1116         file->size = dest - file->buf;
1117 }
1118
1119 static struct type void_type;
1120 static void use_triple(struct triple *used, struct triple *user)
1121 {
1122         struct triple_set **ptr, *new;
1123         if (!used)
1124                 return;
1125         if (!user)
1126                 return;
1127         ptr = &used->use;
1128         while(*ptr) {
1129                 if ((*ptr)->member == user) {
1130                         return;
1131                 }
1132                 ptr = &(*ptr)->next;
1133         }
1134         /* Append new to the head of the list, 
1135          * copy_func and rename_block_variables
1136          * depends on this.
1137          */
1138         new = xcmalloc(sizeof(*new), "triple_set");
1139         new->member = user;
1140         new->next   = used->use;
1141         used->use   = new;
1142 }
1143
1144 static void unuse_triple(struct triple *used, struct triple *unuser)
1145 {
1146         struct triple_set *use, **ptr;
1147         if (!used) {
1148                 return;
1149         }
1150         ptr = &used->use;
1151         while(*ptr) {
1152                 use = *ptr;
1153                 if (use->member == unuser) {
1154                         *ptr = use->next;
1155                         xfree(use);
1156                 }
1157                 else {
1158                         ptr = &use->next;
1159                 }
1160         }
1161 }
1162
1163 static void push_triple(struct triple *used, struct triple *user)
1164 {
1165         struct triple_set *new;
1166         if (!used)
1167                 return;
1168         if (!user)
1169                 return;
1170         /* Append new to the head of the list,
1171          * it's the only sensible behavoir for a stack.
1172          */
1173         new = xcmalloc(sizeof(*new), "triple_set");
1174         new->member = user;
1175         new->next   = used->use;
1176         used->use   = new;
1177 }
1178
1179 static void pop_triple(struct triple *used, struct triple *unuser)
1180 {
1181         struct triple_set *use, **ptr;
1182         ptr = &used->use;
1183         while(*ptr) {
1184                 use = *ptr;
1185                 if (use->member == unuser) {
1186                         *ptr = use->next;
1187                         xfree(use);
1188                         /* Only free one occurance from the stack */
1189                         return;
1190                 }
1191                 else {
1192                         ptr = &use->next;
1193                 }
1194         }
1195 }
1196
1197
1198 /* The zero triple is used as a place holder when we are removing pointers
1199  * from a triple.  Having allows certain sanity checks to pass even
1200  * when the original triple that was pointed to is gone.
1201  */
1202 static struct triple zero_triple = {
1203         .next     = &zero_triple,
1204         .prev     = &zero_triple,
1205         .use      = 0,
1206         .op       = OP_INTCONST,
1207         .sizes    = TRIPLE_SIZES(0, 0, 0, 0),
1208         .id       = -1, /* An invalid id */
1209         .u = { .cval   = 0, },
1210         .filename = __FILE__,
1211         .line     = __LINE__,
1212         .col      = 0,
1213         .param { [0] = 0, [1] = 0, },
1214 };
1215
1216
1217 static unsigned short triple_sizes(struct compile_state *state,
1218         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1219 {
1220         int lhs, rhs, misc, targ;
1221         valid_op(state, op);
1222         lhs = table_ops[op].lhs;
1223         rhs = table_ops[op].rhs;
1224         misc = table_ops[op].misc;
1225         targ = table_ops[op].targ;
1226         
1227         
1228         if (op == OP_CALL) {
1229                 struct type *param;
1230                 rhs = 0;
1231                 param = type->right;
1232                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1233                         rhs++;
1234                         param = param->right;
1235                 }
1236                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1237                         rhs++;
1238                 }
1239                 lhs = 0;
1240                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1241                         lhs = type->left->elements;
1242                 }
1243         }
1244         else if (op == OP_VAL_VEC) {
1245                 rhs = type->elements;
1246         }
1247         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1248                 rhs = rhs_wanted;
1249         }
1250         else if (op == OP_ASM) {
1251                 rhs = rhs_wanted;
1252                 lhs = lhs_wanted;
1253         }
1254         if ((rhs < 0) || (rhs > MAX_RHS)) {
1255                 internal_error(state, 0, "bad rhs");
1256         }
1257         if ((lhs < 0) || (lhs > MAX_LHS)) {
1258                 internal_error(state, 0, "bad lhs");
1259         }
1260         if ((misc < 0) || (misc > MAX_MISC)) {
1261                 internal_error(state, 0, "bad misc");
1262         }
1263         if ((targ < 0) || (targ > MAX_TARG)) {
1264                 internal_error(state, 0, "bad targs");
1265         }
1266         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1267 }
1268
1269 static struct triple *alloc_triple(struct compile_state *state, 
1270         int op, struct type *type, int lhs, int rhs,
1271         const char *filename, int line, int col)
1272 {
1273         size_t size, sizes, extra_count, min_count;
1274         struct triple *ret;
1275         sizes = triple_sizes(state, op, type, lhs, rhs);
1276
1277         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1278         extra_count = TRIPLE_SIZE(sizes);
1279         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1280
1281         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1282         ret = xcmalloc(size, "tripple");
1283         ret->op       = op;
1284         ret->sizes    = sizes;
1285         ret->type     = type;
1286         ret->next     = ret;
1287         ret->prev     = ret;
1288         ret->filename = filename;
1289         ret->line     = line;
1290         ret->col      = col;
1291         return ret;
1292 }
1293
1294 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1295 {
1296         struct triple *dup;
1297         int src_lhs, src_rhs, src_size;
1298         src_lhs = TRIPLE_LHS(src->sizes);
1299         src_rhs = TRIPLE_RHS(src->sizes);
1300         src_size = TRIPLE_SIZE(src->sizes);
1301         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1302                 src->filename, src->line, src->col);
1303         memcpy(dup, src, sizeof(*src));
1304         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1305         return dup;
1306 }
1307
1308 static struct triple *new_triple(struct compile_state *state, 
1309         int op, struct type *type, int lhs, int rhs)
1310 {
1311         struct triple *ret;
1312         const char *filename;
1313         int line, col;
1314         filename = 0;
1315         line = 0;
1316         col  = 0;
1317         if (state->file) {
1318                 filename = state->file->basename;
1319                 line     = state->file->line;
1320                 col      = get_col(state->file);
1321         }
1322         ret = alloc_triple(state, op, type, lhs, rhs,
1323                 filename, line, col);
1324         return ret;
1325 }
1326
1327 static struct triple *build_triple(struct compile_state *state, 
1328         int op, struct type *type, struct triple *left, struct triple *right,
1329         const char *filename, int line, int col)
1330 {
1331         struct triple *ret;
1332         size_t count;
1333         ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1334         count = TRIPLE_SIZE(ret->sizes);
1335         if (count > 0) {
1336                 ret->param[0] = left;
1337         }
1338         if (count > 1) {
1339                 ret->param[1] = right;
1340         }
1341         return ret;
1342 }
1343
1344 static struct triple *triple(struct compile_state *state, 
1345         int op, struct type *type, struct triple *left, struct triple *right)
1346 {
1347         struct triple *ret;
1348         size_t count;
1349         ret = new_triple(state, op, type, -1, -1);
1350         count = TRIPLE_SIZE(ret->sizes);
1351         if (count >= 1) {
1352                 ret->param[0] = left;
1353         }
1354         if (count >= 2) {
1355                 ret->param[1] = right;
1356         }
1357         return ret;
1358 }
1359
1360 static struct triple *branch(struct compile_state *state, 
1361         struct triple *targ, struct triple *test)
1362 {
1363         struct triple *ret;
1364         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1365         if (test) {
1366                 RHS(ret, 0) = test;
1367         }
1368         TARG(ret, 0) = targ;
1369         /* record the branch target was used */
1370         if (!targ || (targ->op != OP_LABEL)) {
1371                 internal_error(state, 0, "branch not to label");
1372                 use_triple(targ, ret);
1373         }
1374         return ret;
1375 }
1376
1377
1378 static void insert_triple(struct compile_state *state,
1379         struct triple *first, struct triple *ptr)
1380 {
1381         if (ptr) {
1382                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1383                         internal_error(state, ptr, "expression already used");
1384                 }
1385                 ptr->next       = first;
1386                 ptr->prev       = first->prev;
1387                 ptr->prev->next = ptr;
1388                 ptr->next->prev = ptr;
1389                 if ((ptr->prev->op == OP_BRANCH) && 
1390                         TRIPLE_RHS(ptr->prev->sizes)) {
1391                         unuse_triple(first, ptr->prev);
1392                         use_triple(ptr, ptr->prev);
1393                 }
1394         }
1395 }
1396
1397 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1398 {
1399         /* This function is used to determine if u.block 
1400          * is utilized to store the current block number.
1401          */
1402         int stores_block;
1403         valid_ins(state, ins);
1404         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1405         return stores_block;
1406 }
1407
1408 static struct block *block_of_triple(struct compile_state *state, 
1409         struct triple *ins)
1410 {
1411         struct triple *first;
1412         first = RHS(state->main_function, 0);
1413         while(ins != first && !triple_stores_block(state, ins)) {
1414                 if (ins == ins->prev) {
1415                         internal_error(state, 0, "ins == ins->prev?");
1416                 }
1417                 ins = ins->prev;
1418         }
1419         if (!triple_stores_block(state, ins)) {
1420                 internal_error(state, ins, "Cannot find block");
1421         }
1422         return ins->u.block;
1423 }
1424
1425 static struct triple *pre_triple(struct compile_state *state,
1426         struct triple *base,
1427         int op, struct type *type, struct triple *left, struct triple *right)
1428 {
1429         struct block *block;
1430         struct triple *ret;
1431         block = block_of_triple(state, base);
1432         ret = build_triple(state, op, type, left, right, 
1433                 base->filename, base->line, base->col);
1434         if (triple_stores_block(state, ret)) {
1435                 ret->u.block = block;
1436         }
1437         insert_triple(state, base, ret);
1438         if (block->first == base) {
1439                 block->first = ret;
1440         }
1441         return ret;
1442 }
1443
1444 static struct triple *post_triple(struct compile_state *state,
1445         struct triple *base,
1446         int op, struct type *type, struct triple *left, struct triple *right)
1447 {
1448         struct block *block;
1449         struct triple *ret;
1450         block = block_of_triple(state, base);
1451         ret = build_triple(state, op, type, left, right, 
1452                 base->filename, base->line, base->col);
1453         if (triple_stores_block(state, ret)) {
1454                 ret->u.block = block;
1455         }
1456         insert_triple(state, base->next, ret);
1457         if (block->last == base) {
1458                 block->last = ret;
1459         }
1460         return ret;
1461 }
1462
1463 static struct triple *label(struct compile_state *state)
1464 {
1465         /* Labels don't get a type */
1466         struct triple *result;
1467         result = triple(state, OP_LABEL, &void_type, 0, 0);
1468         return result;
1469 }
1470
1471 static void display_triple(FILE *fp, struct triple *ins)
1472 {
1473         if (ins->op == OP_INTCONST) {
1474                 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx>          @ %s:%d.%d\n",
1475                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1476                         ins->u.cval,
1477                         ins->filename, ins->line, ins->col);
1478         }
1479         else if (ins->op == OP_ADDRCONST) {
1480                 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1481                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1482                         MISC(ins, 0), ins->u.cval,
1483                         ins->filename, ins->line, ins->col);
1484         }
1485         else {
1486                 int i, count;
1487                 fprintf(fp, "(%p) %3d %-2d %-10s", 
1488                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1489                 count = TRIPLE_SIZE(ins->sizes);
1490                 for(i = 0; i < count; i++) {
1491                         fprintf(fp, " %-10p", ins->param[i]);
1492                 }
1493                 for(; i < 2; i++) {
1494                         printf("           ");
1495                 }
1496                 fprintf(fp, " @ %s:%d.%d\n", 
1497                         ins->filename, ins->line, ins->col);
1498         }
1499         fflush(fp);
1500 }
1501
1502 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1503 {
1504         /* Does the triple have no side effects.
1505          * I.e. Rexecuting the triple with the same arguments 
1506          * gives the same value.
1507          */
1508         unsigned pure;
1509         valid_ins(state, ins);
1510         pure = PURE_BITS(table_ops[ins->op].flags);
1511         if ((pure != PURE) && (pure != IMPURE)) {
1512                 internal_error(state, 0, "Purity of %s not known\n",
1513                         tops(ins->op));
1514         }
1515         return pure == PURE;
1516 }
1517
1518 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1519 {
1520         /* This function is used to determine which triples need
1521          * a register.
1522          */
1523         int is_branch;
1524         valid_ins(state, ins);
1525         is_branch = (table_ops[ins->op].targ != 0);
1526         return is_branch;
1527 }
1528
1529 static int triple_is_def(struct compile_state *state, struct triple *ins)
1530 {
1531         /* This function is used to determine which triples need
1532          * a register.
1533          */
1534         int is_def;
1535         valid_ins(state, ins);
1536         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1537         return is_def;
1538 }
1539
1540 static struct triple **triple_iter(struct compile_state *state,
1541         size_t count, struct triple **vector,
1542         struct triple *ins, struct triple **last)
1543 {
1544         struct triple **ret;
1545         ret = 0;
1546         if (count) {
1547                 if (!last) {
1548                         ret = vector;
1549                 }
1550                 else if ((last >= vector) && (last < (vector + count - 1))) {
1551                         ret = last + 1;
1552                 }
1553         }
1554         return ret;
1555         
1556 }
1557
1558 static struct triple **triple_lhs(struct compile_state *state,
1559         struct triple *ins, struct triple **last)
1560 {
1561         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1562                 ins, last);
1563 }
1564
1565 static struct triple **triple_rhs(struct compile_state *state,
1566         struct triple *ins, struct triple **last)
1567 {
1568         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1569                 ins, last);
1570 }
1571
1572 static struct triple **triple_misc(struct compile_state *state,
1573         struct triple *ins, struct triple **last)
1574 {
1575         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1576                 ins, last);
1577 }
1578
1579 static struct triple **triple_targ(struct compile_state *state,
1580         struct triple *ins, struct triple **last)
1581 {
1582         size_t count;
1583         struct triple **ret, **vector;
1584         ret = 0;
1585         count = TRIPLE_TARG(ins->sizes);
1586         vector = &TARG(ins, 0);
1587         if (count) {
1588                 if (!last) {
1589                         ret = vector;
1590                 }
1591                 else if ((last >= vector) && (last < (vector + count - 1))) {
1592                         ret = last + 1;
1593                 }
1594                 else if ((last == (vector + count - 1)) && 
1595                         TRIPLE_RHS(ins->sizes)) {
1596                         ret = &ins->next;
1597                 }
1598         }
1599         return ret;
1600 }
1601
1602
1603 static void verify_use(struct compile_state *state,
1604         struct triple *user, struct triple *used)
1605 {
1606         int size, i;
1607         size = TRIPLE_SIZE(user->sizes);
1608         for(i = 0; i < size; i++) {
1609                 if (user->param[i] == used) {
1610                         break;
1611                 }
1612         }
1613         if (triple_is_branch(state, user)) {
1614                 if (user->next == used) {
1615                         i = -1;
1616                 }
1617         }
1618         if (i == size) {
1619                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1620                         tops(user->op), user, tops(used->op), used);
1621         }
1622 }
1623
1624 static int find_rhs_use(struct compile_state *state, 
1625         struct triple *user, struct triple *used)
1626 {
1627         struct triple **param;
1628         int size, i;
1629         verify_use(state, user, used);
1630         size = TRIPLE_RHS(user->sizes);
1631         param = &RHS(user, 0);
1632         for(i = 0; i < size; i++) {
1633                 if (param[i] == used) {
1634                         return i;
1635                 }
1636         }
1637         return -1;
1638 }
1639
1640 static void free_triple(struct compile_state *state, struct triple *ptr)
1641 {
1642         size_t size;
1643         size = sizeof(*ptr) - sizeof(ptr->param) +
1644                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1645         ptr->prev->next = ptr->next;
1646         ptr->next->prev = ptr->prev;
1647         if (ptr->use) {
1648                 internal_error(state, ptr, "ptr->use != 0");
1649         }
1650         memset(ptr, -1, size);
1651         xfree(ptr);
1652 }
1653
1654 static void release_triple(struct compile_state *state, struct triple *ptr)
1655 {
1656         struct triple_set *set, *next;
1657         struct triple **expr;
1658         /* Remove ptr from use chains where it is the user */
1659         expr = triple_rhs(state, ptr, 0);
1660         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1661                 if (*expr) {
1662                         unuse_triple(*expr, ptr);
1663                 }
1664         }
1665         expr = triple_lhs(state, ptr, 0);
1666         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1667                 if (*expr) {
1668                         unuse_triple(*expr, ptr);
1669                 }
1670         }
1671         expr = triple_misc(state, ptr, 0);
1672         for(; expr; expr = triple_misc(state, ptr, expr)) {
1673                 if (*expr) {
1674                         unuse_triple(*expr, ptr);
1675                 }
1676         }
1677         expr = triple_targ(state, ptr, 0);
1678         for(; expr; expr = triple_targ(state, ptr, expr)) {
1679                 if (*expr) {
1680                         unuse_triple(*expr, ptr);
1681                 }
1682         }
1683         /* Reomve ptr from use chains where it is used */
1684         for(set = ptr->use; set; set = next) {
1685                 next = set->next;
1686                 expr = triple_rhs(state, set->member, 0);
1687                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1688                         if (*expr == ptr) {
1689                                 *expr = &zero_triple;
1690                         }
1691                 }
1692                 expr = triple_lhs(state, set->member, 0);
1693                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1694                         if (*expr == ptr) {
1695                                 *expr = &zero_triple;
1696                         }
1697                 }
1698                 expr = triple_misc(state, set->member, 0);
1699                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1700                         if (*expr == ptr) {
1701                                 *expr = &zero_triple;
1702                         }
1703                 }
1704                 expr = triple_targ(state, set->member, 0);
1705                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1706                         if (*expr == ptr) {
1707                                 *expr = &zero_triple;
1708                         }
1709                 }
1710                 unuse_triple(ptr, set->member);
1711         }
1712         free_triple(state, ptr);
1713 }
1714
1715 static void print_triple(struct compile_state *state, struct triple *ptr);
1716
1717 #define TOK_UNKNOWN     0
1718 #define TOK_SPACE       1
1719 #define TOK_SEMI        2
1720 #define TOK_LBRACE      3
1721 #define TOK_RBRACE      4
1722 #define TOK_COMMA       5
1723 #define TOK_EQ          6
1724 #define TOK_COLON       7
1725 #define TOK_LBRACKET    8
1726 #define TOK_RBRACKET    9
1727 #define TOK_LPAREN      10
1728 #define TOK_RPAREN      11
1729 #define TOK_STAR        12
1730 #define TOK_DOTS        13
1731 #define TOK_MORE        14
1732 #define TOK_LESS        15
1733 #define TOK_TIMESEQ     16
1734 #define TOK_DIVEQ       17
1735 #define TOK_MODEQ       18
1736 #define TOK_PLUSEQ      19
1737 #define TOK_MINUSEQ     20
1738 #define TOK_SLEQ        21
1739 #define TOK_SREQ        22
1740 #define TOK_ANDEQ       23
1741 #define TOK_XOREQ       24
1742 #define TOK_OREQ        25
1743 #define TOK_EQEQ        26
1744 #define TOK_NOTEQ       27
1745 #define TOK_QUEST       28
1746 #define TOK_LOGOR       29
1747 #define TOK_LOGAND      30
1748 #define TOK_OR          31
1749 #define TOK_AND         32
1750 #define TOK_XOR         33
1751 #define TOK_LESSEQ      34
1752 #define TOK_MOREEQ      35
1753 #define TOK_SL          36
1754 #define TOK_SR          37
1755 #define TOK_PLUS        38
1756 #define TOK_MINUS       39
1757 #define TOK_DIV         40
1758 #define TOK_MOD         41
1759 #define TOK_PLUSPLUS    42
1760 #define TOK_MINUSMINUS  43
1761 #define TOK_BANG        44
1762 #define TOK_ARROW       45
1763 #define TOK_DOT         46
1764 #define TOK_TILDE       47
1765 #define TOK_LIT_STRING  48
1766 #define TOK_LIT_CHAR    49
1767 #define TOK_LIT_INT     50
1768 #define TOK_LIT_FLOAT   51
1769 #define TOK_MACRO       52
1770 #define TOK_CONCATENATE 53
1771
1772 #define TOK_IDENT       54
1773 #define TOK_STRUCT_NAME 55
1774 #define TOK_ENUM_CONST  56
1775 #define TOK_TYPE_NAME   57
1776
1777 #define TOK_AUTO        58
1778 #define TOK_BREAK       59
1779 #define TOK_CASE        60
1780 #define TOK_CHAR        61
1781 #define TOK_CONST       62
1782 #define TOK_CONTINUE    63
1783 #define TOK_DEFAULT     64
1784 #define TOK_DO          65
1785 #define TOK_DOUBLE      66
1786 #define TOK_ELSE        67
1787 #define TOK_ENUM        68
1788 #define TOK_EXTERN      69
1789 #define TOK_FLOAT       70
1790 #define TOK_FOR         71
1791 #define TOK_GOTO        72
1792 #define TOK_IF          73
1793 #define TOK_INLINE      74
1794 #define TOK_INT         75
1795 #define TOK_LONG        76
1796 #define TOK_REGISTER    77
1797 #define TOK_RESTRICT    78
1798 #define TOK_RETURN      79
1799 #define TOK_SHORT       80
1800 #define TOK_SIGNED      81
1801 #define TOK_SIZEOF      82
1802 #define TOK_STATIC      83
1803 #define TOK_STRUCT      84
1804 #define TOK_SWITCH      85
1805 #define TOK_TYPEDEF     86
1806 #define TOK_UNION       87
1807 #define TOK_UNSIGNED    88
1808 #define TOK_VOID        89
1809 #define TOK_VOLATILE    90
1810 #define TOK_WHILE       91
1811 #define TOK_ASM         92
1812 #define TOK_ATTRIBUTE   93
1813 #define TOK_ALIGNOF     94
1814 #define TOK_FIRST_KEYWORD TOK_AUTO
1815 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1816
1817 #define TOK_DEFINE      100
1818 #define TOK_UNDEF       101
1819 #define TOK_INCLUDE     102
1820 #define TOK_LINE        103
1821 #define TOK_ERROR       104
1822 #define TOK_WARNING     105
1823 #define TOK_PRAGMA      106
1824 #define TOK_IFDEF       107
1825 #define TOK_IFNDEF      108
1826 #define TOK_ELIF        109
1827 #define TOK_ENDIF       110
1828
1829 #define TOK_FIRST_MACRO TOK_DEFINE
1830 #define TOK_LAST_MACRO  TOK_ENDIF
1831          
1832 #define TOK_EOF         111
1833
1834 static const char *tokens[] = {
1835 [TOK_UNKNOWN     ] = "unknown",
1836 [TOK_SPACE       ] = ":space:",
1837 [TOK_SEMI        ] = ";",
1838 [TOK_LBRACE      ] = "{",
1839 [TOK_RBRACE      ] = "}",
1840 [TOK_COMMA       ] = ",",
1841 [TOK_EQ          ] = "=",
1842 [TOK_COLON       ] = ":",
1843 [TOK_LBRACKET    ] = "[",
1844 [TOK_RBRACKET    ] = "]",
1845 [TOK_LPAREN      ] = "(",
1846 [TOK_RPAREN      ] = ")",
1847 [TOK_STAR        ] = "*",
1848 [TOK_DOTS        ] = "...",
1849 [TOK_MORE        ] = ">",
1850 [TOK_LESS        ] = "<",
1851 [TOK_TIMESEQ     ] = "*=",
1852 [TOK_DIVEQ       ] = "/=",
1853 [TOK_MODEQ       ] = "%=",
1854 [TOK_PLUSEQ      ] = "+=",
1855 [TOK_MINUSEQ     ] = "-=",
1856 [TOK_SLEQ        ] = "<<=",
1857 [TOK_SREQ        ] = ">>=",
1858 [TOK_ANDEQ       ] = "&=",
1859 [TOK_XOREQ       ] = "^=",
1860 [TOK_OREQ        ] = "|=",
1861 [TOK_EQEQ        ] = "==",
1862 [TOK_NOTEQ       ] = "!=",
1863 [TOK_QUEST       ] = "?",
1864 [TOK_LOGOR       ] = "||",
1865 [TOK_LOGAND      ] = "&&",
1866 [TOK_OR          ] = "|",
1867 [TOK_AND         ] = "&",
1868 [TOK_XOR         ] = "^",
1869 [TOK_LESSEQ      ] = "<=",
1870 [TOK_MOREEQ      ] = ">=",
1871 [TOK_SL          ] = "<<",
1872 [TOK_SR          ] = ">>",
1873 [TOK_PLUS        ] = "+",
1874 [TOK_MINUS       ] = "-",
1875 [TOK_DIV         ] = "/",
1876 [TOK_MOD         ] = "%",
1877 [TOK_PLUSPLUS    ] = "++",
1878 [TOK_MINUSMINUS  ] = "--",
1879 [TOK_BANG        ] = "!",
1880 [TOK_ARROW       ] = "->",
1881 [TOK_DOT         ] = ".",
1882 [TOK_TILDE       ] = "~",
1883 [TOK_LIT_STRING  ] = ":string:",
1884 [TOK_IDENT       ] = ":ident:",
1885 [TOK_TYPE_NAME   ] = ":typename:",
1886 [TOK_LIT_CHAR    ] = ":char:",
1887 [TOK_LIT_INT     ] = ":integer:",
1888 [TOK_LIT_FLOAT   ] = ":float:",
1889 [TOK_MACRO       ] = "#",
1890 [TOK_CONCATENATE ] = "##",
1891
1892 [TOK_AUTO        ] = "auto",
1893 [TOK_BREAK       ] = "break",
1894 [TOK_CASE        ] = "case",
1895 [TOK_CHAR        ] = "char",
1896 [TOK_CONST       ] = "const",
1897 [TOK_CONTINUE    ] = "continue",
1898 [TOK_DEFAULT     ] = "default",
1899 [TOK_DO          ] = "do",
1900 [TOK_DOUBLE      ] = "double",
1901 [TOK_ELSE        ] = "else",
1902 [TOK_ENUM        ] = "enum",
1903 [TOK_EXTERN      ] = "extern",
1904 [TOK_FLOAT       ] = "float",
1905 [TOK_FOR         ] = "for",
1906 [TOK_GOTO        ] = "goto",
1907 [TOK_IF          ] = "if",
1908 [TOK_INLINE      ] = "inline",
1909 [TOK_INT         ] = "int",
1910 [TOK_LONG        ] = "long",
1911 [TOK_REGISTER    ] = "register",
1912 [TOK_RESTRICT    ] = "restrict",
1913 [TOK_RETURN      ] = "return",
1914 [TOK_SHORT       ] = "short",
1915 [TOK_SIGNED      ] = "signed",
1916 [TOK_SIZEOF      ] = "sizeof",
1917 [TOK_STATIC      ] = "static",
1918 [TOK_STRUCT      ] = "struct",
1919 [TOK_SWITCH      ] = "switch",
1920 [TOK_TYPEDEF     ] = "typedef",
1921 [TOK_UNION       ] = "union",
1922 [TOK_UNSIGNED    ] = "unsigned",
1923 [TOK_VOID        ] = "void",
1924 [TOK_VOLATILE    ] = "volatile",
1925 [TOK_WHILE       ] = "while",
1926 [TOK_ASM         ] = "asm",
1927 [TOK_ATTRIBUTE   ] = "__attribute__",
1928 [TOK_ALIGNOF     ] = "__alignof__",
1929
1930 [TOK_DEFINE      ] = "define",
1931 [TOK_UNDEF       ] = "undef",
1932 [TOK_INCLUDE     ] = "include",
1933 [TOK_LINE        ] = "line",
1934 [TOK_ERROR       ] = "error",
1935 [TOK_WARNING     ] = "warning",
1936 [TOK_PRAGMA      ] = "pragma",
1937 [TOK_IFDEF       ] = "ifdef",
1938 [TOK_IFNDEF      ] = "ifndef",
1939 [TOK_ELIF        ] = "elif",
1940 [TOK_ENDIF       ] = "endif",
1941
1942 [TOK_EOF         ] = "EOF",
1943 };
1944
1945 static unsigned int hash(const char *str, int str_len)
1946 {
1947         unsigned int hash;
1948         const char *end;
1949         end = str + str_len;
1950         hash = 0;
1951         for(; str < end; str++) {
1952                 hash = (hash *263) + *str;
1953         }
1954         hash = hash & (HASH_TABLE_SIZE -1);
1955         return hash;
1956 }
1957
1958 static struct hash_entry *lookup(
1959         struct compile_state *state, const char *name, int name_len)
1960 {
1961         struct hash_entry *entry;
1962         unsigned int index;
1963         index = hash(name, name_len);
1964         entry = state->hash_table[index];
1965         while(entry && 
1966                 ((entry->name_len != name_len) ||
1967                         (memcmp(entry->name, name, name_len) != 0))) {
1968                 entry = entry->next;
1969         }
1970         if (!entry) {
1971                 char *new_name;
1972                 /* Get a private copy of the name */
1973                 new_name = xmalloc(name_len + 1, "hash_name");
1974                 memcpy(new_name, name, name_len);
1975                 new_name[name_len] = '\0';
1976
1977                 /* Create a new hash entry */
1978                 entry = xcmalloc(sizeof(*entry), "hash_entry");
1979                 entry->next = state->hash_table[index];
1980                 entry->name = new_name;
1981                 entry->name_len = name_len;
1982
1983                 /* Place the new entry in the hash table */
1984                 state->hash_table[index] = entry;
1985         }
1986         return entry;
1987 }
1988
1989 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1990 {
1991         struct hash_entry *entry;
1992         entry = tk->ident;
1993         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1994                 (entry->tok == TOK_ENUM_CONST) ||
1995                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
1996                         (entry->tok <= TOK_LAST_KEYWORD)))) {
1997                 tk->tok = entry->tok;
1998         }
1999 }
2000
2001 static void ident_to_macro(struct compile_state *state, struct token *tk)
2002 {
2003         struct hash_entry *entry;
2004         entry = tk->ident;
2005         if (entry && 
2006                 (entry->tok >= TOK_FIRST_MACRO) &&
2007                 (entry->tok <= TOK_LAST_MACRO)) {
2008                 tk->tok = entry->tok;
2009         }
2010 }
2011
2012 static void hash_keyword(
2013         struct compile_state *state, const char *keyword, int tok)
2014 {
2015         struct hash_entry *entry;
2016         entry = lookup(state, keyword, strlen(keyword));
2017         if (entry && entry->tok != TOK_UNKNOWN) {
2018                 die("keyword %s already hashed", keyword);
2019         }
2020         entry->tok  = tok;
2021 }
2022
2023 static void symbol(
2024         struct compile_state *state, struct hash_entry *ident,
2025         struct symbol **chain, struct triple *def, struct type *type)
2026 {
2027         struct symbol *sym;
2028         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2029                 error(state, 0, "%s already defined", ident->name);
2030         }
2031         sym = xcmalloc(sizeof(*sym), "symbol");
2032         sym->ident = ident;
2033         sym->def   = def;
2034         sym->type  = type;
2035         sym->scope_depth = state->scope_depth;
2036         sym->next = *chain;
2037         *chain    = sym;
2038 }
2039
2040 static void start_scope(struct compile_state *state)
2041 {
2042         state->scope_depth++;
2043 }
2044
2045 static void end_scope_syms(struct symbol **chain, int depth)
2046 {
2047         struct symbol *sym, *next;
2048         sym = *chain;
2049         while(sym && (sym->scope_depth == depth)) {
2050                 next = sym->next;
2051                 xfree(sym);
2052                 sym = next;
2053         }
2054         *chain = sym;
2055 }
2056
2057 static void end_scope(struct compile_state *state)
2058 {
2059         int i;
2060         int depth;
2061         /* Walk through the hash table and remove all symbols
2062          * in the current scope. 
2063          */
2064         depth = state->scope_depth;
2065         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2066                 struct hash_entry *entry;
2067                 entry = state->hash_table[i];
2068                 while(entry) {
2069                         end_scope_syms(&entry->sym_label,  depth);
2070                         end_scope_syms(&entry->sym_struct, depth);
2071                         end_scope_syms(&entry->sym_ident,  depth);
2072                         entry = entry->next;
2073                 }
2074         }
2075         state->scope_depth = depth - 1;
2076 }
2077
2078 static void register_keywords(struct compile_state *state)
2079 {
2080         hash_keyword(state, "auto",          TOK_AUTO);
2081         hash_keyword(state, "break",         TOK_BREAK);
2082         hash_keyword(state, "case",          TOK_CASE);
2083         hash_keyword(state, "char",          TOK_CHAR);
2084         hash_keyword(state, "const",         TOK_CONST);
2085         hash_keyword(state, "continue",      TOK_CONTINUE);
2086         hash_keyword(state, "default",       TOK_DEFAULT);
2087         hash_keyword(state, "do",            TOK_DO);
2088         hash_keyword(state, "double",        TOK_DOUBLE);
2089         hash_keyword(state, "else",          TOK_ELSE);
2090         hash_keyword(state, "enum",          TOK_ENUM);
2091         hash_keyword(state, "extern",        TOK_EXTERN);
2092         hash_keyword(state, "float",         TOK_FLOAT);
2093         hash_keyword(state, "for",           TOK_FOR);
2094         hash_keyword(state, "goto",          TOK_GOTO);
2095         hash_keyword(state, "if",            TOK_IF);
2096         hash_keyword(state, "inline",        TOK_INLINE);
2097         hash_keyword(state, "int",           TOK_INT);
2098         hash_keyword(state, "long",          TOK_LONG);
2099         hash_keyword(state, "register",      TOK_REGISTER);
2100         hash_keyword(state, "restrict",      TOK_RESTRICT);
2101         hash_keyword(state, "return",        TOK_RETURN);
2102         hash_keyword(state, "short",         TOK_SHORT);
2103         hash_keyword(state, "signed",        TOK_SIGNED);
2104         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2105         hash_keyword(state, "static",        TOK_STATIC);
2106         hash_keyword(state, "struct",        TOK_STRUCT);
2107         hash_keyword(state, "switch",        TOK_SWITCH);
2108         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2109         hash_keyword(state, "union",         TOK_UNION);
2110         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2111         hash_keyword(state, "void",          TOK_VOID);
2112         hash_keyword(state, "volatile",      TOK_VOLATILE);
2113         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2114         hash_keyword(state, "while",         TOK_WHILE);
2115         hash_keyword(state, "asm",           TOK_ASM);
2116         hash_keyword(state, "__asm__",       TOK_ASM);
2117         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2118         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2119 }
2120
2121 static void register_macro_keywords(struct compile_state *state)
2122 {
2123         hash_keyword(state, "define",        TOK_DEFINE);
2124         hash_keyword(state, "undef",         TOK_UNDEF);
2125         hash_keyword(state, "include",       TOK_INCLUDE);
2126         hash_keyword(state, "line",          TOK_LINE);
2127         hash_keyword(state, "error",         TOK_ERROR);
2128         hash_keyword(state, "warning",       TOK_WARNING);
2129         hash_keyword(state, "pragma",        TOK_PRAGMA);
2130         hash_keyword(state, "ifdef",         TOK_IFDEF);
2131         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2132         hash_keyword(state, "elif",          TOK_ELIF);
2133         hash_keyword(state, "endif",         TOK_ENDIF);
2134 }
2135
2136 static int spacep(int c)
2137 {
2138         int ret = 0;
2139         switch(c) {
2140         case ' ':
2141         case '\t':
2142         case '\f':
2143         case '\v':
2144         case '\r':
2145         case '\n':
2146                 ret = 1;
2147                 break;
2148         }
2149         return ret;
2150 }
2151
2152 static int digitp(int c)
2153 {
2154         int ret = 0;
2155         switch(c) {
2156         case '0': case '1': case '2': case '3': case '4': 
2157         case '5': case '6': case '7': case '8': case '9':
2158                 ret = 1;
2159                 break;
2160         }
2161         return ret;
2162 }
2163 static int digval(int c)
2164 {
2165         int val = -1;
2166         if ((c >= '0') && (c <= '9')) {
2167                 val = c - '0';
2168         }
2169         return val;
2170 }
2171
2172 static int hexdigitp(int c)
2173 {
2174         int ret = 0;
2175         switch(c) {
2176         case '0': case '1': case '2': case '3': case '4': 
2177         case '5': case '6': case '7': case '8': case '9':
2178         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2179         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2180                 ret = 1;
2181                 break;
2182         }
2183         return ret;
2184 }
2185 static int hexdigval(int c) 
2186 {
2187         int val = -1;
2188         if ((c >= '0') && (c <= '9')) {
2189                 val = c - '0';
2190         }
2191         else if ((c >= 'A') && (c <= 'F')) {
2192                 val = 10 + (c - 'A');
2193         }
2194         else if ((c >= 'a') && (c <= 'f')) {
2195                 val = 10 + (c - 'a');
2196         }
2197         return val;
2198 }
2199
2200 static int octdigitp(int c)
2201 {
2202         int ret = 0;
2203         switch(c) {
2204         case '0': case '1': case '2': case '3': 
2205         case '4': case '5': case '6': case '7':
2206                 ret = 1;
2207                 break;
2208         }
2209         return ret;
2210 }
2211 static int octdigval(int c)
2212 {
2213         int val = -1;
2214         if ((c >= '0') && (c <= '7')) {
2215                 val = c - '0';
2216         }
2217         return val;
2218 }
2219
2220 static int letterp(int c)
2221 {
2222         int ret = 0;
2223         switch(c) {
2224         case 'a': case 'b': case 'c': case 'd': case 'e':
2225         case 'f': case 'g': case 'h': case 'i': case 'j':
2226         case 'k': case 'l': case 'm': case 'n': case 'o':
2227         case 'p': case 'q': case 'r': case 's': case 't':
2228         case 'u': case 'v': case 'w': case 'x': case 'y':
2229         case 'z':
2230         case 'A': case 'B': case 'C': case 'D': case 'E':
2231         case 'F': case 'G': case 'H': case 'I': case 'J':
2232         case 'K': case 'L': case 'M': case 'N': case 'O':
2233         case 'P': case 'Q': case 'R': case 'S': case 'T':
2234         case 'U': case 'V': case 'W': case 'X': case 'Y':
2235         case 'Z':
2236         case '_':
2237                 ret = 1;
2238                 break;
2239         }
2240         return ret;
2241 }
2242
2243 static int char_value(struct compile_state *state,
2244         const signed char **strp, const signed char *end)
2245 {
2246         const signed char *str;
2247         int c;
2248         str = *strp;
2249         c = *str++;
2250         if ((c == '\\') && (str < end)) {
2251                 switch(*str) {
2252                 case 'n':  c = '\n'; str++; break;
2253                 case 't':  c = '\t'; str++; break;
2254                 case 'v':  c = '\v'; str++; break;
2255                 case 'b':  c = '\b'; str++; break;
2256                 case 'r':  c = '\r'; str++; break;
2257                 case 'f':  c = '\f'; str++; break;
2258                 case 'a':  c = '\a'; str++; break;
2259                 case '\\': c = '\\'; str++; break;
2260                 case '?':  c = '?';  str++; break;
2261                 case '\'': c = '\''; str++; break;
2262                 case '"':  c = '"';  break;
2263                 case 'x': 
2264                         c = 0;
2265                         str++;
2266                         while((str < end) && hexdigitp(*str)) {
2267                                 c <<= 4;
2268                                 c += hexdigval(*str);
2269                                 str++;
2270                         }
2271                         break;
2272                 case '0': case '1': case '2': case '3': 
2273                 case '4': case '5': case '6': case '7':
2274                         c = 0;
2275                         while((str < end) && octdigitp(*str)) {
2276                                 c <<= 3;
2277                                 c += octdigval(*str);
2278                                 str++;
2279                         }
2280                         break;
2281                 default:
2282                         error(state, 0, "Invalid character constant");
2283                         break;
2284                 }
2285         }
2286         *strp = str;
2287         return c;
2288 }
2289
2290 static char *after_digits(char *ptr, char *end)
2291 {
2292         while((ptr < end) && digitp(*ptr)) {
2293                 ptr++;
2294         }
2295         return ptr;
2296 }
2297
2298 static char *after_octdigits(char *ptr, char *end)
2299 {
2300         while((ptr < end) && octdigitp(*ptr)) {
2301                 ptr++;
2302         }
2303         return ptr;
2304 }
2305
2306 static char *after_hexdigits(char *ptr, char *end)
2307 {
2308         while((ptr < end) && hexdigitp(*ptr)) {
2309                 ptr++;
2310         }
2311         return ptr;
2312 }
2313
2314 static void save_string(struct compile_state *state, 
2315         struct token *tk, char *start, char *end, const char *id)
2316 {
2317         char *str;
2318         int str_len;
2319         /* Create a private copy of the string */
2320         str_len = end - start + 1;
2321         str = xmalloc(str_len + 1, id);
2322         memcpy(str, start, str_len);
2323         str[str_len] = '\0';
2324
2325         /* Store the copy in the token */
2326         tk->val.str = str;
2327         tk->str_len = str_len;
2328 }
2329 static void next_token(struct compile_state *state, int index)
2330 {
2331         struct file_state *file;
2332         struct token *tk;
2333         char *token;
2334         int c, c1, c2, c3;
2335         char *tokp, *end;
2336         int tok;
2337 next_token:
2338         file = state->file;
2339         tk = &state->token[index];
2340         tk->str_len = 0;
2341         tk->ident = 0;
2342         token = tokp = file->pos;
2343         end = file->buf + file->size;
2344         tok = TOK_UNKNOWN;
2345         c = -1;
2346         if (tokp < end) {
2347                 c = *tokp;
2348         }
2349         c1 = -1;
2350         if ((tokp + 1) < end) {
2351                 c1 = tokp[1];
2352         }
2353         c2 = -1;
2354         if ((tokp + 2) < end) {
2355                 c2 = tokp[2];
2356         }
2357         c3 = -1;
2358         if ((tokp + 3) < end) {
2359                 c3 = tokp[3];
2360         }
2361         if (tokp >= end) {
2362                 tok = TOK_EOF;
2363                 tokp = end;
2364         }
2365         /* Whitespace */
2366         else if (spacep(c)) {
2367                 tok = TOK_SPACE;
2368                 while ((tokp < end) && spacep(c)) {
2369                         if (c == '\n') {
2370                                 file->line++;
2371                                 file->line_start = tokp + 1;
2372                         }
2373                         c = *(++tokp);
2374                 }
2375                 if (!spacep(c)) {
2376                         tokp--;
2377                 }
2378         }
2379         /* EOL Comments */
2380         else if ((c == '/') && (c1 == '/')) {
2381                 tok = TOK_SPACE;
2382                 for(tokp += 2; tokp < end; tokp++) {
2383                         c = *tokp;
2384                         if (c == '\n') {
2385                                 file->line++;
2386                                 file->line_start = tokp +1;
2387                                 break;
2388                         }
2389                 }
2390         }
2391         /* Comments */
2392         else if ((c == '/') && (c1 == '*')) {
2393                 int line;
2394                 char *line_start;
2395                 line = file->line;
2396                 line_start = file->line_start;
2397                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2398                         c = *tokp;
2399                         if (c == '\n') {
2400                                 line++;
2401                                 line_start = tokp +1;
2402                         }
2403                         else if ((c == '*') && (tokp[1] == '/')) {
2404                                 tok = TOK_SPACE;
2405                                 tokp += 1;
2406                                 break;
2407                         }
2408                 }
2409                 if (tok == TOK_UNKNOWN) {
2410                         error(state, 0, "unterminated comment");
2411                 }
2412                 file->line = line;
2413                 file->line_start = line_start;
2414         }
2415         /* string constants */
2416         else if ((c == '"') ||
2417                 ((c == 'L') && (c1 == '"'))) {
2418                 int line;
2419                 char *line_start;
2420                 int wchar;
2421                 line = file->line;
2422                 line_start = file->line_start;
2423                 wchar = 0;
2424                 if (c == 'L') {
2425                         wchar = 1;
2426                         tokp++;
2427                 }
2428                 for(tokp += 1; tokp < end; tokp++) {
2429                         c = *tokp;
2430                         if (c == '\n') {
2431                                 line++;
2432                                 line_start = tokp + 1;
2433                         }
2434                         else if ((c == '\\') && (tokp +1 < end)) {
2435                                 tokp++;
2436                         }
2437                         else if (c == '"') {
2438                                 tok = TOK_LIT_STRING;
2439                                 break;
2440                         }
2441                 }
2442                 if (tok == TOK_UNKNOWN) {
2443                         error(state, 0, "unterminated string constant");
2444                 }
2445                 if (line != file->line) {
2446                         warning(state, 0, "multiline string constant");
2447                 }
2448                 file->line = line;
2449                 file->line_start = line_start;
2450
2451                 /* Save the string value */
2452                 save_string(state, tk, token, tokp, "literal string");
2453         }
2454         /* character constants */
2455         else if ((c == '\'') ||
2456                 ((c == 'L') && (c1 == '\''))) {
2457                 int line;
2458                 char *line_start;
2459                 int wchar;
2460                 line = file->line;
2461                 line_start = file->line_start;
2462                 wchar = 0;
2463                 if (c == 'L') {
2464                         wchar = 1;
2465                         tokp++;
2466                 }
2467                 for(tokp += 1; tokp < end; tokp++) {
2468                         c = *tokp;
2469                         if (c == '\n') {
2470                                 line++;
2471                                 line_start = tokp + 1;
2472                         }
2473                         else if ((c == '\\') && (tokp +1 < end)) {
2474                                 tokp++;
2475                         }
2476                         else if (c == '\'') {
2477                                 tok = TOK_LIT_CHAR;
2478                                 break;
2479                         }
2480                 }
2481                 if (tok == TOK_UNKNOWN) {
2482                         error(state, 0, "unterminated character constant");
2483                 }
2484                 if (line != file->line) {
2485                         warning(state, 0, "multiline character constant");
2486                 }
2487                 file->line = line;
2488                 file->line_start = line_start;
2489
2490                 /* Save the character value */
2491                 save_string(state, tk, token, tokp, "literal character");
2492         }
2493         /* integer and floating constants 
2494          * Integer Constants
2495          * {digits}
2496          * 0[Xx]{hexdigits}
2497          * 0{octdigit}+
2498          * 
2499          * Floating constants
2500          * {digits}.{digits}[Ee][+-]?{digits}
2501          * {digits}.{digits}
2502          * {digits}[Ee][+-]?{digits}
2503          * .{digits}[Ee][+-]?{digits}
2504          * .{digits}
2505          */
2506         
2507         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2508                 char *next, *new;
2509                 int is_float;
2510                 is_float = 0;
2511                 if (c != '.') {
2512                         next = after_digits(tokp, end);
2513                 }
2514                 else {
2515                         next = tokp;
2516                 }
2517                 if (next[0] == '.') {
2518                         new = after_digits(next, end);
2519                         is_float = (new != next);
2520                         next = new;
2521                 }
2522                 if ((next[0] == 'e') || (next[0] == 'E')) {
2523                         if (((next + 1) < end) && 
2524                                 ((next[1] == '+') || (next[1] == '-'))) {
2525                                 next++;
2526                         }
2527                         new = after_digits(next, end);
2528                         is_float = (new != next);
2529                         next = new;
2530                 }
2531                 if (is_float) {
2532                         tok = TOK_LIT_FLOAT;
2533                         if ((next < end) && (
2534                                 (next[0] == 'f') ||
2535                                 (next[0] == 'F') ||
2536                                 (next[0] == 'l') ||
2537                                 (next[0] == 'L'))
2538                                 ) {
2539                                 next++;
2540                         }
2541                 }
2542                 if (!is_float && digitp(c)) {
2543                         tok = TOK_LIT_INT;
2544                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2545                                 next = after_hexdigits(tokp + 2, end);
2546                         }
2547                         else if (c == '0') {
2548                                 next = after_octdigits(tokp, end);
2549                         }
2550                         else {
2551                                 next = after_digits(tokp, end);
2552                         }
2553                         /* crazy integer suffixes */
2554                         if ((next < end) && 
2555                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2556                                 next++;
2557                                 if ((next < end) &&
2558                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2559                                         next++;
2560                                 }
2561                         }
2562                         else if ((next < end) &&
2563                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2564                                 next++;
2565                                 if ((next < end) && 
2566                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2567                                         next++;
2568                                 }
2569                         }
2570                 }
2571                 tokp = next - 1;
2572
2573                 /* Save the integer/floating point value */
2574                 save_string(state, tk, token, tokp, "literal number");
2575         }
2576         /* identifiers */
2577         else if (letterp(c)) {
2578                 tok = TOK_IDENT;
2579                 for(tokp += 1; tokp < end; tokp++) {
2580                         c = *tokp;
2581                         if (!letterp(c) && !digitp(c)) {
2582                                 break;
2583                         }
2584                 }
2585                 tokp -= 1;
2586                 tk->ident = lookup(state, token, tokp +1 - token);
2587         }
2588         /* C99 alternate macro characters */
2589         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2590                 tokp += 3; 
2591                 tok = TOK_CONCATENATE; 
2592         }
2593         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2594         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2595         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2596         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2597         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2598         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2599         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2600         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2601         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2602         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2603         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2604         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2605         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2606         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2607         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2608         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2609         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2610         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2611         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2612         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2613         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2614         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2615         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2616         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2617         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2618         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2619         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2620         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2621         else if (c == ';') { tok = TOK_SEMI; }
2622         else if (c == '{') { tok = TOK_LBRACE; }
2623         else if (c == '}') { tok = TOK_RBRACE; }
2624         else if (c == ',') { tok = TOK_COMMA; }
2625         else if (c == '=') { tok = TOK_EQ; }
2626         else if (c == ':') { tok = TOK_COLON; }
2627         else if (c == '[') { tok = TOK_LBRACKET; }
2628         else if (c == ']') { tok = TOK_RBRACKET; }
2629         else if (c == '(') { tok = TOK_LPAREN; }
2630         else if (c == ')') { tok = TOK_RPAREN; }
2631         else if (c == '*') { tok = TOK_STAR; }
2632         else if (c == '>') { tok = TOK_MORE; }
2633         else if (c == '<') { tok = TOK_LESS; }
2634         else if (c == '?') { tok = TOK_QUEST; }
2635         else if (c == '|') { tok = TOK_OR; }
2636         else if (c == '&') { tok = TOK_AND; }
2637         else if (c == '^') { tok = TOK_XOR; }
2638         else if (c == '+') { tok = TOK_PLUS; }
2639         else if (c == '-') { tok = TOK_MINUS; }
2640         else if (c == '/') { tok = TOK_DIV; }
2641         else if (c == '%') { tok = TOK_MOD; }
2642         else if (c == '!') { tok = TOK_BANG; }
2643         else if (c == '.') { tok = TOK_DOT; }
2644         else if (c == '~') { tok = TOK_TILDE; }
2645         else if (c == '#') { tok = TOK_MACRO; }
2646         if (tok == TOK_MACRO) {
2647                 /* Only match preprocessor directives at the start of a line */
2648                 char *ptr;
2649                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2650                         ;
2651                 if (ptr != tokp) {
2652                         tok = TOK_UNKNOWN;
2653                 }
2654         }
2655         if (tok == TOK_UNKNOWN) {
2656                 error(state, 0, "unknown token");
2657         }
2658
2659         file->pos = tokp + 1;
2660         tk->tok = tok;
2661         if (tok == TOK_IDENT) {
2662                 ident_to_keyword(state, tk);
2663         }
2664         /* Don't return space tokens. */
2665         if (tok == TOK_SPACE) {
2666                 goto next_token;
2667         }
2668 }
2669
2670 static void compile_macro(struct compile_state *state, struct token *tk)
2671 {
2672         struct file_state *file;
2673         struct hash_entry *ident;
2674         ident = tk->ident;
2675         file = xmalloc(sizeof(*file), "file_state");
2676         file->basename = xstrdup(tk->ident->name);
2677         file->dirname = xstrdup("");
2678         file->size = ident->sym_define->buf_len;
2679         file->buf = xmalloc(file->size +2,  file->basename);
2680         memcpy(file->buf, ident->sym_define->buf, file->size);
2681         file->buf[file->size] = '\n';
2682         file->buf[file->size + 1] = '\0';
2683         file->pos = file->buf;
2684         file->line_start = file->pos;
2685         file->line = 1;
2686         file->prev = state->file;
2687         state->file = file;
2688 }
2689
2690
2691 static int mpeek(struct compile_state *state, int index)
2692 {
2693         struct token *tk;
2694         int rescan;
2695         tk = &state->token[index + 1];
2696         if (tk->tok == -1) {
2697                 next_token(state, index + 1);
2698         }
2699         do {
2700                 rescan = 0;
2701                 if ((tk->tok == TOK_EOF) && 
2702                         (state->file != state->macro_file) &&
2703                         (state->file->prev)) {
2704                         struct file_state *file = state->file;
2705                         state->file = file->prev;
2706                         /* file->basename is used keep it */
2707                         xfree(file->dirname);
2708                         xfree(file->buf);
2709                         xfree(file);
2710                         next_token(state, index + 1);
2711                         rescan = 1;
2712                 }
2713                 else if (tk->ident && tk->ident->sym_define) {
2714                         compile_macro(state, tk);
2715                         next_token(state, index + 1);
2716                         rescan = 1;
2717                 }
2718         } while(rescan);
2719         /* Don't show the token on the next line */
2720         if (state->macro_line < state->macro_file->line) {
2721                 return TOK_EOF;
2722         }
2723         return state->token[index +1].tok;
2724 }
2725
2726 static void meat(struct compile_state *state, int index, int tok)
2727 {
2728         int next_tok;
2729         int i;
2730         next_tok = mpeek(state, index);
2731         if (next_tok != tok) {
2732                 const char *name1, *name2;
2733                 name1 = tokens[next_tok];
2734                 name2 = "";
2735                 if (next_tok == TOK_IDENT) {
2736                         name2 = state->token[index + 1].ident->name;
2737                 }
2738                 error(state, 0, "found %s %s expected %s", 
2739                         name1, name2, tokens[tok]);
2740         }
2741         /* Free the old token value */
2742         if (state->token[index].str_len) {
2743                 memset((void *)(state->token[index].val.str), -1, 
2744                         state->token[index].str_len);
2745                 xfree(state->token[index].val.str);
2746         }
2747         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2748                 state->token[i] = state->token[i + 1];
2749         }
2750         memset(&state->token[i], 0, sizeof(state->token[i]));
2751         state->token[i].tok = -1;
2752 }
2753
2754 static long_t mcexpr(struct compile_state *state, int index);
2755
2756 static long_t mprimary_expr(struct compile_state *state, int index)
2757 {
2758         long_t val;
2759         int tok;
2760         tok = mpeek(state, index);
2761         while(state->token[index + 1].ident && 
2762                 state->token[index + 1].ident->sym_define) {
2763                 meat(state, index, tok);
2764                 compile_macro(state, &state->token[index]);
2765                 tok = mpeek(state, index);
2766         }
2767         switch(tok) {
2768         case TOK_LPAREN:
2769                 meat(state, index, TOK_LPAREN);
2770                 val = mcexpr(state, index);
2771                 meat(state, index, TOK_RPAREN);
2772                 break;
2773         case TOK_LIT_INT:
2774         {
2775                 char *end;
2776                 meat(state, index, TOK_LIT_INT);
2777                 errno = 0;
2778                 val = strtol(state->token[index].val.str, &end, 0);
2779                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2780                         (errno == ERANGE)) {
2781                         error(state, 0, "Integer constant to large");
2782                 }
2783                 break;
2784         }
2785         default:
2786                 meat(state, index, TOK_LIT_INT);
2787                 val = 0;
2788         }
2789         return val;
2790 }
2791 static long_t munary_expr(struct compile_state *state, int index)
2792 {
2793         long_t val;
2794         switch(mpeek(state, index)) {
2795         case TOK_PLUS:
2796                 meat(state, index, TOK_PLUS);
2797                 val = munary_expr(state, index);
2798                 val = + val;
2799                 break;
2800         case TOK_MINUS:
2801                 meat(state, index, TOK_MINUS);
2802                 val = munary_expr(state, index);
2803                 val = - val;
2804                 break;
2805         case TOK_TILDE:
2806                 meat(state, index, TOK_BANG);
2807                 val = munary_expr(state, index);
2808                 val = ~ val;
2809                 break;
2810         case TOK_BANG:
2811                 meat(state, index, TOK_BANG);
2812                 val = munary_expr(state, index);
2813                 val = ! val;
2814                 break;
2815         default:
2816                 val = mprimary_expr(state, index);
2817                 break;
2818         }
2819         return val;
2820         
2821 }
2822 static long_t mmul_expr(struct compile_state *state, int index)
2823 {
2824         long_t val;
2825         int done;
2826         val = munary_expr(state, index);
2827         do {
2828                 long_t right;
2829                 done = 0;
2830                 switch(mpeek(state, index)) {
2831                 case TOK_STAR:
2832                         meat(state, index, TOK_STAR);
2833                         right = munary_expr(state, index);
2834                         val = val * right;
2835                         break;
2836                 case TOK_DIV:
2837                         meat(state, index, TOK_DIV);
2838                         right = munary_expr(state, index);
2839                         val = val / right;
2840                         break;
2841                 case TOK_MOD:
2842                         meat(state, index, TOK_MOD);
2843                         right = munary_expr(state, index);
2844                         val = val % right;
2845                         break;
2846                 default:
2847                         done = 1;
2848                         break;
2849                 }
2850         } while(!done);
2851
2852         return val;
2853 }
2854
2855 static long_t madd_expr(struct compile_state *state, int index)
2856 {
2857         long_t val;
2858         int done;
2859         val = mmul_expr(state, index);
2860         do {
2861                 long_t right;
2862                 done = 0;
2863                 switch(mpeek(state, index)) {
2864                 case TOK_PLUS:
2865                         meat(state, index, TOK_PLUS);
2866                         right = mmul_expr(state, index);
2867                         val = val + right;
2868                         break;
2869                 case TOK_MINUS:
2870                         meat(state, index, TOK_MINUS);
2871                         right = mmul_expr(state, index);
2872                         val = val - right;
2873                         break;
2874                 default:
2875                         done = 1;
2876                         break;
2877                 }
2878         } while(!done);
2879
2880         return val;
2881 }
2882
2883 static long_t mshift_expr(struct compile_state *state, int index)
2884 {
2885         long_t val;
2886         int done;
2887         val = madd_expr(state, index);
2888         do {
2889                 long_t right;
2890                 done = 0;
2891                 switch(mpeek(state, index)) {
2892                 case TOK_SL:
2893                         meat(state, index, TOK_SL);
2894                         right = madd_expr(state, index);
2895                         val = val << right;
2896                         break;
2897                 case TOK_SR:
2898                         meat(state, index, TOK_SR);
2899                         right = madd_expr(state, index);
2900                         val = val >> right;
2901                         break;
2902                 default:
2903                         done = 1;
2904                         break;
2905                 }
2906         } while(!done);
2907
2908         return val;
2909 }
2910
2911 static long_t mrel_expr(struct compile_state *state, int index)
2912 {
2913         long_t val;
2914         int done;
2915         val = mshift_expr(state, index);
2916         do {
2917                 long_t right;
2918                 done = 0;
2919                 switch(mpeek(state, index)) {
2920                 case TOK_LESS:
2921                         meat(state, index, TOK_LESS);
2922                         right = mshift_expr(state, index);
2923                         val = val < right;
2924                         break;
2925                 case TOK_MORE:
2926                         meat(state, index, TOK_MORE);
2927                         right = mshift_expr(state, index);
2928                         val = val > right;
2929                         break;
2930                 case TOK_LESSEQ:
2931                         meat(state, index, TOK_LESSEQ);
2932                         right = mshift_expr(state, index);
2933                         val = val <= right;
2934                         break;
2935                 case TOK_MOREEQ:
2936                         meat(state, index, TOK_MOREEQ);
2937                         right = mshift_expr(state, index);
2938                         val = val >= right;
2939                         break;
2940                 default:
2941                         done = 1;
2942                         break;
2943                 }
2944         } while(!done);
2945         return val;
2946 }
2947
2948 static long_t meq_expr(struct compile_state *state, int index)
2949 {
2950         long_t val;
2951         int done;
2952         val = mrel_expr(state, index);
2953         do {
2954                 long_t right;
2955                 done = 0;
2956                 switch(mpeek(state, index)) {
2957                 case TOK_EQEQ:
2958                         meat(state, index, TOK_EQEQ);
2959                         right = mrel_expr(state, index);
2960                         val = val == right;
2961                         break;
2962                 case TOK_NOTEQ:
2963                         meat(state, index, TOK_NOTEQ);
2964                         right = mrel_expr(state, index);
2965                         val = val != right;
2966                         break;
2967                 default:
2968                         done = 1;
2969                         break;
2970                 }
2971         } while(!done);
2972         return val;
2973 }
2974
2975 static long_t mand_expr(struct compile_state *state, int index)
2976 {
2977         long_t val;
2978         val = meq_expr(state, index);
2979         if (mpeek(state, index) == TOK_AND) {
2980                 long_t right;
2981                 meat(state, index, TOK_AND);
2982                 right = meq_expr(state, index);
2983                 val = val & right;
2984         }
2985         return val;
2986 }
2987
2988 static long_t mxor_expr(struct compile_state *state, int index)
2989 {
2990         long_t val;
2991         val = mand_expr(state, index);
2992         if (mpeek(state, index) == TOK_XOR) {
2993                 long_t right;
2994                 meat(state, index, TOK_XOR);
2995                 right = mand_expr(state, index);
2996                 val = val ^ right;
2997         }
2998         return val;
2999 }
3000
3001 static long_t mor_expr(struct compile_state *state, int index)
3002 {
3003         long_t val;
3004         val = mxor_expr(state, index);
3005         if (mpeek(state, index) == TOK_OR) {
3006                 long_t right;
3007                 meat(state, index, TOK_OR);
3008                 right = mxor_expr(state, index);
3009                 val = val | right;
3010         }
3011         return val;
3012 }
3013
3014 static long_t mland_expr(struct compile_state *state, int index)
3015 {
3016         long_t val;
3017         val = mor_expr(state, index);
3018         if (mpeek(state, index) == TOK_LOGAND) {
3019                 long_t right;
3020                 meat(state, index, TOK_LOGAND);
3021                 right = mor_expr(state, index);
3022                 val = val && right;
3023         }
3024         return val;
3025 }
3026 static long_t mlor_expr(struct compile_state *state, int index)
3027 {
3028         long_t val;
3029         val = mland_expr(state, index);
3030         if (mpeek(state, index) == TOK_LOGOR) {
3031                 long_t right;
3032                 meat(state, index, TOK_LOGOR);
3033                 right = mland_expr(state, index);
3034                 val = val || right;
3035         }
3036         return val;
3037 }
3038
3039 static long_t mcexpr(struct compile_state *state, int index)
3040 {
3041         return mlor_expr(state, index);
3042 }
3043 static void preprocess(struct compile_state *state, int index)
3044 {
3045         /* Doing much more with the preprocessor would require
3046          * a parser and a major restructuring.
3047          * Postpone that for later.
3048          */
3049         struct file_state *file;
3050         struct token *tk;
3051         int line;
3052         int tok;
3053         
3054         file = state->file;
3055         tk = &state->token[index];
3056         state->macro_line = line = file->line;
3057         state->macro_file = file;
3058
3059         next_token(state, index);
3060         ident_to_macro(state, tk);
3061         if (tk->tok == TOK_IDENT) {
3062                 error(state, 0, "undefined preprocessing directive `%s'",
3063                         tk->ident->name);
3064         }
3065         switch(tk->tok) {
3066         case TOK_UNDEF:
3067         case TOK_LINE:
3068         case TOK_PRAGMA:
3069                 if (state->if_value < 0) {
3070                         break;
3071                 }
3072                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3073                         tk->ident->name);
3074                 break;
3075         case TOK_ELIF:
3076                 error(state, 0, "#elif not supported");
3077 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3078                 if (state->if_depth == 0) {
3079                         error(state, 0, "#elif without #if");
3080                 }
3081                 /* If the #if was taken the #elif just disables the following code */
3082                 if (state->if_value >= 0) {
3083                         state->if_value = - state->if_value;
3084                 }
3085                 /* If the previous #if was not taken see if the #elif enables the 
3086                  * trailing code.
3087                  */
3088                 else if ((state->if_value < 0) && 
3089                         (state->if_depth == - state->if_value))
3090                 {
3091                         if (mcexpr(state, index) != 0) {
3092                                 state->if_value = state->if_depth;
3093                         }
3094                         else {
3095                                 state->if_value = - state->if_depth;
3096                         }
3097                 }
3098                 break;
3099         case TOK_IF:
3100                 state->if_depth++;
3101                 if (state->if_value < 0) {
3102                         break;
3103                 }
3104                 if (mcexpr(state, index) != 0) {
3105                         state->if_value = state->if_depth;
3106                 }
3107                 else {
3108                         state->if_value = - state->if_depth;
3109                 }
3110                 break;
3111         case TOK_IFNDEF:
3112                 state->if_depth++;
3113                 if (state->if_value < 0) {
3114                         break;
3115                 }
3116                 next_token(state, index);
3117                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3118                         error(state, 0, "Invalid macro name");
3119                 }
3120                 if (tk->ident->sym_define == 0) {
3121                         state->if_value = state->if_depth;
3122                 } 
3123                 else {
3124                         state->if_value = - state->if_depth;
3125                 }
3126                 break;
3127         case TOK_IFDEF:
3128                 state->if_depth++;
3129                 if (state->if_value < 0) {
3130                         break;
3131                 }
3132                 next_token(state, index);
3133                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3134                         error(state, 0, "Invalid macro name");
3135                 }
3136                 if (tk->ident->sym_define != 0) {
3137                         state->if_value = state->if_depth;
3138                 }
3139                 else {
3140                         state->if_value = - state->if_depth;
3141                 }
3142                 break;
3143         case TOK_ELSE:
3144                 if (state->if_depth == 0) {
3145                         error(state, 0, "#else without #if");
3146                 }
3147                 if ((state->if_value >= 0) ||
3148                         ((state->if_value < 0) && 
3149                                 (state->if_depth == -state->if_value)))
3150                 {
3151                         state->if_value = - state->if_value;
3152                 }
3153                 break;
3154         case TOK_ENDIF:
3155                 if (state->if_depth == 0) {
3156                         error(state, 0, "#endif without #if");
3157                 }
3158                 if ((state->if_value >= 0) ||
3159                         ((state->if_value < 0) &&
3160                                 (state->if_depth == -state->if_value))) 
3161                 {
3162                         state->if_value = state->if_depth - 1;
3163                 }
3164                 state->if_depth--;
3165                 break;
3166         case TOK_DEFINE:
3167         {
3168                 struct hash_entry *ident;
3169                 struct macro *macro;
3170                 char *ptr;
3171                 
3172                 if (state->if_value < 0) /* quit early when #if'd out */
3173                         break;
3174
3175                 meat(state, index, TOK_IDENT);
3176                 ident = tk->ident;
3177                 
3178
3179                 if (*file->pos == '(') {
3180 #warning "FIXME macros with arguments not supported"
3181                         error(state, 0, "Macros with arguments not supported");
3182                 }
3183
3184                 /* Find the end of the line to get an estimate of
3185                  * the macro's length.
3186                  */
3187                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3188                         ;
3189
3190                 if (ident->sym_define != 0) {
3191                         error(state, 0, "macro %s already defined\n", ident->name);
3192                 }
3193                 macro = xmalloc(sizeof(*macro), "macro");
3194                 macro->ident = ident;
3195                 macro->buf_len = ptr - file->pos +1;
3196                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3197
3198                 memcpy(macro->buf, file->pos, macro->buf_len);
3199                 macro->buf[macro->buf_len] = '\n';
3200                 macro->buf[macro->buf_len +1] = '\0';
3201
3202                 ident->sym_define = macro;
3203                 break;
3204         }
3205         case TOK_ERROR:
3206         {
3207                 char *end;
3208                 int len;
3209                 /* Find the end of the line */
3210                 for(end = file->pos; *end != '\n'; end++)
3211                         ;
3212                 len = (end - file->pos);
3213                 if (state->if_value >= 0) {
3214                         error(state, 0, "%*.*s", len, len, file->pos);
3215                 }
3216                 file->pos = end;
3217                 break;
3218         }
3219         case TOK_WARNING:
3220         {
3221                 char *end;
3222                 int len;
3223                 /* Find the end of the line */
3224                 for(end = file->pos; *end != '\n'; end++)
3225                         ;
3226                 len = (end - file->pos);
3227                 if (state->if_value >= 0) {
3228                         warning(state, 0, "%*.*s", len, len, file->pos);
3229                 }
3230                 file->pos = end;
3231                 break;
3232         }
3233         case TOK_INCLUDE:
3234         {
3235                 char *name;
3236                 char *ptr;
3237                 int local;
3238                 local = 0;
3239                 name = 0;
3240                 next_token(state, index);
3241                 if (tk->tok == TOK_LIT_STRING) {
3242                         const char *token;
3243                         int name_len;
3244                         name = xmalloc(tk->str_len, "include");
3245                         token = tk->val.str +1;
3246                         name_len = tk->str_len -2;
3247                         if (*token == '"') {
3248                                 token++;
3249                                 name_len--;
3250                         }
3251                         memcpy(name, token, name_len);
3252                         name[name_len] = '\0';
3253                         local = 1;
3254                 }
3255                 else if (tk->tok == TOK_LESS) {
3256                         char *start, *end;
3257                         start = file->pos;
3258                         for(end = start; *end != '\n'; end++) {
3259                                 if (*end == '>') {
3260                                         break;
3261                                 }
3262                         }
3263                         if (*end == '\n') {
3264                                 error(state, 0, "Unterminated included directive");
3265                         }
3266                         name = xmalloc(end - start + 1, "include");
3267                         memcpy(name, start, end - start);
3268                         name[end - start] = '\0';
3269                         file->pos = end +1;
3270                         local = 0;
3271                 }
3272                 else {
3273                         error(state, 0, "Invalid include directive");
3274                 }
3275                 /* Error if there are any characters after the include */
3276                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3277                         switch(*ptr) {
3278                         case ' ':
3279                         case '\t':
3280                         case '\v':
3281                                 break;
3282                         default:
3283                                 error(state, 0, "garbage after include directive");
3284                         }
3285                 }
3286                 if (state->if_value >= 0) {
3287                         compile_file(state, name, local);
3288                 }
3289                 xfree(name);
3290                 next_token(state, index);
3291                 return;
3292         }
3293         default:
3294                 /* Ignore # without a following ident */
3295                 if (tk->tok == TOK_IDENT) {
3296                         error(state, 0, "Invalid preprocessor directive: %s", 
3297                                 tk->ident->name);
3298                 }
3299                 break;
3300         }
3301         /* Consume the rest of the macro line */
3302         do {
3303                 tok = mpeek(state, index);
3304                 meat(state, index, tok);
3305         } while(tok != TOK_EOF);
3306         return;
3307 }
3308
3309 static void token(struct compile_state *state, int index)
3310 {
3311         struct file_state *file;
3312         struct token *tk;
3313         int rescan;
3314
3315         tk = &state->token[index];
3316         next_token(state, index);
3317         do {
3318                 rescan = 0;
3319                 file = state->file;
3320                 if (tk->tok == TOK_EOF && file->prev) {
3321                         state->file = file->prev;
3322                         /* file->basename is used keep it */
3323                         xfree(file->dirname);
3324                         xfree(file->buf);
3325                         xfree(file);
3326                         next_token(state, index);
3327                         rescan = 1;
3328                 }
3329                 else if (tk->tok == TOK_MACRO) {
3330                         preprocess(state, index);
3331                         rescan = 1;
3332                 }
3333                 else if (tk->ident && tk->ident->sym_define) {
3334                         compile_macro(state, tk);
3335                         next_token(state, index);
3336                         rescan = 1;
3337                 }
3338                 else if (state->if_value < 0) {
3339                         next_token(state, index);
3340                         rescan = 1;
3341                 }
3342         } while(rescan);
3343 }
3344
3345 static int peek(struct compile_state *state)
3346 {
3347         if (state->token[1].tok == -1) {
3348                 token(state, 1);
3349         }
3350         return state->token[1].tok;
3351 }
3352
3353 static int peek2(struct compile_state *state)
3354 {
3355         if (state->token[1].tok == -1) {
3356                 token(state, 1);
3357         }
3358         if (state->token[2].tok == -1) {
3359                 token(state, 2);
3360         }
3361         return state->token[2].tok;
3362 }
3363
3364 static void eat(struct compile_state *state, int tok)
3365 {
3366         int next_tok;
3367         int i;
3368         next_tok = peek(state);
3369         if (next_tok != tok) {
3370                 const char *name1, *name2;
3371                 name1 = tokens[next_tok];
3372                 name2 = "";
3373                 if (next_tok == TOK_IDENT) {
3374                         name2 = state->token[1].ident->name;
3375                 }
3376                 error(state, 0, "\tfound %s %s expected %s",
3377                         name1, name2 ,tokens[tok]);
3378         }
3379         /* Free the old token value */
3380         if (state->token[0].str_len) {
3381                 xfree((void *)(state->token[0].val.str));
3382         }
3383         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3384                 state->token[i] = state->token[i + 1];
3385         }
3386         memset(&state->token[i], 0, sizeof(state->token[i]));
3387         state->token[i].tok = -1;
3388 }
3389
3390 #warning "FIXME do not hardcode the include paths"
3391 static char *include_paths[] = {
3392         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3393         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3394         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3395         0
3396 };
3397
3398 static void compile_file(struct compile_state *state, const char *filename, int local)
3399 {
3400         char cwd[4096];
3401         const char *subdir, *base;
3402         int subdir_len;
3403         struct file_state *file;
3404         char *basename;
3405         file = xmalloc(sizeof(*file), "file_state");
3406
3407         base = strrchr(filename, '/');
3408         subdir = filename;
3409         if (base != 0) {
3410                 subdir_len = base - filename;
3411                 base++;
3412         }
3413         else {
3414                 base = filename;
3415                 subdir_len = 0;
3416         }
3417         basename = xmalloc(strlen(base) +1, "basename");
3418         strcpy(basename, base);
3419         file->basename = basename;
3420
3421         if (getcwd(cwd, sizeof(cwd)) == 0) {
3422                 die("cwd buffer to small");
3423         }
3424         
3425         if (subdir[0] == '/') {
3426                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3427                 memcpy(file->dirname, subdir, subdir_len);
3428                 file->dirname[subdir_len] = '\0';
3429         }
3430         else {
3431                 char *dir;
3432                 int dirlen;
3433                 char **path;
3434                 /* Find the appropriate directory... */
3435                 dir = 0;
3436                 if (!state->file && exists(cwd, filename)) {
3437                         dir = cwd;
3438                 }
3439                 if (local && state->file && exists(state->file->dirname, filename)) {
3440                         dir = state->file->dirname;
3441                 }
3442                 for(path = include_paths; !dir && *path; path++) {
3443                         if (exists(*path, filename)) {
3444                                 dir = *path;
3445                         }
3446                 }
3447                 if (!dir) {
3448                         error(state, 0, "Cannot find `%s'\n", filename);
3449                 }
3450                 dirlen = strlen(dir);
3451                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3452                 memcpy(file->dirname, dir, dirlen);
3453                 file->dirname[dirlen] = '/';
3454                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3455                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3456         }
3457         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3458         xchdir(cwd);
3459
3460         file->pos = file->buf;
3461         file->line_start = file->pos;
3462         file->line = 1;
3463
3464         file->prev = state->file;
3465         state->file = file;
3466         
3467         process_trigraphs(state);
3468         splice_lines(state);
3469 }
3470
3471 /* Type helper functions */
3472
3473 static struct type *new_type(
3474         unsigned int type, struct type *left, struct type *right)
3475 {
3476         struct type *result;
3477         result = xmalloc(sizeof(*result), "type");
3478         result->type = type;
3479         result->left = left;
3480         result->right = right;
3481         result->field_ident = 0;
3482         result->type_ident = 0;
3483         return result;
3484 }
3485
3486 static struct type *clone_type(unsigned int specifiers, struct type *old)
3487 {
3488         struct type *result;
3489         result = xmalloc(sizeof(*result), "type");
3490         memcpy(result, old, sizeof(*result));
3491         result->type &= TYPE_MASK;
3492         result->type |= specifiers;
3493         return result;
3494 }
3495
3496 #define SIZEOF_SHORT 2
3497 #define SIZEOF_INT   4
3498 #define SIZEOF_LONG  (sizeof(long_t))
3499
3500 #define ALIGNOF_SHORT 2
3501 #define ALIGNOF_INT   4
3502 #define ALIGNOF_LONG  (sizeof(long_t))
3503
3504 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3505 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3506 static inline ulong_t mask_uint(ulong_t x)
3507 {
3508         if (SIZEOF_INT < SIZEOF_LONG) {
3509                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3510                 x &= mask;
3511         }
3512         return x;
3513 }
3514 #define MASK_UINT(X)      (mask_uint(X))
3515 #define MASK_ULONG(X)    (X)
3516
3517 static struct type void_type   = { .type  = TYPE_VOID };
3518 static struct type char_type   = { .type  = TYPE_CHAR };
3519 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3520 static struct type short_type  = { .type  = TYPE_SHORT };
3521 static struct type ushort_type = { .type  = TYPE_USHORT };
3522 static struct type int_type    = { .type  = TYPE_INT };
3523 static struct type uint_type   = { .type  = TYPE_UINT };
3524 static struct type long_type   = { .type  = TYPE_LONG };
3525 static struct type ulong_type  = { .type  = TYPE_ULONG };
3526
3527 static struct triple *variable(struct compile_state *state, struct type *type)
3528 {
3529         struct triple *result;
3530         if ((type->type & STOR_MASK) != STOR_PERM) {
3531                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3532                         result = triple(state, OP_ADECL, type, 0, 0);
3533                 } else {
3534                         struct type *field;
3535                         struct triple **vector;
3536                         ulong_t index;
3537                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3538                         vector = &result->param[0];
3539
3540                         field = type->left;
3541                         index = 0;
3542                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3543                                 vector[index] = variable(state, field->left);
3544                                 field = field->right;
3545                                 index++;
3546                         }
3547                         vector[index] = variable(state, field);
3548                 }
3549         }
3550         else {
3551                 result = triple(state, OP_SDECL, type, 0, 0);
3552         }
3553         return result;
3554 }
3555
3556 static void stor_of(FILE *fp, struct type *type)
3557 {
3558         switch(type->type & STOR_MASK) {
3559         case STOR_AUTO:
3560                 fprintf(fp, "auto ");
3561                 break;
3562         case STOR_STATIC:
3563                 fprintf(fp, "static ");
3564                 break;
3565         case STOR_EXTERN:
3566                 fprintf(fp, "extern ");
3567                 break;
3568         case STOR_REGISTER:
3569                 fprintf(fp, "register ");
3570                 break;
3571         case STOR_TYPEDEF:
3572                 fprintf(fp, "typedef ");
3573                 break;
3574         case STOR_INLINE:
3575                 fprintf(fp, "inline ");
3576                 break;
3577         }
3578 }
3579 static void qual_of(FILE *fp, struct type *type)
3580 {
3581         if (type->type & QUAL_CONST) {
3582                 fprintf(fp, " const");
3583         }
3584         if (type->type & QUAL_VOLATILE) {
3585                 fprintf(fp, " volatile");
3586         }
3587         if (type->type & QUAL_RESTRICT) {
3588                 fprintf(fp, " restrict");
3589         }
3590 }
3591
3592 static void name_of(FILE *fp, struct type *type)
3593 {
3594         stor_of(fp, type);
3595         switch(type->type & TYPE_MASK) {
3596         case TYPE_VOID:
3597                 fprintf(fp, "void");
3598                 qual_of(fp, type);
3599                 break;
3600         case TYPE_CHAR:
3601                 fprintf(fp, "signed char");
3602                 qual_of(fp, type);
3603                 break;
3604         case TYPE_UCHAR:
3605                 fprintf(fp, "unsigned char");
3606                 qual_of(fp, type);
3607                 break;
3608         case TYPE_SHORT:
3609                 fprintf(fp, "signed short");
3610                 qual_of(fp, type);
3611                 break;
3612         case TYPE_USHORT:
3613                 fprintf(fp, "unsigned short");
3614                 qual_of(fp, type);
3615                 break;
3616         case TYPE_INT:
3617                 fprintf(fp, "signed int");
3618                 qual_of(fp, type);
3619                 break;
3620         case TYPE_UINT:
3621                 fprintf(fp, "unsigned int");
3622                 qual_of(fp, type);
3623                 break;
3624         case TYPE_LONG:
3625                 fprintf(fp, "signed long");
3626                 qual_of(fp, type);
3627                 break;
3628         case TYPE_ULONG:
3629                 fprintf(fp, "unsigned long");
3630                 qual_of(fp, type);
3631                 break;
3632         case TYPE_POINTER:
3633                 name_of(fp, type->left);
3634                 fprintf(fp, " * ");
3635                 qual_of(fp, type);
3636                 break;
3637         case TYPE_PRODUCT:
3638         case TYPE_OVERLAP:
3639                 name_of(fp, type->left);
3640                 fprintf(fp, ", ");
3641                 name_of(fp, type->right);
3642                 break;
3643         case TYPE_ENUM:
3644                 fprintf(fp, "enum %s", type->type_ident->name);
3645                 qual_of(fp, type);
3646                 break;
3647         case TYPE_STRUCT:
3648                 fprintf(fp, "struct %s", type->type_ident->name);
3649                 qual_of(fp, type);
3650                 break;
3651         case TYPE_FUNCTION:
3652         {
3653                 name_of(fp, type->left);
3654                 fprintf(fp, " (*)(");
3655                 name_of(fp, type->right);
3656                 fprintf(fp, ")");
3657                 break;
3658         }
3659         case TYPE_ARRAY:
3660                 name_of(fp, type->left);
3661                 fprintf(fp, " [%ld]", type->elements);
3662                 break;
3663         default:
3664                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3665                 break;
3666         }
3667 }
3668
3669 static size_t align_of(struct compile_state *state, struct type *type)
3670 {
3671         size_t align;
3672         align = 0;
3673         switch(type->type & TYPE_MASK) {
3674         case TYPE_VOID:
3675                 align = 1;
3676                 break;
3677         case TYPE_CHAR:
3678         case TYPE_UCHAR:
3679                 align = 1;
3680                 break;
3681         case TYPE_SHORT:
3682         case TYPE_USHORT:
3683                 align = ALIGNOF_SHORT;
3684                 break;
3685         case TYPE_INT:
3686         case TYPE_UINT:
3687         case TYPE_ENUM:
3688                 align = ALIGNOF_INT;
3689                 break;
3690         case TYPE_LONG:
3691         case TYPE_ULONG:
3692         case TYPE_POINTER:
3693                 align = ALIGNOF_LONG;
3694                 break;
3695         case TYPE_PRODUCT:
3696         case TYPE_OVERLAP:
3697         {
3698                 size_t left_align, right_align;
3699                 left_align  = align_of(state, type->left);
3700                 right_align = align_of(state, type->right);
3701                 align = (left_align >= right_align) ? left_align : right_align;
3702                 break;
3703         }
3704         case TYPE_ARRAY:
3705                 align = align_of(state, type->left);
3706                 break;
3707         case TYPE_STRUCT:
3708                 align = align_of(state, type->left);
3709                 break;
3710         default:
3711                 error(state, 0, "alignof not yet defined for type\n");
3712                 break;
3713         }
3714         return align;
3715 }
3716
3717 static size_t size_of(struct compile_state *state, struct type *type)
3718 {
3719         size_t size;
3720         size = 0;
3721         switch(type->type & TYPE_MASK) {
3722         case TYPE_VOID:
3723                 size = 0;
3724                 break;
3725         case TYPE_CHAR:
3726         case TYPE_UCHAR:
3727                 size = 1;
3728                 break;
3729         case TYPE_SHORT:
3730         case TYPE_USHORT:
3731                 size = SIZEOF_SHORT;
3732                 break;
3733         case TYPE_INT:
3734         case TYPE_UINT:
3735         case TYPE_ENUM:
3736                 size = SIZEOF_INT;
3737                 break;
3738         case TYPE_LONG:
3739         case TYPE_ULONG:
3740         case TYPE_POINTER:
3741                 size = SIZEOF_LONG;
3742                 break;
3743         case TYPE_PRODUCT:
3744         {
3745                 size_t align, pad;
3746                 size = size_of(state, type->left);
3747                 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3748                         type = type->right;
3749                         align = align_of(state, type->left);
3750                         pad = align - (size % align);
3751                         size = size + pad + size_of(state, type->left);
3752                 }
3753                 align = align_of(state, type->right);
3754                 pad = align - (size % align);
3755                 size = size + pad + sizeof(type->right);
3756                 break;
3757         }
3758         case TYPE_OVERLAP:
3759         {
3760                 size_t size_left, size_right;
3761                 size_left = size_of(state, type->left);
3762                 size_right = size_of(state, type->right);
3763                 size = (size_left >= size_right)? size_left : size_right;
3764                 break;
3765         }
3766         case TYPE_ARRAY:
3767                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3768                         internal_error(state, 0, "Invalid array type");
3769                 } else {
3770                         size = size_of(state, type->left) * type->elements;
3771                 }
3772                 break;
3773         case TYPE_STRUCT:
3774                 size = size_of(state, type->left);
3775                 break;
3776         default:
3777                 error(state, 0, "sizeof not yet defined for type\n");
3778                 break;
3779         }
3780         return size;
3781 }
3782
3783 static size_t field_offset(struct compile_state *state, 
3784         struct type *type, struct hash_entry *field)
3785 {
3786         size_t size, align, pad;
3787         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3788                 internal_error(state, 0, "field_offset only works on structures");
3789         }
3790         size = 0;
3791         type = type->left;
3792         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3793                 if (type->left->field_ident == field) {
3794                         type = type->left;
3795                 }
3796                 size += size_of(state, type->left);
3797                 type = type->right;
3798                 align = align_of(state, type->left);
3799                 pad = align - (size % align);
3800                 size += pad;
3801         }
3802         if (type->field_ident != field) {
3803                 internal_error(state, 0, "field_offset: member %s not present",
3804                         field->name);
3805         }
3806         return size;
3807 }
3808
3809 static struct type *field_type(struct compile_state *state, 
3810         struct type *type, struct hash_entry *field)
3811 {
3812         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3813                 internal_error(state, 0, "field_type only works on structures");
3814         }
3815         type = type->left;
3816         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3817                 if (type->left->field_ident == field) {
3818                         type = type->left;
3819                         break;
3820                 }
3821                 type = type->right;
3822         }
3823         if (type->field_ident != field) {
3824                 internal_error(state, 0, "field_type: member %s not present", 
3825                         field->name);
3826         }
3827         return type;
3828 }
3829
3830 static struct triple *struct_field(struct compile_state *state,
3831         struct triple *decl, struct hash_entry *field)
3832 {
3833         struct triple **vector;
3834         struct type *type;
3835         ulong_t index;
3836         type = decl->type;
3837         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3838                 return decl;
3839         }
3840         if (decl->op != OP_VAL_VEC) {
3841                 internal_error(state, 0, "Invalid struct variable");
3842         }
3843         if (!field) {
3844                 internal_error(state, 0, "Missing structure field");
3845         }
3846         type = type->left;
3847         vector = &RHS(decl, 0);
3848         index = 0;
3849         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3850                 if (type->left->field_ident == field) {
3851                         type = type->left;
3852                         break;
3853                 }
3854                 index += 1;
3855                 type = type->right;
3856         }
3857         if (type->field_ident != field) {
3858                 internal_error(state, 0, "field %s not found?", field->name);
3859         }
3860         return vector[index];
3861 }
3862
3863 static void arrays_complete(struct compile_state *state, struct type *type)
3864 {
3865         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3866                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3867                         error(state, 0, "array size not specified");
3868                 }
3869                 arrays_complete(state, type->left);
3870         }
3871 }
3872
3873 static unsigned int do_integral_promotion(unsigned int type)
3874 {
3875         type &= TYPE_MASK;
3876         if (TYPE_INTEGER(type) && 
3877                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3878                 type = TYPE_INT;
3879         }
3880         return type;
3881 }
3882
3883 static unsigned int do_arithmetic_conversion(
3884         unsigned int left, unsigned int right)
3885 {
3886         left &= TYPE_MASK;
3887         right &= TYPE_MASK;
3888         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3889                 return TYPE_LDOUBLE;
3890         }
3891         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3892                 return TYPE_DOUBLE;
3893         }
3894         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3895                 return TYPE_FLOAT;
3896         }
3897         left = do_integral_promotion(left);
3898         right = do_integral_promotion(right);
3899         /* If both operands have the same size done */
3900         if (left == right) {
3901                 return left;
3902         }
3903         /* If both operands have the same signedness pick the larger */
3904         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3905                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3906         }
3907         /* If the signed type can hold everything use it */
3908         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3909                 return left;
3910         }
3911         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3912                 return right;
3913         }
3914         /* Convert to the unsigned type with the same rank as the signed type */
3915         else if (TYPE_SIGNED(left)) {
3916                 return TYPE_MKUNSIGNED(left);
3917         }
3918         else {
3919                 return TYPE_MKUNSIGNED(right);
3920         }
3921 }
3922
3923 /* see if two types are the same except for qualifiers */
3924 static int equiv_types(struct type *left, struct type *right)
3925 {
3926         unsigned int type;
3927         /* Error if the basic types do not match */
3928         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3929                 return 0;
3930         }
3931         type = left->type & TYPE_MASK;
3932         /* if the basic types match and it is an arithmetic type we are done */
3933         if (TYPE_ARITHMETIC(type)) {
3934                 return 1;
3935         }
3936         /* If it is a pointer type recurse and keep testing */
3937         if (type == TYPE_POINTER) {
3938                 return equiv_types(left->left, right->left);
3939         }
3940         else if (type == TYPE_ARRAY) {
3941                 return (left->elements == right->elements) &&
3942                         equiv_types(left->left, right->left);
3943         }
3944         /* test for struct/union equality */
3945         else if (type == TYPE_STRUCT) {
3946                 return left->type_ident == right->type_ident;
3947         }
3948         /* Test for equivalent functions */
3949         else if (type == TYPE_FUNCTION) {
3950                 return equiv_types(left->left, right->left) &&
3951                         equiv_types(left->right, right->right);
3952         }
3953         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3954         else if (type == TYPE_PRODUCT) {
3955                 return equiv_types(left->left, right->left) &&
3956                         equiv_types(left->right, right->right);
3957         }
3958         /* We should see TYPE_OVERLAP */
3959         else {
3960                 return 0;
3961         }
3962 }
3963
3964 static int equiv_ptrs(struct type *left, struct type *right)
3965 {
3966         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3967                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3968                 return 0;
3969         }
3970         return equiv_types(left->left, right->left);
3971 }
3972
3973 static struct type *compatible_types(struct type *left, struct type *right)
3974 {
3975         struct type *result;
3976         unsigned int type, qual_type;
3977         /* Error if the basic types do not match */
3978         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3979                 return 0;
3980         }
3981         type = left->type & TYPE_MASK;
3982         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3983         result = 0;
3984         /* if the basic types match and it is an arithmetic type we are done */
3985         if (TYPE_ARITHMETIC(type)) {
3986                 result = new_type(qual_type, 0, 0);
3987         }
3988         /* If it is a pointer type recurse and keep testing */
3989         else if (type == TYPE_POINTER) {
3990                 result = compatible_types(left->left, right->left);
3991                 if (result) {
3992                         result = new_type(qual_type, result, 0);
3993                 }
3994         }
3995         /* test for struct/union equality */
3996         else if (type == TYPE_STRUCT) {
3997                 if (left->type_ident == right->type_ident) {
3998                         result = left;
3999                 }
4000         }
4001         /* Test for equivalent functions */
4002         else if (type == TYPE_FUNCTION) {
4003                 struct type *lf, *rf;
4004                 lf = compatible_types(left->left, right->left);
4005                 rf = compatible_types(left->right, right->right);
4006                 if (lf && rf) {
4007                         result = new_type(qual_type, lf, rf);
4008                 }
4009         }
4010         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4011         else if (type == TYPE_PRODUCT) {
4012                 struct type *lf, *rf;
4013                 lf = compatible_types(left->left, right->left);
4014                 rf = compatible_types(left->right, right->right);
4015                 if (lf && rf) {
4016                         result = new_type(qual_type, lf, rf);
4017                 }
4018         }
4019         else {
4020                 /* Nothing else is compatible */
4021         }
4022         return result;
4023 }
4024
4025 static struct type *compatible_ptrs(struct type *left, struct type *right)
4026 {
4027         struct type *result;
4028         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4029                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4030                 return 0;
4031         }
4032         result = compatible_types(left->left, right->left);
4033         if (result) {
4034                 unsigned int qual_type;
4035                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4036                 result = new_type(qual_type, result, 0);
4037         }
4038         return result;
4039         
4040 }
4041 static struct triple *integral_promotion(
4042         struct compile_state *state, struct triple *def)
4043 {
4044         struct type *type;
4045         type = def->type;
4046         /* As all operations are carried out in registers
4047          * the values are converted on load I just convert
4048          * logical type of the operand.
4049          */
4050         if (TYPE_INTEGER(type->type)) {
4051                 unsigned int int_type;
4052                 int_type = type->type & ~TYPE_MASK;
4053                 int_type |= do_integral_promotion(type->type);
4054                 if (int_type != type->type) {
4055                         def->type = new_type(int_type, 0, 0);
4056                 }
4057         }
4058         return def;
4059 }
4060
4061
4062 static void arithmetic(struct compile_state *state, struct triple *def)
4063 {
4064         if (!TYPE_ARITHMETIC(def->type->type)) {
4065                 error(state, 0, "arithmetic type expexted");
4066         }
4067 }
4068
4069 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4070 {
4071         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4072                 error(state, def, "pointer or arithmetic type expected");
4073         }
4074 }
4075
4076 static int is_integral(struct triple *ins)
4077 {
4078         return TYPE_INTEGER(ins->type->type);
4079 }
4080
4081 static void integral(struct compile_state *state, struct triple *def)
4082 {
4083         if (!is_integral(def)) {
4084                 error(state, 0, "integral type expected");
4085         }
4086 }
4087
4088
4089 static void bool(struct compile_state *state, struct triple *def)
4090 {
4091         if (!TYPE_ARITHMETIC(def->type->type) &&
4092                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4093                 error(state, 0, "arithmetic or pointer type expected");
4094         }
4095 }
4096
4097 static int is_signed(struct type *type)
4098 {
4099         return !!TYPE_SIGNED(type->type);
4100 }
4101
4102 /* Is this value located in a register otherwise it must be in memory */
4103 static int is_in_reg(struct compile_state *state, struct triple *def)
4104 {
4105         int in_reg;
4106         if (def->op == OP_ADECL) {
4107                 in_reg = 1;
4108         }
4109         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4110                 in_reg = 0;
4111         }
4112         else if (def->op == OP_VAL_VEC) {
4113                 in_reg = is_in_reg(state, RHS(def, 0));
4114         }
4115         else if (def->op == OP_DOT) {
4116                 in_reg = is_in_reg(state, RHS(def, 0));
4117         }
4118         else {
4119                 internal_error(state, 0, "unknown expr storage location");
4120                 in_reg = -1;
4121         }
4122         return in_reg;
4123 }
4124
4125 /* Is this a stable variable location otherwise it must be a temporary */
4126 static int is_stable(struct compile_state *state, struct triple *def)
4127 {
4128         int ret;
4129         ret = 0;
4130         if (!def) {
4131                 return 0;
4132         }
4133         if ((def->op == OP_ADECL) || 
4134                 (def->op == OP_SDECL) || 
4135                 (def->op == OP_DEREF) ||
4136                 (def->op == OP_BLOBCONST)) {
4137                 ret = 1;
4138         }
4139         else if (def->op == OP_DOT) {
4140                 ret = is_stable(state, RHS(def, 0));
4141         }
4142         else if (def->op == OP_VAL_VEC) {
4143                 struct triple **vector;
4144                 ulong_t i;
4145                 ret = 1;
4146                 vector = &RHS(def, 0);
4147                 for(i = 0; i < def->type->elements; i++) {
4148                         if (!is_stable(state, vector[i])) {
4149                                 ret = 0;
4150                                 break;
4151                         }
4152                 }
4153         }
4154         return ret;
4155 }
4156
4157 static int is_lvalue(struct compile_state *state, struct triple *def)
4158 {
4159         int ret;
4160         ret = 1;
4161         if (!def) {
4162                 return 0;
4163         }
4164         if (!is_stable(state, def)) {
4165                 return 0;
4166         }
4167         if (def->type->type & QUAL_CONST) {
4168                 ret = 0;
4169         }
4170         else if (def->op == OP_DOT) {
4171                 ret = is_lvalue(state, RHS(def, 0));
4172         }
4173         return ret;
4174 }
4175
4176 static void lvalue(struct compile_state *state, struct triple *def)
4177 {
4178         if (!def) {
4179                 internal_error(state, def, "nothing where lvalue expected?");
4180         }
4181         if (!is_lvalue(state, def)) { 
4182                 error(state, def, "lvalue expected");
4183         }
4184 }
4185
4186 static int is_pointer(struct triple *def)
4187 {
4188         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4189 }
4190
4191 static void pointer(struct compile_state *state, struct triple *def)
4192 {
4193         if (!is_pointer(def)) {
4194                 error(state, def, "pointer expected");
4195         }
4196 }
4197
4198 static struct triple *int_const(
4199         struct compile_state *state, struct type *type, ulong_t value)
4200 {
4201         struct triple *result;
4202         switch(type->type & TYPE_MASK) {
4203         case TYPE_CHAR:
4204         case TYPE_INT:   case TYPE_UINT:
4205         case TYPE_LONG:  case TYPE_ULONG:
4206                 break;
4207         default:
4208                 internal_error(state, 0, "constant for unkown type");
4209         }
4210         result = triple(state, OP_INTCONST, type, 0, 0);
4211         result->u.cval = value;
4212         return result;
4213 }
4214
4215
4216 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4217         struct triple *expr, struct type *type, ulong_t offset)
4218 {
4219         struct triple *result;
4220         lvalue(state, expr);
4221
4222         result = 0;
4223         if (expr->op == OP_ADECL) {
4224                 error(state, expr, "address of auto variables not supported");
4225         }
4226         else if (expr->op == OP_SDECL) {
4227                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4228                 MISC(result, 0) = expr;
4229                 result->u.cval = offset;
4230         }
4231         else if (expr->op == OP_DEREF) {
4232                 result = triple(state, OP_ADD, type,
4233                         RHS(expr, 0),
4234                         int_const(state, &ulong_type, offset));
4235         }
4236         return result;
4237 }
4238
4239 static struct triple *mk_addr_expr(
4240         struct compile_state *state, struct triple *expr, ulong_t offset)
4241 {
4242         struct type *type;
4243         
4244         type = new_type(
4245                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4246                 expr->type, 0);
4247
4248         return do_mk_addr_expr(state, expr, type, offset);
4249 }
4250
4251 static struct triple *mk_deref_expr(
4252         struct compile_state *state, struct triple *expr)
4253 {
4254         struct type *base_type;
4255         pointer(state, expr);
4256         base_type = expr->type->left;
4257         if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4258                 error(state, 0, 
4259                         "Only pointer and arithmetic values can be dereferenced");
4260         }
4261         return triple(state, OP_DEREF, base_type, expr, 0);
4262 }
4263
4264 static struct triple *deref_field(
4265         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4266 {
4267         struct triple *result;
4268         struct type *type, *member;
4269         if (!field) {
4270                 internal_error(state, 0, "No field passed to deref_field");
4271         }
4272         result = 0;
4273         type = expr->type;
4274         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4275                 error(state, 0, "request for member %s in something not a struct or union",
4276                         field->name);
4277         }
4278         member = type->left;
4279         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4280                 if (member->left->field_ident == field) {
4281                         member = member->left;
4282                         break;
4283                 }
4284                 member = member->right;
4285         }
4286         if (member->field_ident != field) {
4287                 error(state, 0, "%s is not a member", field->name);
4288         }
4289         if ((type->type & STOR_MASK) == STOR_PERM) {
4290                 /* Do the pointer arithmetic to get a deref the field */
4291                 ulong_t offset;
4292                 offset = field_offset(state, type, field);
4293                 result = do_mk_addr_expr(state, expr, member, offset);
4294                 result = mk_deref_expr(state, result);
4295         }
4296         else {
4297                 /* Find the variable for the field I want. */
4298                 result = triple(state, OP_DOT, 
4299                         field_type(state, type, field), expr, 0);
4300                 result->u.field = field;
4301         }
4302         return result;
4303 }
4304
4305 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4306 {
4307         int op;
4308         if  (!def) {
4309                 return 0;
4310         }
4311         if (!is_stable(state, def)) {
4312                 return def;
4313         }
4314         /* Tranform an array to a pointer to the first element */
4315 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4316         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4317                 struct type *type;
4318                 struct triple *result;
4319                 type = new_type(
4320                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4321                         def->type->left, 0);
4322                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4323                 MISC(result, 0) = def;
4324                 return result;
4325         }
4326         if (is_in_reg(state, def)) {
4327                 op = OP_READ;
4328         } else {
4329                 op = OP_LOAD;
4330         }
4331         return triple(state, op, def->type, def, 0);
4332 }
4333
4334 static void write_compatible(struct compile_state *state,
4335         struct type *dest, struct type *rval)
4336 {
4337         int compatible = 0;
4338         /* Both operands have arithmetic type */
4339         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4340                 compatible = 1;
4341         }
4342         /* One operand is a pointer and the other is a pointer to void */
4343         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4344                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4345                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4346                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4347                 compatible = 1;
4348         }
4349         /* If both types are the same without qualifiers we are good */
4350         else if (equiv_ptrs(dest, rval)) {
4351                 compatible = 1;
4352         }
4353         /* test for struct/union equality  */
4354         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4355                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4356                 (dest->type_ident == rval->type_ident)) {
4357                 compatible = 1;
4358         }
4359         if (!compatible) {
4360                 error(state, 0, "Incompatible types in assignment");
4361         }
4362 }
4363
4364 static struct triple *write_expr(
4365         struct compile_state *state, struct triple *dest, struct triple *rval)
4366 {
4367         struct triple *def;
4368         int op;
4369
4370         def = 0;
4371         if (!rval) {
4372                 internal_error(state, 0, "missing rval");
4373         }
4374
4375         if (rval->op == OP_LIST) {
4376                 internal_error(state, 0, "expression of type OP_LIST?");
4377         }
4378         if (!is_lvalue(state, dest)) {
4379                 internal_error(state, 0, "writing to a non lvalue?");
4380         }
4381
4382         write_compatible(state, dest->type, rval->type);
4383
4384         /* Now figure out which assignment operator to use */
4385         op = -1;
4386         if (is_in_reg(state, dest)) {
4387                 op = OP_WRITE;
4388         } else {
4389                 op = OP_STORE;
4390         }
4391         def = triple(state, op, dest->type, dest, rval);
4392         return def;
4393 }
4394
4395 static struct triple *init_expr(
4396         struct compile_state *state, struct triple *dest, struct triple *rval)
4397 {
4398         struct triple *def;
4399
4400         def = 0;
4401         if (!rval) {
4402                 internal_error(state, 0, "missing rval");
4403         }
4404         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4405                 rval = read_expr(state, rval);
4406                 def = write_expr(state, dest, rval);
4407         }
4408         else {
4409                 /* Fill in the array size if necessary */
4410                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4411                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4412                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4413                                 dest->type->elements = rval->type->elements;
4414                         }
4415                 }
4416                 if (!equiv_types(dest->type, rval->type)) {
4417                         error(state, 0, "Incompatible types in inializer");
4418                 }
4419                 MISC(dest, 0) = rval;
4420                 insert_triple(state, dest, rval);
4421                 rval->id |= TRIPLE_FLAG_FLATTENED;
4422                 use_triple(MISC(dest, 0), dest);
4423         }
4424         return def;
4425 }
4426
4427 struct type *arithmetic_result(
4428         struct compile_state *state, struct triple *left, struct triple *right)
4429 {
4430         struct type *type;
4431         /* Sanity checks to ensure I am working with arithmetic types */
4432         arithmetic(state, left);
4433         arithmetic(state, right);
4434         type = new_type(
4435                 do_arithmetic_conversion(
4436                         left->type->type, 
4437                         right->type->type), 0, 0);
4438         return type;
4439 }
4440
4441 struct type *ptr_arithmetic_result(
4442         struct compile_state *state, struct triple *left, struct triple *right)
4443 {
4444         struct type *type;
4445         /* Sanity checks to ensure I am working with the proper types */
4446         ptr_arithmetic(state, left);
4447         arithmetic(state, right);
4448         if (TYPE_ARITHMETIC(left->type->type) && 
4449                 TYPE_ARITHMETIC(right->type->type)) {
4450                 type = arithmetic_result(state, left, right);
4451         }
4452         else if (TYPE_PTR(left->type->type)) {
4453                 type = left->type;
4454         }
4455         else {
4456                 internal_error(state, 0, "huh?");
4457                 type = 0;
4458         }
4459         return type;
4460 }
4461
4462
4463 /* boolean helper function */
4464
4465 static struct triple *ltrue_expr(struct compile_state *state, 
4466         struct triple *expr)
4467 {
4468         switch(expr->op) {
4469         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4470         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4471         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4472                 /* If the expression is already boolean do nothing */
4473                 break;
4474         default:
4475                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4476                 break;
4477         }
4478         return expr;
4479 }
4480
4481 static struct triple *lfalse_expr(struct compile_state *state, 
4482         struct triple *expr)
4483 {
4484         return triple(state, OP_LFALSE, &int_type, expr, 0);
4485 }
4486
4487 static struct triple *cond_expr(
4488         struct compile_state *state, 
4489         struct triple *test, struct triple *left, struct triple *right)
4490 {
4491         struct triple *def;
4492         struct type *result_type;
4493         unsigned int left_type, right_type;
4494         bool(state, test);
4495         left_type = left->type->type;
4496         right_type = right->type->type;
4497         result_type = 0;
4498         /* Both operands have arithmetic type */
4499         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4500                 result_type = arithmetic_result(state, left, right);
4501         }
4502         /* Both operands have void type */
4503         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4504                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4505                 result_type = &void_type;
4506         }
4507         /* pointers to the same type... */
4508         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4509                 ;
4510         }
4511         /* Both operands are pointers and left is a pointer to void */
4512         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4513                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4514                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4515                 result_type = right->type;
4516         }
4517         /* Both operands are pointers and right is a pointer to void */
4518         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4519                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4520                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4521                 result_type = left->type;
4522         }
4523         if (!result_type) {
4524                 error(state, 0, "Incompatible types in conditional expression");
4525         }
4526         /* Cleanup and invert the test */
4527         test = lfalse_expr(state, read_expr(state, test));
4528         def = new_triple(state, OP_COND, result_type, 0, 3);
4529         def->param[0] = test;
4530         def->param[1] = left;
4531         def->param[2] = right;
4532         return def;
4533 }
4534
4535
4536 static int expr_depth(struct compile_state *state, struct triple *ins)
4537 {
4538         int count;
4539         count = 0;
4540         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4541                 count = 0;
4542         }
4543         else if (ins->op == OP_DEREF) {
4544                 count = expr_depth(state, RHS(ins, 0)) - 1;
4545         }
4546         else if (ins->op == OP_VAL) {
4547                 count = expr_depth(state, RHS(ins, 0)) - 1;
4548         }
4549         else if (ins->op == OP_COMMA) {
4550                 int ldepth, rdepth;
4551                 ldepth = expr_depth(state, RHS(ins, 0));
4552                 rdepth = expr_depth(state, RHS(ins, 1));
4553                 count = (ldepth >= rdepth)? ldepth : rdepth;
4554         }
4555         else if (ins->op == OP_CALL) {
4556                 /* Don't figure the depth of a call just guess it is huge */
4557                 count = 1000;
4558         }
4559         else {
4560                 struct triple **expr;
4561                 expr = triple_rhs(state, ins, 0);
4562                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4563                         if (*expr) {
4564                                 int depth;
4565                                 depth = expr_depth(state, *expr);
4566                                 if (depth > count) {
4567                                         count = depth;
4568                                 }
4569                         }
4570                 }
4571         }
4572         return count + 1;
4573 }
4574
4575 static struct triple *flatten(
4576         struct compile_state *state, struct triple *first, struct triple *ptr);
4577
4578 static struct triple *flatten_generic(
4579         struct compile_state *state, struct triple *first, struct triple *ptr)
4580 {
4581         struct rhs_vector {
4582                 int depth;
4583                 struct triple **ins;
4584         } vector[MAX_RHS];
4585         int i, rhs, lhs;
4586         /* Only operations with just a rhs should come here */
4587         rhs = TRIPLE_RHS(ptr->sizes);
4588         lhs = TRIPLE_LHS(ptr->sizes);
4589         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4590                 internal_error(state, ptr, "unexpected args for: %d %s",
4591                         ptr->op, tops(ptr->op));
4592         }
4593         /* Find the depth of the rhs elements */
4594         for(i = 0; i < rhs; i++) {
4595                 vector[i].ins = &RHS(ptr, i);
4596                 vector[i].depth = expr_depth(state, *vector[i].ins);
4597         }
4598         /* Selection sort the rhs */
4599         for(i = 0; i < rhs; i++) {
4600                 int j, max = i;
4601                 for(j = i + 1; j < rhs; j++ ) {
4602                         if (vector[j].depth > vector[max].depth) {
4603                                 max = j;
4604                         }
4605                 }
4606                 if (max != i) {
4607                         struct rhs_vector tmp;
4608                         tmp = vector[i];
4609                         vector[i] = vector[max];
4610                         vector[max] = tmp;
4611                 }
4612         }
4613         /* Now flatten the rhs elements */
4614         for(i = 0; i < rhs; i++) {
4615                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4616                 use_triple(*vector[i].ins, ptr);
4617         }
4618         
4619         /* Now flatten the lhs elements */
4620         for(i = 0; i < lhs; i++) {
4621                 struct triple **ins = &LHS(ptr, i);
4622                 *ins = flatten(state, first, *ins);
4623                 use_triple(*ins, ptr);
4624         }
4625         return ptr;
4626 }
4627
4628 static struct triple *flatten_land(
4629         struct compile_state *state, struct triple *first, struct triple *ptr)
4630 {
4631         struct triple *left, *right;
4632         struct triple *val, *test, *jmp, *label1, *end;
4633
4634         /* Find the triples */
4635         left = RHS(ptr, 0);
4636         right = RHS(ptr, 1);
4637
4638         /* Generate the needed triples */
4639         end = label(state);
4640
4641         /* Thread the triples together */
4642         val          = flatten(state, first, variable(state, ptr->type));
4643         left         = flatten(state, first, write_expr(state, val, left));
4644         test         = flatten(state, first, 
4645                 lfalse_expr(state, read_expr(state, val)));
4646         jmp          = flatten(state, first, branch(state, end, test));
4647         label1       = flatten(state, first, label(state));
4648         right        = flatten(state, first, write_expr(state, val, right));
4649         TARG(jmp, 0) = flatten(state, first, end); 
4650         
4651         /* Now give the caller something to chew on */
4652         return read_expr(state, val);
4653 }
4654
4655 static struct triple *flatten_lor(
4656         struct compile_state *state, struct triple *first, struct triple *ptr)
4657 {
4658         struct triple *left, *right;
4659         struct triple *val, *jmp, *label1, *end;
4660
4661         /* Find the triples */
4662         left = RHS(ptr, 0);
4663         right = RHS(ptr, 1);
4664
4665         /* Generate the needed triples */
4666         end = label(state);
4667
4668         /* Thread the triples together */
4669         val          = flatten(state, first, variable(state, ptr->type));
4670         left         = flatten(state, first, write_expr(state, val, left));
4671         jmp          = flatten(state, first, branch(state, end, left));
4672         label1       = flatten(state, first, label(state));
4673         right        = flatten(state, first, write_expr(state, val, right));
4674         TARG(jmp, 0) = flatten(state, first, end);
4675        
4676         
4677         /* Now give the caller something to chew on */
4678         return read_expr(state, val);
4679 }
4680
4681 static struct triple *flatten_cond(
4682         struct compile_state *state, struct triple *first, struct triple *ptr)
4683 {
4684         struct triple *test, *left, *right;
4685         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4686
4687         /* Find the triples */
4688         test = RHS(ptr, 0);
4689         left = RHS(ptr, 1);
4690         right = RHS(ptr, 2);
4691
4692         /* Generate the needed triples */
4693         end = label(state);
4694         middle = label(state);
4695
4696         /* Thread the triples together */
4697         val           = flatten(state, first, variable(state, ptr->type));
4698         test          = flatten(state, first, test);
4699         jmp1          = flatten(state, first, branch(state, middle, test));
4700         label1        = flatten(state, first, label(state));
4701         left          = flatten(state, first, left);
4702         mv1           = flatten(state, first, write_expr(state, val, left));
4703         jmp2          = flatten(state, first, branch(state, end, 0));
4704         TARG(jmp1, 0) = flatten(state, first, middle);
4705         right         = flatten(state, first, right);
4706         mv2           = flatten(state, first, write_expr(state, val, right));
4707         TARG(jmp2, 0) = flatten(state, first, end);
4708         
4709         /* Now give the caller something to chew on */
4710         return read_expr(state, val);
4711 }
4712
4713 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4714 {
4715         struct triple *nfunc;
4716         struct triple *nfirst, *ofirst;
4717         struct triple *new, *old;
4718
4719 #if 0
4720         fprintf(stdout, "\n");
4721         loc(stdout, state, 0);
4722         fprintf(stdout, "\n__________ copy_func _________\n");
4723         print_triple(state, ofunc);
4724         fprintf(stdout, "__________ copy_func _________ done\n\n");
4725 #endif
4726
4727         /* Make a new copy of the old function */
4728         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4729         nfirst = 0;
4730         ofirst = old = RHS(ofunc, 0);
4731         do {
4732                 struct triple *new;
4733                 int old_lhs, old_rhs;
4734                 old_lhs = TRIPLE_LHS(old->sizes);
4735                 old_rhs = TRIPLE_RHS(old->sizes);
4736                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4737                         old->filename, old->line, old->col);
4738                 if (!triple_stores_block(state, new)) {
4739                         memcpy(&new->u, &old->u, sizeof(new->u));
4740                 }
4741                 if (!nfirst) {
4742                         RHS(nfunc, 0) = nfirst = new;
4743                 }
4744                 else {
4745                         insert_triple(state, nfirst, new);
4746                 }
4747                 new->id |= TRIPLE_FLAG_FLATTENED;
4748                 
4749                 /* During the copy remember new as user of old */
4750                 use_triple(old, new);
4751
4752                 /* Populate the return type if present */
4753                 if (old == MISC(ofunc, 0)) {
4754                         MISC(nfunc, 0) = new;
4755                 }
4756                 old = old->next;
4757         } while(old != ofirst);
4758
4759         /* Make a second pass to fix up any unresolved references */
4760         old = ofirst;
4761         new = nfirst;
4762         do {
4763                 struct triple **oexpr, **nexpr;
4764                 int count, i;
4765                 /* Lookup where the copy is, to join pointers */
4766                 count = TRIPLE_SIZE(old->sizes);
4767                 for(i = 0; i < count; i++) {
4768                         oexpr = &old->param[i];
4769                         nexpr = &new->param[i];
4770                         if (!*nexpr && *oexpr && (*oexpr)->use) {
4771                                 *nexpr = (*oexpr)->use->member;
4772                                 if (*nexpr == old) {
4773                                         internal_error(state, 0, "new == old?");
4774                                 }
4775                                 use_triple(*nexpr, new);
4776                         }
4777                         if (!*nexpr && *oexpr) {
4778                                 internal_error(state, 0, "Could not copy %d\n", i);
4779                         }
4780                 }
4781                 old = old->next;
4782                 new = new->next;
4783         } while((old != ofirst) && (new != nfirst));
4784         
4785         /* Make a third pass to cleanup the extra useses */
4786         old = ofirst;
4787         new = nfirst;
4788         do {
4789                 unuse_triple(old, new);
4790                 old = old->next;
4791                 new = new->next;
4792         } while ((old != ofirst) && (new != nfirst));
4793         return nfunc;
4794 }
4795
4796 static struct triple *flatten_call(
4797         struct compile_state *state, struct triple *first, struct triple *ptr)
4798 {
4799         /* Inline the function call */
4800         struct type *ptype;
4801         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4802         struct triple *end, *nend;
4803         int pvals, i;
4804
4805         /* Find the triples */
4806         ofunc = MISC(ptr, 0);
4807         if (ofunc->op != OP_LIST) {
4808                 internal_error(state, 0, "improper function");
4809         }
4810         nfunc = copy_func(state, ofunc);
4811         nfirst = RHS(nfunc, 0)->next;
4812         /* Prepend the parameter reading into the new function list */
4813         ptype = nfunc->type->right;
4814         param = RHS(nfunc, 0)->next;
4815         pvals = TRIPLE_RHS(ptr->sizes);
4816         for(i = 0; i < pvals; i++) {
4817                 struct type *atype;
4818                 struct triple *arg;
4819                 atype = ptype;
4820                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4821                         atype = ptype->left;
4822                 }
4823                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4824                         param = param->next;
4825                 }
4826                 arg = RHS(ptr, i);
4827                 flatten(state, nfirst, write_expr(state, param, arg));
4828                 ptype = ptype->right;
4829                 param = param->next;
4830         }
4831         result = 0;
4832         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4833                 result = read_expr(state, MISC(nfunc,0));
4834         }
4835 #if 0
4836         fprintf(stdout, "\n");
4837         loc(stdout, state, 0);
4838         fprintf(stdout, "\n__________ flatten_call _________\n");
4839         print_triple(state, nfunc);
4840         fprintf(stdout, "__________ flatten_call _________ done\n\n");
4841 #endif
4842
4843         /* Get rid of the extra triples */
4844         nfirst = RHS(nfunc, 0)->next;
4845         free_triple(state, RHS(nfunc, 0));
4846         RHS(nfunc, 0) = 0;
4847         free_triple(state, nfunc);
4848
4849         /* Append the new function list onto the return list */
4850         end = first->prev;
4851         nend = nfirst->prev;
4852         end->next    = nfirst;
4853         nfirst->prev = end;
4854         nend->next   = first;
4855         first->prev  = nend;
4856
4857         return result;
4858 }
4859
4860 static struct triple *flatten(
4861         struct compile_state *state, struct triple *first, struct triple *ptr)
4862 {
4863         struct triple *orig_ptr;
4864         if (!ptr)
4865                 return 0;
4866         do {
4867                 orig_ptr = ptr;
4868                 /* Only flatten triples once */
4869                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4870                         return ptr;
4871                 }
4872                 switch(ptr->op) {
4873                 case OP_WRITE:
4874                 case OP_STORE:
4875                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4876                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4877                         use_triple(LHS(ptr, 0), ptr);
4878                         use_triple(RHS(ptr, 0), ptr);
4879                         break;
4880                 case OP_COMMA:
4881                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4882                         ptr = RHS(ptr, 1);
4883                         break;
4884                 case OP_VAL:
4885                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4886                         return MISC(ptr, 0);
4887                         break;
4888                 case OP_LAND:
4889                         ptr = flatten_land(state, first, ptr);
4890                         break;
4891                 case OP_LOR:
4892                         ptr = flatten_lor(state, first, ptr);
4893                         break;
4894                 case OP_COND:
4895                         ptr = flatten_cond(state, first, ptr);
4896                         break;
4897                 case OP_CALL:
4898                         ptr = flatten_call(state, first, ptr);
4899                         break;
4900                 case OP_READ:
4901                 case OP_LOAD:
4902                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4903                         use_triple(RHS(ptr, 0), ptr);
4904                         break;
4905                 case OP_BRANCH:
4906                         use_triple(TARG(ptr, 0), ptr);
4907                         if (TRIPLE_RHS(ptr->sizes)) {
4908                                 use_triple(RHS(ptr, 0), ptr);
4909                                 if (ptr->next != ptr) {
4910                                         use_triple(ptr->next, ptr);
4911                                 }
4912                         }
4913                         break;
4914                 case OP_BLOBCONST:
4915                         insert_triple(state, first, ptr);
4916                         ptr->id |= TRIPLE_FLAG_FLATTENED;
4917                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4918                         use_triple(MISC(ptr, 0), ptr);
4919                         break;
4920                 case OP_DEREF:
4921                         /* Since OP_DEREF is just a marker delete it when I flatten it */
4922                         ptr = RHS(ptr, 0);
4923                         RHS(orig_ptr, 0) = 0;
4924                         free_triple(state, orig_ptr);
4925                         break;
4926                 case OP_DOT:
4927                 {
4928                         struct triple *base;
4929                         base = RHS(ptr, 0);
4930                         base = flatten(state, first, base);
4931                         if (base->op == OP_VAL_VEC) {
4932                                 ptr = struct_field(state, base, ptr->u.field);
4933                         }
4934                         break;
4935                 }
4936                 case OP_PIECE:
4937                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4938                         use_triple(MISC(ptr, 0), ptr);
4939                         use_triple(ptr, MISC(ptr, 0));
4940                         break;
4941                 case OP_ADDRCONST:
4942                 case OP_SDECL:
4943                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4944                         use_triple(MISC(ptr, 0), ptr);
4945                         break;
4946                 case OP_ADECL:
4947                         break;
4948                 default:
4949                         /* Flatten the easy cases we don't override */
4950                         ptr = flatten_generic(state, first, ptr);
4951                         break;
4952                 }
4953         } while(ptr && (ptr != orig_ptr));
4954         if (ptr) {
4955                 insert_triple(state, first, ptr);
4956                 ptr->id |= TRIPLE_FLAG_FLATTENED;
4957         }
4958         return ptr;
4959 }
4960
4961 static void release_expr(struct compile_state *state, struct triple *expr)
4962 {
4963         struct triple *head;
4964         head = label(state);
4965         flatten(state, head, expr);
4966         while(head->next != head) {
4967                 release_triple(state, head->next);
4968         }
4969         free_triple(state, head);
4970 }
4971
4972 static int replace_rhs_use(struct compile_state *state,
4973         struct triple *orig, struct triple *new, struct triple *use)
4974 {
4975         struct triple **expr;
4976         int found;
4977         found = 0;
4978         expr = triple_rhs(state, use, 0);
4979         for(;expr; expr = triple_rhs(state, use, expr)) {
4980                 if (*expr == orig) {
4981                         *expr = new;
4982                         found = 1;
4983                 }
4984         }
4985         if (found) {
4986                 unuse_triple(orig, use);
4987                 use_triple(new, use);
4988         }
4989         return found;
4990 }
4991
4992 static int replace_lhs_use(struct compile_state *state,
4993         struct triple *orig, struct triple *new, struct triple *use)
4994 {
4995         struct triple **expr;
4996         int found;
4997         found = 0;
4998         expr = triple_lhs(state, use, 0);
4999         for(;expr; expr = triple_lhs(state, use, expr)) {
5000                 if (*expr == orig) {
5001                         *expr = new;
5002                         found = 1;
5003                 }
5004         }
5005         if (found) {
5006                 unuse_triple(orig, use);
5007                 use_triple(new, use);
5008         }
5009         return found;
5010 }
5011
5012 static void propogate_use(struct compile_state *state,
5013         struct triple *orig, struct triple *new)
5014 {
5015         struct triple_set *user, *next;
5016         for(user = orig->use; user; user = next) {
5017                 struct triple *use;
5018                 int found;
5019                 next = user->next;
5020                 use = user->member;
5021                 found = 0;
5022                 found |= replace_rhs_use(state, orig, new, use);
5023                 found |= replace_lhs_use(state, orig, new, use);
5024                 if (!found) {
5025                         internal_error(state, use, "use without use");
5026                 }
5027         }
5028         if (orig->use) {
5029                 internal_error(state, orig, "used after propogate_use");
5030         }
5031 }
5032
5033 /*
5034  * Code generators
5035  * ===========================
5036  */
5037
5038 static struct triple *mk_add_expr(
5039         struct compile_state *state, struct triple *left, struct triple *right)
5040 {
5041         struct type *result_type;
5042         /* Put pointer operands on the left */
5043         if (is_pointer(right)) {
5044                 struct triple *tmp;
5045                 tmp = left;
5046                 left = right;
5047                 right = tmp;
5048         }
5049         left  = read_expr(state, left);
5050         right = read_expr(state, right);
5051         result_type = ptr_arithmetic_result(state, left, right);
5052         if (is_pointer(left)) {
5053                 right = triple(state, 
5054                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5055                         &ulong_type, 
5056                         right, 
5057                         int_const(state, &ulong_type, 
5058                                 size_of(state, left->type->left)));
5059         }
5060         return triple(state, OP_ADD, result_type, left, right);
5061 }
5062
5063 static struct triple *mk_sub_expr(
5064         struct compile_state *state, struct triple *left, struct triple *right)
5065 {
5066         struct type *result_type;
5067         result_type = ptr_arithmetic_result(state, left, right);
5068         left  = read_expr(state, left);
5069         right = read_expr(state, right);
5070         if (is_pointer(left)) {
5071                 right = triple(state, 
5072                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5073                         &ulong_type, 
5074                         right, 
5075                         int_const(state, &ulong_type, 
5076                                 size_of(state, left->type->left)));
5077         }
5078         return triple(state, OP_SUB, result_type, left, right);
5079 }
5080
5081 static struct triple *mk_pre_inc_expr(
5082         struct compile_state *state, struct triple *def)
5083 {
5084         struct triple *val;
5085         lvalue(state, def);
5086         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5087         return triple(state, OP_VAL, def->type,
5088                 write_expr(state, def, val),
5089                 val);
5090 }
5091
5092 static struct triple *mk_pre_dec_expr(
5093         struct compile_state *state, struct triple *def)
5094 {
5095         struct triple *val;
5096         lvalue(state, def);
5097         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5098         return triple(state, OP_VAL, def->type,
5099                 write_expr(state, def, val),
5100                 val);
5101 }
5102
5103 static struct triple *mk_post_inc_expr(
5104         struct compile_state *state, struct triple *def)
5105 {
5106         struct triple *val;
5107         lvalue(state, def);
5108         val = read_expr(state, def);
5109         return triple(state, OP_VAL, def->type,
5110                 write_expr(state, def,
5111                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5112                 , val);
5113 }
5114
5115 static struct triple *mk_post_dec_expr(
5116         struct compile_state *state, struct triple *def)
5117 {
5118         struct triple *val;
5119         lvalue(state, def);
5120         val = read_expr(state, def);
5121         return triple(state, OP_VAL, def->type, 
5122                 write_expr(state, def,
5123                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5124                 , val);
5125 }
5126
5127 static struct triple *mk_subscript_expr(
5128         struct compile_state *state, struct triple *left, struct triple *right)
5129 {
5130         left  = read_expr(state, left);
5131         right = read_expr(state, right);
5132         if (!is_pointer(left) && !is_pointer(right)) {
5133                 error(state, left, "subscripted value is not a pointer");
5134         }
5135         return mk_deref_expr(state, mk_add_expr(state, left, right));
5136 }
5137
5138 /*
5139  * Compile time evaluation
5140  * ===========================
5141  */
5142 static int is_const(struct triple *ins)
5143 {
5144         return IS_CONST_OP(ins->op);
5145 }
5146
5147 static int constants_equal(struct compile_state *state, 
5148         struct triple *left, struct triple *right)
5149 {
5150         int equal;
5151         if (!is_const(left) || !is_const(right)) {
5152                 equal = 0;
5153         }
5154         else if (left->op != right->op) {
5155                 equal = 0;
5156         }
5157         else if (!equiv_types(left->type, right->type)) {
5158                 equal = 0;
5159         }
5160         else {
5161                 equal = 0;
5162                 switch(left->op) {
5163                 case OP_INTCONST:
5164                         if (left->u.cval == right->u.cval) {
5165                                 equal = 1;
5166                         }
5167                         break;
5168                 case OP_BLOBCONST:
5169                 {
5170                         size_t lsize, rsize;
5171                         lsize = size_of(state, left->type);
5172                         rsize = size_of(state, right->type);
5173                         if (lsize != rsize) {
5174                                 break;
5175                         }
5176                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5177                                 equal = 1;
5178                         }
5179                         break;
5180                 }
5181                 case OP_ADDRCONST:
5182                         if ((MISC(left, 0) == MISC(right, 0)) &&
5183                                 (left->u.cval == right->u.cval)) {
5184                                 equal = 1;
5185                         }
5186                         break;
5187                 default:
5188                         internal_error(state, left, "uknown constant type");
5189                         break;
5190                 }
5191         }
5192         return equal;
5193 }
5194
5195 static int is_zero(struct triple *ins)
5196 {
5197         return is_const(ins) && (ins->u.cval == 0);
5198 }
5199
5200 static int is_one(struct triple *ins)
5201 {
5202         return is_const(ins) && (ins->u.cval == 1);
5203 }
5204
5205 static long_t bsr(ulong_t value)
5206 {
5207         int i;
5208         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5209                 ulong_t mask;
5210                 mask = 1;
5211                 mask <<= i;
5212                 if (value & mask) {
5213                         return i;
5214                 }
5215         }
5216         return -1;
5217 }
5218
5219 static long_t bsf(ulong_t value)
5220 {
5221         int i;
5222         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5223                 ulong_t mask;
5224                 mask = 1;
5225                 mask <<= 1;
5226                 if (value & mask) {
5227                         return i;
5228                 }
5229         }
5230         return -1;
5231 }
5232
5233 static long_t log2(ulong_t value)
5234 {
5235         return bsr(value);
5236 }
5237
5238 static long_t tlog2(struct triple *ins)
5239 {
5240         return log2(ins->u.cval);
5241 }
5242
5243 static int is_pow2(struct triple *ins)
5244 {
5245         ulong_t value, mask;
5246         long_t log;
5247         if (!is_const(ins)) {
5248                 return 0;
5249         }
5250         value = ins->u.cval;
5251         log = log2(value);
5252         if (log == -1) {
5253                 return 0;
5254         }
5255         mask = 1;
5256         mask <<= log;
5257         return  ((value & mask) == value);
5258 }
5259
5260 static ulong_t read_const(struct compile_state *state,
5261         struct triple *ins, struct triple **expr)
5262 {
5263         struct triple *rhs;
5264         rhs = *expr;
5265         switch(rhs->type->type &TYPE_MASK) {
5266         case TYPE_CHAR:   
5267         case TYPE_SHORT:
5268         case TYPE_INT:
5269         case TYPE_LONG:
5270         case TYPE_UCHAR:   
5271         case TYPE_USHORT:  
5272         case TYPE_UINT:
5273         case TYPE_ULONG:
5274         case TYPE_POINTER:
5275                 break;
5276         default:
5277                 internal_error(state, rhs, "bad type to read_const\n");
5278                 break;
5279         }
5280         return rhs->u.cval;
5281 }
5282
5283 static long_t read_sconst(struct triple *ins, struct triple **expr)
5284 {
5285         struct triple *rhs;
5286         rhs = *expr;
5287         return (long_t)(rhs->u.cval);
5288 }
5289
5290 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5291 {
5292         struct triple **expr;
5293         expr = triple_rhs(state, ins, 0);
5294         for(;expr;expr = triple_rhs(state, ins, expr)) {
5295                 if (*expr) {
5296                         unuse_triple(*expr, ins);
5297                         *expr = 0;
5298                 }
5299         }
5300 }
5301
5302 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5303 {
5304         struct triple **expr;
5305         expr = triple_lhs(state, ins, 0);
5306         for(;expr;expr = triple_lhs(state, ins, expr)) {
5307                 unuse_triple(*expr, ins);
5308                 *expr = 0;
5309         }
5310 }
5311
5312 static void check_lhs(struct compile_state *state, struct triple *ins)
5313 {
5314         struct triple **expr;
5315         expr = triple_lhs(state, ins, 0);
5316         for(;expr;expr = triple_lhs(state, ins, expr)) {
5317                 internal_error(state, ins, "unexpected lhs");
5318         }
5319         
5320 }
5321 static void check_targ(struct compile_state *state, struct triple *ins)
5322 {
5323         struct triple **expr;
5324         expr = triple_targ(state, ins, 0);
5325         for(;expr;expr = triple_targ(state, ins, expr)) {
5326                 internal_error(state, ins, "unexpected targ");
5327         }
5328 }
5329
5330 static void wipe_ins(struct compile_state *state, struct triple *ins)
5331 {
5332         /* Becareful which instructions you replace the wiped
5333          * instruction with, as there are not enough slots
5334          * in all instructions to hold all others.
5335          */
5336         check_targ(state, ins);
5337         unuse_rhs(state, ins);
5338         unuse_lhs(state, ins);
5339 }
5340
5341 static void mkcopy(struct compile_state *state, 
5342         struct triple *ins, struct triple *rhs)
5343 {
5344         wipe_ins(state, ins);
5345         ins->op = OP_COPY;
5346         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5347         RHS(ins, 0) = rhs;
5348         use_triple(RHS(ins, 0), ins);
5349 }
5350
5351 static void mkconst(struct compile_state *state, 
5352         struct triple *ins, ulong_t value)
5353 {
5354         if (!is_integral(ins) && !is_pointer(ins)) {
5355                 internal_error(state, ins, "unknown type to make constant\n");
5356         }
5357         wipe_ins(state, ins);
5358         ins->op = OP_INTCONST;
5359         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5360         ins->u.cval = value;
5361 }
5362
5363 static void mkaddr_const(struct compile_state *state,
5364         struct triple *ins, struct triple *sdecl, ulong_t value)
5365 {
5366         wipe_ins(state, ins);
5367         ins->op = OP_ADDRCONST;
5368         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5369         MISC(ins, 0) = sdecl;
5370         ins->u.cval = value;
5371         use_triple(sdecl, ins);
5372 }
5373
5374 /* Transform multicomponent variables into simple register variables */
5375 static void flatten_structures(struct compile_state *state)
5376 {
5377         struct triple *ins, *first;
5378         first = RHS(state->main_function, 0);
5379         ins = first;
5380         /* Pass one expand structure values into valvecs.
5381          */
5382         ins = first;
5383         do {
5384                 struct triple *next;
5385                 next = ins->next;
5386                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5387                         if (ins->op == OP_VAL_VEC) {
5388                                 /* Do nothing */
5389                         }
5390                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5391                                 struct triple *def, **vector;
5392                                 struct type *tptr;
5393                                 int op;
5394                                 ulong_t i;
5395
5396                                 op = ins->op;
5397                                 def = RHS(ins, 0);
5398                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5399                                         ins->filename, ins->line, ins->col);
5400
5401                                 vector = &RHS(next, 0);
5402                                 tptr = next->type->left;
5403                                 for(i = 0; i < next->type->elements; i++) {
5404                                         struct triple *sfield;
5405                                         struct type *mtype;
5406                                         mtype = tptr;
5407                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5408                                                 mtype = mtype->left;
5409                                         }
5410                                         sfield = deref_field(state, def, mtype->field_ident);
5411                                         
5412                                         vector[i] = triple(
5413                                                 state, op, mtype, sfield, 0);
5414                                         vector[i]->filename = next->filename;
5415                                         vector[i]->line = next->line;
5416                                         vector[i]->col = next->col;
5417                                         tptr = tptr->right;
5418                                 }
5419                                 propogate_use(state, ins, next);
5420                                 flatten(state, ins, next);
5421                                 free_triple(state, ins);
5422                         }
5423                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5424                                 struct triple *src, *dst, **vector;
5425                                 struct type *tptr;
5426                                 int op;
5427                                 ulong_t i;
5428
5429                                 op = ins->op;
5430                                 src = RHS(ins, 0);
5431                                 dst = LHS(ins, 0);
5432                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5433                                         ins->filename, ins->line, ins->col);
5434                                 
5435                                 vector = &RHS(next, 0);
5436                                 tptr = next->type->left;
5437                                 for(i = 0; i < ins->type->elements; i++) {
5438                                         struct triple *dfield, *sfield;
5439                                         struct type *mtype;
5440                                         mtype = tptr;
5441                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5442                                                 mtype = mtype->left;
5443                                         }
5444                                         sfield = deref_field(state, src, mtype->field_ident);
5445                                         dfield = deref_field(state, dst, mtype->field_ident);
5446                                         vector[i] = triple(
5447                                                 state, op, mtype, dfield, sfield);
5448                                         vector[i]->filename = next->filename;
5449                                         vector[i]->line = next->line;
5450                                         vector[i]->col = next->col;
5451                                         tptr = tptr->right;
5452                                 }
5453                                 propogate_use(state, ins, next);
5454                                 flatten(state, ins, next);
5455                                 free_triple(state, ins);
5456                         }
5457                 }
5458                 ins = next;
5459         } while(ins != first);
5460         /* Pass two flatten the valvecs.
5461          */
5462         ins = first;
5463         do {
5464                 struct triple *next;
5465                 next = ins->next;
5466                 if (ins->op == OP_VAL_VEC) {
5467                         release_triple(state, ins);
5468                 } 
5469                 ins = next;
5470         } while(ins != first);
5471         /* Pass three verify the state and set ->id to 0.
5472          */
5473         ins = first;
5474         do {
5475                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5476                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5477                         internal_error(state, 0, "STRUCT_TYPE remains?");
5478                 }
5479                 if (ins->op == OP_DOT) {
5480                         internal_error(state, 0, "OP_DOT remains?");
5481                 }
5482                 if (ins->op == OP_VAL_VEC) {
5483                         internal_error(state, 0, "OP_VAL_VEC remains?");
5484                 }
5485                 ins = ins->next;
5486         } while(ins != first);
5487 }
5488
5489 /* For those operations that cannot be simplified */
5490 static void simplify_noop(struct compile_state *state, struct triple *ins)
5491 {
5492         return;
5493 }
5494
5495 static void simplify_smul(struct compile_state *state, struct triple *ins)
5496 {
5497         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5498                 struct triple *tmp;
5499                 tmp = RHS(ins, 0);
5500                 RHS(ins, 0) = RHS(ins, 1);
5501                 RHS(ins, 1) = tmp;
5502         }
5503         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5504                 long_t left, right;
5505                 left  = read_sconst(ins, &RHS(ins, 0));
5506                 right = read_sconst(ins, &RHS(ins, 1));
5507                 mkconst(state, ins, left * right);
5508         }
5509         else if (is_zero(RHS(ins, 1))) {
5510                 mkconst(state, ins, 0);
5511         }
5512         else if (is_one(RHS(ins, 1))) {
5513                 mkcopy(state, ins, RHS(ins, 0));
5514         }
5515         else if (is_pow2(RHS(ins, 1))) {
5516                 struct triple *val;
5517                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5518                 ins->op = OP_SL;
5519                 insert_triple(state, ins, val);
5520                 unuse_triple(RHS(ins, 1), ins);
5521                 use_triple(val, ins);
5522                 RHS(ins, 1) = val;
5523         }
5524 }
5525
5526 static void simplify_umul(struct compile_state *state, struct triple *ins)
5527 {
5528         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5529                 struct triple *tmp;
5530                 tmp = RHS(ins, 0);
5531                 RHS(ins, 0) = RHS(ins, 1);
5532                 RHS(ins, 1) = tmp;
5533         }
5534         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5535                 ulong_t left, right;
5536                 left  = read_const(state, ins, &RHS(ins, 0));
5537                 right = read_const(state, ins, &RHS(ins, 1));
5538                 mkconst(state, ins, left * right);
5539         }
5540         else if (is_zero(RHS(ins, 1))) {
5541                 mkconst(state, ins, 0);
5542         }
5543         else if (is_one(RHS(ins, 1))) {
5544                 mkcopy(state, ins, RHS(ins, 0));
5545         }
5546         else if (is_pow2(RHS(ins, 1))) {
5547                 struct triple *val;
5548                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5549                 ins->op = OP_SL;
5550                 insert_triple(state, ins, val);
5551                 unuse_triple(RHS(ins, 1), ins);
5552                 use_triple(val, ins);
5553                 RHS(ins, 1) = val;
5554         }
5555 }
5556
5557 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5558 {
5559         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5560                 long_t left, right;
5561                 left  = read_sconst(ins, &RHS(ins, 0));
5562                 right = read_sconst(ins, &RHS(ins, 1));
5563                 mkconst(state, ins, left / right);
5564         }
5565         else if (is_zero(RHS(ins, 0))) {
5566                 mkconst(state, ins, 0);
5567         }
5568         else if (is_zero(RHS(ins, 1))) {
5569                 error(state, ins, "division by zero");
5570         }
5571         else if (is_one(RHS(ins, 1))) {
5572                 mkcopy(state, ins, RHS(ins, 0));
5573         }
5574         else if (is_pow2(RHS(ins, 1))) {
5575                 struct triple *val;
5576                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5577                 ins->op = OP_SSR;
5578                 insert_triple(state, ins, val);
5579                 unuse_triple(RHS(ins, 1), ins);
5580                 use_triple(val, ins);
5581                 RHS(ins, 1) = val;
5582         }
5583 }
5584
5585 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5586 {
5587         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5588                 ulong_t left, right;
5589                 left  = read_const(state, ins, &RHS(ins, 0));
5590                 right = read_const(state, ins, &RHS(ins, 1));
5591                 mkconst(state, ins, left / right);
5592         }
5593         else if (is_zero(RHS(ins, 0))) {
5594                 mkconst(state, ins, 0);
5595         }
5596         else if (is_zero(RHS(ins, 1))) {
5597                 error(state, ins, "division by zero");
5598         }
5599         else if (is_one(RHS(ins, 1))) {
5600                 mkcopy(state, ins, RHS(ins, 0));
5601         }
5602         else if (is_pow2(RHS(ins, 1))) {
5603                 struct triple *val;
5604                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5605                 ins->op = OP_USR;
5606                 insert_triple(state, ins, val);
5607                 unuse_triple(RHS(ins, 1), ins);
5608                 use_triple(val, ins);
5609                 RHS(ins, 1) = val;
5610         }
5611 }
5612
5613 static void simplify_smod(struct compile_state *state, struct triple *ins)
5614 {
5615         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5616                 long_t left, right;
5617                 left  = read_const(state, ins, &RHS(ins, 0));
5618                 right = read_const(state, ins, &RHS(ins, 1));
5619                 mkconst(state, ins, left % right);
5620         }
5621         else if (is_zero(RHS(ins, 0))) {
5622                 mkconst(state, ins, 0);
5623         }
5624         else if (is_zero(RHS(ins, 1))) {
5625                 error(state, ins, "division by zero");
5626         }
5627         else if (is_one(RHS(ins, 1))) {
5628                 mkconst(state, ins, 0);
5629         }
5630         else if (is_pow2(RHS(ins, 1))) {
5631                 struct triple *val;
5632                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5633                 ins->op = OP_AND;
5634                 insert_triple(state, ins, val);
5635                 unuse_triple(RHS(ins, 1), ins);
5636                 use_triple(val, ins);
5637                 RHS(ins, 1) = val;
5638         }
5639 }
5640 static void simplify_umod(struct compile_state *state, struct triple *ins)
5641 {
5642         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5643                 ulong_t left, right;
5644                 left  = read_const(state, ins, &RHS(ins, 0));
5645                 right = read_const(state, ins, &RHS(ins, 1));
5646                 mkconst(state, ins, left % right);
5647         }
5648         else if (is_zero(RHS(ins, 0))) {
5649                 mkconst(state, ins, 0);
5650         }
5651         else if (is_zero(RHS(ins, 1))) {
5652                 error(state, ins, "division by zero");
5653         }
5654         else if (is_one(RHS(ins, 1))) {
5655                 mkconst(state, ins, 0);
5656         }
5657         else if (is_pow2(RHS(ins, 1))) {
5658                 struct triple *val;
5659                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5660                 ins->op = OP_AND;
5661                 insert_triple(state, ins, val);
5662                 unuse_triple(RHS(ins, 1), ins);
5663                 use_triple(val, ins);
5664                 RHS(ins, 1) = val;
5665         }
5666 }
5667
5668 static void simplify_add(struct compile_state *state, struct triple *ins)
5669 {
5670         /* start with the pointer on the left */
5671         if (is_pointer(RHS(ins, 1))) {
5672                 struct triple *tmp;
5673                 tmp = RHS(ins, 0);
5674                 RHS(ins, 0) = RHS(ins, 1);
5675                 RHS(ins, 1) = tmp;
5676         }
5677         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5678                 if (!is_pointer(RHS(ins, 0))) {
5679                         ulong_t left, right;
5680                         left  = read_const(state, ins, &RHS(ins, 0));
5681                         right = read_const(state, ins, &RHS(ins, 1));
5682                         mkconst(state, ins, left + right);
5683                 }
5684                 else /* op == OP_ADDRCONST */ {
5685                         struct triple *sdecl;
5686                         ulong_t left, right;
5687                         sdecl = MISC(RHS(ins, 0), 0);
5688                         left  = RHS(ins, 0)->u.cval;
5689                         right = RHS(ins, 1)->u.cval;
5690                         mkaddr_const(state, ins, sdecl, left + right);
5691                 }
5692         }
5693         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5694                 struct triple *tmp;
5695                 tmp = RHS(ins, 1);
5696                 RHS(ins, 1) = RHS(ins, 0);
5697                 RHS(ins, 0) = tmp;
5698         }
5699 }
5700
5701 static void simplify_sub(struct compile_state *state, struct triple *ins)
5702 {
5703         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5704                 if (!is_pointer(RHS(ins, 0))) {
5705                         ulong_t left, right;
5706                         left  = read_const(state, ins, &RHS(ins, 0));
5707                         right = read_const(state, ins, &RHS(ins, 1));
5708                         mkconst(state, ins, left - right);
5709                 }
5710                 else /* op == OP_ADDRCONST */ {
5711                         struct triple *sdecl;
5712                         ulong_t left, right;
5713                         sdecl = MISC(RHS(ins, 0), 0);
5714                         left  = RHS(ins, 0)->u.cval;
5715                         right = RHS(ins, 1)->u.cval;
5716                         mkaddr_const(state, ins, sdecl, left - right);
5717                 }
5718         }
5719 }
5720
5721 static void simplify_sl(struct compile_state *state, struct triple *ins)
5722 {
5723         if (is_const(RHS(ins, 1))) {
5724                 ulong_t right;
5725                 right = read_const(state, ins, &RHS(ins, 1));
5726                 if (right >= (size_of(state, ins->type)*8)) {
5727                         warning(state, ins, "left shift count >= width of type");
5728                 }
5729         }
5730         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5731                 ulong_t left, right;
5732                 left  = read_const(state, ins, &RHS(ins, 0));
5733                 right = read_const(state, ins, &RHS(ins, 1));
5734                 mkconst(state, ins,  left << right);
5735         }
5736 }
5737
5738 static void simplify_usr(struct compile_state *state, struct triple *ins)
5739 {
5740         if (is_const(RHS(ins, 1))) {
5741                 ulong_t right;
5742                 right = read_const(state, ins, &RHS(ins, 1));
5743                 if (right >= (size_of(state, ins->type)*8)) {
5744                         warning(state, ins, "right shift count >= width of type");
5745                 }
5746         }
5747         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5748                 ulong_t left, right;
5749                 left  = read_const(state, ins, &RHS(ins, 0));
5750                 right = read_const(state, ins, &RHS(ins, 1));
5751                 mkconst(state, ins, left >> right);
5752         }
5753 }
5754
5755 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5756 {
5757         if (is_const(RHS(ins, 1))) {
5758                 ulong_t right;
5759                 right = read_const(state, ins, &RHS(ins, 1));
5760                 if (right >= (size_of(state, ins->type)*8)) {
5761                         warning(state, ins, "right shift count >= width of type");
5762                 }
5763         }
5764         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5765                 long_t left, right;
5766                 left  = read_sconst(ins, &RHS(ins, 0));
5767                 right = read_sconst(ins, &RHS(ins, 1));
5768                 mkconst(state, ins, left >> right);
5769         }
5770 }
5771
5772 static void simplify_and(struct compile_state *state, struct triple *ins)
5773 {
5774         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5775                 ulong_t left, right;
5776                 left  = read_const(state, ins, &RHS(ins, 0));
5777                 right = read_const(state, ins, &RHS(ins, 1));
5778                 mkconst(state, ins, left & right);
5779         }
5780 }
5781
5782 static void simplify_or(struct compile_state *state, struct triple *ins)
5783 {
5784         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5785                 ulong_t left, right;
5786                 left  = read_const(state, ins, &RHS(ins, 0));
5787                 right = read_const(state, ins, &RHS(ins, 1));
5788                 mkconst(state, ins, left | right);
5789         }
5790 }
5791
5792 static void simplify_xor(struct compile_state *state, struct triple *ins)
5793 {
5794         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5795                 ulong_t left, right;
5796                 left  = read_const(state, ins, &RHS(ins, 0));
5797                 right = read_const(state, ins, &RHS(ins, 1));
5798                 mkconst(state, ins, left ^ right);
5799         }
5800 }
5801
5802 static void simplify_pos(struct compile_state *state, struct triple *ins)
5803 {
5804         if (is_const(RHS(ins, 0))) {
5805                 mkconst(state, ins, RHS(ins, 0)->u.cval);
5806         }
5807         else {
5808                 mkcopy(state, ins, RHS(ins, 0));
5809         }
5810 }
5811
5812 static void simplify_neg(struct compile_state *state, struct triple *ins)
5813 {
5814         if (is_const(RHS(ins, 0))) {
5815                 ulong_t left;
5816                 left = read_const(state, ins, &RHS(ins, 0));
5817                 mkconst(state, ins, -left);
5818         }
5819         else if (RHS(ins, 0)->op == OP_NEG) {
5820                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5821         }
5822 }
5823
5824 static void simplify_invert(struct compile_state *state, struct triple *ins)
5825 {
5826         if (is_const(RHS(ins, 0))) {
5827                 ulong_t left;
5828                 left = read_const(state, ins, &RHS(ins, 0));
5829                 mkconst(state, ins, ~left);
5830         }
5831 }
5832
5833 static void simplify_eq(struct compile_state *state, struct triple *ins)
5834 {
5835         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5836                 ulong_t left, right;
5837                 left  = read_const(state, ins, &RHS(ins, 0));
5838                 right = read_const(state, ins, &RHS(ins, 1));
5839                 mkconst(state, ins, left == right);
5840         }
5841         else if (RHS(ins, 0) == RHS(ins, 1)) {
5842                 mkconst(state, ins, 1);
5843         }
5844 }
5845
5846 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5847 {
5848         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5849                 ulong_t left, right;
5850                 left  = read_const(state, ins, &RHS(ins, 0));
5851                 right = read_const(state, ins, &RHS(ins, 1));
5852                 mkconst(state, ins, left != right);
5853         }
5854         else if (RHS(ins, 0) == RHS(ins, 1)) {
5855                 mkconst(state, ins, 0);
5856         }
5857 }
5858
5859 static void simplify_sless(struct compile_state *state, struct triple *ins)
5860 {
5861         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5862                 long_t left, right;
5863                 left  = read_sconst(ins, &RHS(ins, 0));
5864                 right = read_sconst(ins, &RHS(ins, 1));
5865                 mkconst(state, ins, left < right);
5866         }
5867         else if (RHS(ins, 0) == RHS(ins, 1)) {
5868                 mkconst(state, ins, 0);
5869         }
5870 }
5871
5872 static void simplify_uless(struct compile_state *state, struct triple *ins)
5873 {
5874         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5875                 ulong_t left, right;
5876                 left  = read_const(state, ins, &RHS(ins, 0));
5877                 right = read_const(state, ins, &RHS(ins, 1));
5878                 mkconst(state, ins, left < right);
5879         }
5880         else if (is_zero(RHS(ins, 0))) {
5881                 mkconst(state, ins, 1);
5882         }
5883         else if (RHS(ins, 0) == RHS(ins, 1)) {
5884                 mkconst(state, ins, 0);
5885         }
5886 }
5887
5888 static void simplify_smore(struct compile_state *state, struct triple *ins)
5889 {
5890         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5891                 long_t left, right;
5892                 left  = read_sconst(ins, &RHS(ins, 0));
5893                 right = read_sconst(ins, &RHS(ins, 1));
5894                 mkconst(state, ins, left > right);
5895         }
5896         else if (RHS(ins, 0) == RHS(ins, 1)) {
5897                 mkconst(state, ins, 0);
5898         }
5899 }
5900
5901 static void simplify_umore(struct compile_state *state, struct triple *ins)
5902 {
5903         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5904                 ulong_t left, right;
5905                 left  = read_const(state, ins, &RHS(ins, 0));
5906                 right = read_const(state, ins, &RHS(ins, 1));
5907                 mkconst(state, ins, left > right);
5908         }
5909         else if (is_zero(RHS(ins, 1))) {
5910                 mkconst(state, ins, 1);
5911         }
5912         else if (RHS(ins, 0) == RHS(ins, 1)) {
5913                 mkconst(state, ins, 0);
5914         }
5915 }
5916
5917
5918 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5919 {
5920         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5921                 long_t left, right;
5922                 left  = read_sconst(ins, &RHS(ins, 0));
5923                 right = read_sconst(ins, &RHS(ins, 1));
5924                 mkconst(state, ins, left <= right);
5925         }
5926         else if (RHS(ins, 0) == RHS(ins, 1)) {
5927                 mkconst(state, ins, 1);
5928         }
5929 }
5930
5931 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5932 {
5933         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5934                 ulong_t left, right;
5935                 left  = read_const(state, ins, &RHS(ins, 0));
5936                 right = read_const(state, ins, &RHS(ins, 1));
5937                 mkconst(state, ins, left <= right);
5938         }
5939         else if (is_zero(RHS(ins, 0))) {
5940                 mkconst(state, ins, 1);
5941         }
5942         else if (RHS(ins, 0) == RHS(ins, 1)) {
5943                 mkconst(state, ins, 1);
5944         }
5945 }
5946
5947 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5948 {
5949         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5950                 long_t left, right;
5951                 left  = read_sconst(ins, &RHS(ins, 0));
5952                 right = read_sconst(ins, &RHS(ins, 1));
5953                 mkconst(state, ins, left >= right);
5954         }
5955         else if (RHS(ins, 0) == RHS(ins, 1)) {
5956                 mkconst(state, ins, 1);
5957         }
5958 }
5959
5960 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5961 {
5962         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5963                 ulong_t left, right;
5964                 left  = read_const(state, ins, &RHS(ins, 0));
5965                 right = read_const(state, ins, &RHS(ins, 1));
5966                 mkconst(state, ins, left >= right);
5967         }
5968         else if (is_zero(RHS(ins, 1))) {
5969                 mkconst(state, ins, 1);
5970         }
5971         else if (RHS(ins, 0) == RHS(ins, 1)) {
5972                 mkconst(state, ins, 1);
5973         }
5974 }
5975
5976 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5977 {
5978         if (is_const(RHS(ins, 0))) {
5979                 ulong_t left;
5980                 left = read_const(state, ins, &RHS(ins, 0));
5981                 mkconst(state, ins, left == 0);
5982         }
5983         /* Otherwise if I am the only user... */
5984         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5985                 int need_copy = 1;
5986                 /* Invert a boolean operation */
5987                 switch(RHS(ins, 0)->op) {
5988                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
5989                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
5990                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
5991                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
5992                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
5993                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
5994                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
5995                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
5996                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
5997                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
5998                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
5999                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6000                 default:
6001                         need_copy = 0;
6002                         break;
6003                 }
6004                 if (need_copy) {
6005                         mkcopy(state, ins, RHS(ins, 0));
6006                 }
6007         }
6008 }
6009
6010 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6011 {
6012         if (is_const(RHS(ins, 0))) {
6013                 ulong_t left;
6014                 left = read_const(state, ins, &RHS(ins, 0));
6015                 mkconst(state, ins, left != 0);
6016         }
6017         else switch(RHS(ins, 0)->op) {
6018         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6019         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6020         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6021                 mkcopy(state, ins, RHS(ins, 0));
6022         }
6023
6024 }
6025
6026 static void simplify_copy(struct compile_state *state, struct triple *ins)
6027 {
6028         if (is_const(RHS(ins, 0))) {
6029                 switch(RHS(ins, 0)->op) {
6030                 case OP_INTCONST:
6031                 {
6032                         ulong_t left;
6033                         left = read_const(state, ins, &RHS(ins, 0));
6034                         mkconst(state, ins, left);
6035                         break;
6036                 }
6037                 case OP_ADDRCONST:
6038                 {
6039                         struct triple *sdecl;
6040                         ulong_t offset;
6041                         sdecl  = MISC(RHS(ins, 0), 0);
6042                         offset = RHS(ins, 0)->u.cval;
6043                         mkaddr_const(state, ins, sdecl, offset);
6044                         break;
6045                 }
6046                 default:
6047                         internal_error(state, ins, "uknown constant");
6048                         break;
6049                 }
6050         }
6051 }
6052
6053 static void simplify_branch(struct compile_state *state, struct triple *ins)
6054 {
6055         struct block *block;
6056         if (ins->op != OP_BRANCH) {
6057                 internal_error(state, ins, "not branch");
6058         }
6059         if (ins->use != 0) {
6060                 internal_error(state, ins, "branch use");
6061         }
6062 #warning "FIXME implement simplify branch."
6063         /* The challenge here with simplify branch is that I need to 
6064          * make modifications to the control flow graph as well
6065          * as to the branch instruction itself.
6066          */
6067         block = ins->u.block;
6068         
6069         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6070                 struct triple *targ;
6071                 ulong_t value;
6072                 value = read_const(state, ins, &RHS(ins, 0));
6073                 unuse_triple(RHS(ins, 0), ins);
6074                 targ = TARG(ins, 0);
6075                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6076                 if (value) {
6077                         unuse_triple(ins->next, ins);
6078                         TARG(ins, 0) = targ;
6079                 }
6080                 else {
6081                         unuse_triple(targ, ins);
6082                         TARG(ins, 0) = ins->next;
6083                 }
6084 #warning "FIXME handle the case of making a branch unconditional"
6085         }
6086         if (TARG(ins, 0) == ins->next) {
6087                 unuse_triple(ins->next, ins);
6088                 if (TRIPLE_RHS(ins->sizes)) {
6089                         unuse_triple(RHS(ins, 0), ins);
6090                         unuse_triple(ins->next, ins);
6091                 }
6092                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6093                 ins->op = OP_NOOP;
6094                 if (ins->use) {
6095                         internal_error(state, ins, "noop use != 0");
6096                 }
6097 #warning "FIXME handle the case of killing a branch"
6098         }
6099 }
6100
6101 static void simplify_phi(struct compile_state *state, struct triple *ins)
6102 {
6103         struct triple **expr;
6104         ulong_t value;
6105         expr = triple_rhs(state, ins, 0);
6106         if (!*expr || !is_const(*expr)) {
6107                 return;
6108         }
6109         value = read_const(state, ins, expr);
6110         for(;expr;expr = triple_rhs(state, ins, expr)) {
6111                 if (!*expr || !is_const(*expr)) {
6112                         return;
6113                 }
6114                 if (value != read_const(state, ins, expr)) {
6115                         return;
6116                 }
6117         }
6118         mkconst(state, ins, value);
6119 }
6120
6121
6122 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6123 {
6124         if (is_const(RHS(ins, 0))) {
6125                 ulong_t left;
6126                 left = read_const(state, ins, &RHS(ins, 0));
6127                 mkconst(state, ins, bsf(left));
6128         }
6129 }
6130
6131 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6132 {
6133         if (is_const(RHS(ins, 0))) {
6134                 ulong_t left;
6135                 left = read_const(state, ins, &RHS(ins, 0));
6136                 mkconst(state, ins, bsr(left));
6137         }
6138 }
6139
6140
6141 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6142 static const simplify_t table_simplify[] = {
6143 #if 0
6144 #define simplify_smul     simplify_noop
6145 #define simplify_umul     simplify_noop
6146 #define simplify_sdiv     simplify_noop
6147 #define simplify_udiv     simplify_noop
6148 #define simplify_smod     simplify_noop
6149 #define simplify_umod     simplify_noop
6150 #endif
6151 #if 0
6152 #define simplify_add      simplify_noop
6153 #define simplify_sub      simplify_noop
6154 #endif
6155 #if 0
6156 #define simplify_sl       simplify_noop
6157 #define simplify_usr      simplify_noop
6158 #define simplify_ssr      simplify_noop
6159 #endif
6160 #if 0
6161 #define simplify_and      simplify_noop
6162 #define simplify_xor      simplify_noop
6163 #define simplify_or       simplify_noop
6164 #endif
6165 #if 0
6166 #define simplify_pos      simplify_noop
6167 #define simplify_neg      simplify_noop
6168 #define simplify_invert   simplify_noop
6169 #endif
6170
6171 #if 0
6172 #define simplify_eq       simplify_noop
6173 #define simplify_noteq    simplify_noop
6174 #endif
6175 #if 0
6176 #define simplify_sless    simplify_noop
6177 #define simplify_uless    simplify_noop
6178 #define simplify_smore    simplify_noop
6179 #define simplify_umore    simplify_noop
6180 #endif
6181 #if 0
6182 #define simplify_slesseq  simplify_noop
6183 #define simplify_ulesseq  simplify_noop
6184 #define simplify_smoreeq  simplify_noop
6185 #define simplify_umoreeq  simplify_noop
6186 #endif
6187 #if 0
6188 #define simplify_lfalse   simplify_noop
6189 #endif
6190 #if 0
6191 #define simplify_ltrue    simplify_noop
6192 #endif
6193
6194 #if 0
6195 #define simplify_copy     simplify_noop
6196 #endif
6197
6198 #if 0
6199 #define simplify_branch   simplify_noop
6200 #endif
6201
6202 #if 0
6203 #define simplify_phi      simplify_noop
6204 #endif
6205
6206 #if 0
6207 #define simplify_bsf      simplify_noop
6208 #define simplify_bsr      simplify_noop
6209 #endif
6210
6211 [OP_SMUL       ] = simplify_smul,
6212 [OP_UMUL       ] = simplify_umul,
6213 [OP_SDIV       ] = simplify_sdiv,
6214 [OP_UDIV       ] = simplify_udiv,
6215 [OP_SMOD       ] = simplify_smod,
6216 [OP_UMOD       ] = simplify_umod,
6217 [OP_ADD        ] = simplify_add,
6218 [OP_SUB        ] = simplify_sub,
6219 [OP_SL         ] = simplify_sl,
6220 [OP_USR        ] = simplify_usr,
6221 [OP_SSR        ] = simplify_ssr,
6222 [OP_AND        ] = simplify_and,
6223 [OP_XOR        ] = simplify_xor,
6224 [OP_OR         ] = simplify_or,
6225 [OP_POS        ] = simplify_pos,
6226 [OP_NEG        ] = simplify_neg,
6227 [OP_INVERT     ] = simplify_invert,
6228
6229 [OP_EQ         ] = simplify_eq,
6230 [OP_NOTEQ      ] = simplify_noteq,
6231 [OP_SLESS      ] = simplify_sless,
6232 [OP_ULESS      ] = simplify_uless,
6233 [OP_SMORE      ] = simplify_smore,
6234 [OP_UMORE      ] = simplify_umore,
6235 [OP_SLESSEQ    ] = simplify_slesseq,
6236 [OP_ULESSEQ    ] = simplify_ulesseq,
6237 [OP_SMOREEQ    ] = simplify_smoreeq,
6238 [OP_UMOREEQ    ] = simplify_umoreeq,
6239 [OP_LFALSE     ] = simplify_lfalse,
6240 [OP_LTRUE      ] = simplify_ltrue,
6241
6242 [OP_LOAD       ] = simplify_noop,
6243 [OP_STORE      ] = simplify_noop,
6244
6245 [OP_NOOP       ] = simplify_noop,
6246
6247 [OP_INTCONST   ] = simplify_noop,
6248 [OP_BLOBCONST  ] = simplify_noop,
6249 [OP_ADDRCONST  ] = simplify_noop,
6250
6251 [OP_WRITE      ] = simplify_noop,
6252 [OP_READ       ] = simplify_noop,
6253 [OP_COPY       ] = simplify_copy,
6254 [OP_PIECE      ] = simplify_noop,
6255 [OP_ASM        ] = simplify_noop,
6256
6257 [OP_DOT        ] = simplify_noop,
6258 [OP_VAL_VEC    ] = simplify_noop,
6259
6260 [OP_LIST       ] = simplify_noop,
6261 [OP_BRANCH     ] = simplify_branch,
6262 [OP_LABEL      ] = simplify_noop,
6263 [OP_ADECL      ] = simplify_noop,
6264 [OP_SDECL      ] = simplify_noop,
6265 [OP_PHI        ] = simplify_phi,
6266
6267 [OP_INB        ] = simplify_noop,
6268 [OP_INW        ] = simplify_noop,
6269 [OP_INL        ] = simplify_noop,
6270 [OP_OUTB       ] = simplify_noop,
6271 [OP_OUTW       ] = simplify_noop,
6272 [OP_OUTL       ] = simplify_noop,
6273 [OP_BSF        ] = simplify_bsf,
6274 [OP_BSR        ] = simplify_bsr,
6275 [OP_RDMSR      ] = simplify_noop,
6276 [OP_WRMSR      ] = simplify_noop,                    
6277 [OP_HLT        ] = simplify_noop,
6278 };
6279
6280 static void simplify(struct compile_state *state, struct triple *ins)
6281 {
6282         int op;
6283         simplify_t do_simplify;
6284         do {
6285                 op = ins->op;
6286                 do_simplify = 0;
6287                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6288                         do_simplify = 0;
6289                 }
6290                 else {
6291                         do_simplify = table_simplify[op];
6292                 }
6293                 if (!do_simplify) {
6294                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6295                                 op, tops(op));
6296                         return;
6297                 }
6298                 do_simplify(state, ins);
6299         } while(ins->op != op);
6300 }
6301
6302 static void simplify_all(struct compile_state *state)
6303 {
6304         struct triple *ins, *first;
6305         first = RHS(state->main_function, 0);
6306         ins = first;
6307         do {
6308                 simplify(state, ins);
6309                 ins = ins->next;
6310         } while(ins != first);
6311 }
6312
6313 /*
6314  * Builtins....
6315  * ============================
6316  */
6317
6318 static void register_builtin_function(struct compile_state *state,
6319         const char *name, int op, struct type *rtype, ...)
6320 {
6321         struct type *ftype, *atype, *param, **next;
6322         struct triple *def, *arg, *result, *work, *last, *first;
6323         struct hash_entry *ident;
6324         struct file_state file;
6325         int parameters;
6326         int name_len;
6327         va_list args;
6328         int i;
6329
6330         /* Dummy file state to get debug handling right */
6331         memset(&file, 0, sizeof(file));
6332         file.basename = name;
6333         file.line = 1;
6334         file.prev = state->file;
6335         state->file = &file;
6336
6337         /* Find the Parameter count */
6338         valid_op(state, op);
6339         parameters = table_ops[op].rhs;
6340         if (parameters < 0 ) {
6341                 internal_error(state, 0, "Invalid builtin parameter count");
6342         }
6343
6344         /* Find the function type */
6345         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6346         next = &ftype->right;
6347         va_start(args, rtype);
6348         for(i = 0; i < parameters; i++) {
6349                 atype = va_arg(args, struct type *);
6350                 if (!*next) {
6351                         *next = atype;
6352                 } else {
6353                         *next = new_type(TYPE_PRODUCT, *next, atype);
6354                         next = &((*next)->right);
6355                 }
6356         }
6357         if (!*next) {
6358                 *next = &void_type;
6359         }
6360         va_end(args);
6361
6362         /* Generate the needed triples */
6363         def = triple(state, OP_LIST, ftype, 0, 0);
6364         first = label(state);
6365         RHS(def, 0) = first;
6366
6367         /* Now string them together */
6368         param = ftype->right;
6369         for(i = 0; i < parameters; i++) {
6370                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6371                         atype = param->left;
6372                 } else {
6373                         atype = param;
6374                 }
6375                 arg = flatten(state, first, variable(state, atype));
6376                 param = param->right;
6377         }
6378         result = 0;
6379         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6380                 result = flatten(state, first, variable(state, rtype));
6381         }
6382         MISC(def, 0) = result;
6383         work = new_triple(state, op, rtype, -1, parameters);
6384         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6385                 RHS(work, i) = read_expr(state, arg);
6386         }
6387         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6388                 struct triple *val;
6389                 /* Populate the LHS with the target registers */
6390                 work = flatten(state, first, work);
6391                 work->type = &void_type;
6392                 param = rtype->left;
6393                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6394                         internal_error(state, 0, "Invalid result type");
6395                 }
6396                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6397                 for(i = 0; i < rtype->elements; i++) {
6398                         struct triple *piece;
6399                         atype = param;
6400                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6401                                 atype = param->left;
6402                         }
6403                         if (!TYPE_ARITHMETIC(atype->type) &&
6404                                 !TYPE_PTR(atype->type)) {
6405                                 internal_error(state, 0, "Invalid lhs type");
6406                         }
6407                         piece = triple(state, OP_PIECE, atype, work, 0);
6408                         piece->u.cval = i;
6409                         LHS(work, i) = piece;
6410                         RHS(val, i) = piece;
6411                 }
6412                 work = val;
6413         }
6414         if (result) {
6415                 work = write_expr(state, result, work);
6416         }
6417         work = flatten(state, first, work);
6418         last = flatten(state, first, label(state));
6419         name_len = strlen(name);
6420         ident = lookup(state, name, name_len);
6421         symbol(state, ident, &ident->sym_ident, def, ftype);
6422         
6423         state->file = file.prev;
6424 #if 0
6425         fprintf(stdout, "\n");
6426         loc(stdout, state, 0);
6427         fprintf(stdout, "\n__________ builtin_function _________\n");
6428         print_triple(state, def);
6429         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6430 #endif
6431 }
6432
6433 static struct type *partial_struct(struct compile_state *state,
6434         const char *field_name, struct type *type, struct type *rest)
6435 {
6436         struct hash_entry *field_ident;
6437         struct type *result;
6438         int field_name_len;
6439
6440         field_name_len = strlen(field_name);
6441         field_ident = lookup(state, field_name, field_name_len);
6442
6443         result = clone_type(0, type);
6444         result->field_ident = field_ident;
6445
6446         if (rest) {
6447                 result = new_type(TYPE_PRODUCT, result, rest);
6448         }
6449         return result;
6450 }
6451
6452 static struct type *register_builtin_type(struct compile_state *state,
6453         const char *name, struct type *type)
6454 {
6455         struct hash_entry *ident;
6456         int name_len;
6457
6458         name_len = strlen(name);
6459         ident = lookup(state, name, name_len);
6460         
6461         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6462                 ulong_t elements = 0;
6463                 struct type *field;
6464                 type = new_type(TYPE_STRUCT, type, 0);
6465                 field = type->left;
6466                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6467                         elements++;
6468                         field = field->right;
6469                 }
6470                 elements++;
6471                 symbol(state, ident, &ident->sym_struct, 0, type);
6472                 type->type_ident = ident;
6473                 type->elements = elements;
6474         }
6475         symbol(state, ident, &ident->sym_ident, 0, type);
6476         ident->tok = TOK_TYPE_NAME;
6477         return type;
6478 }
6479
6480
6481 static void register_builtins(struct compile_state *state)
6482 {
6483         struct type *msr_type;
6484
6485         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6486                 &ushort_type);
6487         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6488                 &ushort_type);
6489         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6490                 &ushort_type);
6491
6492         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6493                 &uchar_type, &ushort_type);
6494         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6495                 &ushort_type, &ushort_type);
6496         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6497                 &uint_type, &ushort_type);
6498         
6499         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6500                 &int_type);
6501         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6502                 &int_type);
6503
6504         msr_type = register_builtin_type(state, "__builtin_msr_t",
6505                 partial_struct(state, "lo", &ulong_type,
6506                 partial_struct(state, "hi", &ulong_type, 0)));
6507
6508         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6509                 &ulong_type);
6510         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6511                 &ulong_type, &ulong_type, &ulong_type);
6512         
6513         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6514                 &void_type);
6515 }
6516
6517 static struct type *declarator(
6518         struct compile_state *state, struct type *type, 
6519         struct hash_entry **ident, int need_ident);
6520 static void decl(struct compile_state *state, struct triple *first);
6521 static struct type *specifier_qualifier_list(struct compile_state *state);
6522 static int isdecl_specifier(int tok);
6523 static struct type *decl_specifiers(struct compile_state *state);
6524 static int istype(int tok);
6525 static struct triple *expr(struct compile_state *state);
6526 static struct triple *assignment_expr(struct compile_state *state);
6527 static struct type *type_name(struct compile_state *state);
6528 static void statement(struct compile_state *state, struct triple *fist);
6529
6530 static struct triple *call_expr(
6531         struct compile_state *state, struct triple *func)
6532 {
6533         struct triple *def;
6534         struct type *param, *type;
6535         ulong_t pvals, index;
6536
6537         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6538                 error(state, 0, "Called object is not a function");
6539         }
6540         if (func->op != OP_LIST) {
6541                 internal_error(state, 0, "improper function");
6542         }
6543         eat(state, TOK_LPAREN);
6544         /* Find the return type without any specifiers */
6545         type = clone_type(0, func->type->left);
6546         def = new_triple(state, OP_CALL, func->type, -1, -1);
6547         def->type = type;
6548
6549         pvals = TRIPLE_RHS(def->sizes);
6550         MISC(def, 0) = func;
6551
6552         param = func->type->right;
6553         for(index = 0; index < pvals; index++) {
6554                 struct triple *val;
6555                 struct type *arg_type;
6556                 val = read_expr(state, assignment_expr(state));
6557                 arg_type = param;
6558                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6559                         arg_type = param->left;
6560                 }
6561                 write_compatible(state, arg_type, val->type);
6562                 RHS(def, index) = val;
6563                 if (index != (pvals - 1)) {
6564                         eat(state, TOK_COMMA);
6565                         param = param->right;
6566                 }
6567         }
6568         eat(state, TOK_RPAREN);
6569         return def;
6570 }
6571
6572
6573 static struct triple *character_constant(struct compile_state *state)
6574 {
6575         struct triple *def;
6576         struct token *tk;
6577         const signed char *str, *end;
6578         int c;
6579         int str_len;
6580         eat(state, TOK_LIT_CHAR);
6581         tk = &state->token[0];
6582         str = tk->val.str + 1;
6583         str_len = tk->str_len - 2;
6584         if (str_len <= 0) {
6585                 error(state, 0, "empty character constant");
6586         }
6587         end = str + str_len;
6588         c = char_value(state, &str, end);
6589         if (str != end) {
6590                 error(state, 0, "multibyte character constant not supported");
6591         }
6592         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6593         return def;
6594 }
6595
6596 static struct triple *string_constant(struct compile_state *state)
6597 {
6598         struct triple *def;
6599         struct token *tk;
6600         struct type *type;
6601         const signed char *str, *end;
6602         signed char *buf, *ptr;
6603         int str_len;
6604
6605         buf = 0;
6606         type = new_type(TYPE_ARRAY, &char_type, 0);
6607         type->elements = 0;
6608         /* The while loop handles string concatenation */
6609         do {
6610                 eat(state, TOK_LIT_STRING);
6611                 tk = &state->token[0];
6612                 str = tk->val.str + 1;
6613                 str_len = tk->str_len - 2;
6614                 if (str_len < 0) {
6615                         error(state, 0, "negative string constant length");
6616                 }
6617                 end = str + str_len;
6618                 ptr = buf;
6619                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6620                 memcpy(buf, ptr, type->elements);
6621                 ptr = buf + type->elements;
6622                 do {
6623                         *ptr++ = char_value(state, &str, end);
6624                 } while(str < end);
6625                 type->elements = ptr - buf;
6626         } while(peek(state) == TOK_LIT_STRING);
6627         *ptr = '\0';
6628         type->elements += 1;
6629         def = triple(state, OP_BLOBCONST, type, 0, 0);
6630         def->u.blob = buf;
6631         return def;
6632 }
6633
6634
6635 static struct triple *integer_constant(struct compile_state *state)
6636 {
6637         struct triple *def;
6638         unsigned long val;
6639         struct token *tk;
6640         char *end;
6641         int u, l, decimal;
6642         struct type *type;
6643
6644         eat(state, TOK_LIT_INT);
6645         tk = &state->token[0];
6646         errno = 0;
6647         decimal = (tk->val.str[0] != '0');
6648         val = strtoul(tk->val.str, &end, 0);
6649         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6650                 error(state, 0, "Integer constant to large");
6651         }
6652         u = l = 0;
6653         if ((*end == 'u') || (*end == 'U')) {
6654                 u = 1;
6655                         end++;
6656         }
6657         if ((*end == 'l') || (*end == 'L')) {
6658                 l = 1;
6659                 end++;
6660         }
6661         if ((*end == 'u') || (*end == 'U')) {
6662                 u = 1;
6663                 end++;
6664         }
6665         if (*end) {
6666                 error(state, 0, "Junk at end of integer constant");
6667         }
6668         if (u && l)  {
6669                 type = &ulong_type;
6670         }
6671         else if (l) {
6672                 type = &long_type;
6673                 if (!decimal && (val > LONG_MAX)) {
6674                         type = &ulong_type;
6675                 }
6676         }
6677         else if (u) {
6678                 type = &uint_type;
6679                 if (val > UINT_MAX) {
6680                         type = &ulong_type;
6681                 }
6682         }
6683         else {
6684                 type = &int_type;
6685                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6686                         type = &uint_type;
6687                 }
6688                 else if (!decimal && (val > LONG_MAX)) {
6689                         type = &ulong_type;
6690                 }
6691                 else if (val > INT_MAX) {
6692                         type = &long_type;
6693                 }
6694         }
6695         def = int_const(state, type, val);
6696         return def;
6697 }
6698
6699 static struct triple *primary_expr(struct compile_state *state)
6700 {
6701         struct triple *def;
6702         int tok;
6703         tok = peek(state);
6704         switch(tok) {
6705         case TOK_IDENT:
6706         {
6707                 struct hash_entry *ident;
6708                 /* Here ident is either:
6709                  * a varable name
6710                  * a function name
6711                  * an enumeration constant.
6712                  */
6713                 eat(state, TOK_IDENT);
6714                 ident = state->token[0].ident;
6715                 if (!ident->sym_ident) {
6716                         error(state, 0, "%s undeclared", ident->name);
6717                 }
6718                 def = ident->sym_ident->def;
6719                 break;
6720         }
6721         case TOK_ENUM_CONST:
6722                 /* Here ident is an enumeration constant */
6723                 eat(state, TOK_ENUM_CONST);
6724                 def = 0;
6725                 FINISHME();
6726                 break;
6727         case TOK_LPAREN:
6728                 eat(state, TOK_LPAREN);
6729                 def = expr(state);
6730                 eat(state, TOK_RPAREN);
6731                 break;
6732         case TOK_LIT_INT:
6733                 def = integer_constant(state);
6734                 break;
6735         case TOK_LIT_FLOAT:
6736                 eat(state, TOK_LIT_FLOAT);
6737                 error(state, 0, "Floating point constants not supported");
6738                 def = 0;
6739                 FINISHME();
6740                 break;
6741         case TOK_LIT_CHAR:
6742                 def = character_constant(state);
6743                 break;
6744         case TOK_LIT_STRING:
6745                 def = string_constant(state);
6746                 break;
6747         default:
6748                 def = 0;
6749                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6750         }
6751         return def;
6752 }
6753
6754 static struct triple *postfix_expr(struct compile_state *state)
6755 {
6756         struct triple *def;
6757         int postfix;
6758         def = primary_expr(state);
6759         do {
6760                 struct triple *left;
6761                 int tok;
6762                 postfix = 1;
6763                 left = def;
6764                 switch((tok = peek(state))) {
6765                 case TOK_LBRACKET:
6766                         eat(state, TOK_LBRACKET);
6767                         def = mk_subscript_expr(state, left, expr(state));
6768                         eat(state, TOK_RBRACKET);
6769                         break;
6770                 case TOK_LPAREN:
6771                         def = call_expr(state, def);
6772                         break;
6773                 case TOK_DOT:
6774                 {
6775                         struct hash_entry *field;
6776                         eat(state, TOK_DOT);
6777                         eat(state, TOK_IDENT);
6778                         field = state->token[0].ident;
6779                         def = deref_field(state, def, field);
6780                         break;
6781                 }
6782                 case TOK_ARROW:
6783                 {
6784                         struct hash_entry *field;
6785                         eat(state, TOK_ARROW);
6786                         eat(state, TOK_IDENT);
6787                         field = state->token[0].ident;
6788                         def = mk_deref_expr(state, read_expr(state, def));
6789                         def = deref_field(state, def, field);
6790                         break;
6791                 }
6792                 case TOK_PLUSPLUS:
6793                         eat(state, TOK_PLUSPLUS);
6794                         def = mk_post_inc_expr(state, left);
6795                         break;
6796                 case TOK_MINUSMINUS:
6797                         eat(state, TOK_MINUSMINUS);
6798                         def = mk_post_dec_expr(state, left);
6799                         break;
6800                 default:
6801                         postfix = 0;
6802                         break;
6803                 }
6804         } while(postfix);
6805         return def;
6806 }
6807
6808 static struct triple *cast_expr(struct compile_state *state);
6809
6810 static struct triple *unary_expr(struct compile_state *state)
6811 {
6812         struct triple *def, *right;
6813         int tok;
6814         switch((tok = peek(state))) {
6815         case TOK_PLUSPLUS:
6816                 eat(state, TOK_PLUSPLUS);
6817                 def = mk_pre_inc_expr(state, unary_expr(state));
6818                 break;
6819         case TOK_MINUSMINUS:
6820                 eat(state, TOK_MINUSMINUS);
6821                 def = mk_pre_dec_expr(state, unary_expr(state));
6822                 break;
6823         case TOK_AND:
6824                 eat(state, TOK_AND);
6825                 def = mk_addr_expr(state, cast_expr(state), 0);
6826                 break;
6827         case TOK_STAR:
6828                 eat(state, TOK_STAR);
6829                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6830                 break;
6831         case TOK_PLUS:
6832                 eat(state, TOK_PLUS);
6833                 right = read_expr(state, cast_expr(state));
6834                 arithmetic(state, right);
6835                 def = integral_promotion(state, right);
6836                 break;
6837         case TOK_MINUS:
6838                 eat(state, TOK_MINUS);
6839                 right = read_expr(state, cast_expr(state));
6840                 arithmetic(state, right);
6841                 def = integral_promotion(state, right);
6842                 def = triple(state, OP_NEG, def->type, def, 0);
6843                 break;
6844         case TOK_TILDE:
6845                 eat(state, TOK_TILDE);
6846                 right = read_expr(state, cast_expr(state));
6847                 integral(state, right);
6848                 def = integral_promotion(state, right);
6849                 def = triple(state, OP_INVERT, def->type, def, 0);
6850                 break;
6851         case TOK_BANG:
6852                 eat(state, TOK_BANG);
6853                 right = read_expr(state, cast_expr(state));
6854                 bool(state, right);
6855                 def = lfalse_expr(state, right);
6856                 break;
6857         case TOK_SIZEOF:
6858         {
6859                 struct type *type;
6860                 int tok1, tok2;
6861                 eat(state, TOK_SIZEOF);
6862                 tok1 = peek(state);
6863                 tok2 = peek2(state);
6864                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6865                         eat(state, TOK_LPAREN);
6866                         type = type_name(state);
6867                         eat(state, TOK_RPAREN);
6868                 }
6869                 else {
6870                         struct triple *expr;
6871                         expr = unary_expr(state);
6872                         type = expr->type;
6873                         release_expr(state, expr);
6874                 }
6875                 def = int_const(state, &ulong_type, size_of(state, type));
6876                 break;
6877         }
6878         case TOK_ALIGNOF:
6879         {
6880                 struct type *type;
6881                 int tok1, tok2;
6882                 eat(state, TOK_ALIGNOF);
6883                 tok1 = peek(state);
6884                 tok2 = peek2(state);
6885                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6886                         eat(state, TOK_LPAREN);
6887                         type = type_name(state);
6888                         eat(state, TOK_RPAREN);
6889                 }
6890                 else {
6891                         struct triple *expr;
6892                         expr = unary_expr(state);
6893                         type = expr->type;
6894                         release_expr(state, expr);
6895                 }
6896                 def = int_const(state, &ulong_type, align_of(state, type));
6897                 break;
6898         }
6899         default:
6900                 def = postfix_expr(state);
6901                 break;
6902         }
6903         return def;
6904 }
6905
6906 static struct triple *cast_expr(struct compile_state *state)
6907 {
6908         struct triple *def;
6909         int tok1, tok2;
6910         tok1 = peek(state);
6911         tok2 = peek2(state);
6912         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6913                 struct type *type;
6914                 eat(state, TOK_LPAREN);
6915                 type = type_name(state);
6916                 eat(state, TOK_RPAREN);
6917                 def = read_expr(state, cast_expr(state));
6918                 def = triple(state, OP_COPY, type, def, 0);
6919         }
6920         else {
6921                 def = unary_expr(state);
6922         }
6923         return def;
6924 }
6925
6926 static struct triple *mult_expr(struct compile_state *state)
6927 {
6928         struct triple *def;
6929         int done;
6930         def = cast_expr(state);
6931         do {
6932                 struct triple *left, *right;
6933                 struct type *result_type;
6934                 int tok, op, sign;
6935                 done = 0;
6936                 switch(tok = (peek(state))) {
6937                 case TOK_STAR:
6938                 case TOK_DIV:
6939                 case TOK_MOD:
6940                         left = read_expr(state, def);
6941                         arithmetic(state, left);
6942
6943                         eat(state, tok);
6944
6945                         right = read_expr(state, cast_expr(state));
6946                         arithmetic(state, right);
6947
6948                         result_type = arithmetic_result(state, left, right);
6949                         sign = is_signed(result_type);
6950                         op = -1;
6951                         switch(tok) {
6952                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6953                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
6954                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
6955                         }
6956                         def = triple(state, op, result_type, left, right);
6957                         break;
6958                 default:
6959                         done = 1;
6960                         break;
6961                 }
6962         } while(!done);
6963         return def;
6964 }
6965
6966 static struct triple *add_expr(struct compile_state *state)
6967 {
6968         struct triple *def;
6969         int done;
6970         def = mult_expr(state);
6971         do {
6972                 done = 0;
6973                 switch( peek(state)) {
6974                 case TOK_PLUS:
6975                         eat(state, TOK_PLUS);
6976                         def = mk_add_expr(state, def, mult_expr(state));
6977                         break;
6978                 case TOK_MINUS:
6979                         eat(state, TOK_MINUS);
6980                         def = mk_sub_expr(state, def, mult_expr(state));
6981                         break;
6982                 default:
6983                         done = 1;
6984                         break;
6985                 }
6986         } while(!done);
6987         return def;
6988 }
6989
6990 static struct triple *shift_expr(struct compile_state *state)
6991 {
6992         struct triple *def;
6993         int done;
6994         def = add_expr(state);
6995         do {
6996                 struct triple *left, *right;
6997                 int tok, op;
6998                 done = 0;
6999                 switch((tok = peek(state))) {
7000                 case TOK_SL:
7001                 case TOK_SR:
7002                         left = read_expr(state, def);
7003                         integral(state, left);
7004                         left = integral_promotion(state, left);
7005
7006                         eat(state, tok);
7007
7008                         right = read_expr(state, add_expr(state));
7009                         integral(state, right);
7010                         right = integral_promotion(state, right);
7011                         
7012                         op = (tok == TOK_SL)? OP_SL : 
7013                                 is_signed(left->type)? OP_SSR: OP_USR;
7014
7015                         def = triple(state, op, left->type, left, right);
7016                         break;
7017                 default:
7018                         done = 1;
7019                         break;
7020                 }
7021         } while(!done);
7022         return def;
7023 }
7024
7025 static struct triple *relational_expr(struct compile_state *state)
7026 {
7027 #warning "Extend relational exprs to work on more than arithmetic types"
7028         struct triple *def;
7029         int done;
7030         def = shift_expr(state);
7031         do {
7032                 struct triple *left, *right;
7033                 struct type *arg_type;
7034                 int tok, op, sign;
7035                 done = 0;
7036                 switch((tok = peek(state))) {
7037                 case TOK_LESS:
7038                 case TOK_MORE:
7039                 case TOK_LESSEQ:
7040                 case TOK_MOREEQ:
7041                         left = read_expr(state, def);
7042                         arithmetic(state, left);
7043
7044                         eat(state, tok);
7045
7046                         right = read_expr(state, shift_expr(state));
7047                         arithmetic(state, right);
7048
7049                         arg_type = arithmetic_result(state, left, right);
7050                         sign = is_signed(arg_type);
7051                         op = -1;
7052                         switch(tok) {
7053                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7054                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7055                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7056                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7057                         }
7058                         def = triple(state, op, &int_type, left, right);
7059                         break;
7060                 default:
7061                         done = 1;
7062                         break;
7063                 }
7064         } while(!done);
7065         return def;
7066 }
7067
7068 static struct triple *equality_expr(struct compile_state *state)
7069 {
7070 #warning "Extend equality exprs to work on more than arithmetic types"
7071         struct triple *def;
7072         int done;
7073         def = relational_expr(state);
7074         do {
7075                 struct triple *left, *right;
7076                 int tok, op;
7077                 done = 0;
7078                 switch((tok = peek(state))) {
7079                 case TOK_EQEQ:
7080                 case TOK_NOTEQ:
7081                         left = read_expr(state, def);
7082                         arithmetic(state, left);
7083                         eat(state, tok);
7084                         right = read_expr(state, relational_expr(state));
7085                         arithmetic(state, right);
7086                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7087                         def = triple(state, op, &int_type, left, right);
7088                         break;
7089                 default:
7090                         done = 1;
7091                         break;
7092                 }
7093         } while(!done);
7094         return def;
7095 }
7096
7097 static struct triple *and_expr(struct compile_state *state)
7098 {
7099         struct triple *def;
7100         def = equality_expr(state);
7101         while(peek(state) == TOK_AND) {
7102                 struct triple *left, *right;
7103                 struct type *result_type;
7104                 left = read_expr(state, def);
7105                 integral(state, left);
7106                 eat(state, TOK_AND);
7107                 right = read_expr(state, equality_expr(state));
7108                 integral(state, right);
7109                 result_type = arithmetic_result(state, left, right);
7110                 def = triple(state, OP_AND, result_type, left, right);
7111         }
7112         return def;
7113 }
7114
7115 static struct triple *xor_expr(struct compile_state *state)
7116 {
7117         struct triple *def;
7118         def = and_expr(state);
7119         while(peek(state) == TOK_XOR) {
7120                 struct triple *left, *right;
7121                 struct type *result_type;
7122                 left = read_expr(state, def);
7123                 integral(state, left);
7124                 eat(state, TOK_XOR);
7125                 right = read_expr(state, and_expr(state));
7126                 integral(state, right);
7127                 result_type = arithmetic_result(state, left, right);
7128                 def = triple(state, OP_XOR, result_type, left, right);
7129         }
7130         return def;
7131 }
7132
7133 static struct triple *or_expr(struct compile_state *state)
7134 {
7135         struct triple *def;
7136         def = xor_expr(state);
7137         while(peek(state) == TOK_OR) {
7138                 struct triple *left, *right;
7139                 struct type *result_type;
7140                 left = read_expr(state, def);
7141                 integral(state, left);
7142                 eat(state, TOK_OR);
7143                 right = read_expr(state, xor_expr(state));
7144                 integral(state, right);
7145                 result_type = arithmetic_result(state, left, right);
7146                 def = triple(state, OP_OR, result_type, left, right);
7147         }
7148         return def;
7149 }
7150
7151 static struct triple *land_expr(struct compile_state *state)
7152 {
7153         struct triple *def;
7154         def = or_expr(state);
7155         while(peek(state) == TOK_LOGAND) {
7156                 struct triple *left, *right;
7157                 left = read_expr(state, def);
7158                 bool(state, left);
7159                 eat(state, TOK_LOGAND);
7160                 right = read_expr(state, or_expr(state));
7161                 bool(state, right);
7162
7163                 def = triple(state, OP_LAND, &int_type,
7164                         ltrue_expr(state, left),
7165                         ltrue_expr(state, right));
7166         }
7167         return def;
7168 }
7169
7170 static struct triple *lor_expr(struct compile_state *state)
7171 {
7172         struct triple *def;
7173         def = land_expr(state);
7174         while(peek(state) == TOK_LOGOR) {
7175                 struct triple *left, *right;
7176                 left = read_expr(state, def);
7177                 bool(state, left);
7178                 eat(state, TOK_LOGOR);
7179                 right = read_expr(state, land_expr(state));
7180                 bool(state, right);
7181                 
7182                 def = triple(state, OP_LOR, &int_type,
7183                         ltrue_expr(state, left),
7184                         ltrue_expr(state, right));
7185         }
7186         return def;
7187 }
7188
7189 static struct triple *conditional_expr(struct compile_state *state)
7190 {
7191         struct triple *def;
7192         def = lor_expr(state);
7193         if (peek(state) == TOK_QUEST) {
7194                 struct triple *test, *left, *right;
7195                 bool(state, def);
7196                 test = ltrue_expr(state, read_expr(state, def));
7197                 eat(state, TOK_QUEST);
7198                 left = read_expr(state, expr(state));
7199                 eat(state, TOK_COLON);
7200                 right = read_expr(state, conditional_expr(state));
7201
7202                 def = cond_expr(state, test, left, right);
7203         }
7204         return def;
7205 }
7206
7207 static struct triple *eval_const_expr(
7208         struct compile_state *state, struct triple *expr)
7209 {
7210         struct triple *def;
7211         struct triple *head, *ptr;
7212         head = label(state); /* dummy initial triple */
7213         flatten(state, head, expr);
7214         for(ptr = head->next; ptr != head; ptr = ptr->next) {
7215                 simplify(state, ptr);
7216         }
7217         /* Remove the constant value the tail of the list */
7218         def = head->prev;
7219         def->prev->next = def->next;
7220         def->next->prev = def->prev;
7221         def->next = def->prev = def;
7222         if (!is_const(def)) {
7223                 internal_error(state, 0, "Not a constant expression");
7224         }
7225         /* Free the intermediate expressions */
7226         while(head->next != head) {
7227                 release_triple(state, head->next);
7228         }
7229         free_triple(state, head);
7230         return def;
7231 }
7232
7233 static struct triple *constant_expr(struct compile_state *state)
7234 {
7235         return eval_const_expr(state, conditional_expr(state));
7236 }
7237
7238 static struct triple *assignment_expr(struct compile_state *state)
7239 {
7240         struct triple *def, *left, *right;
7241         int tok, op, sign;
7242         /* The C grammer in K&R shows assignment expressions
7243          * only taking unary expressions as input on their
7244          * left hand side.  But specifies the precedence of
7245          * assignemnt as the lowest operator except for comma.
7246          *
7247          * Allowing conditional expressions on the left hand side
7248          * of an assignement results in a grammar that accepts
7249          * a larger set of statements than standard C.   As long
7250          * as the subset of the grammar that is standard C behaves
7251          * correctly this should cause no problems.
7252          * 
7253          * For the extra token strings accepted by the grammar
7254          * none of them should produce a valid lvalue, so they
7255          * should not produce functioning programs.
7256          *
7257          * GCC has this bug as well, so surprises should be minimal.
7258          */
7259         def = conditional_expr(state);
7260         left = def;
7261         switch((tok = peek(state))) {
7262         case TOK_EQ:
7263                 lvalue(state, left);
7264                 eat(state, TOK_EQ);
7265                 def = write_expr(state, left, 
7266                         read_expr(state, assignment_expr(state)));
7267                 break;
7268         case TOK_TIMESEQ:
7269         case TOK_DIVEQ:
7270         case TOK_MODEQ:
7271                 lvalue(state, left);
7272                 arithmetic(state, left);
7273                 eat(state, tok);
7274                 right = read_expr(state, assignment_expr(state));
7275                 arithmetic(state, right);
7276
7277                 sign = is_signed(left->type);
7278                 op = -1;
7279                 switch(tok) {
7280                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7281                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7282                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7283                 }
7284                 def = write_expr(state, left,
7285                         triple(state, op, left->type, 
7286                                 read_expr(state, left), right));
7287                 break;
7288         case TOK_PLUSEQ:
7289                 lvalue(state, left);
7290                 eat(state, TOK_PLUSEQ);
7291                 def = write_expr(state, left,
7292                         mk_add_expr(state, left, assignment_expr(state)));
7293                 break;
7294         case TOK_MINUSEQ:
7295                 lvalue(state, left);
7296                 eat(state, TOK_MINUSEQ);
7297                 def = write_expr(state, left,
7298                         mk_sub_expr(state, left, assignment_expr(state)));
7299                 break;
7300         case TOK_SLEQ:
7301         case TOK_SREQ:
7302         case TOK_ANDEQ:
7303         case TOK_XOREQ:
7304         case TOK_OREQ:
7305                 lvalue(state, left);
7306                 integral(state, left);
7307                 eat(state, tok);
7308                 right = read_expr(state, assignment_expr(state));
7309                 integral(state, right);
7310                 right = integral_promotion(state, right);
7311                 sign = is_signed(left->type);
7312                 op = -1;
7313                 switch(tok) {
7314                 case TOK_SLEQ:  op = OP_SL; break;
7315                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7316                 case TOK_ANDEQ: op = OP_AND; break;
7317                 case TOK_XOREQ: op = OP_XOR; break;
7318                 case TOK_OREQ:  op = OP_OR; break;
7319                 }
7320                 def = write_expr(state, left,
7321                         triple(state, op, left->type, 
7322                                 read_expr(state, left), right));
7323                 break;
7324         }
7325         return def;
7326 }
7327
7328 static struct triple *expr(struct compile_state *state)
7329 {
7330         struct triple *def;
7331         def = assignment_expr(state);
7332         while(peek(state) == TOK_COMMA) {
7333                 struct triple *left, *right;
7334                 left = def;
7335                 eat(state, TOK_COMMA);
7336                 right = assignment_expr(state);
7337                 def = triple(state, OP_COMMA, right->type, left, right);
7338         }
7339         return def;
7340 }
7341
7342 static void expr_statement(struct compile_state *state, struct triple *first)
7343 {
7344         if (peek(state) != TOK_SEMI) {
7345                 flatten(state, first, expr(state));
7346         }
7347         eat(state, TOK_SEMI);
7348 }
7349
7350 static void if_statement(struct compile_state *state, struct triple *first)
7351 {
7352         struct triple *test, *jmp1, *jmp2, *middle, *end;
7353
7354         jmp1 = jmp2 = middle = 0;
7355         eat(state, TOK_IF);
7356         eat(state, TOK_LPAREN);
7357         test = expr(state);
7358         bool(state, test);
7359         /* Cleanup and invert the test */
7360         test = lfalse_expr(state, read_expr(state, test));
7361         eat(state, TOK_RPAREN);
7362         /* Generate the needed pieces */
7363         middle = label(state);
7364         jmp1 = branch(state, middle, test);
7365         /* Thread the pieces together */
7366         flatten(state, first, test);
7367         flatten(state, first, jmp1);
7368         flatten(state, first, label(state));
7369         statement(state, first);
7370         if (peek(state) == TOK_ELSE) {
7371                 eat(state, TOK_ELSE);
7372                 /* Generate the rest of the pieces */
7373                 end = label(state);
7374                 jmp2 = branch(state, end, 0);
7375                 /* Thread them together */
7376                 flatten(state, first, jmp2);
7377                 flatten(state, first, middle);
7378                 statement(state, first);
7379                 flatten(state, first, end);
7380         }
7381         else {
7382                 flatten(state, first, middle);
7383         }
7384 }
7385
7386 static void for_statement(struct compile_state *state, struct triple *first)
7387 {
7388         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7389         struct triple *label1, *label2, *label3;
7390         struct hash_entry *ident;
7391
7392         eat(state, TOK_FOR);
7393         eat(state, TOK_LPAREN);
7394         head = test = tail = jmp1 = jmp2 = 0;
7395         if (peek(state) != TOK_SEMI) {
7396                 head = expr(state);
7397         } 
7398         eat(state, TOK_SEMI);
7399         if (peek(state) != TOK_SEMI) {
7400                 test = expr(state);
7401                 bool(state, test);
7402                 test = ltrue_expr(state, read_expr(state, test));
7403         }
7404         eat(state, TOK_SEMI);
7405         if (peek(state) != TOK_RPAREN) {
7406                 tail = expr(state);
7407         }
7408         eat(state, TOK_RPAREN);
7409         /* Generate the needed pieces */
7410         label1 = label(state);
7411         label2 = label(state);
7412         label3 = label(state);
7413         if (test) {
7414                 jmp1 = branch(state, label3, 0);
7415                 jmp2 = branch(state, label1, test);
7416         }
7417         else {
7418                 jmp2 = branch(state, label1, 0);
7419         }
7420         end = label(state);
7421         /* Remember where break and continue go */
7422         start_scope(state);
7423         ident = state->i_break;
7424         symbol(state, ident, &ident->sym_ident, end, end->type);
7425         ident = state->i_continue;
7426         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7427         /* Now include the body */
7428         flatten(state, first, head);
7429         flatten(state, first, jmp1);
7430         flatten(state, first, label1);
7431         statement(state, first);
7432         flatten(state, first, label2);
7433         flatten(state, first, tail);
7434         flatten(state, first, label3);
7435         flatten(state, first, test);
7436         flatten(state, first, jmp2);
7437         flatten(state, first, end);
7438         /* Cleanup the break/continue scope */
7439         end_scope(state);
7440 }
7441
7442 static void while_statement(struct compile_state *state, struct triple *first)
7443 {
7444         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7445         struct hash_entry *ident;
7446         eat(state, TOK_WHILE);
7447         eat(state, TOK_LPAREN);
7448         test = expr(state);
7449         bool(state, test);
7450         test = ltrue_expr(state, read_expr(state, test));
7451         eat(state, TOK_RPAREN);
7452         /* Generate the needed pieces */
7453         label1 = label(state);
7454         label2 = label(state);
7455         jmp1 = branch(state, label2, 0);
7456         jmp2 = branch(state, label1, test);
7457         end = label(state);
7458         /* Remember where break and continue go */
7459         start_scope(state);
7460         ident = state->i_break;
7461         symbol(state, ident, &ident->sym_ident, end, end->type);
7462         ident = state->i_continue;
7463         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7464         /* Thread them together */
7465         flatten(state, first, jmp1);
7466         flatten(state, first, label1);
7467         statement(state, first);
7468         flatten(state, first, label2);
7469         flatten(state, first, test);
7470         flatten(state, first, jmp2);
7471         flatten(state, first, end);
7472         /* Cleanup the break/continue scope */
7473         end_scope(state);
7474 }
7475
7476 static void do_statement(struct compile_state *state, struct triple *first)
7477 {
7478         struct triple *label1, *label2, *test, *end;
7479         struct hash_entry *ident;
7480         eat(state, TOK_DO);
7481         /* Generate the needed pieces */
7482         label1 = label(state);
7483         label2 = label(state);
7484         end = label(state);
7485         /* Remember where break and continue go */
7486         start_scope(state);
7487         ident = state->i_break;
7488         symbol(state, ident, &ident->sym_ident, end, end->type);
7489         ident = state->i_continue;
7490         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7491         /* Now include the body */
7492         flatten(state, first, label1);
7493         statement(state, first);
7494         /* Cleanup the break/continue scope */
7495         end_scope(state);
7496         /* Eat the rest of the loop */
7497         eat(state, TOK_WHILE);
7498         eat(state, TOK_LPAREN);
7499         test = read_expr(state, expr(state));
7500         bool(state, test);
7501         eat(state, TOK_RPAREN);
7502         eat(state, TOK_SEMI);
7503         /* Thread the pieces together */
7504         test = ltrue_expr(state, test);
7505         flatten(state, first, label2);
7506         flatten(state, first, test);
7507         flatten(state, first, branch(state, label1, test));
7508         flatten(state, first, end);
7509 }
7510
7511
7512 static void return_statement(struct compile_state *state, struct triple *first)
7513 {
7514         struct triple *jmp, *mv, *dest, *var, *val;
7515         int last;
7516         eat(state, TOK_RETURN);
7517
7518 #warning "FIXME implement a more general excess branch elimination"
7519         val = 0;
7520         /* If we have a return value do some more work */
7521         if (peek(state) != TOK_SEMI) {
7522                 val = read_expr(state, expr(state));
7523         }
7524         eat(state, TOK_SEMI);
7525
7526         /* See if this last statement in a function */
7527         last = ((peek(state) == TOK_RBRACE) && 
7528                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7529
7530         /* Find the return variable */
7531         var = MISC(state->main_function, 0);
7532         /* Find the return destination */
7533         dest = RHS(state->main_function, 0)->prev;
7534         mv = jmp = 0;
7535         /* If needed generate a jump instruction */
7536         if (!last) {
7537                 jmp = branch(state, dest, 0);
7538         }
7539         /* If needed generate an assignment instruction */
7540         if (val) {
7541                 mv = write_expr(state, var, val);
7542         }
7543         /* Now put the code together */
7544         if (mv) {
7545                 flatten(state, first, mv);
7546                 flatten(state, first, jmp);
7547         }
7548         else if (jmp) {
7549                 flatten(state, first, jmp);
7550         }
7551 }
7552
7553 static void break_statement(struct compile_state *state, struct triple *first)
7554 {
7555         struct triple *dest;
7556         eat(state, TOK_BREAK);
7557         eat(state, TOK_SEMI);
7558         if (!state->i_break->sym_ident) {
7559                 error(state, 0, "break statement not within loop or switch");
7560         }
7561         dest = state->i_break->sym_ident->def;
7562         flatten(state, first, branch(state, dest, 0));
7563 }
7564
7565 static void continue_statement(struct compile_state *state, struct triple *first)
7566 {
7567         struct triple *dest;
7568         eat(state, TOK_CONTINUE);
7569         eat(state, TOK_SEMI);
7570         if (!state->i_continue->sym_ident) {
7571                 error(state, 0, "continue statement outside of a loop");
7572         }
7573         dest = state->i_continue->sym_ident->def;
7574         flatten(state, first, branch(state, dest, 0));
7575 }
7576
7577 static void goto_statement(struct compile_state *state, struct triple *first)
7578 {
7579         FINISHME();
7580         eat(state, TOK_GOTO);
7581         eat(state, TOK_IDENT);
7582         eat(state, TOK_SEMI);
7583         error(state, 0, "goto is not implemeted");
7584         FINISHME();
7585 }
7586
7587 static void labeled_statement(struct compile_state *state, struct triple *first)
7588 {
7589         FINISHME();
7590         eat(state, TOK_IDENT);
7591         eat(state, TOK_COLON);
7592         statement(state, first);
7593         error(state, 0, "labeled statements are not implemented");
7594         FINISHME();
7595 }
7596
7597 static void switch_statement(struct compile_state *state, struct triple *first)
7598 {
7599         FINISHME();
7600         eat(state, TOK_SWITCH);
7601         eat(state, TOK_LPAREN);
7602         expr(state);
7603         eat(state, TOK_RPAREN);
7604         statement(state, first);
7605         error(state, 0, "switch statements are not implemented");
7606         FINISHME();
7607 }
7608
7609 static void case_statement(struct compile_state *state, struct triple *first)
7610 {
7611         FINISHME();
7612         eat(state, TOK_CASE);
7613         constant_expr(state);
7614         eat(state, TOK_COLON);
7615         statement(state, first);
7616         error(state, 0, "case statements are not implemented");
7617         FINISHME();
7618 }
7619
7620 static void default_statement(struct compile_state *state, struct triple *first)
7621 {
7622         FINISHME();
7623         eat(state, TOK_DEFAULT);
7624         eat(state, TOK_COLON);
7625         statement(state, first);
7626         error(state, 0, "default statements are not implemented");
7627         FINISHME();
7628 }
7629
7630 static void asm_statement(struct compile_state *state, struct triple *first)
7631 {
7632         struct asm_info *info;
7633         struct {
7634                 struct triple *constraint;
7635                 struct triple *expr;
7636         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7637         struct triple *def, *asm_str;
7638         int out, in, clobbers, more, colons, i;
7639
7640         eat(state, TOK_ASM);
7641         /* For now ignore the qualifiers */
7642         switch(peek(state)) {
7643         case TOK_CONST:
7644                 eat(state, TOK_CONST);
7645                 break;
7646         case TOK_VOLATILE:
7647                 eat(state, TOK_VOLATILE);
7648                 break;
7649         }
7650         eat(state, TOK_LPAREN);
7651         asm_str = string_constant(state);
7652
7653         colons = 0;
7654         out = in = clobbers = 0;
7655         /* Outputs */
7656         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7657                 eat(state, TOK_COLON);
7658                 colons++;
7659                 more = (peek(state) == TOK_LIT_STRING);
7660                 while(more) {
7661                         struct triple *var;
7662                         struct triple *constraint;
7663                         char *str;
7664                         more = 0;
7665                         if (out > MAX_LHS) {
7666                                 error(state, 0, "Maximum output count exceeded.");
7667                         }
7668                         constraint = string_constant(state);
7669                         str = constraint->u.blob;
7670                         if (str[0] != '=') {
7671                                 error(state, 0, "Output constraint does not start with =");
7672                         }
7673                         constraint->u.blob = str + 1;
7674                         eat(state, TOK_LPAREN);
7675                         var = conditional_expr(state);
7676                         eat(state, TOK_RPAREN);
7677
7678                         lvalue(state, var);
7679                         out_param[out].constraint = constraint;
7680                         out_param[out].expr       = var;
7681                         if (peek(state) == TOK_COMMA) {
7682                                 eat(state, TOK_COMMA);
7683                                 more = 1;
7684                         }
7685                         out++;
7686                 }
7687         }
7688         /* Inputs */
7689         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7690                 eat(state, TOK_COLON);
7691                 colons++;
7692                 more = (peek(state) == TOK_LIT_STRING);
7693                 while(more) {
7694                         struct triple *val;
7695                         struct triple *constraint;
7696                         char *str;
7697                         more = 0;
7698                         if (in > MAX_RHS) {
7699                                 error(state, 0, "Maximum input count exceeded.");
7700                         }
7701                         constraint = string_constant(state);
7702                         str = constraint->u.blob;
7703                         if (digitp(str[0] && str[1] == '\0')) {
7704                                 int val;
7705                                 val = digval(str[0]);
7706                                 if ((val < 0) || (val >= out)) {
7707                                         error(state, 0, "Invalid input constraint %d", val);
7708                                 }
7709                         }
7710                         eat(state, TOK_LPAREN);
7711                         val = conditional_expr(state);
7712                         eat(state, TOK_RPAREN);
7713
7714                         in_param[in].constraint = constraint;
7715                         in_param[in].expr       = val;
7716                         if (peek(state) == TOK_COMMA) {
7717                                 eat(state, TOK_COMMA);
7718                                 more = 1;
7719                         }
7720                         in++;
7721                 }
7722         }
7723
7724         /* Clobber */
7725         if ((colons == 2) && (peek(state) == TOK_COLON)) {
7726                 eat(state, TOK_COLON);
7727                 colons++;
7728                 more = (peek(state) == TOK_LIT_STRING);
7729                 while(more) {
7730                         struct triple *clobber;
7731                         more = 0;
7732                         if ((clobbers + out) > MAX_LHS) {
7733                                 error(state, 0, "Maximum clobber limit exceeded.");
7734                         }
7735                         clobber = string_constant(state);
7736                         eat(state, TOK_RPAREN);
7737
7738                         clob_param[clobbers].constraint = clobber;
7739                         if (peek(state) == TOK_COMMA) {
7740                                 eat(state, TOK_COMMA);
7741                                 more = 1;
7742                         }
7743                         clobbers++;
7744                 }
7745         }
7746         eat(state, TOK_RPAREN);
7747         eat(state, TOK_SEMI);
7748
7749
7750         info = xcmalloc(sizeof(*info), "asm_info");
7751         info->str = asm_str->u.blob;
7752         free_triple(state, asm_str);
7753
7754         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7755         def->u.ainfo = info;
7756
7757         /* Find the register constraints */
7758         for(i = 0; i < out; i++) {
7759                 struct triple *constraint;
7760                 constraint = out_param[i].constraint;
7761                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
7762                         out_param[i].expr->type, constraint->u.blob);
7763                 free_triple(state, constraint);
7764         }
7765         for(; i - out < clobbers; i++) {
7766                 struct triple *constraint;
7767                 constraint = clob_param[i - out].constraint;
7768                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7769                 free_triple(state, constraint);
7770         }
7771         for(i = 0; i < in; i++) {
7772                 struct triple *constraint;
7773                 const char *str;
7774                 constraint = in_param[i].constraint;
7775                 str = constraint->u.blob;
7776                 if (digitp(str[0]) && str[1] == '\0') {
7777                         struct reg_info cinfo;
7778                         int val;
7779                         val = digval(str[0]);
7780                         cinfo.reg = info->tmpl.lhs[val].reg;
7781                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
7782                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
7783                         if (cinfo.reg == REG_UNSET) {
7784                                 cinfo.reg = REG_VIRT0 + val;
7785                         }
7786                         if (cinfo.regcm == 0) {
7787                                 error(state, 0, "No registers for %d", val);
7788                         }
7789                         info->tmpl.lhs[val] = cinfo;
7790                         info->tmpl.rhs[i]   = cinfo;
7791                                 
7792                 } else {
7793                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
7794                                 in_param[i].expr->type, str);
7795                 }
7796                 free_triple(state, constraint);
7797         }
7798
7799         /* Now build the helper expressions */
7800         for(i = 0; i < in; i++) {
7801                 RHS(def, i) = read_expr(state,in_param[i].expr);
7802         }
7803         flatten(state, first, def);
7804         for(i = 0; i < out; i++) {
7805                 struct triple *piece;
7806                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7807                 piece->u.cval = i;
7808                 LHS(def, i) = piece;
7809                 flatten(state, first,
7810                         write_expr(state, out_param[i].expr, piece));
7811         }
7812         for(; i - out < clobbers; i++) {
7813                 struct triple *piece;
7814                 piece = triple(state, OP_PIECE, &void_type, def, 0);
7815                 piece->u.cval = i;
7816                 LHS(def, i) = piece;
7817                 flatten(state, first, piece);
7818         }
7819 }
7820
7821
7822 static int isdecl(int tok)
7823 {
7824         switch(tok) {
7825         case TOK_AUTO:
7826         case TOK_REGISTER:
7827         case TOK_STATIC:
7828         case TOK_EXTERN:
7829         case TOK_TYPEDEF:
7830         case TOK_CONST:
7831         case TOK_RESTRICT:
7832         case TOK_VOLATILE:
7833         case TOK_VOID:
7834         case TOK_CHAR:
7835         case TOK_SHORT:
7836         case TOK_INT:
7837         case TOK_LONG:
7838         case TOK_FLOAT:
7839         case TOK_DOUBLE:
7840         case TOK_SIGNED:
7841         case TOK_UNSIGNED:
7842         case TOK_STRUCT:
7843         case TOK_UNION:
7844         case TOK_ENUM:
7845         case TOK_TYPE_NAME: /* typedef name */
7846                 return 1;
7847         default:
7848                 return 0;
7849         }
7850 }
7851
7852 static void compound_statement(struct compile_state *state, struct triple *first)
7853 {
7854         eat(state, TOK_LBRACE);
7855         start_scope(state);
7856
7857         /* statement-list opt */
7858         while (peek(state) != TOK_RBRACE) {
7859                 statement(state, first);
7860         }
7861         end_scope(state);
7862         eat(state, TOK_RBRACE);
7863 }
7864
7865 static void statement(struct compile_state *state, struct triple *first)
7866 {
7867         int tok;
7868         tok = peek(state);
7869         if (tok == TOK_LBRACE) {
7870                 compound_statement(state, first);
7871         }
7872         else if (tok == TOK_IF) {
7873                 if_statement(state, first); 
7874         }
7875         else if (tok == TOK_FOR) {
7876                 for_statement(state, first);
7877         }
7878         else if (tok == TOK_WHILE) {
7879                 while_statement(state, first);
7880         }
7881         else if (tok == TOK_DO) {
7882                 do_statement(state, first);
7883         }
7884         else if (tok == TOK_RETURN) {
7885                 return_statement(state, first);
7886         }
7887         else if (tok == TOK_BREAK) {
7888                 break_statement(state, first);
7889         }
7890         else if (tok == TOK_CONTINUE) {
7891                 continue_statement(state, first);
7892         }
7893         else if (tok == TOK_GOTO) {
7894                 goto_statement(state, first);
7895         }
7896         else if (tok == TOK_SWITCH) {
7897                 switch_statement(state, first);
7898         }
7899         else if (tok == TOK_ASM) {
7900                 asm_statement(state, first);
7901         }
7902         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7903                 labeled_statement(state, first); 
7904         }
7905         else if (tok == TOK_CASE) {
7906                 case_statement(state, first);
7907         }
7908         else if (tok == TOK_DEFAULT) {
7909                 default_statement(state, first);
7910         }
7911         else if (isdecl(tok)) {
7912                 /* This handles C99 intermixing of statements and decls */
7913                 decl(state, first);
7914         }
7915         else {
7916                 expr_statement(state, first);
7917         }
7918 }
7919
7920 static struct type *param_decl(struct compile_state *state)
7921 {
7922         struct type *type;
7923         struct hash_entry *ident;
7924         /* Cheat so the declarator will know we are not global */
7925         start_scope(state); 
7926         ident = 0;
7927         type = decl_specifiers(state);
7928         type = declarator(state, type, &ident, 0);
7929         type->field_ident = ident;
7930         end_scope(state);
7931         return type;
7932 }
7933
7934 static struct type *param_type_list(struct compile_state *state, struct type *type)
7935 {
7936         struct type *ftype, **next;
7937         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7938         next = &ftype->right;
7939         while(peek(state) == TOK_COMMA) {
7940                 eat(state, TOK_COMMA);
7941                 if (peek(state) == TOK_DOTS) {
7942                         eat(state, TOK_DOTS);
7943                         error(state, 0, "variadic functions not supported");
7944                 }
7945                 else {
7946                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7947                         next = &((*next)->right);
7948                 }
7949         }
7950         return ftype;
7951 }
7952
7953
7954 static struct type *type_name(struct compile_state *state)
7955 {
7956         struct type *type;
7957         type = specifier_qualifier_list(state);
7958         /* abstract-declarator (may consume no tokens) */
7959         type = declarator(state, type, 0, 0);
7960         return type;
7961 }
7962
7963 static struct type *direct_declarator(
7964         struct compile_state *state, struct type *type, 
7965         struct hash_entry **ident, int need_ident)
7966 {
7967         struct type *outer;
7968         int op;
7969         outer = 0;
7970         arrays_complete(state, type);
7971         switch(peek(state)) {
7972         case TOK_IDENT:
7973                 eat(state, TOK_IDENT);
7974                 if (!ident) {
7975                         error(state, 0, "Unexpected identifier found");
7976                 }
7977                 /* The name of what we are declaring */
7978                 *ident = state->token[0].ident;
7979                 break;
7980         case TOK_LPAREN:
7981                 eat(state, TOK_LPAREN);
7982                 outer = declarator(state, type, ident, need_ident);
7983                 eat(state, TOK_RPAREN);
7984                 break;
7985         default:
7986                 if (need_ident) {
7987                         error(state, 0, "Identifier expected");
7988                 }
7989                 break;
7990         }
7991         do {
7992                 op = 1;
7993                 arrays_complete(state, type);
7994                 switch(peek(state)) {
7995                 case TOK_LPAREN:
7996                         eat(state, TOK_LPAREN);
7997                         type = param_type_list(state, type);
7998                         eat(state, TOK_RPAREN);
7999                         break;
8000                 case TOK_LBRACKET:
8001                 {
8002                         unsigned int qualifiers;
8003                         struct triple *value;
8004                         value = 0;
8005                         eat(state, TOK_LBRACKET);
8006                         if (peek(state) != TOK_RBRACKET) {
8007                                 value = constant_expr(state);
8008                                 integral(state, value);
8009                         }
8010                         eat(state, TOK_RBRACKET);
8011
8012                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8013                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8014                         if (value) {
8015                                 type->elements = value->u.cval;
8016                                 free_triple(state, value);
8017                         } else {
8018                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8019                                 op = 0;
8020                         }
8021                 }
8022                         break;
8023                 default:
8024                         op = 0;
8025                         break;
8026                 }
8027         } while(op);
8028         if (outer) {
8029                 struct type *inner;
8030                 arrays_complete(state, type);
8031                 FINISHME();
8032                 for(inner = outer; inner->left; inner = inner->left)
8033                         ;
8034                 inner->left = type;
8035                 type = outer;
8036         }
8037         return type;
8038 }
8039
8040 static struct type *declarator(
8041         struct compile_state *state, struct type *type, 
8042         struct hash_entry **ident, int need_ident)
8043 {
8044         while(peek(state) == TOK_STAR) {
8045                 eat(state, TOK_STAR);
8046                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8047         }
8048         type = direct_declarator(state, type, ident, need_ident);
8049         return type;
8050 }
8051
8052
8053 static struct type *typedef_name(
8054         struct compile_state *state, unsigned int specifiers)
8055 {
8056         struct hash_entry *ident;
8057         struct type *type;
8058         eat(state, TOK_TYPE_NAME);
8059         ident = state->token[0].ident;
8060         type = ident->sym_ident->type;
8061         specifiers |= type->type & QUAL_MASK;
8062         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8063                 (type->type & (STOR_MASK | QUAL_MASK))) {
8064                 type = clone_type(specifiers, type);
8065         }
8066         return type;
8067 }
8068
8069 static struct type *enum_specifier(
8070         struct compile_state *state, unsigned int specifiers)
8071 {
8072         int tok;
8073         struct type *type;
8074         type = 0;
8075         FINISHME();
8076         eat(state, TOK_ENUM);
8077         tok = peek(state);
8078         if (tok == TOK_IDENT) {
8079                 eat(state, TOK_IDENT);
8080         }
8081         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8082                 eat(state, TOK_LBRACE);
8083                 do {
8084                         eat(state, TOK_IDENT);
8085                         if (peek(state) == TOK_EQ) {
8086                                 eat(state, TOK_EQ);
8087                                 constant_expr(state);
8088                         }
8089                         if (peek(state) == TOK_COMMA) {
8090                                 eat(state, TOK_COMMA);
8091                         }
8092                 } while(peek(state) != TOK_RBRACE);
8093                 eat(state, TOK_RBRACE);
8094         }
8095         FINISHME();
8096         return type;
8097 }
8098
8099 #if 0
8100 static struct type *struct_declarator(
8101         struct compile_state *state, struct type *type, struct hash_entry **ident)
8102 {
8103         int tok;
8104 #warning "struct_declarator is complicated because of bitfields, kill them?"
8105         tok = peek(state);
8106         if (tok != TOK_COLON) {
8107                 type = declarator(state, type, ident, 1);
8108         }
8109         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8110                 eat(state, TOK_COLON);
8111                 constant_expr(state);
8112         }
8113         FINISHME();
8114         return type;
8115 }
8116 #endif
8117
8118 static struct type *struct_or_union_specifier(
8119         struct compile_state *state, unsigned int specifiers)
8120 {
8121         struct type *struct_type;
8122         struct hash_entry *ident;
8123         unsigned int type_join;
8124         int tok;
8125         struct_type = 0;
8126         ident = 0;
8127         switch(peek(state)) {
8128         case TOK_STRUCT:
8129                 eat(state, TOK_STRUCT);
8130                 type_join = TYPE_PRODUCT;
8131                 break;
8132         case TOK_UNION:
8133                 eat(state, TOK_UNION);
8134                 type_join = TYPE_OVERLAP;
8135                 error(state, 0, "unions not yet supported\n");
8136                 break;
8137         default:
8138                 eat(state, TOK_STRUCT);
8139                 type_join = TYPE_PRODUCT;
8140                 break;
8141         }
8142         tok = peek(state);
8143         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8144                 eat(state, tok);
8145                 ident = state->token[0].ident;
8146         }
8147         if (!ident || (peek(state) == TOK_LBRACE)) {
8148                 ulong_t elements;
8149                 elements = 0;
8150                 eat(state, TOK_LBRACE);
8151                 do {
8152                         struct type *base_type;
8153                         struct type **next;
8154                         int done;
8155                         base_type = specifier_qualifier_list(state);
8156                         next = &struct_type;
8157                         do {
8158                                 struct type *type;
8159                                 struct hash_entry *fident;
8160                                 done = 1;
8161                                 type = declarator(state, base_type, &fident, 1);
8162                                 elements++;
8163                                 if (peek(state) == TOK_COMMA) {
8164                                         done = 0;
8165                                         eat(state, TOK_COMMA);
8166                                 }
8167                                 type = clone_type(0, type);
8168                                 type->field_ident = fident;
8169                                 if (*next) {
8170                                         *next = new_type(type_join, *next, type);
8171                                         next = &((*next)->right);
8172                                 } else {
8173                                         *next = type;
8174                                 }
8175                         } while(!done);
8176                         eat(state, TOK_SEMI);
8177                 } while(peek(state) != TOK_RBRACE);
8178                 eat(state, TOK_RBRACE);
8179                 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8180                 struct_type->type_ident = ident;
8181                 struct_type->elements = elements;
8182                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8183         }
8184         if (ident && ident->sym_struct) {
8185                 struct_type = ident->sym_struct->type;
8186         }
8187         else if (ident && !ident->sym_struct) {
8188                 error(state, 0, "struct %s undeclared", ident->name);
8189         }
8190         return struct_type;
8191 }
8192
8193 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8194 {
8195         unsigned int specifiers;
8196         switch(peek(state)) {
8197         case TOK_AUTO:
8198                 eat(state, TOK_AUTO);
8199                 specifiers = STOR_AUTO;
8200                 break;
8201         case TOK_REGISTER:
8202                 eat(state, TOK_REGISTER);
8203                 specifiers = STOR_REGISTER;
8204                 break;
8205         case TOK_STATIC:
8206                 eat(state, TOK_STATIC);
8207                 specifiers = STOR_STATIC;
8208                 break;
8209         case TOK_EXTERN:
8210                 eat(state, TOK_EXTERN);
8211                 specifiers = STOR_EXTERN;
8212                 break;
8213         case TOK_TYPEDEF:
8214                 eat(state, TOK_TYPEDEF);
8215                 specifiers = STOR_TYPEDEF;
8216                 break;
8217         default:
8218                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8219                         specifiers = STOR_STATIC;
8220                 }
8221                 else {
8222                         specifiers = STOR_AUTO;
8223                 }
8224         }
8225         return specifiers;
8226 }
8227
8228 static unsigned int function_specifier_opt(struct compile_state *state)
8229 {
8230         /* Ignore the inline keyword */
8231         unsigned int specifiers;
8232         specifiers = 0;
8233         switch(peek(state)) {
8234         case TOK_INLINE:
8235                 eat(state, TOK_INLINE);
8236                 specifiers = STOR_INLINE;
8237         }
8238         return specifiers;
8239 }
8240
8241 static unsigned int type_qualifiers(struct compile_state *state)
8242 {
8243         unsigned int specifiers;
8244         int done;
8245         done = 0;
8246         specifiers = QUAL_NONE;
8247         do {
8248                 switch(peek(state)) {
8249                 case TOK_CONST:
8250                         eat(state, TOK_CONST);
8251                         specifiers = QUAL_CONST;
8252                         break;
8253                 case TOK_VOLATILE:
8254                         eat(state, TOK_VOLATILE);
8255                         specifiers = QUAL_VOLATILE;
8256                         break;
8257                 case TOK_RESTRICT:
8258                         eat(state, TOK_RESTRICT);
8259                         specifiers = QUAL_RESTRICT;
8260                         break;
8261                 default:
8262                         done = 1;
8263                         break;
8264                 }
8265         } while(!done);
8266         return specifiers;
8267 }
8268
8269 static struct type *type_specifier(
8270         struct compile_state *state, unsigned int spec)
8271 {
8272         struct type *type;
8273         type = 0;
8274         switch(peek(state)) {
8275         case TOK_VOID:
8276                 eat(state, TOK_VOID);
8277                 type = new_type(TYPE_VOID | spec, 0, 0);
8278                 break;
8279         case TOK_CHAR:
8280                 eat(state, TOK_CHAR);
8281                 type = new_type(TYPE_CHAR | spec, 0, 0);
8282                 break;
8283         case TOK_SHORT:
8284                 eat(state, TOK_SHORT);
8285                 if (peek(state) == TOK_INT) {
8286                         eat(state, TOK_INT);
8287                 }
8288                 type = new_type(TYPE_SHORT | spec, 0, 0);
8289                 break;
8290         case TOK_INT:
8291                 eat(state, TOK_INT);
8292                 type = new_type(TYPE_INT | spec, 0, 0);
8293                 break;
8294         case TOK_LONG:
8295                 eat(state, TOK_LONG);
8296                 switch(peek(state)) {
8297                 case TOK_LONG:
8298                         eat(state, TOK_LONG);
8299                         error(state, 0, "long long not supported");
8300                         break;
8301                 case TOK_DOUBLE:
8302                         eat(state, TOK_DOUBLE);
8303                         error(state, 0, "long double not supported");
8304                         break;
8305                 case TOK_INT:
8306                         eat(state, TOK_INT);
8307                         type = new_type(TYPE_LONG | spec, 0, 0);
8308                         break;
8309                 default:
8310                         type = new_type(TYPE_LONG | spec, 0, 0);
8311                         break;
8312                 }
8313                 break;
8314         case TOK_FLOAT:
8315                 eat(state, TOK_FLOAT);
8316                 error(state, 0, "type float not supported");
8317                 break;
8318         case TOK_DOUBLE:
8319                 eat(state, TOK_DOUBLE);
8320                 error(state, 0, "type double not supported");
8321                 break;
8322         case TOK_SIGNED:
8323                 eat(state, TOK_SIGNED);
8324                 switch(peek(state)) {
8325                 case TOK_LONG:
8326                         eat(state, TOK_LONG);
8327                         switch(peek(state)) {
8328                         case TOK_LONG:
8329                                 eat(state, TOK_LONG);
8330                                 error(state, 0, "type long long not supported");
8331                                 break;
8332                         case TOK_INT:
8333                                 eat(state, TOK_INT);
8334                                 type = new_type(TYPE_LONG | spec, 0, 0);
8335                                 break;
8336                         default:
8337                                 type = new_type(TYPE_LONG | spec, 0, 0);
8338                                 break;
8339                         }
8340                         break;
8341                 case TOK_INT:
8342                         eat(state, TOK_INT);
8343                         type = new_type(TYPE_INT | spec, 0, 0);
8344                         break;
8345                 case TOK_SHORT:
8346                         eat(state, TOK_SHORT);
8347                         type = new_type(TYPE_SHORT | spec, 0, 0);
8348                         break;
8349                 case TOK_CHAR:
8350                         eat(state, TOK_CHAR);
8351                         type = new_type(TYPE_CHAR | spec, 0, 0);
8352                         break;
8353                 default:
8354                         type = new_type(TYPE_INT | spec, 0, 0);
8355                         break;
8356                 }
8357                 break;
8358         case TOK_UNSIGNED:
8359                 eat(state, TOK_UNSIGNED);
8360                 switch(peek(state)) {
8361                 case TOK_LONG:
8362                         eat(state, TOK_LONG);
8363                         switch(peek(state)) {
8364                         case TOK_LONG:
8365                                 eat(state, TOK_LONG);
8366                                 error(state, 0, "unsigned long long not supported");
8367                                 break;
8368                         case TOK_INT:
8369                                 eat(state, TOK_INT);
8370                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8371                                 break;
8372                         default:
8373                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8374                                 break;
8375                         }
8376                         break;
8377                 case TOK_INT:
8378                         eat(state, TOK_INT);
8379                         type = new_type(TYPE_UINT | spec, 0, 0);
8380                         break;
8381                 case TOK_SHORT:
8382                         eat(state, TOK_SHORT);
8383                         type = new_type(TYPE_USHORT | spec, 0, 0);
8384                         break;
8385                 case TOK_CHAR:
8386                         eat(state, TOK_CHAR);
8387                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8388                         break;
8389                 default:
8390                         type = new_type(TYPE_UINT | spec, 0, 0);
8391                         break;
8392                 }
8393                 break;
8394                 /* struct or union specifier */
8395         case TOK_STRUCT:
8396         case TOK_UNION:
8397                 type = struct_or_union_specifier(state, spec);
8398                 break;
8399                 /* enum-spefifier */
8400         case TOK_ENUM:
8401                 type = enum_specifier(state, spec);
8402                 break;
8403                 /* typedef name */
8404         case TOK_TYPE_NAME:
8405                 type = typedef_name(state, spec);
8406                 break;
8407         default:
8408                 error(state, 0, "bad type specifier %s", 
8409                         tokens[peek(state)]);
8410                 break;
8411         }
8412         return type;
8413 }
8414
8415 static int istype(int tok)
8416 {
8417         switch(tok) {
8418         case TOK_CONST:
8419         case TOK_RESTRICT:
8420         case TOK_VOLATILE:
8421         case TOK_VOID:
8422         case TOK_CHAR:
8423         case TOK_SHORT:
8424         case TOK_INT:
8425         case TOK_LONG:
8426         case TOK_FLOAT:
8427         case TOK_DOUBLE:
8428         case TOK_SIGNED:
8429         case TOK_UNSIGNED:
8430         case TOK_STRUCT:
8431         case TOK_UNION:
8432         case TOK_ENUM:
8433         case TOK_TYPE_NAME:
8434                 return 1;
8435         default:
8436                 return 0;
8437         }
8438 }
8439
8440
8441 static struct type *specifier_qualifier_list(struct compile_state *state)
8442 {
8443         struct type *type;
8444         unsigned int specifiers = 0;
8445
8446         /* type qualifiers */
8447         specifiers |= type_qualifiers(state);
8448
8449         /* type specifier */
8450         type = type_specifier(state, specifiers);
8451
8452         return type;
8453 }
8454
8455 static int isdecl_specifier(int tok)
8456 {
8457         switch(tok) {
8458                 /* storage class specifier */
8459         case TOK_AUTO:
8460         case TOK_REGISTER:
8461         case TOK_STATIC:
8462         case TOK_EXTERN:
8463         case TOK_TYPEDEF:
8464                 /* type qualifier */
8465         case TOK_CONST:
8466         case TOK_RESTRICT:
8467         case TOK_VOLATILE:
8468                 /* type specifiers */
8469         case TOK_VOID:
8470         case TOK_CHAR:
8471         case TOK_SHORT:
8472         case TOK_INT:
8473         case TOK_LONG:
8474         case TOK_FLOAT:
8475         case TOK_DOUBLE:
8476         case TOK_SIGNED:
8477         case TOK_UNSIGNED:
8478                 /* struct or union specifier */
8479         case TOK_STRUCT:
8480         case TOK_UNION:
8481                 /* enum-spefifier */
8482         case TOK_ENUM:
8483                 /* typedef name */
8484         case TOK_TYPE_NAME:
8485                 /* function specifiers */
8486         case TOK_INLINE:
8487                 return 1;
8488         default:
8489                 return 0;
8490         }
8491 }
8492
8493 static struct type *decl_specifiers(struct compile_state *state)
8494 {
8495         struct type *type;
8496         unsigned int specifiers;
8497         /* I am overly restrictive in the arragement of specifiers supported.
8498          * C is overly flexible in this department it makes interpreting
8499          * the parse tree difficult.
8500          */
8501         specifiers = 0;
8502
8503         /* storage class specifier */
8504         specifiers |= storage_class_specifier_opt(state);
8505
8506         /* function-specifier */
8507         specifiers |= function_specifier_opt(state);
8508
8509         /* type qualifier */
8510         specifiers |= type_qualifiers(state);
8511
8512         /* type specifier */
8513         type = type_specifier(state, specifiers);
8514         return type;
8515 }
8516
8517 static unsigned designator(struct compile_state *state)
8518 {
8519         int tok;
8520         unsigned index;
8521         index = -1U;
8522         do {
8523                 switch(peek(state)) {
8524                 case TOK_LBRACKET:
8525                 {
8526                         struct triple *value;
8527                         eat(state, TOK_LBRACKET);
8528                         value = constant_expr(state);
8529                         eat(state, TOK_RBRACKET);
8530                         index = value->u.cval;
8531                         break;
8532                 }
8533                 case TOK_DOT:
8534                         eat(state, TOK_DOT);
8535                         eat(state, TOK_IDENT);
8536                         error(state, 0, "Struct Designators not currently supported");
8537                         break;
8538                 default:
8539                         error(state, 0, "Invalid designator");
8540                 }
8541                 tok = peek(state);
8542         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8543         eat(state, TOK_EQ);
8544         return index;
8545 }
8546
8547 static struct triple *initializer(
8548         struct compile_state *state, struct type *type)
8549 {
8550         struct triple *result;
8551         if (peek(state) != TOK_LBRACE) {
8552                 result = assignment_expr(state);
8553         }
8554         else {
8555                 int comma;
8556                 unsigned index, max_index;
8557                 void *buf;
8558                 max_index = index = 0;
8559                 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8560                         max_index = type->elements;
8561                         if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8562                                 type->elements = 0;
8563                         }
8564                 } else {
8565                         error(state, 0, "Struct initializers not currently supported");
8566                 }
8567                 buf = xcmalloc(size_of(state, type), "initializer");
8568                 eat(state, TOK_LBRACE);
8569                 do {
8570                         struct triple *value;
8571                         struct type *value_type;
8572                         size_t value_size;
8573                         int tok;
8574                         comma = 0;
8575                         tok = peek(state);
8576                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8577                                 index = designator(state);
8578                         }
8579                         if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8580                                 (index > max_index)) {
8581                                 error(state, 0, "element beyond bounds");
8582                         }
8583                         value_type = 0;
8584                         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8585                                 value_type = type->left;
8586                         }
8587                         value = eval_const_expr(state, initializer(state, value_type));
8588                         value_size = size_of(state, value_type);
8589                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8590                                 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8591                                 (type->elements <= index)) {
8592                                 void *old_buf;
8593                                 size_t old_size;
8594                                 old_buf = buf;
8595                                 old_size = size_of(state, type);
8596                                 type->elements = index + 1;
8597                                 buf = xmalloc(size_of(state, type), "initializer");
8598                                 memcpy(buf, old_buf, old_size);
8599                                 xfree(old_buf);
8600                         }
8601                         if (value->op == OP_BLOBCONST) {
8602                                 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8603                         }
8604                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8605                                 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8606                         }
8607                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8608                                 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8609                         }
8610                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8611                                 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8612                         }
8613                         else {
8614                                 fprintf(stderr, "%d %d\n",
8615                                         value->op, value_size);
8616                                 internal_error(state, 0, "unhandled constant initializer");
8617                         }
8618                         if (peek(state) == TOK_COMMA) {
8619                                 eat(state, TOK_COMMA);
8620                                 comma = 1;
8621                         }
8622                         index += 1;
8623                 } while(comma && (peek(state) != TOK_RBRACE));
8624                 eat(state, TOK_RBRACE);
8625                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8626                 result->u.blob = buf;
8627         }
8628         return result;
8629 }
8630
8631 static struct triple *function_definition(
8632         struct compile_state *state, struct type *type)
8633 {
8634         struct triple *def, *tmp, *first, *end;
8635         struct hash_entry *ident;
8636         struct type *param;
8637         int i;
8638         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8639                 error(state, 0, "Invalid function header");
8640         }
8641
8642         /* Verify the function type */
8643         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8644                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8645                 (type->right->field_ident == 0)) {
8646                 error(state, 0, "Invalid function parameters");
8647         }
8648         param = type->right;
8649         i = 0;
8650         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8651                 i++;
8652                 if (!param->left->field_ident) {
8653                         error(state, 0, "No identifier for parameter %d\n", i);
8654                 }
8655                 param = param->right;
8656         }
8657         i++;
8658         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8659                 error(state, 0, "No identifier for paramter %d\n", i);
8660         }
8661         
8662         /* Get a list of statements for this function. */
8663         def = triple(state, OP_LIST, type, 0, 0);
8664
8665         /* Start a new scope for the passed parameters */
8666         start_scope(state);
8667
8668         /* Put a label at the very start of a function */
8669         first = label(state);
8670         RHS(def, 0) = first;
8671
8672         /* Put a label at the very end of a function */
8673         end = label(state);
8674         flatten(state, first, end);
8675
8676         /* Walk through the parameters and create symbol table entries
8677          * for them.
8678          */
8679         param = type->right;
8680         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8681                 ident = param->left->field_ident;
8682                 tmp = variable(state, param->left);
8683                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8684                 flatten(state, end, tmp);
8685                 param = param->right;
8686         }
8687         if ((param->type & TYPE_MASK) != TYPE_VOID) {
8688                 /* And don't forget the last parameter */
8689                 ident = param->field_ident;
8690                 tmp = variable(state, param);
8691                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8692                 flatten(state, end, tmp);
8693         }
8694         /* Add a variable for the return value */
8695         MISC(def, 0) = 0;
8696         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8697                 /* Remove all type qualifiers from the return type */
8698                 tmp = variable(state, clone_type(0, type->left));
8699                 flatten(state, end, tmp);
8700                 /* Remember where the return value is */
8701                 MISC(def, 0) = tmp;
8702         }
8703
8704         /* Remember which function I am compiling.
8705          * Also assume the last defined function is the main function.
8706          */
8707         state->main_function = def;
8708
8709         /* Now get the actual function definition */
8710         compound_statement(state, end);
8711
8712         /* Remove the parameter scope */
8713         end_scope(state);
8714 #if 0
8715         fprintf(stdout, "\n");
8716         loc(stdout, state, 0);
8717         fprintf(stdout, "\n__________ function_definition _________\n");
8718         print_triple(state, def);
8719         fprintf(stdout, "__________ function_definition _________ done\n\n");
8720 #endif
8721
8722         return def;
8723 }
8724
8725 static struct triple *do_decl(struct compile_state *state, 
8726         struct type *type, struct hash_entry *ident)
8727 {
8728         struct triple *def;
8729         def = 0;
8730         /* Clean up the storage types used */
8731         switch (type->type & STOR_MASK) {
8732         case STOR_AUTO:
8733         case STOR_STATIC:
8734                 /* These are the good types I am aiming for */
8735                 break;
8736         case STOR_REGISTER:
8737                 type->type &= ~STOR_MASK;
8738                 type->type |= STOR_AUTO;
8739                 break;
8740         case STOR_EXTERN:
8741                 type->type &= ~STOR_MASK;
8742                 type->type |= STOR_STATIC;
8743                 break;
8744         case STOR_TYPEDEF:
8745                 if (!ident) {
8746                         error(state, 0, "typedef without name");
8747                 }
8748                 symbol(state, ident, &ident->sym_ident, 0, type);
8749                 ident->tok = TOK_TYPE_NAME;
8750                 return 0;
8751                 break;
8752         default:
8753                 internal_error(state, 0, "Undefined storage class");
8754         }
8755         if (((type->type & STOR_MASK) == STOR_STATIC) &&
8756                 ((type->type & QUAL_CONST) == 0)) {
8757                 error(state, 0, "non const static variables not supported");
8758         }
8759         if (ident) {
8760                 def = variable(state, type);
8761                 symbol(state, ident, &ident->sym_ident, def, type);
8762         }
8763         return def;
8764 }
8765
8766 static void decl(struct compile_state *state, struct triple *first)
8767 {
8768         struct type *base_type, *type;
8769         struct hash_entry *ident;
8770         struct triple *def;
8771         int global;
8772         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8773         base_type = decl_specifiers(state);
8774         ident = 0;
8775         type = declarator(state, base_type, &ident, 0);
8776         if (global && ident && (peek(state) == TOK_LBRACE)) {
8777                 /* function */
8778                 def = function_definition(state, type);
8779                 symbol(state, ident, &ident->sym_ident, def, type);
8780         }
8781         else {
8782                 int done;
8783                 flatten(state, first, do_decl(state, type, ident));
8784                 /* type or variable definition */
8785                 do {
8786                         done = 1;
8787                         if (peek(state) == TOK_EQ) {
8788                                 if (!ident) {
8789                                         error(state, 0, "cannot assign to a type");
8790                                 }
8791                                 eat(state, TOK_EQ);
8792                                 flatten(state, first,
8793                                         init_expr(state, 
8794                                                 ident->sym_ident->def, 
8795                                                 initializer(state, type)));
8796                         }
8797                         arrays_complete(state, type);
8798                         if (peek(state) == TOK_COMMA) {
8799                                 eat(state, TOK_COMMA);
8800                                 ident = 0;
8801                                 type = declarator(state, base_type, &ident, 0);
8802                                 flatten(state, first, do_decl(state, type, ident));
8803                                 done = 0;
8804                         }
8805                 } while(!done);
8806                 eat(state, TOK_SEMI);
8807         }
8808 }
8809
8810 static void decls(struct compile_state *state)
8811 {
8812         struct triple *list;
8813         int tok;
8814         list = label(state);
8815         while(1) {
8816                 tok = peek(state);
8817                 if (tok == TOK_EOF) {
8818                         return;
8819                 }
8820                 if (tok == TOK_SPACE) {
8821                         eat(state, TOK_SPACE);
8822                 }
8823                 decl(state, list);
8824                 if (list->next != list) {
8825                         error(state, 0, "global variables not supported");
8826                 }
8827         }
8828 }
8829
8830 /*
8831  * Data structurs for optimation.
8832  */
8833
8834 static void do_use_block(
8835         struct block *used, struct block_set **head, struct block *user, 
8836         int front)
8837 {
8838         struct block_set **ptr, *new;
8839         if (!used)
8840                 return;
8841         if (!user)
8842                 return;
8843         ptr = head;
8844         while(*ptr) {
8845                 if ((*ptr)->member == user) {
8846                         return;
8847                 }
8848                 ptr = &(*ptr)->next;
8849         }
8850         new = xcmalloc(sizeof(*new), "block_set");
8851         new->member = user;
8852         if (front) {
8853                 new->next = *head;
8854                 *head = new;
8855         }
8856         else {
8857                 new->next = 0;
8858                 *ptr = new;
8859         }
8860 }
8861 static void do_unuse_block(
8862         struct block *used, struct block_set **head, struct block *unuser)
8863 {
8864         struct block_set *use, **ptr;
8865         ptr = head;
8866         while(*ptr) {
8867                 use = *ptr;
8868                 if (use->member == unuser) {
8869                         *ptr = use->next;
8870                         memset(use, -1, sizeof(*use));
8871                         xfree(use);
8872                 }
8873                 else {
8874                         ptr = &use->next;
8875                 }
8876         }
8877 }
8878
8879 static void use_block(struct block *used, struct block *user)
8880 {
8881         /* Append new to the head of the list, print_block
8882          * depends on this.
8883          */
8884         do_use_block(used, &used->use, user, 1); 
8885         used->users++;
8886 }
8887 static void unuse_block(struct block *used, struct block *unuser)
8888 {
8889         do_unuse_block(used, &used->use, unuser); 
8890         used->users--;
8891 }
8892
8893 static void idom_block(struct block *idom, struct block *user)
8894 {
8895         do_use_block(idom, &idom->idominates, user, 0);
8896 }
8897
8898 static void unidom_block(struct block *idom, struct block *unuser)
8899 {
8900         do_unuse_block(idom, &idom->idominates, unuser);
8901 }
8902
8903 static void domf_block(struct block *block, struct block *domf)
8904 {
8905         do_use_block(block, &block->domfrontier, domf, 0);
8906 }
8907
8908 static void undomf_block(struct block *block, struct block *undomf)
8909 {
8910         do_unuse_block(block, &block->domfrontier, undomf);
8911 }
8912
8913 static void ipdom_block(struct block *ipdom, struct block *user)
8914 {
8915         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8916 }
8917
8918 static void unipdom_block(struct block *ipdom, struct block *unuser)
8919 {
8920         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8921 }
8922
8923 static void ipdomf_block(struct block *block, struct block *ipdomf)
8924 {
8925         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8926 }
8927
8928 static void unipdomf_block(struct block *block, struct block *unipdomf)
8929 {
8930         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8931 }
8932
8933
8934
8935 static int do_walk_triple(struct compile_state *state,
8936         struct triple *ptr, int depth,
8937         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
8938 {
8939         int result;
8940         result = cb(state, ptr, depth);
8941         if ((result == 0) && (ptr->op == OP_LIST)) {
8942                 struct triple *list;
8943                 list = ptr;
8944                 ptr = RHS(list, 0);
8945                 do {
8946                         result = do_walk_triple(state, ptr, depth + 1, cb);
8947                         if (ptr->next->prev != ptr) {
8948                                 internal_error(state, ptr->next, "bad prev");
8949                         }
8950                         ptr = ptr->next;
8951                         
8952                 } while((result == 0) && (ptr != RHS(list, 0)));
8953         }
8954         return result;
8955 }
8956
8957 static int walk_triple(
8958         struct compile_state *state, 
8959         struct triple *ptr, 
8960         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8961 {
8962         return do_walk_triple(state, ptr, 0, cb);
8963 }
8964
8965 static void do_print_prefix(int depth)
8966 {
8967         int i;
8968         for(i = 0; i < depth; i++) {
8969                 printf("  ");
8970         }
8971 }
8972
8973 #define PRINT_LIST 1
8974 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8975 {
8976         int op;
8977         op = ins->op;
8978         if (op == OP_LIST) {
8979 #if !PRINT_LIST
8980                 return 0;
8981 #endif
8982         }
8983         if ((op == OP_LABEL) && (ins->use)) {
8984                 printf("\n%p:\n", ins);
8985         }
8986         do_print_prefix(depth);
8987         display_triple(stdout, ins);
8988
8989         if ((ins->op == OP_BRANCH) && ins->use) {
8990                 internal_error(state, ins, "branch used?");
8991         }
8992 #if 0
8993         {
8994                 struct triple_set *user;
8995                 for(user = ins->use; user; user = user->next) {
8996                         printf("use: %p\n", user->member);
8997                 }
8998         }
8999 #endif
9000         if (triple_is_branch(state, ins)) {
9001                 printf("\n");
9002         }
9003         return 0;
9004 }
9005
9006 static void print_triple(struct compile_state *state, struct triple *ins)
9007 {
9008         walk_triple(state, ins, do_print_triple);
9009 }
9010
9011 static void print_triples(struct compile_state *state)
9012 {
9013         print_triple(state, state->main_function);
9014 }
9015
9016 struct cf_block {
9017         struct block *block;
9018 };
9019 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9020 {
9021         if (!block || (cf[block->vertex].block == block)) {
9022                 return;
9023         }
9024         cf[block->vertex].block = block;
9025         find_cf_blocks(cf, block->left);
9026         find_cf_blocks(cf, block->right);
9027 }
9028
9029 static void print_control_flow(struct compile_state *state)
9030 {
9031         struct cf_block *cf;
9032         int i;
9033         printf("\ncontrol flow\n");
9034         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9035         find_cf_blocks(cf, state->first_block);
9036
9037         for(i = 1; i <= state->last_vertex; i++) {
9038                 struct block *block;
9039                 block = cf[i].block;
9040                 if (!block)
9041                         continue;
9042                 printf("(%p) %d:", block, block->vertex);
9043                 if (block->left) {
9044                         printf(" %d", block->left->vertex);
9045                 }
9046                 if (block->right && (block->right != block->left)) {
9047                         printf(" %d", block->right->vertex);
9048                 }
9049                 printf("\n");
9050         }
9051
9052         xfree(cf);
9053 }
9054
9055
9056 static struct block *basic_block(struct compile_state *state,
9057         struct triple *first)
9058 {
9059         struct block *block;
9060         struct triple *ptr;
9061         int op;
9062         if (first->op != OP_LABEL) {
9063                 internal_error(state, 0, "block does not start with a label");
9064         }
9065         /* See if this basic block has already been setup */
9066         if (first->u.block != 0) {
9067                 return first->u.block;
9068         }
9069         /* Allocate another basic block structure */
9070         state->last_vertex += 1;
9071         block = xcmalloc(sizeof(*block), "block");
9072         block->first = block->last = first;
9073         block->vertex = state->last_vertex;
9074         ptr = first;
9075         do {
9076                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9077                         break;
9078                 }
9079                 block->last = ptr;
9080                 /* If ptr->u is not used remember where the baic block is */
9081                 if (triple_stores_block(state, ptr)) {
9082                         ptr->u.block = block;
9083                 }
9084                 if (ptr->op == OP_BRANCH) {
9085                         break;
9086                 }
9087                 ptr = ptr->next;
9088         } while (ptr != RHS(state->main_function, 0));
9089         if (ptr == RHS(state->main_function, 0))
9090                 return block;
9091         op = ptr->op;
9092         if (op == OP_LABEL) {
9093                 block->left = basic_block(state, ptr);
9094                 block->right = 0;
9095                 use_block(block->left, block);
9096         }
9097         else if (op == OP_BRANCH) {
9098                 block->left = 0;
9099                 /* Trace the branch target */
9100                 block->right = basic_block(state, TARG(ptr, 0));
9101                 use_block(block->right, block);
9102                 /* If there is a test trace the branch as well */
9103                 if (TRIPLE_RHS(ptr->sizes)) {
9104                         block->left = basic_block(state, ptr->next);
9105                         use_block(block->left, block);
9106                 }
9107         }
9108         else {
9109                 internal_error(state, 0, "Bad basic block split");
9110         }
9111         return block;
9112 }
9113
9114
9115 static void walk_blocks(struct compile_state *state,
9116         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9117         void *arg)
9118 {
9119         struct triple *ptr, *first;
9120         struct block *last_block;
9121         last_block = 0;
9122         first = RHS(state->main_function, 0);
9123         ptr = first;
9124         do {
9125                 struct block *block;
9126                 if (ptr->op == OP_LABEL) {
9127                         block = ptr->u.block;
9128                         if (block && (block != last_block)) {
9129                                 cb(state, block, arg);
9130                         }
9131                         last_block = block;
9132                 }
9133                 ptr = ptr->next;
9134         } while(ptr != first);
9135 }
9136
9137 static void print_block(
9138         struct compile_state *state, struct block *block, void *arg)
9139 {
9140         struct triple *ptr;
9141         FILE *fp = arg;
9142
9143         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9144                 block, 
9145                 block->vertex,
9146                 block->left, 
9147                 block->left && block->left->use?block->left->use->member : 0,
9148                 block->right, 
9149                 block->right && block->right->use?block->right->use->member : 0);
9150         if (block->first->op == OP_LABEL) {
9151                 fprintf(fp, "%p:\n", block->first);
9152         }
9153         for(ptr = block->first; ; ptr = ptr->next) {
9154                 struct triple_set *user;
9155                 int op = ptr->op;
9156                 
9157                 if (triple_stores_block(state, ptr)) {
9158                         if (ptr->u.block != block) {
9159                                 internal_error(state, ptr, 
9160                                         "Wrong block pointer: %p\n",
9161                                         ptr->u.block);
9162                         }
9163                 }
9164                 if (op == OP_ADECL) {
9165                         for(user = ptr->use; user; user = user->next) {
9166                                 if (!user->member->u.block) {
9167                                         internal_error(state, user->member, 
9168                                                 "Use %p not in a block?\n",
9169                                                 user->member);
9170                                 }
9171                         }
9172                 }
9173                 display_triple(fp, ptr);
9174
9175 #if 0
9176                 for(user = ptr->use; user; user = user->next) {
9177                         fprintf(fp, "use: %p\n", user->member);
9178                 }
9179 #endif
9180
9181                 /* Sanity checks... */
9182                 valid_ins(state, ptr);
9183                 for(user = ptr->use; user; user = user->next) {
9184                         struct triple *use;
9185                         use = user->member;
9186                         valid_ins(state, use);
9187                         if (triple_stores_block(state, user->member) &&
9188                                 !user->member->u.block) {
9189                                 internal_error(state, user->member,
9190                                         "Use %p not in a block?",
9191                                         user->member);
9192                         }
9193                 }
9194
9195                 if (ptr == block->last)
9196                         break;
9197         }
9198         fprintf(fp,"\n");
9199 }
9200
9201
9202 static void print_blocks(struct compile_state *state, FILE *fp)
9203 {
9204         fprintf(fp, "--------------- blocks ---------------\n");
9205         walk_blocks(state, print_block, fp);
9206 }
9207
9208 static void prune_nonblock_triples(struct compile_state *state)
9209 {
9210         struct block *block;
9211         struct triple *first, *ins, *next;
9212         /* Delete the triples not in a basic block */
9213         first = RHS(state->main_function, 0);
9214         block = 0;
9215         ins = first;
9216         do {
9217                 next = ins->next;
9218                 if (ins->op == OP_LABEL) {
9219                         block = ins->u.block;
9220                 }
9221                 if (!block) {
9222                         release_triple(state, ins);
9223                 }
9224                 ins = next;
9225         } while(ins != first);
9226 }
9227
9228 static void setup_basic_blocks(struct compile_state *state)
9229 {
9230         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9231                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9232                 internal_error(state, 0, "ins will not store block?");
9233         }
9234         /* Find the basic blocks */
9235         state->last_vertex = 0;
9236         state->first_block = basic_block(state, RHS(state->main_function,0));
9237         /* Delete the triples not in a basic block */
9238         prune_nonblock_triples(state);
9239         /* Find the last basic block */
9240         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9241         if (!state->last_block) {
9242                 internal_error(state, 0, "end not used?");
9243         }
9244         /* Insert an extra unused edge from start to the end 
9245          * This helps with reverse control flow calculations.
9246          */
9247         use_block(state->first_block, state->last_block);
9248         /* If we are debugging print what I have just done */
9249         if (state->debug & DEBUG_BASIC_BLOCKS) {
9250                 print_blocks(state, stdout);
9251                 print_control_flow(state);
9252         }
9253 }
9254
9255 static void free_basic_block(struct compile_state *state, struct block *block)
9256 {
9257         struct block_set *entry, *next;
9258         struct block *child;
9259         if (!block) {
9260                 return;
9261         }
9262         if (block->vertex == -1) {
9263                 return;
9264         }
9265         block->vertex = -1;
9266         if (block->left) {
9267                 unuse_block(block->left, block);
9268         }
9269         if (block->right) {
9270                 unuse_block(block->right, block);
9271         }
9272         if (block->idom) {
9273                 unidom_block(block->idom, block);
9274         }
9275         block->idom = 0;
9276         if (block->ipdom) {
9277                 unipdom_block(block->ipdom, block);
9278         }
9279         block->ipdom = 0;
9280         for(entry = block->use; entry; entry = next) {
9281                 next = entry->next;
9282                 child = entry->member;
9283                 unuse_block(block, child);
9284                 if (child->left == block) {
9285                         child->left = 0;
9286                 }
9287                 if (child->right == block) {
9288                         child->right = 0;
9289                 }
9290         }
9291         for(entry = block->idominates; entry; entry = next) {
9292                 next = entry->next;
9293                 child = entry->member;
9294                 unidom_block(block, child);
9295                 child->idom = 0;
9296         }
9297         for(entry = block->domfrontier; entry; entry = next) {
9298                 next = entry->next;
9299                 child = entry->member;
9300                 undomf_block(block, child);
9301         }
9302         for(entry = block->ipdominates; entry; entry = next) {
9303                 next = entry->next;
9304                 child = entry->member;
9305                 unipdom_block(block, child);
9306                 child->ipdom = 0;
9307         }
9308         for(entry = block->ipdomfrontier; entry; entry = next) {
9309                 next = entry->next;
9310                 child = entry->member;
9311                 unipdomf_block(block, child);
9312         }
9313         if (block->users != 0) {
9314                 internal_error(state, 0, "block still has users");
9315         }
9316         free_basic_block(state, block->left);
9317         block->left = 0;
9318         free_basic_block(state, block->right);
9319         block->right = 0;
9320         memset(block, -1, sizeof(*block));
9321         xfree(block);
9322 }
9323
9324 static void free_basic_blocks(struct compile_state *state)
9325 {
9326         struct triple *first, *ins;
9327         free_basic_block(state, state->first_block);
9328         state->last_vertex = 0;
9329         state->first_block = state->last_block = 0;
9330         first = RHS(state->main_function, 0);
9331         ins = first;
9332         do {
9333                 if (triple_stores_block(state, ins)) {
9334                         ins->u.block = 0;
9335                 }
9336                 ins = ins->next;
9337         } while(ins != first);
9338         
9339 }
9340
9341 struct sdom_block {
9342         struct block *block;
9343         struct sdom_block *sdominates;
9344         struct sdom_block *sdom_next;
9345         struct sdom_block *sdom;
9346         struct sdom_block *label;
9347         struct sdom_block *parent;
9348         struct sdom_block *ancestor;
9349         int vertex;
9350 };
9351
9352
9353 static void unsdom_block(struct sdom_block *block)
9354 {
9355         struct sdom_block **ptr;
9356         if (!block->sdom_next) {
9357                 return;
9358         }
9359         ptr = &block->sdom->sdominates;
9360         while(*ptr) {
9361                 if ((*ptr) == block) {
9362                         *ptr = block->sdom_next;
9363                         return;
9364                 }
9365                 ptr = &(*ptr)->sdom_next;
9366         }
9367 }
9368
9369 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9370 {
9371         unsdom_block(block);
9372         block->sdom = sdom;
9373         block->sdom_next = sdom->sdominates;
9374         sdom->sdominates = block;
9375 }
9376
9377
9378
9379 static int initialize_sdblock(struct sdom_block *sd,
9380         struct block *parent, struct block *block, int vertex)
9381 {
9382         if (!block || (sd[block->vertex].block == block)) {
9383                 return vertex;
9384         }
9385         vertex += 1;
9386         /* Renumber the blocks in a convinient fashion */
9387         block->vertex = vertex;
9388         sd[vertex].block    = block;
9389         sd[vertex].sdom     = &sd[vertex];
9390         sd[vertex].label    = &sd[vertex];
9391         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9392         sd[vertex].ancestor = 0;
9393         sd[vertex].vertex   = vertex;
9394         vertex = initialize_sdblock(sd, block, block->left, vertex);
9395         vertex = initialize_sdblock(sd, block, block->right, vertex);
9396         return vertex;
9397 }
9398
9399 static int initialize_sdpblock(struct sdom_block *sd,
9400         struct block *parent, struct block *block, int vertex)
9401 {
9402         struct block_set *user;
9403         if (!block || (sd[block->vertex].block == block)) {
9404                 return vertex;
9405         }
9406         vertex += 1;
9407         /* Renumber the blocks in a convinient fashion */
9408         block->vertex = vertex;
9409         sd[vertex].block    = block;
9410         sd[vertex].sdom     = &sd[vertex];
9411         sd[vertex].label    = &sd[vertex];
9412         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9413         sd[vertex].ancestor = 0;
9414         sd[vertex].vertex   = vertex;
9415         for(user = block->use; user; user = user->next) {
9416                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9417         }
9418         return vertex;
9419 }
9420
9421 static void compress_ancestors(struct sdom_block *v)
9422 {
9423         /* This procedure assumes ancestor(v) != 0 */
9424         /* if (ancestor(ancestor(v)) != 0) {
9425          *      compress(ancestor(ancestor(v)));
9426          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9427          *              label(v) = label(ancestor(v));
9428          *      }
9429          *      ancestor(v) = ancestor(ancestor(v));
9430          * }
9431          */
9432         if (!v->ancestor) {
9433                 return;
9434         }
9435         if (v->ancestor->ancestor) {
9436                 compress_ancestors(v->ancestor->ancestor);
9437                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9438                         v->label = v->ancestor->label;
9439                 }
9440                 v->ancestor = v->ancestor->ancestor;
9441         }
9442 }
9443
9444 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9445 {
9446         int i;
9447         /* // step 2 
9448          *  for each v <= pred(w) {
9449          *      u = EVAL(v);
9450          *      if (semi[u] < semi[w] { 
9451          *              semi[w] = semi[u]; 
9452          *      } 
9453          * }
9454          * add w to bucket(vertex(semi[w]));
9455          * LINK(parent(w), w);
9456          *
9457          * // step 3
9458          * for each v <= bucket(parent(w)) {
9459          *      delete v from bucket(parent(w));
9460          *      u = EVAL(v);
9461          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9462          * }
9463          */
9464         for(i = state->last_vertex; i >= 2; i--) {
9465                 struct sdom_block *v, *parent, *next;
9466                 struct block_set *user;
9467                 struct block *block;
9468                 block = sd[i].block;
9469                 parent = sd[i].parent;
9470                 /* Step 2 */
9471                 for(user = block->use; user; user = user->next) {
9472                         struct sdom_block *v, *u;
9473                         v = &sd[user->member->vertex];
9474                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9475                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9476                                 sd[i].sdom = u->sdom;
9477                         }
9478                 }
9479                 sdom_block(sd[i].sdom, &sd[i]);
9480                 sd[i].ancestor = parent;
9481                 /* Step 3 */
9482                 for(v = parent->sdominates; v; v = next) {
9483                         struct sdom_block *u;
9484                         next = v->sdom_next;
9485                         unsdom_block(v);
9486                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9487                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9488                                 u->block : parent->block;
9489                 }
9490         }
9491 }
9492
9493 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9494 {
9495         int i;
9496         /* // step 2 
9497          *  for each v <= pred(w) {
9498          *      u = EVAL(v);
9499          *      if (semi[u] < semi[w] { 
9500          *              semi[w] = semi[u]; 
9501          *      } 
9502          * }
9503          * add w to bucket(vertex(semi[w]));
9504          * LINK(parent(w), w);
9505          *
9506          * // step 3
9507          * for each v <= bucket(parent(w)) {
9508          *      delete v from bucket(parent(w));
9509          *      u = EVAL(v);
9510          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9511          * }
9512          */
9513         for(i = state->last_vertex; i >= 2; i--) {
9514                 struct sdom_block *u, *v, *parent, *next;
9515                 struct block *block;
9516                 block = sd[i].block;
9517                 parent = sd[i].parent;
9518                 /* Step 2 */
9519                 if (block->left) {
9520                         v = &sd[block->left->vertex];
9521                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9522                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9523                                 sd[i].sdom = u->sdom;
9524                         }
9525                 }
9526                 if (block->right && (block->right != block->left)) {
9527                         v = &sd[block->right->vertex];
9528                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9529                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9530                                 sd[i].sdom = u->sdom;
9531                         }
9532                 }
9533                 sdom_block(sd[i].sdom, &sd[i]);
9534                 sd[i].ancestor = parent;
9535                 /* Step 3 */
9536                 for(v = parent->sdominates; v; v = next) {
9537                         struct sdom_block *u;
9538                         next = v->sdom_next;
9539                         unsdom_block(v);
9540                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9541                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9542                                 u->block : parent->block;
9543                 }
9544         }
9545 }
9546
9547 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9548 {
9549         int i;
9550         for(i = 2; i <= state->last_vertex; i++) {
9551                 struct block *block;
9552                 block = sd[i].block;
9553                 if (block->idom->vertex != sd[i].sdom->vertex) {
9554                         block->idom = block->idom->idom;
9555                 }
9556                 idom_block(block->idom, block);
9557         }
9558         sd[1].block->idom = 0;
9559 }
9560
9561 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9562 {
9563         int i;
9564         for(i = 2; i <= state->last_vertex; i++) {
9565                 struct block *block;
9566                 block = sd[i].block;
9567                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9568                         block->ipdom = block->ipdom->ipdom;
9569                 }
9570                 ipdom_block(block->ipdom, block);
9571         }
9572         sd[1].block->ipdom = 0;
9573 }
9574
9575         /* Theorem 1:
9576          *   Every vertex of a flowgraph G = (V, E, r) except r has
9577          *   a unique immediate dominator.  
9578          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9579          *   rooted at r, called the dominator tree of G, such that 
9580          *   v dominates w if and only if v is a proper ancestor of w in
9581          *   the dominator tree.
9582          */
9583         /* Lemma 1:  
9584          *   If v and w are vertices of G such that v <= w,
9585          *   than any path from v to w must contain a common ancestor
9586          *   of v and w in T.
9587          */
9588         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9589         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9590         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9591         /* Theorem 2:
9592          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9593          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9594          */
9595         /* Theorem 3:
9596          *   Let w != r and let u be a vertex for which sdom(u) is 
9597          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9598          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9599          */
9600         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9601          *           Then v -> idom(w) or idom(w) -> idom(v)
9602          */
9603
9604 static void find_immediate_dominators(struct compile_state *state)
9605 {
9606         struct sdom_block *sd;
9607         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9608          *           vi > w for (1 <= i <= k - 1}
9609          */
9610         /* Theorem 4:
9611          *   For any vertex w != r.
9612          *   sdom(w) = min(
9613          *                 {v|(v,w) <= E  and v < w } U 
9614          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9615          */
9616         /* Corollary 1:
9617          *   Let w != r and let u be a vertex for which sdom(u) is 
9618          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9619          *   Then:
9620          *                   { sdom(w) if sdom(w) = sdom(u),
9621          *        idom(w) = {
9622          *                   { idom(u) otherwise
9623          */
9624         /* The algorithm consists of the following 4 steps.
9625          * Step 1.  Carry out a depth-first search of the problem graph.  
9626          *    Number the vertices from 1 to N as they are reached during
9627          *    the search.  Initialize the variables used in succeeding steps.
9628          * Step 2.  Compute the semidominators of all vertices by applying
9629          *    theorem 4.   Carry out the computation vertex by vertex in
9630          *    decreasing order by number.
9631          * Step 3.  Implicitly define the immediate dominator of each vertex
9632          *    by applying Corollary 1.
9633          * Step 4.  Explicitly define the immediate dominator of each vertex,
9634          *    carrying out the computation vertex by vertex in increasing order
9635          *    by number.
9636          */
9637         /* Step 1 initialize the basic block information */
9638         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9639         initialize_sdblock(sd, 0, state->first_block, 0);
9640 #if 0
9641         sd[1].size  = 0;
9642         sd[1].label = 0;
9643         sd[1].sdom  = 0;
9644 #endif
9645         /* Step 2 compute the semidominators */
9646         /* Step 3 implicitly define the immediate dominator of each vertex */
9647         compute_sdom(state, sd);
9648         /* Step 4 explicitly define the immediate dominator of each vertex */
9649         compute_idom(state, sd);
9650         xfree(sd);
9651 }
9652
9653 static void find_post_dominators(struct compile_state *state)
9654 {
9655         struct sdom_block *sd;
9656         /* Step 1 initialize the basic block information */
9657         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9658
9659         initialize_sdpblock(sd, 0, state->last_block, 0);
9660
9661         /* Step 2 compute the semidominators */
9662         /* Step 3 implicitly define the immediate dominator of each vertex */
9663         compute_spdom(state, sd);
9664         /* Step 4 explicitly define the immediate dominator of each vertex */
9665         compute_ipdom(state, sd);
9666         xfree(sd);
9667 }
9668
9669
9670
9671 static void find_block_domf(struct compile_state *state, struct block *block)
9672 {
9673         struct block *child;
9674         struct block_set *user;
9675         if (block->domfrontier != 0) {
9676                 internal_error(state, block->first, "domfrontier present?");
9677         }
9678         for(user = block->idominates; user; user = user->next) {
9679                 child = user->member;
9680                 if (child->idom != block) {
9681                         internal_error(state, block->first, "bad idom");
9682                 }
9683                 find_block_domf(state, child);
9684         }
9685         if (block->left && block->left->idom != block) {
9686                 domf_block(block, block->left);
9687         }
9688         if (block->right && block->right->idom != block) {
9689                 domf_block(block, block->right);
9690         }
9691         for(user = block->idominates; user; user = user->next) {
9692                 struct block_set *frontier;
9693                 child = user->member;
9694                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9695                         if (frontier->member->idom != block) {
9696                                 domf_block(block, frontier->member);
9697                         }
9698                 }
9699         }
9700 }
9701
9702 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9703 {
9704         struct block *child;
9705         struct block_set *user;
9706         if (block->ipdomfrontier != 0) {
9707                 internal_error(state, block->first, "ipdomfrontier present?");
9708         }
9709         for(user = block->ipdominates; user; user = user->next) {
9710                 child = user->member;
9711                 if (child->ipdom != block) {
9712                         internal_error(state, block->first, "bad ipdom");
9713                 }
9714                 find_block_ipdomf(state, child);
9715         }
9716         if (block->left && block->left->ipdom != block) {
9717                 ipdomf_block(block, block->left);
9718         }
9719         if (block->right && block->right->ipdom != block) {
9720                 ipdomf_block(block, block->right);
9721         }
9722         for(user = block->idominates; user; user = user->next) {
9723                 struct block_set *frontier;
9724                 child = user->member;
9725                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9726                         if (frontier->member->ipdom != block) {
9727                                 ipdomf_block(block, frontier->member);
9728                         }
9729                 }
9730         }
9731 }
9732
9733 static void print_dominated(
9734         struct compile_state *state, struct block *block, void *arg)
9735 {
9736         struct block_set *user;
9737         FILE *fp = arg;
9738
9739         fprintf(fp, "%d:", block->vertex);
9740         for(user = block->idominates; user; user = user->next) {
9741                 fprintf(fp, " %d", user->member->vertex);
9742                 if (user->member->idom != block) {
9743                         internal_error(state, user->member->first, "bad idom");
9744                 }
9745         }
9746         fprintf(fp,"\n");
9747 }
9748
9749 static void print_dominators(struct compile_state *state, FILE *fp)
9750 {
9751         fprintf(fp, "\ndominates\n");
9752         walk_blocks(state, print_dominated, fp);
9753 }
9754
9755
9756 static int print_frontiers(
9757         struct compile_state *state, struct block *block, int vertex)
9758 {
9759         struct block_set *user;
9760
9761         if (!block || (block->vertex != vertex + 1)) {
9762                 return vertex;
9763         }
9764         vertex += 1;
9765
9766         printf("%d:", block->vertex);
9767         for(user = block->domfrontier; user; user = user->next) {
9768                 printf(" %d", user->member->vertex);
9769         }
9770         printf("\n");
9771
9772         vertex = print_frontiers(state, block->left, vertex);
9773         vertex = print_frontiers(state, block->right, vertex);
9774         return vertex;
9775 }
9776 static void print_dominance_frontiers(struct compile_state *state)
9777 {
9778         printf("\ndominance frontiers\n");
9779         print_frontiers(state, state->first_block, 0);
9780         
9781 }
9782
9783 static void analyze_idominators(struct compile_state *state)
9784 {
9785         /* Find the immediate dominators */
9786         find_immediate_dominators(state);
9787         /* Find the dominance frontiers */
9788         find_block_domf(state, state->first_block);
9789         /* If debuging print the print what I have just found */
9790         if (state->debug & DEBUG_FDOMINATORS) {
9791                 print_dominators(state, stdout);
9792                 print_dominance_frontiers(state);
9793                 print_control_flow(state);
9794         }
9795 }
9796
9797
9798
9799 static void print_ipdominated(
9800         struct compile_state *state, struct block *block, void *arg)
9801 {
9802         struct block_set *user;
9803         FILE *fp = arg;
9804
9805         fprintf(fp, "%d:", block->vertex);
9806         for(user = block->ipdominates; user; user = user->next) {
9807                 fprintf(fp, " %d", user->member->vertex);
9808                 if (user->member->ipdom != block) {
9809                         internal_error(state, user->member->first, "bad ipdom");
9810                 }
9811         }
9812         fprintf(fp, "\n");
9813 }
9814
9815 static void print_ipdominators(struct compile_state *state, FILE *fp)
9816 {
9817         fprintf(fp, "\nipdominates\n");
9818         walk_blocks(state, print_ipdominated, fp);
9819 }
9820
9821 static int print_pfrontiers(
9822         struct compile_state *state, struct block *block, int vertex)
9823 {
9824         struct block_set *user;
9825
9826         if (!block || (block->vertex != vertex + 1)) {
9827                 return vertex;
9828         }
9829         vertex += 1;
9830
9831         printf("%d:", block->vertex);
9832         for(user = block->ipdomfrontier; user; user = user->next) {
9833                 printf(" %d", user->member->vertex);
9834         }
9835         printf("\n");
9836         for(user = block->use; user; user = user->next) {
9837                 vertex = print_pfrontiers(state, user->member, vertex);
9838         }
9839         return vertex;
9840 }
9841 static void print_ipdominance_frontiers(struct compile_state *state)
9842 {
9843         printf("\nipdominance frontiers\n");
9844         print_pfrontiers(state, state->last_block, 0);
9845         
9846 }
9847
9848 static void analyze_ipdominators(struct compile_state *state)
9849 {
9850         /* Find the post dominators */
9851         find_post_dominators(state);
9852         /* Find the control dependencies (post dominance frontiers) */
9853         find_block_ipdomf(state, state->last_block);
9854         /* If debuging print the print what I have just found */
9855         if (state->debug & DEBUG_RDOMINATORS) {
9856                 print_ipdominators(state, stdout);
9857                 print_ipdominance_frontiers(state);
9858                 print_control_flow(state);
9859         }
9860 }
9861
9862 static int bdominates(struct compile_state *state,
9863         struct block *dom, struct block *sub)
9864 {
9865         while(sub && (sub != dom)) {
9866                 sub = sub->idom;
9867         }
9868         return sub == dom;
9869 }
9870
9871 static int tdominates(struct compile_state *state,
9872         struct triple *dom, struct triple *sub)
9873 {
9874         struct block *bdom, *bsub;
9875         int result;
9876         bdom = block_of_triple(state, dom);
9877         bsub = block_of_triple(state, sub);
9878         if (bdom != bsub) {
9879                 result = bdominates(state, bdom, bsub);
9880         } 
9881         else {
9882                 struct triple *ins;
9883                 ins = sub;
9884                 while((ins != bsub->first) && (ins != dom)) {
9885                         ins = ins->prev;
9886                 }
9887                 result = (ins == dom);
9888         }
9889         return result;
9890 }
9891
9892 static void insert_phi_operations(struct compile_state *state)
9893 {
9894         size_t size;
9895         struct triple *first;
9896         int *has_already, *work;
9897         struct block *work_list, **work_list_tail;
9898         int iter;
9899         struct triple *var;
9900
9901         size = sizeof(int) * (state->last_vertex + 1);
9902         has_already = xcmalloc(size, "has_already");
9903         work =        xcmalloc(size, "work");
9904         iter = 0;
9905
9906         first = RHS(state->main_function, 0);
9907         for(var = first->next; var != first ; var = var->next) {
9908                 struct block *block;
9909                 struct triple_set *user;
9910                 if ((var->op != OP_ADECL) || !var->use) {
9911                         continue;
9912                 }
9913                 iter += 1;
9914                 work_list = 0;
9915                 work_list_tail = &work_list;
9916                 for(user = var->use; user; user = user->next) {
9917                         if (user->member->op == OP_READ) {
9918                                 continue;
9919                         }
9920                         if (user->member->op != OP_WRITE) {
9921                                 internal_error(state, user->member, 
9922                                         "bad variable access");
9923                         }
9924                         block = user->member->u.block;
9925                         if (!block) {
9926                                 warning(state, user->member, "dead code");
9927                         }
9928                         if (work[block->vertex] >= iter) {
9929                                 continue;
9930                         }
9931                         work[block->vertex] = iter;
9932                         *work_list_tail = block;
9933                         block->work_next = 0;
9934                         work_list_tail = &block->work_next;
9935                 }
9936                 for(block = work_list; block; block = block->work_next) {
9937                         struct block_set *df;
9938                         for(df = block->domfrontier; df; df = df->next) {
9939                                 struct triple *phi;
9940                                 struct block *front;
9941                                 int in_edges;
9942                                 front = df->member;
9943
9944                                 if (has_already[front->vertex] >= iter) {
9945                                         continue;
9946                                 }
9947                                 /* Count how many edges flow into this block */
9948                                 in_edges = front->users;
9949                                 /* Insert a phi function for this variable */
9950                                 phi = alloc_triple(
9951                                         state, OP_PHI, var->type, -1, in_edges, 
9952                                         front->first->filename, 
9953                                         front->first->line,
9954                                         front->first->col);
9955                                 phi->u.block = front;
9956                                 MISC(phi, 0) = var;
9957                                 use_triple(var, phi);
9958                                 /* Insert the phi functions immediately after the label */
9959                                 insert_triple(state, front->first->next, phi);
9960                                 if (front->first == front->last) {
9961                                         front->last = front->first->next;
9962                                 }
9963                                 has_already[front->vertex] = iter;
9964
9965                                 /* If necessary plan to visit the basic block */
9966                                 if (work[front->vertex] >= iter) {
9967                                         continue;
9968                                 }
9969                                 work[front->vertex] = iter;
9970                                 *work_list_tail = front;
9971                                 front->work_next = 0;
9972                                 work_list_tail = &front->work_next;
9973                         }
9974                 }
9975         }
9976         xfree(has_already);
9977         xfree(work);
9978 }
9979
9980 /*
9981  * C(V)
9982  * S(V)
9983  */
9984 static void fixup_block_phi_variables(
9985         struct compile_state *state, struct block *parent, struct block *block)
9986 {
9987         struct block_set *set;
9988         struct triple *ptr;
9989         int edge;
9990         if (!parent || !block)
9991                 return;
9992         /* Find the edge I am coming in on */
9993         edge = 0;
9994         for(set = block->use; set; set = set->next, edge++) {
9995                 if (set->member == parent) {
9996                         break;
9997                 }
9998         }
9999         if (!set) {
10000                 internal_error(state, 0, "phi input is not on a control predecessor");
10001         }
10002         for(ptr = block->first; ; ptr = ptr->next) {
10003                 if (ptr->op == OP_PHI) {
10004                         struct triple *var, *val, **slot;
10005                         var = MISC(ptr, 0);
10006                         if (!var) {
10007                                 internal_error(state, ptr, "no var???");
10008                         }
10009                         /* Find the current value of the variable */
10010                         val = var->use->member;
10011                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10012                                 internal_error(state, val, "bad value in phi");
10013                         }
10014                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10015                                 internal_error(state, ptr, "edges > phi rhs");
10016                         }
10017                         slot = &RHS(ptr, edge);
10018                         if ((*slot != 0) && (*slot != val)) {
10019                                 internal_error(state, ptr, "phi already bound on this edge");
10020                         }
10021                         *slot = val;
10022                         use_triple(val, ptr);
10023                 }
10024                 if (ptr == block->last) {
10025                         break;
10026                 }
10027         }
10028 }
10029
10030
10031 static void rename_block_variables(
10032         struct compile_state *state, struct block *block)
10033 {
10034         struct block_set *user;
10035         struct triple *ptr, *next, *last;
10036         int done;
10037         if (!block)
10038                 return;
10039         last = block->first;
10040         done = 0;
10041         for(ptr = block->first; !done; ptr = next) {
10042                 next = ptr->next;
10043                 if (ptr == block->last) {
10044                         done = 1;
10045                 }
10046                 /* RHS(A) */
10047                 if (ptr->op == OP_READ) {
10048                         struct triple *var, *val;
10049                         var = RHS(ptr, 0);
10050                         unuse_triple(var, ptr);
10051                         if (!var->use) {
10052                                 error(state, ptr, "variable used without being set");
10053                         }
10054                         /* Find the current value of the variable */
10055                         val = var->use->member;
10056                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10057                                 internal_error(state, val, "bad value in read");
10058                         }
10059                         propogate_use(state, ptr, val);
10060                         release_triple(state, ptr);
10061                         continue;
10062                 }
10063                 /* LHS(A) */
10064                 if (ptr->op == OP_WRITE) {
10065                         struct triple *var, *val;
10066                         var = LHS(ptr, 0);
10067                         val = RHS(ptr, 0);
10068                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10069                                 internal_error(state, val, "bad value in write");
10070                         }
10071                         propogate_use(state, ptr, val);
10072                         unuse_triple(var, ptr);
10073                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10074                         push_triple(var, val);
10075                 }
10076                 if (ptr->op == OP_PHI) {
10077                         struct triple *var;
10078                         var = MISC(ptr, 0);
10079                         /* Push OP_PHI onto a stack of variable uses */
10080                         push_triple(var, ptr);
10081                 }
10082                 last = ptr;
10083         }
10084         block->last = last;
10085
10086         /* Fixup PHI functions in the cf successors */
10087         fixup_block_phi_variables(state, block, block->left);
10088         fixup_block_phi_variables(state, block, block->right);
10089         /* rename variables in the dominated nodes */
10090         for(user = block->idominates; user; user = user->next) {
10091                 rename_block_variables(state, user->member);
10092         }
10093         /* pop the renamed variable stack */
10094         last = block->first;
10095         done = 0;
10096         for(ptr = block->first; !done ; ptr = next) {
10097                 next = ptr->next;
10098                 if (ptr == block->last) {
10099                         done = 1;
10100                 }
10101                 if (ptr->op == OP_WRITE) {
10102                         struct triple *var;
10103                         var = LHS(ptr, 0);
10104                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10105                         pop_triple(var, RHS(ptr, 0));
10106                         release_triple(state, ptr);
10107                         continue;
10108                 }
10109                 if (ptr->op == OP_PHI) {
10110                         struct triple *var;
10111                         var = MISC(ptr, 0);
10112                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10113                         pop_triple(var, ptr);
10114                 }
10115                 last = ptr;
10116         }
10117         block->last = last;
10118 }
10119
10120 static void prune_block_variables(struct compile_state *state,
10121         struct block *block)
10122 {
10123         struct block_set *user;
10124         struct triple *next, *last, *ptr;
10125         int done;
10126         last = block->first;
10127         done = 0;
10128         for(ptr = block->first; !done; ptr = next) {
10129                 next = ptr->next;
10130                 if (ptr == block->last) {
10131                         done = 1;
10132                 }
10133                 if (ptr->op == OP_ADECL) {
10134                         struct triple_set *user, *next;
10135                         for(user = ptr->use; user; user = next) {
10136                                 struct triple *use;
10137                                 next = user->next;
10138                                 use = user->member;
10139                                 if (use->op != OP_PHI) {
10140                                         internal_error(state, use, "decl still used");
10141                                 }
10142                                 if (MISC(use, 0) != ptr) {
10143                                         internal_error(state, use, "bad phi use of decl");
10144                                 }
10145                                 unuse_triple(ptr, use);
10146                                 MISC(use, 0) = 0;
10147                         }
10148                         release_triple(state, ptr);
10149                         continue;
10150                 }
10151                 last = ptr;
10152         }
10153         block->last = last;
10154         for(user = block->idominates; user; user = user->next) {
10155                 prune_block_variables(state, user->member);
10156         }
10157 }
10158
10159 static void transform_to_ssa_form(struct compile_state *state)
10160 {
10161         insert_phi_operations(state);
10162 #if 0
10163         printf("@%s:%d\n", __FILE__, __LINE__);
10164         print_blocks(state, stdout);
10165 #endif
10166         rename_block_variables(state, state->first_block);
10167         prune_block_variables(state, state->first_block);
10168 }
10169
10170
10171 static void clear_vertex(
10172         struct compile_state *state, struct block *block, void *arg)
10173 {
10174         block->vertex = 0;
10175 }
10176
10177 static void mark_live_block(
10178         struct compile_state *state, struct block *block, int *next_vertex)
10179 {
10180         /* See if this is a block that has not been marked */
10181         if (block->vertex != 0) {
10182                 return;
10183         }
10184         block->vertex = *next_vertex;
10185         *next_vertex += 1;
10186         if (triple_is_branch(state, block->last)) {
10187                 struct triple **targ;
10188                 targ = triple_targ(state, block->last, 0);
10189                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10190                         if (!*targ) {
10191                                 continue;
10192                         }
10193                         if (!triple_stores_block(state, *targ)) {
10194                                 internal_error(state, 0, "bad targ");
10195                         }
10196                         mark_live_block(state, (*targ)->u.block, next_vertex);
10197                 }
10198         }
10199         else if (block->last->next != RHS(state->main_function, 0)) {
10200                 struct triple *ins;
10201                 ins = block->last->next;
10202                 if (!triple_stores_block(state, ins)) {
10203                         internal_error(state, 0, "bad block start");
10204                 }
10205                 mark_live_block(state, ins->u.block, next_vertex);
10206         }
10207 }
10208
10209 static void transform_from_ssa_form(struct compile_state *state)
10210 {
10211         /* To get out of ssa form we insert moves on the incoming
10212          * edges to blocks containting phi functions.
10213          */
10214         struct triple *first;
10215         struct triple *phi, *next;
10216         int next_vertex;
10217
10218         /* Walk the control flow to see which blocks remain alive */
10219         walk_blocks(state, clear_vertex, 0);
10220         next_vertex = 1;
10221         mark_live_block(state, state->first_block, &next_vertex);
10222
10223         /* Walk all of the operations to find the phi functions */
10224         first = RHS(state->main_function, 0);
10225         for(phi = first->next; phi != first ; phi = next) {
10226                 struct block_set *set;
10227                 struct block *block;
10228                 struct triple **slot;
10229                 struct triple *var, *read;
10230                 struct triple_set *use, *use_next;
10231                 int edge, used;
10232                 next = phi->next;
10233                 if (phi->op != OP_PHI) {
10234                         continue;
10235                 }
10236                 block = phi->u.block;
10237                 slot  = &RHS(phi, 0);
10238
10239                 /* Forget uses from code in dead blocks */
10240                 for(use = phi->use; use; use = use_next) {
10241                         struct block *ublock;
10242                         struct triple **expr;
10243                         use_next = use->next;
10244                         ublock = block_of_triple(state, use->member);
10245                         if ((use->member == phi) || (ublock->vertex != 0)) {
10246                                 continue;
10247                         }
10248                         expr = triple_rhs(state, use->member, 0);
10249                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10250                                 if (*expr == phi) {
10251                                         *expr = 0;
10252                                 }
10253                         }
10254                         unuse_triple(phi, use->member);
10255                 }
10256
10257                 /* A variable to replace the phi function */
10258                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10259                 /* A read of the single value that is set into the variable */
10260                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10261                 use_triple(var, read);
10262
10263                 /* Replaces uses of the phi with variable reads */
10264                 propogate_use(state, phi, read);
10265
10266                 /* Walk all of the incoming edges/blocks and insert moves.
10267                  */
10268                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10269                         struct block *eblock;
10270                         struct triple *move;
10271                         struct triple *val;
10272                         eblock = set->member;
10273                         val = slot[edge];
10274                         slot[edge] = 0;
10275                         unuse_triple(val, phi);
10276
10277                         if (!val || (val == &zero_triple) ||
10278                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10279                                 (val == phi) || (val == read)) {
10280                                 continue;
10281                         }
10282                         
10283                         move = post_triple(state, 
10284                                 val, OP_WRITE, phi->type, var, val);
10285                         use_triple(val, move);
10286                         use_triple(var, move);
10287                 }               
10288                 /* See if there are any writers of var */
10289                 used = 0;
10290                 for(use = var->use; use; use = use->next) {
10291                         struct triple **expr;
10292                         expr = triple_lhs(state, use->member, 0);
10293                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10294                                 if (*expr == var) {
10295                                         used = 1;
10296                                 }
10297                         }
10298                 }
10299                 /* If var is not used free it */
10300                 if (!used) {
10301                         unuse_triple(var, read);
10302                         free_triple(state, read);
10303                         free_triple(state, var);
10304                 }
10305
10306                 /* Release the phi function */
10307                 release_triple(state, phi);
10308         }
10309         
10310 }
10311
10312
10313 /* 
10314  * Register conflict resolution
10315  * =========================================================
10316  */
10317
10318 static struct reg_info find_def_color(
10319         struct compile_state *state, struct triple *def)
10320 {
10321         struct triple_set *set;
10322         struct reg_info info;
10323         info.reg = REG_UNSET;
10324         info.regcm = 0;
10325         if (!triple_is_def(state, def)) {
10326                 return info;
10327         }
10328         info = arch_reg_lhs(state, def, 0);
10329         if (info.reg >= MAX_REGISTERS) {
10330                 info.reg = REG_UNSET;
10331         }
10332         for(set = def->use; set; set = set->next) {
10333                 struct reg_info tinfo;
10334                 int i;
10335                 i = find_rhs_use(state, set->member, def);
10336                 if (i < 0) {
10337                         continue;
10338                 }
10339                 tinfo = arch_reg_rhs(state, set->member, i);
10340                 if (tinfo.reg >= MAX_REGISTERS) {
10341                         tinfo.reg = REG_UNSET;
10342                 }
10343                 if ((tinfo.reg != REG_UNSET) && 
10344                         (info.reg != REG_UNSET) &&
10345                         (tinfo.reg != info.reg)) {
10346                         internal_error(state, def, "register conflict");
10347                 }
10348                 if ((info.regcm & tinfo.regcm) == 0) {
10349                         internal_error(state, def, "regcm conflict %x & %x == 0",
10350                                 info.regcm, tinfo.regcm);
10351                 }
10352                 if (info.reg == REG_UNSET) {
10353                         info.reg = tinfo.reg;
10354                 }
10355                 info.regcm &= tinfo.regcm;
10356         }
10357         if (info.reg >= MAX_REGISTERS) {
10358                 internal_error(state, def, "register out of range");
10359         }
10360         return info;
10361 }
10362
10363 static struct reg_info find_lhs_pre_color(
10364         struct compile_state *state, struct triple *ins, int index)
10365 {
10366         struct reg_info info;
10367         int zlhs, zrhs, i;
10368         zrhs = TRIPLE_RHS(ins->sizes);
10369         zlhs = TRIPLE_LHS(ins->sizes);
10370         if (!zlhs && triple_is_def(state, ins)) {
10371                 zlhs = 1;
10372         }
10373         if (index >= zlhs) {
10374                 internal_error(state, ins, "Bad lhs %d", index);
10375         }
10376         info = arch_reg_lhs(state, ins, index);
10377         for(i = 0; i < zrhs; i++) {
10378                 struct reg_info rinfo;
10379                 rinfo = arch_reg_rhs(state, ins, i);
10380                 if ((info.reg == rinfo.reg) &&
10381                         (rinfo.reg >= MAX_REGISTERS)) {
10382                         struct reg_info tinfo;
10383                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10384                         info.reg = tinfo.reg;
10385                         info.regcm &= tinfo.regcm;
10386                         break;
10387                 }
10388         }
10389         if (info.reg >= MAX_REGISTERS) {
10390                 info.reg = REG_UNSET;
10391         }
10392         return info;
10393 }
10394
10395 static struct reg_info find_rhs_post_color(
10396         struct compile_state *state, struct triple *ins, int index);
10397
10398 static struct reg_info find_lhs_post_color(
10399         struct compile_state *state, struct triple *ins, int index)
10400 {
10401         struct triple_set *set;
10402         struct reg_info info;
10403         struct triple *lhs;
10404 #if 0
10405         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10406                 ins, index);
10407 #endif
10408         if ((index == 0) && triple_is_def(state, ins)) {
10409                 lhs = ins;
10410         }
10411         else if (index < TRIPLE_LHS(ins->sizes)) {
10412                 lhs = LHS(ins, index);
10413         }
10414         else {
10415                 internal_error(state, ins, "Bad lhs %d", index);
10416                 lhs = 0;
10417         }
10418         info = arch_reg_lhs(state, ins, index);
10419         if (info.reg >= MAX_REGISTERS) {
10420                 info.reg = REG_UNSET;
10421         }
10422         for(set = lhs->use; set; set = set->next) {
10423                 struct reg_info rinfo;
10424                 struct triple *user;
10425                 int zrhs, i;
10426                 user = set->member;
10427                 zrhs = TRIPLE_RHS(user->sizes);
10428                 for(i = 0; i < zrhs; i++) {
10429                         if (RHS(user, i) != lhs) {
10430                                 continue;
10431                         }
10432                         rinfo = find_rhs_post_color(state, user, i);
10433                         if ((info.reg != REG_UNSET) &&
10434                                 (rinfo.reg != REG_UNSET) &&
10435                                 (info.reg != rinfo.reg)) {
10436                                 internal_error(state, ins, "register conflict");
10437                         }
10438                         if ((info.regcm & rinfo.regcm) == 0) {
10439                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10440                                         info.regcm, rinfo.regcm);
10441                         }
10442                         if (info.reg == REG_UNSET) {
10443                                 info.reg = rinfo.reg;
10444                         }
10445                         info.regcm &= rinfo.regcm;
10446                 }
10447         }
10448 #if 0
10449         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10450                 ins, index, info.reg, info.regcm);
10451 #endif
10452         return info;
10453 }
10454
10455 static struct reg_info find_rhs_post_color(
10456         struct compile_state *state, struct triple *ins, int index)
10457 {
10458         struct reg_info info, rinfo;
10459         int zlhs, i;
10460 #if 0
10461         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10462                 ins, index);
10463 #endif
10464         rinfo = arch_reg_rhs(state, ins, index);
10465         zlhs = TRIPLE_LHS(ins->sizes);
10466         if (!zlhs && triple_is_def(state, ins)) {
10467                 zlhs = 1;
10468         }
10469         info = rinfo;
10470         if (info.reg >= MAX_REGISTERS) {
10471                 info.reg = REG_UNSET;
10472         }
10473         for(i = 0; i < zlhs; i++) {
10474                 struct reg_info linfo;
10475                 linfo = arch_reg_lhs(state, ins, i);
10476                 if ((linfo.reg == rinfo.reg) &&
10477                         (linfo.reg >= MAX_REGISTERS)) {
10478                         struct reg_info tinfo;
10479                         tinfo = find_lhs_post_color(state, ins, i);
10480                         if (tinfo.reg >= MAX_REGISTERS) {
10481                                 tinfo.reg = REG_UNSET;
10482                         }
10483                         info.regcm &= linfo.reg;
10484                         info.regcm &= tinfo.regcm;
10485                         if (info.reg != REG_UNSET) {
10486                                 internal_error(state, ins, "register conflict");
10487                         }
10488                         if (info.regcm == 0) {
10489                                 internal_error(state, ins, "regcm conflict");
10490                         }
10491                         info.reg = tinfo.reg;
10492                 }
10493         }
10494 #if 0
10495         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10496                 ins, index, info.reg, info.regcm);
10497 #endif
10498         return info;
10499 }
10500
10501 static struct reg_info find_lhs_color(
10502         struct compile_state *state, struct triple *ins, int index)
10503 {
10504         struct reg_info pre, post, info;
10505 #if 0
10506         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10507                 ins, index);
10508 #endif
10509         pre = find_lhs_pre_color(state, ins, index);
10510         post = find_lhs_post_color(state, ins, index);
10511         if ((pre.reg != post.reg) &&
10512                 (pre.reg != REG_UNSET) &&
10513                 (post.reg != REG_UNSET)) {
10514                 internal_error(state, ins, "register conflict");
10515         }
10516         info.regcm = pre.regcm & post.regcm;
10517         info.reg = pre.reg;
10518         if (info.reg == REG_UNSET) {
10519                 info.reg = post.reg;
10520         }
10521 #if 0
10522         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10523                 ins, index, info.reg, info.regcm);
10524 #endif
10525         return info;
10526 }
10527
10528 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10529 {
10530         struct triple_set *entry, *next;
10531         struct triple *out;
10532         struct reg_info info, rinfo;
10533
10534         info = arch_reg_lhs(state, ins, 0);
10535         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10536         use_triple(RHS(out, 0), out);
10537         /* Get the users of ins to use out instead */
10538         for(entry = ins->use; entry; entry = next) {
10539                 int i;
10540                 next = entry->next;
10541                 if (entry->member == out) {
10542                         continue;
10543                 }
10544                 i = find_rhs_use(state, entry->member, ins);
10545                 if (i < 0) {
10546                         continue;
10547                 }
10548                 rinfo = arch_reg_rhs(state, entry->member, i);
10549                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10550                         continue;
10551                 }
10552                 replace_rhs_use(state, ins, out, entry->member);
10553         }
10554         transform_to_arch_instruction(state, out);
10555         return out;
10556 }
10557
10558 static struct triple *pre_copy(
10559         struct compile_state *state, struct triple *ins, int index)
10560 {
10561         /* Carefully insert enough operations so that I can
10562          * enter any operation with a GPR32.
10563          */
10564         struct triple *in;
10565         struct triple **expr;
10566         expr = &RHS(ins, index);
10567         in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10568         unuse_triple(*expr, ins);
10569         *expr = in;
10570         use_triple(RHS(in, 0), in);
10571         use_triple(in, ins);
10572         transform_to_arch_instruction(state, in);
10573         return in;
10574 }
10575
10576
10577 static void insert_copies_to_phi(struct compile_state *state)
10578 {
10579         /* To get out of ssa form we insert moves on the incoming
10580          * edges to blocks containting phi functions.
10581          */
10582         struct triple *first;
10583         struct triple *phi;
10584
10585         /* Walk all of the operations to find the phi functions */
10586         first = RHS(state->main_function, 0);
10587         for(phi = first->next; phi != first ; phi = phi->next) {
10588                 struct block_set *set;
10589                 struct block *block;
10590                 struct triple **slot;
10591                 int edge;
10592                 if (phi->op != OP_PHI) {
10593                         continue;
10594                 }
10595                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10596                 block = phi->u.block;
10597                 slot  = &RHS(phi, 0);
10598                 /* Walk all of the incoming edges/blocks and insert moves.
10599                  */
10600                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10601                         struct block *eblock;
10602                         struct triple *move;
10603                         struct triple *val;
10604                         struct triple *ptr;
10605                         eblock = set->member;
10606                         val = slot[edge];
10607
10608                         if (val == phi) {
10609                                 continue;
10610                         }
10611
10612                         move = build_triple(state, OP_COPY, phi->type, val, 0,
10613                                 val->filename, val->line, val->col);
10614                         move->u.block = eblock;
10615                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
10616                         use_triple(val, move);
10617                         
10618                         slot[edge] = move;
10619                         unuse_triple(val, phi);
10620                         use_triple(move, phi);
10621
10622                         /* Walk through the block backwards to find
10623                          * an appropriate location for the OP_COPY.
10624                          */
10625                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10626                                 struct triple **expr;
10627                                 if ((ptr == phi) || (ptr == val)) {
10628                                         goto out;
10629                                 }
10630                                 expr = triple_rhs(state, ptr, 0);
10631                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10632                                         if ((*expr) == phi) {
10633                                                 goto out;
10634                                         }
10635                                 }
10636                         }
10637                 out:
10638                         if (triple_is_branch(state, ptr)) {
10639                                 internal_error(state, ptr,
10640                                         "Could not insert write to phi");
10641                         }
10642                         insert_triple(state, ptr->next, move);
10643                         if (eblock->last == ptr) {
10644                                 eblock->last = move;
10645                         }
10646                         transform_to_arch_instruction(state, move);
10647                 }
10648         }
10649 }
10650
10651 struct triple_reg_set {
10652         struct triple_reg_set *next;
10653         struct triple *member;
10654         struct triple *new;
10655 };
10656
10657 struct reg_block {
10658         struct block *block;
10659         struct triple_reg_set *in;
10660         struct triple_reg_set *out;
10661         int vertex;
10662 };
10663
10664 static int do_triple_set(struct triple_reg_set **head, 
10665         struct triple *member, struct triple *new_member)
10666 {
10667         struct triple_reg_set **ptr, *new;
10668         if (!member)
10669                 return 0;
10670         ptr = head;
10671         while(*ptr) {
10672                 if ((*ptr)->member == member) {
10673                         return 0;
10674                 }
10675                 ptr = &(*ptr)->next;
10676         }
10677         new = xcmalloc(sizeof(*new), "triple_set");
10678         new->member = member;
10679         new->new    = new_member;
10680         new->next   = *head;
10681         *head       = new;
10682         return 1;
10683 }
10684
10685 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10686 {
10687         struct triple_reg_set *entry, **ptr;
10688         ptr = head;
10689         while(*ptr) {
10690                 entry = *ptr;
10691                 if (entry->member == member) {
10692                         *ptr = entry->next;
10693                         xfree(entry);
10694                         return;
10695                 }
10696                 else {
10697                         ptr = &entry->next;
10698                 }
10699         }
10700 }
10701
10702 static int in_triple(struct reg_block *rb, struct triple *in)
10703 {
10704         return do_triple_set(&rb->in, in, 0);
10705 }
10706 static void unin_triple(struct reg_block *rb, struct triple *unin)
10707 {
10708         do_triple_unset(&rb->in, unin);
10709 }
10710
10711 static int out_triple(struct reg_block *rb, struct triple *out)
10712 {
10713         return do_triple_set(&rb->out, out, 0);
10714 }
10715 static void unout_triple(struct reg_block *rb, struct triple *unout)
10716 {
10717         do_triple_unset(&rb->out, unout);
10718 }
10719
10720 static int initialize_regblock(struct reg_block *blocks,
10721         struct block *block, int vertex)
10722 {
10723         struct block_set *user;
10724         if (!block || (blocks[block->vertex].block == block)) {
10725                 return vertex;
10726         }
10727         vertex += 1;
10728         /* Renumber the blocks in a convinient fashion */
10729         block->vertex = vertex;
10730         blocks[vertex].block    = block;
10731         blocks[vertex].vertex   = vertex;
10732         for(user = block->use; user; user = user->next) {
10733                 vertex = initialize_regblock(blocks, user->member, vertex);
10734         }
10735         return vertex;
10736 }
10737
10738 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10739         struct reg_block *rb, struct block *suc)
10740 {
10741         /* Read the conditional input set of a successor block
10742          * (i.e. the input to the phi nodes) and place it in the
10743          * current blocks output set.
10744          */
10745         struct block_set *set;
10746         struct triple *ptr;
10747         int edge;
10748         int done, change;
10749         change = 0;
10750         /* Find the edge I am coming in on */
10751         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10752                 if (set->member == rb->block) {
10753                         break;
10754                 }
10755         }
10756         if (!set) {
10757                 internal_error(state, 0, "Not coming on a control edge?");
10758         }
10759         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10760                 struct triple **slot, *expr, *ptr2;
10761                 int out_change, done2;
10762                 done = (ptr == suc->last);
10763                 if (ptr->op != OP_PHI) {
10764                         continue;
10765                 }
10766                 slot = &RHS(ptr, 0);
10767                 expr = slot[edge];
10768                 out_change = out_triple(rb, expr);
10769                 if (!out_change) {
10770                         continue;
10771                 }
10772                 /* If we don't define the variable also plast it
10773                  * in the current blocks input set.
10774                  */
10775                 ptr2 = rb->block->first;
10776                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10777                         if (ptr2 == expr) {
10778                                 break;
10779                         }
10780                         done2 = (ptr2 == rb->block->last);
10781                 }
10782                 if (!done2) {
10783                         continue;
10784                 }
10785                 change |= in_triple(rb, expr);
10786         }
10787         return change;
10788 }
10789
10790 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10791         struct reg_block *rb, struct block *suc)
10792 {
10793         struct triple_reg_set *in_set;
10794         int change;
10795         change = 0;
10796         /* Read the input set of a successor block
10797          * and place it in the current blocks output set.
10798          */
10799         in_set = blocks[suc->vertex].in;
10800         for(; in_set; in_set = in_set->next) {
10801                 int out_change, done;
10802                 struct triple *first, *last, *ptr;
10803                 out_change = out_triple(rb, in_set->member);
10804                 if (!out_change) {
10805                         continue;
10806                 }
10807                 /* If we don't define the variable also place it
10808                  * in the current blocks input set.
10809                  */
10810                 first = rb->block->first;
10811                 last = rb->block->last;
10812                 done = 0;
10813                 for(ptr = first; !done; ptr = ptr->next) {
10814                         if (ptr == in_set->member) {
10815                                 break;
10816                         }
10817                         done = (ptr == last);
10818                 }
10819                 if (!done) {
10820                         continue;
10821                 }
10822                 change |= in_triple(rb, in_set->member);
10823         }
10824         change |= phi_in(state, blocks, rb, suc);
10825         return change;
10826 }
10827
10828
10829 static int use_in(struct compile_state *state, struct reg_block *rb)
10830 {
10831         /* Find the variables we use but don't define and add
10832          * it to the current blocks input set.
10833          */
10834 #warning "FIXME is this O(N^2) algorithm bad?"
10835         struct block *block;
10836         struct triple *ptr;
10837         int done;
10838         int change;
10839         block = rb->block;
10840         change = 0;
10841         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10842                 struct triple **expr;
10843                 done = (ptr == block->first);
10844                 /* The variable a phi function uses depends on the
10845                  * control flow, and is handled in phi_in, not
10846                  * here.
10847                  */
10848                 if (ptr->op == OP_PHI) {
10849                         continue;
10850                 }
10851                 expr = triple_rhs(state, ptr, 0);
10852                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10853                         struct triple *rhs, *test;
10854                         int tdone;
10855                         rhs = *expr;
10856                         if (!rhs) {
10857                                 continue;
10858                         }
10859                         /* See if rhs is defined in this block */
10860                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10861                                 tdone = (test == block->first);
10862                                 if (test == rhs) {
10863                                         rhs = 0;
10864                                         break;
10865                                 }
10866                         }
10867                         /* If I still have a valid rhs add it to in */
10868                         change |= in_triple(rb, rhs);
10869                 }
10870         }
10871         return change;
10872 }
10873
10874 static struct reg_block *compute_variable_lifetimes(
10875         struct compile_state *state)
10876 {
10877         struct reg_block *blocks;
10878         int change;
10879         blocks = xcmalloc(
10880                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10881         initialize_regblock(blocks, state->last_block, 0);
10882         do {
10883                 int i;
10884                 change = 0;
10885                 for(i = 1; i <= state->last_vertex; i++) {
10886                         struct reg_block *rb;
10887                         rb = &blocks[i];
10888                         /* Add the left successor's input set to in */
10889                         if (rb->block->left) {
10890                                 change |= reg_in(state, blocks, rb, rb->block->left);
10891                         }
10892                         /* Add the right successor's input set to in */
10893                         if ((rb->block->right) && 
10894                                 (rb->block->right != rb->block->left)) {
10895                                 change |= reg_in(state, blocks, rb, rb->block->right);
10896                         }
10897                         /* Add use to in... */
10898                         change |= use_in(state, rb);
10899                 }
10900         } while(change);
10901         return blocks;
10902 }
10903
10904 static void free_variable_lifetimes(
10905         struct compile_state *state, struct reg_block *blocks)
10906 {
10907         int i;
10908         /* free in_set && out_set on each block */
10909         for(i = 1; i <= state->last_vertex; i++) {
10910                 struct triple_reg_set *entry, *next;
10911                 struct reg_block *rb;
10912                 rb = &blocks[i];
10913                 for(entry = rb->in; entry ; entry = next) {
10914                         next = entry->next;
10915                         do_triple_unset(&rb->in, entry->member);
10916                 }
10917                 for(entry = rb->out; entry; entry = next) {
10918                         next = entry->next;
10919                         do_triple_unset(&rb->out, entry->member);
10920                 }
10921         }
10922         xfree(blocks);
10923
10924 }
10925
10926 typedef void (*wvl_cb_t)(
10927         struct compile_state *state, 
10928         struct reg_block *blocks, struct triple_reg_set *live, 
10929         struct reg_block *rb, struct triple *ins, void *arg);
10930
10931 static void walk_variable_lifetimes(struct compile_state *state,
10932         struct reg_block *blocks, wvl_cb_t cb, void *arg)
10933 {
10934         int i;
10935         
10936         for(i = 1; i <= state->last_vertex; i++) {
10937                 struct triple_reg_set *live;
10938                 struct triple_reg_set *entry, *next;
10939                 struct triple *ptr, *prev;
10940                 struct reg_block *rb;
10941                 struct block *block;
10942                 int done;
10943
10944                 /* Get the blocks */
10945                 rb = &blocks[i];
10946                 block = rb->block;
10947
10948                 /* Copy out into live */
10949                 live = 0;
10950                 for(entry = rb->out; entry; entry = next) {
10951                         next = entry->next;
10952                         do_triple_set(&live, entry->member, entry->new);
10953                 }
10954                 /* Walk through the basic block calculating live */
10955                 for(done = 0, ptr = block->last; !done; ptr = prev) {
10956                         struct triple **expr;
10957
10958                         prev = ptr->prev;
10959                         done = (ptr == block->first);
10960
10961                         /* Ensure the current definition is in live */
10962                         if (triple_is_def(state, ptr)) {
10963                                 do_triple_set(&live, ptr, 0);
10964                         }
10965
10966                         /* Inform the callback function of what is
10967                          * going on.
10968                          */
10969                          cb(state, blocks, live, rb, ptr, arg);
10970                         
10971                         /* Remove the current definition from live */
10972                         do_triple_unset(&live, ptr);
10973
10974                         /* Add the current uses to live.
10975                          *
10976                          * It is safe to skip phi functions because they do
10977                          * not have any block local uses, and the block
10978                          * output sets already properly account for what
10979                          * control flow depedent uses phi functions do have.
10980                          */
10981                         if (ptr->op == OP_PHI) {
10982                                 continue;
10983                         }
10984                         expr = triple_rhs(state, ptr, 0);
10985                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
10986                                 /* If the triple is not a definition skip it. */
10987                                 if (!*expr || !triple_is_def(state, *expr)) {
10988                                         continue;
10989                                 }
10990                                 do_triple_set(&live, *expr, 0);
10991                         }
10992                 }
10993                 /* Free live */
10994                 for(entry = live; entry; entry = next) {
10995                         next = entry->next;
10996                         do_triple_unset(&live, entry->member);
10997                 }
10998         }
10999 }
11000
11001 static int count_triples(struct compile_state *state)
11002 {
11003         struct triple *first, *ins;
11004         int triples = 0;
11005         first = RHS(state->main_function, 0);
11006         ins = first;
11007         do {
11008                 triples++;
11009                 ins = ins->next;
11010         } while (ins != first);
11011         return triples;
11012 }
11013 struct dead_triple {
11014         struct triple *triple;
11015         struct dead_triple *work_next;
11016         struct block *block;
11017         int color;
11018         int flags;
11019 #define TRIPLE_FLAG_ALIVE 1
11020 };
11021
11022
11023 static void awaken(
11024         struct compile_state *state,
11025         struct dead_triple *dtriple, struct triple **expr,
11026         struct dead_triple ***work_list_tail)
11027 {
11028         struct triple *triple;
11029         struct dead_triple *dt;
11030         if (!expr) {
11031                 return;
11032         }
11033         triple = *expr;
11034         if (!triple) {
11035                 return;
11036         }
11037         if (triple->id <= 0)  {
11038                 internal_error(state, triple, "bad triple id: %d",
11039                         triple->id);
11040         }
11041         if (triple->op == OP_NOOP) {
11042                 internal_warning(state, triple, "awakening noop?");
11043                 return;
11044         }
11045         dt = &dtriple[triple->id];
11046         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11047                 dt->flags |= TRIPLE_FLAG_ALIVE;
11048                 if (!dt->work_next) {
11049                         **work_list_tail = dt;
11050                         *work_list_tail = &dt->work_next;
11051                 }
11052         }
11053 }
11054
11055 static void eliminate_inefectual_code(struct compile_state *state)
11056 {
11057         struct block *block;
11058         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11059         int triples, i;
11060         struct triple *first, *ins;
11061
11062         /* Setup the work list */
11063         work_list = 0;
11064         work_list_tail = &work_list;
11065
11066         first = RHS(state->main_function, 0);
11067
11068         /* Count how many triples I have */
11069         triples = count_triples(state);
11070
11071         /* Now put then in an array and mark all of the triples dead */
11072         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11073         
11074         ins = first;
11075         i = 1;
11076         block = 0;
11077         do {
11078                 if (ins->op == OP_LABEL) {
11079                         block = ins->u.block;
11080                 }
11081                 dtriple[i].triple = ins;
11082                 dtriple[i].block  = block;
11083                 dtriple[i].flags  = 0;
11084                 dtriple[i].color  = ins->id;
11085                 ins->id = i;
11086                 /* See if it is an operation we always keep */
11087 #warning "FIXME handle the case of killing a branch instruction"
11088                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11089                         awaken(state, dtriple, &ins, &work_list_tail);
11090                 }
11091                 i++;
11092                 ins = ins->next;
11093         } while(ins != first);
11094         while(work_list) {
11095                 struct dead_triple *dt;
11096                 struct block_set *user;
11097                 struct triple **expr;
11098                 dt = work_list;
11099                 work_list = dt->work_next;
11100                 if (!work_list) {
11101                         work_list_tail = &work_list;
11102                 }
11103                 /* Wake up the data depencencies of this triple */
11104                 expr = 0;
11105                 do {
11106                         expr = triple_rhs(state, dt->triple, expr);
11107                         awaken(state, dtriple, expr, &work_list_tail);
11108                 } while(expr);
11109                 do {
11110                         expr = triple_lhs(state, dt->triple, expr);
11111                         awaken(state, dtriple, expr, &work_list_tail);
11112                 } while(expr);
11113                 do {
11114                         expr = triple_misc(state, dt->triple, expr);
11115                         awaken(state, dtriple, expr, &work_list_tail);
11116                 } while(expr);
11117                 /* Wake up the forward control dependencies */
11118                 do {
11119                         expr = triple_targ(state, dt->triple, expr);
11120                         awaken(state, dtriple, expr, &work_list_tail);
11121                 } while(expr);
11122                 /* Wake up the reverse control dependencies of this triple */
11123                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11124                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11125                 }
11126         }
11127         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11128                 if ((dt->triple->op == OP_NOOP) && 
11129                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11130                         internal_error(state, dt->triple, "noop effective?");
11131                 }
11132                 dt->triple->id = dt->color;     /* Restore the color */
11133                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11134 #warning "FIXME handle the case of killing a basic block"
11135                         if (dt->block->first == dt->triple) {
11136                                 continue;
11137                         }
11138                         if (dt->block->last == dt->triple) {
11139                                 dt->block->last = dt->triple->prev;
11140                         }
11141                         release_triple(state, dt->triple);
11142                 }
11143         }
11144         xfree(dtriple);
11145 }
11146
11147
11148 static void insert_mandatory_copies(struct compile_state *state)
11149 {
11150         struct triple *ins, *first;
11151
11152         /* The object is with a minimum of inserted copies,
11153          * to resolve in fundamental register conflicts between
11154          * register value producers and consumers.
11155          * Theoretically we may be greater than minimal when we
11156          * are inserting copies before instructions but that
11157          * case should be rare.
11158          */
11159         first = RHS(state->main_function, 0);
11160         ins = first;
11161         do {
11162                 struct triple_set *entry, *next;
11163                 struct triple *tmp;
11164                 struct reg_info info;
11165                 unsigned reg, regcm;
11166                 int do_post_copy, do_pre_copy;
11167                 tmp = 0;
11168                 if (!triple_is_def(state, ins)) {
11169                         goto next;
11170                 }
11171                 /* Find the architecture specific color information */
11172                 info = arch_reg_lhs(state, ins, 0);
11173                 if (info.reg >= MAX_REGISTERS) {
11174                         info.reg = REG_UNSET;
11175                 }
11176                 
11177                 reg = REG_UNSET;
11178                 regcm = arch_type_to_regcm(state, ins->type);
11179                 do_post_copy = do_pre_copy = 0;
11180
11181                 /* Walk through the uses of ins and check for conflicts */
11182                 for(entry = ins->use; entry; entry = next) {
11183                         struct reg_info rinfo;
11184                         int i;
11185                         next = entry->next;
11186                         i = find_rhs_use(state, entry->member, ins);
11187                         if (i < 0) {
11188                                 continue;
11189                         }
11190                         
11191                         /* Find the users color requirements */
11192                         rinfo = arch_reg_rhs(state, entry->member, i);
11193                         if (rinfo.reg >= MAX_REGISTERS) {
11194                                 rinfo.reg = REG_UNSET;
11195                         }
11196                         
11197                         /* See if I need a pre_copy */
11198                         if (rinfo.reg != REG_UNSET) {
11199                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11200                                         do_pre_copy = 1;
11201                                 }
11202                                 reg = rinfo.reg;
11203                         }
11204                         regcm &= rinfo.regcm;
11205                         regcm = arch_regcm_normalize(state, regcm);
11206                         if (regcm == 0) {
11207                                 do_pre_copy = 1;
11208                         }
11209                 }
11210                 do_post_copy =
11211                         !do_pre_copy &&
11212                         (((info.reg != REG_UNSET) && 
11213                                 (reg != REG_UNSET) &&
11214                                 (info.reg != reg)) ||
11215                         ((info.regcm & regcm) == 0));
11216
11217                 reg = info.reg;
11218                 regcm = info.regcm;
11219                 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11220                 for(entry = ins->use; entry; entry = next) {
11221                         struct reg_info rinfo;
11222                         int i;
11223                         next = entry->next;
11224                         i = find_rhs_use(state, entry->member, ins);
11225                         if (i < 0) {
11226                                 continue;
11227                         }
11228                         
11229                         /* Find the users color requirements */
11230                         rinfo = arch_reg_rhs(state, entry->member, i);
11231                         if (rinfo.reg >= MAX_REGISTERS) {
11232                                 rinfo.reg = REG_UNSET;
11233                         }
11234
11235                         /* Now see if it is time to do the pre_copy */
11236                         if (rinfo.reg != REG_UNSET) {
11237                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11238                                         ((regcm & rinfo.regcm) == 0) ||
11239                                         /* Don't let a mandatory coalesce sneak
11240                                          * into a operation that is marked to prevent
11241                                          * coalescing.
11242                                          */
11243                                         ((reg != REG_UNNEEDED) &&
11244                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11245                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11246                                         ) {
11247                                         if (do_pre_copy) {
11248                                                 struct triple *user;
11249                                                 user = entry->member;
11250                                                 if (RHS(user, i) != ins) {
11251                                                         internal_error(state, user, "bad rhs");
11252                                                 }
11253                                                 tmp = pre_copy(state, user, i);
11254                                                 continue;
11255                                         } else {
11256                                                 do_post_copy = 1;
11257                                         }
11258                                 }
11259                                 reg = rinfo.reg;
11260                         }
11261                         if ((regcm & rinfo.regcm) == 0) {
11262                                 if (do_pre_copy) {
11263                                         struct triple *user;
11264                                         user = entry->member;
11265                                         if (RHS(user, i) != ins) {
11266                                                 internal_error(state, user, "bad rhs");
11267                                         }
11268                                         tmp = pre_copy(state, user, i);
11269                                         continue;
11270                                 } else {
11271                                         do_post_copy = 1;
11272                                 }
11273                         }
11274                         regcm &= rinfo.regcm;
11275                         
11276                 }
11277                 if (do_post_copy) {
11278                         struct reg_info pre, post;
11279                         tmp = post_copy(state, ins);
11280                         pre = arch_reg_lhs(state, ins, 0);
11281                         post = arch_reg_lhs(state, tmp, 0);
11282                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11283                                 internal_error(state, tmp, "useless copy");
11284                         }
11285                 }
11286         next:
11287                 ins = ins->next;
11288         } while(ins != first);
11289 }
11290
11291
11292 struct live_range_edge;
11293 struct live_range_def;
11294 struct live_range {
11295         struct live_range_edge *edges;
11296         struct live_range_def *defs;
11297 /* Note. The list pointed to by defs is kept in order.
11298  * That is baring splits in the flow control
11299  * defs dominates defs->next wich dominates defs->next->next
11300  * etc.
11301  */
11302         unsigned color;
11303         unsigned classes;
11304         unsigned degree;
11305         unsigned length;
11306         struct live_range *group_next, **group_prev;
11307 };
11308
11309 struct live_range_edge {
11310         struct live_range_edge *next;
11311         struct live_range *node;
11312 };
11313
11314 struct live_range_def {
11315         struct live_range_def *next;
11316         struct live_range_def *prev;
11317         struct live_range *lr;
11318         struct triple *def;
11319         unsigned orig_id;
11320 };
11321
11322 #define LRE_HASH_SIZE 2048
11323 struct lre_hash {
11324         struct lre_hash *next;
11325         struct live_range *left;
11326         struct live_range *right;
11327 };
11328
11329
11330 struct reg_state {
11331         struct lre_hash *hash[LRE_HASH_SIZE];
11332         struct reg_block *blocks;
11333         struct live_range_def *lrd;
11334         struct live_range *lr;
11335         struct live_range *low, **low_tail;
11336         struct live_range *high, **high_tail;
11337         unsigned defs;
11338         unsigned ranges;
11339         int passes, max_passes;
11340 #define MAX_ALLOCATION_PASSES 100
11341 };
11342
11343
11344 static unsigned regc_max_size(struct compile_state *state, int classes)
11345 {
11346         unsigned max_size;
11347         int i;
11348         max_size = 0;
11349         for(i = 0; i < MAX_REGC; i++) {
11350                 if (classes & (1 << i)) {
11351                         unsigned size;
11352                         size = arch_regc_size(state, i);
11353                         if (size > max_size) {
11354                                 max_size = size;
11355                         }
11356                 }
11357         }
11358         return max_size;
11359 }
11360
11361 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11362 {
11363         unsigned equivs[MAX_REG_EQUIVS];
11364         int i;
11365         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11366                 internal_error(state, 0, "invalid register");
11367         }
11368         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11369                 internal_error(state, 0, "invalid register");
11370         }
11371         arch_reg_equivs(state, equivs, reg1);
11372         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11373                 if (equivs[i] == reg2) {
11374                         return 1;
11375                 }
11376         }
11377         return 0;
11378 }
11379
11380 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11381 {
11382         unsigned equivs[MAX_REG_EQUIVS];
11383         int i;
11384         if (reg == REG_UNNEEDED) {
11385                 return;
11386         }
11387         arch_reg_equivs(state, equivs, reg);
11388         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11389                 used[equivs[i]] = 1;
11390         }
11391         return;
11392 }
11393
11394 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11395 {
11396         unsigned equivs[MAX_REG_EQUIVS];
11397         int i;
11398         if (reg == REG_UNNEEDED) {
11399                 return;
11400         }
11401         arch_reg_equivs(state, equivs, reg);
11402         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11403                 used[equivs[i]] += 1;
11404         }
11405         return;
11406 }
11407
11408 static unsigned int hash_live_edge(
11409         struct live_range *left, struct live_range *right)
11410 {
11411         unsigned int hash, val;
11412         unsigned long lval, rval;
11413         lval = ((unsigned long)left)/sizeof(struct live_range);
11414         rval = ((unsigned long)right)/sizeof(struct live_range);
11415         hash = 0;
11416         while(lval) {
11417                 val = lval & 0xff;
11418                 lval >>= 8;
11419                 hash = (hash *263) + val;
11420         }
11421         while(rval) {
11422                 val = rval & 0xff;
11423                 rval >>= 8;
11424                 hash = (hash *263) + val;
11425         }
11426         hash = hash & (LRE_HASH_SIZE - 1);
11427         return hash;
11428 }
11429
11430 static struct lre_hash **lre_probe(struct reg_state *rstate,
11431         struct live_range *left, struct live_range *right)
11432 {
11433         struct lre_hash **ptr;
11434         unsigned int index;
11435         /* Ensure left <= right */
11436         if (left > right) {
11437                 struct live_range *tmp;
11438                 tmp = left;
11439                 left = right;
11440                 right = tmp;
11441         }
11442         index = hash_live_edge(left, right);
11443         
11444         ptr = &rstate->hash[index];
11445         while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11446                 ptr = &(*ptr)->next;
11447         }
11448         return ptr;
11449 }
11450
11451 static int interfere(struct reg_state *rstate,
11452         struct live_range *left, struct live_range *right)
11453 {
11454         struct lre_hash **ptr;
11455         ptr = lre_probe(rstate, left, right);
11456         return ptr && *ptr;
11457 }
11458
11459 static void add_live_edge(struct reg_state *rstate, 
11460         struct live_range *left, struct live_range *right)
11461 {
11462         /* FIXME the memory allocation overhead is noticeable here... */
11463         struct lre_hash **ptr, *new_hash;
11464         struct live_range_edge *edge;
11465
11466         if (left == right) {
11467                 return;
11468         }
11469         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11470                 return;
11471         }
11472         /* Ensure left <= right */
11473         if (left > right) {
11474                 struct live_range *tmp;
11475                 tmp = left;
11476                 left = right;
11477                 right = tmp;
11478         }
11479         ptr = lre_probe(rstate, left, right);
11480         if (*ptr) {
11481                 return;
11482         }
11483         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11484         new_hash->next  = *ptr;
11485         new_hash->left  = left;
11486         new_hash->right = right;
11487         *ptr = new_hash;
11488
11489         edge = xmalloc(sizeof(*edge), "live_range_edge");
11490         edge->next   = left->edges;
11491         edge->node   = right;
11492         left->edges  = edge;
11493         left->degree += 1;
11494         
11495         edge = xmalloc(sizeof(*edge), "live_range_edge");
11496         edge->next    = right->edges;
11497         edge->node    = left;
11498         right->edges  = edge;
11499         right->degree += 1;
11500 }
11501
11502 static void remove_live_edge(struct reg_state *rstate,
11503         struct live_range *left, struct live_range *right)
11504 {
11505         struct live_range_edge *edge, **ptr;
11506         struct lre_hash **hptr, *entry;
11507         hptr = lre_probe(rstate, left, right);
11508         if (!hptr || !*hptr) {
11509                 return;
11510         }
11511         entry = *hptr;
11512         *hptr = entry->next;
11513         xfree(entry);
11514
11515         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11516                 edge = *ptr;
11517                 if (edge->node == right) {
11518                         *ptr = edge->next;
11519                         memset(edge, 0, sizeof(*edge));
11520                         xfree(edge);
11521                         break;
11522                 }
11523         }
11524         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11525                 edge = *ptr;
11526                 if (edge->node == left) {
11527                         *ptr = edge->next;
11528                         memset(edge, 0, sizeof(*edge));
11529                         xfree(edge);
11530                         break;
11531                 }
11532         }
11533 }
11534
11535 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11536 {
11537         struct live_range_edge *edge, *next;
11538         for(edge = range->edges; edge; edge = next) {
11539                 next = edge->next;
11540                 remove_live_edge(rstate, range, edge->node);
11541         }
11542 }
11543
11544
11545 /* Interference graph...
11546  * 
11547  * new(n) --- Return a graph with n nodes but no edges.
11548  * add(g,x,y) --- Return a graph including g with an between x and y
11549  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11550  *                x and y in the graph g
11551  * degree(g, x) --- Return the degree of the node x in the graph g
11552  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11553  *
11554  * Implement with a hash table && a set of adjcency vectors.
11555  * The hash table supports constant time implementations of add and interfere.
11556  * The adjacency vectors support an efficient implementation of neighbors.
11557  */
11558
11559 /* 
11560  *     +---------------------------------------------------+
11561  *     |         +--------------+                          |
11562  *     v         v              |                          |
11563  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
11564  *
11565  * -- In simplify implment optimistic coloring... (No backtracking)
11566  * -- Implement Rematerialization it is the only form of spilling we can perform
11567  *    Essentially this means dropping a constant from a register because
11568  *    we can regenerate it later.
11569  *
11570  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11571  *     coalesce at phi points...
11572  * --- Bias coloring if at all possible do the coalesing a compile time.
11573  *
11574  *
11575  */
11576
11577 static void different_colored(
11578         struct compile_state *state, struct reg_state *rstate, 
11579         struct triple *parent, struct triple *ins)
11580 {
11581         struct live_range *lr;
11582         struct triple **expr;
11583         lr = rstate->lrd[ins->id].lr;
11584         expr = triple_rhs(state, ins, 0);
11585         for(;expr; expr = triple_rhs(state, ins, expr)) {
11586                 struct live_range *lr2;
11587                 if (!*expr || (*expr == parent) || (*expr == ins)) {
11588                         continue;
11589                 }
11590                 lr2 = rstate->lrd[(*expr)->id].lr;
11591                 if (lr->color == lr2->color) {
11592                         internal_error(state, ins, "live range too big");
11593                 }
11594         }
11595 }
11596
11597
11598 static struct live_range *coalesce_ranges(
11599         struct compile_state *state, struct reg_state *rstate,
11600         struct live_range *lr1, struct live_range *lr2)
11601 {
11602         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11603         unsigned color;
11604         unsigned classes;
11605         if (lr1 == lr2) {
11606                 return lr1;
11607         }
11608         if (!lr1->defs || !lr2->defs) {
11609                 internal_error(state, 0,
11610                         "cannot coalese dead live ranges");
11611         }
11612         if ((lr1->color == REG_UNNEEDED) ||
11613                 (lr2->color == REG_UNNEEDED)) {
11614                 internal_error(state, 0, 
11615                         "cannot coalesce live ranges without a possible color");
11616         }
11617         if ((lr1->color != lr2->color) &&
11618                 (lr1->color != REG_UNSET) &&
11619                 (lr2->color != REG_UNSET)) {
11620                 internal_error(state, lr1->defs->def, 
11621                         "cannot coalesce live ranges of different colors");
11622         }
11623         color = lr1->color;
11624         if (color == REG_UNSET) {
11625                 color = lr2->color;
11626         }
11627         classes = lr1->classes & lr2->classes;
11628         if (!classes) {
11629                 internal_error(state, lr1->defs->def,
11630                         "cannot coalesce live ranges with dissimilar register classes");
11631         }
11632         /* If there is a clear dominate live range put it in lr1,
11633          * For purposes of this test phi functions are
11634          * considered dominated by the definitions that feed into
11635          * them. 
11636          */
11637         if ((lr1->defs->prev->def->op == OP_PHI) ||
11638                 ((lr2->defs->prev->def->op != OP_PHI) &&
11639                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11640                 struct live_range *tmp;
11641                 tmp = lr1;
11642                 lr1 = lr2;
11643                 lr2 = tmp;
11644         }
11645 #if 0
11646         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11647                 fprintf(stderr, "lr1 post\n");
11648         }
11649         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11650                 fprintf(stderr, "lr1 pre\n");
11651         }
11652         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11653                 fprintf(stderr, "lr2 post\n");
11654         }
11655         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11656                 fprintf(stderr, "lr2 pre\n");
11657         }
11658 #endif
11659 #if 0
11660         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11661                 lr1->defs->def,
11662                 lr1->color,
11663                 lr2->defs->def,
11664                 lr2->color);
11665 #endif
11666         
11667         lr1->classes = classes;
11668         /* Append lr2 onto lr1 */
11669 #warning "FIXME should this be a merge instead of a splice?"
11670         head = lr1->defs;
11671         mid1 = lr1->defs->prev;
11672         mid2 = lr2->defs;
11673         end  = lr2->defs->prev;
11674         
11675         head->prev = end;
11676         end->next  = head;
11677
11678         mid1->next = mid2;
11679         mid2->prev = mid1;
11680
11681         /* Fixup the live range in the added live range defs */
11682         lrd = head;
11683         do {
11684                 lrd->lr = lr1;
11685                 lrd = lrd->next;
11686         } while(lrd != head);
11687
11688         /* Mark lr2 as free. */
11689         lr2->defs = 0;
11690         lr2->color = REG_UNNEEDED;
11691         lr2->classes = 0;
11692
11693         if (!lr1->defs) {
11694                 internal_error(state, 0, "lr1->defs == 0 ?");
11695         }
11696
11697         lr1->color   = color;
11698         lr1->classes = classes;
11699
11700         return lr1;
11701 }
11702
11703 static struct live_range_def *live_range_head(
11704         struct compile_state *state, struct live_range *lr,
11705         struct live_range_def *last)
11706 {
11707         struct live_range_def *result;
11708         result = 0;
11709         if (last == 0) {
11710                 result = lr->defs;
11711         }
11712         else if (!tdominates(state, lr->defs->def, last->next->def)) {
11713                 result = last->next;
11714         }
11715         return result;
11716 }
11717
11718 static struct live_range_def *live_range_end(
11719         struct compile_state *state, struct live_range *lr,
11720         struct live_range_def *last)
11721 {
11722         struct live_range_def *result;
11723         result = 0;
11724         if (last == 0) {
11725                 result = lr->defs->prev;
11726         }
11727         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11728                 result = last->prev;
11729         }
11730         return result;
11731 }
11732
11733
11734 static void initialize_live_ranges(
11735         struct compile_state *state, struct reg_state *rstate)
11736 {
11737         struct triple *ins, *first;
11738         size_t count, size;
11739         int i, j;
11740
11741         first = RHS(state->main_function, 0);
11742         /* First count how many instructions I have.
11743          */
11744         count = count_triples(state);
11745         /* Potentially I need one live range definitions for each
11746          * instruction, plus an extra for the split routines.
11747          */
11748         rstate->defs = count + 1;
11749         /* Potentially I need one live range for each instruction
11750          * plus an extra for the dummy live range.
11751          */
11752         rstate->ranges = count + 1;
11753         size = sizeof(rstate->lrd[0]) * rstate->defs;
11754         rstate->lrd = xcmalloc(size, "live_range_def");
11755         size = sizeof(rstate->lr[0]) * rstate->ranges;
11756         rstate->lr  = xcmalloc(size, "live_range");
11757
11758         /* Setup the dummy live range */
11759         rstate->lr[0].classes = 0;
11760         rstate->lr[0].color = REG_UNSET;
11761         rstate->lr[0].defs = 0;
11762         i = j = 0;
11763         ins = first;
11764         do {
11765                 /* If the triple is a variable give it a live range */
11766                 if (triple_is_def(state, ins)) {
11767                         struct reg_info info;
11768                         /* Find the architecture specific color information */
11769                         info = find_def_color(state, ins);
11770
11771                         i++;
11772                         rstate->lr[i].defs    = &rstate->lrd[j];
11773                         rstate->lr[i].color   = info.reg;
11774                         rstate->lr[i].classes = info.regcm;
11775                         rstate->lr[i].degree  = 0;
11776                         rstate->lrd[j].lr = &rstate->lr[i];
11777                 } 
11778                 /* Otherwise give the triple the dummy live range. */
11779                 else {
11780                         rstate->lrd[j].lr = &rstate->lr[0];
11781                 }
11782
11783                 /* Initalize the live_range_def */
11784                 rstate->lrd[j].next    = &rstate->lrd[j];
11785                 rstate->lrd[j].prev    = &rstate->lrd[j];
11786                 rstate->lrd[j].def     = ins;
11787                 rstate->lrd[j].orig_id = ins->id;
11788                 ins->id = j;
11789
11790                 j++;
11791                 ins = ins->next;
11792         } while(ins != first);
11793         rstate->ranges = i;
11794         rstate->defs -= 1;
11795
11796         /* Make a second pass to handle achitecture specific register
11797          * constraints.
11798          */
11799         ins = first;
11800         do {
11801                 int zlhs, zrhs, i, j;
11802                 if (ins->id > rstate->defs) {
11803                         internal_error(state, ins, "bad id");
11804                 }
11805                 
11806                 /* Walk through the template of ins and coalesce live ranges */
11807                 zlhs = TRIPLE_LHS(ins->sizes);
11808                 if ((zlhs == 0) && triple_is_def(state, ins)) {
11809                         zlhs = 1;
11810                 }
11811                 zrhs = TRIPLE_RHS(ins->sizes);
11812                 
11813                 for(i = 0; i < zlhs; i++) {
11814                         struct reg_info linfo;
11815                         struct live_range_def *lhs;
11816                         linfo = arch_reg_lhs(state, ins, i);
11817                         if (linfo.reg < MAX_REGISTERS) {
11818                                 continue;
11819                         }
11820                         if (triple_is_def(state, ins)) {
11821                                 lhs = &rstate->lrd[ins->id];
11822                         } else {
11823                                 lhs = &rstate->lrd[LHS(ins, i)->id];
11824                         }
11825                         for(j = 0; j < zrhs; j++) {
11826                                 struct reg_info rinfo;
11827                                 struct live_range_def *rhs;
11828                                 rinfo = arch_reg_rhs(state, ins, j);
11829                                 if (rinfo.reg < MAX_REGISTERS) {
11830                                         continue;
11831                                 }
11832                                 rhs = &rstate->lrd[RHS(ins, i)->id];
11833                                 if (rinfo.reg == linfo.reg) {
11834                                         coalesce_ranges(state, rstate, 
11835                                                 lhs->lr, rhs->lr);
11836                                 }
11837                         }
11838                 }
11839                 ins = ins->next;
11840         } while(ins != first);
11841 }
11842
11843 static void graph_ins(
11844         struct compile_state *state, 
11845         struct reg_block *blocks, struct triple_reg_set *live, 
11846         struct reg_block *rb, struct triple *ins, void *arg)
11847 {
11848         struct reg_state *rstate = arg;
11849         struct live_range *def;
11850         struct triple_reg_set *entry;
11851
11852         /* If the triple is not a definition
11853          * we do not have a definition to add to
11854          * the interference graph.
11855          */
11856         if (!triple_is_def(state, ins)) {
11857                 return;
11858         }
11859         def = rstate->lrd[ins->id].lr;
11860         
11861         /* Create an edge between ins and everything that is
11862          * alive, unless the live_range cannot share
11863          * a physical register with ins.
11864          */
11865         for(entry = live; entry; entry = entry->next) {
11866                 struct live_range *lr;
11867                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11868                         internal_error(state, 0, "bad entry?");
11869                 }
11870                 lr = rstate->lrd[entry->member->id].lr;
11871                 if (def == lr) {
11872                         continue;
11873                 }
11874                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11875                         continue;
11876                 }
11877                 add_live_edge(rstate, def, lr);
11878         }
11879         return;
11880 }
11881
11882
11883 static void print_interference_ins(
11884         struct compile_state *state, 
11885         struct reg_block *blocks, struct triple_reg_set *live, 
11886         struct reg_block *rb, struct triple *ins, void *arg)
11887 {
11888         struct reg_state *rstate = arg;
11889         struct live_range *lr;
11890
11891         lr = rstate->lrd[ins->id].lr;
11892         display_triple(stdout, ins);
11893
11894         if (lr->defs) {
11895                 struct live_range_def *lrd;
11896                 printf("       range:");
11897                 lrd = lr->defs;
11898                 do {
11899                         printf(" %-10p", lrd->def);
11900                         lrd = lrd->next;
11901                 } while(lrd != lr->defs);
11902                 printf("\n");
11903         }
11904         if (live) {
11905                 struct triple_reg_set *entry;
11906                 printf("        live:");
11907                 for(entry = live; entry; entry = entry->next) {
11908                         printf(" %-10p", entry->member);
11909                 }
11910                 printf("\n");
11911         }
11912         if (lr->edges) {
11913                 struct live_range_edge *entry;
11914                 printf("       edges:");
11915                 for(entry = lr->edges; entry; entry = entry->next) {
11916                         struct live_range_def *lrd;
11917                         lrd = entry->node->defs;
11918                         do {
11919                                 printf(" %-10p", lrd->def);
11920                                 lrd = lrd->next;
11921                         } while(lrd != entry->node->defs);
11922                         printf("|");
11923                 }
11924                 printf("\n");
11925         }
11926         if (triple_is_branch(state, ins)) {
11927                 printf("\n");
11928         }
11929         return;
11930 }
11931
11932 static int coalesce_live_ranges(
11933         struct compile_state *state, struct reg_state *rstate)
11934 {
11935         /* At the point where a value is moved from one
11936          * register to another that value requires two
11937          * registers, thus increasing register pressure.
11938          * Live range coaleescing reduces the register
11939          * pressure by keeping a value in one register
11940          * longer.
11941          *
11942          * In the case of a phi function all paths leading
11943          * into it must be allocated to the same register
11944          * otherwise the phi function may not be removed.
11945          *
11946          * Forcing a value to stay in a single register
11947          * for an extended period of time does have
11948          * limitations when applied to non homogenous
11949          * register pool.  
11950          *
11951          * The two cases I have identified are:
11952          * 1) Two forced register assignments may
11953          *    collide.
11954          * 2) Registers may go unused because they
11955          *    are only good for storing the value
11956          *    and not manipulating it.
11957          *
11958          * Because of this I need to split live ranges,
11959          * even outside of the context of coalesced live
11960          * ranges.  The need to split live ranges does
11961          * impose some constraints on live range coalescing.
11962          *
11963          * - Live ranges may not be coalesced across phi
11964          *   functions.  This creates a 2 headed live
11965          *   range that cannot be sanely split.
11966          *
11967          * - phi functions (coalesced in initialize_live_ranges) 
11968          *   are handled as pre split live ranges so we will
11969          *   never attempt to split them.
11970          */
11971         int coalesced;
11972         int i;
11973
11974         coalesced = 0;
11975         for(i = 0; i <= rstate->ranges; i++) {
11976                 struct live_range *lr1;
11977                 struct live_range_def *lrd1;
11978                 lr1 = &rstate->lr[i];
11979                 if (!lr1->defs) {
11980                         continue;
11981                 }
11982                 lrd1 = live_range_end(state, lr1, 0);
11983                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11984                         struct triple_set *set;
11985                         if (lrd1->def->op != OP_COPY) {
11986                                 continue;
11987                         }
11988                         /* Skip copies that are the result of a live range split. */
11989                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11990                                 continue;
11991                         }
11992                         for(set = lrd1->def->use; set; set = set->next) {
11993                                 struct live_range_def *lrd2;
11994                                 struct live_range *lr2, *res;
11995
11996                                 lrd2 = &rstate->lrd[set->member->id];
11997
11998                                 /* Don't coalesce with instructions
11999                                  * that are the result of a live range
12000                                  * split.
12001                                  */
12002                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12003                                         continue;
12004                                 }
12005                                 lr2 = rstate->lrd[set->member->id].lr;
12006                                 if (lr1 == lr2) {
12007                                         continue;
12008                                 }
12009                                 if ((lr1->color != lr2->color) &&
12010                                         (lr1->color != REG_UNSET) &&
12011                                         (lr2->color != REG_UNSET)) {
12012                                         continue;
12013                                 }
12014                                 if ((lr1->classes & lr2->classes) == 0) {
12015                                         continue;
12016                                 }
12017                                 
12018                                 if (interfere(rstate, lr1, lr2)) {
12019                                         continue;
12020                                 }
12021                                 
12022                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12023                                 coalesced += 1;
12024                                 if (res != lr1) {
12025                                         goto next;
12026                                 }
12027                         }
12028                 }
12029         next:
12030                 ;
12031         }
12032         return coalesced;
12033 }
12034
12035
12036 static void fix_coalesce_conflicts(struct compile_state *state,
12037         struct reg_block *blocks, struct triple_reg_set *live,
12038         struct reg_block *rb, struct triple *ins, void *arg)
12039 {
12040         int zlhs, zrhs, i, j;
12041
12042         /* See if we have a mandatory coalesce operation between
12043          * a lhs and a rhs value.  If so and the rhs value is also
12044          * alive then this triple needs to be pre copied.  Otherwise
12045          * we would have two definitions in the same live range simultaneously
12046          * alive.
12047          */
12048         zlhs = TRIPLE_LHS(ins->sizes);
12049         if ((zlhs == 0) && triple_is_def(state, ins)) {
12050                 zlhs = 1;
12051         }
12052         zrhs = TRIPLE_RHS(ins->sizes);
12053         for(i = 0; i < zlhs; i++) {
12054                 struct reg_info linfo;
12055                 linfo = arch_reg_lhs(state, ins, i);
12056                 if (linfo.reg < MAX_REGISTERS) {
12057                         continue;
12058                 }
12059                 for(j = 0; j < zrhs; j++) {
12060                         struct reg_info rinfo;
12061                         struct triple *rhs;
12062                         struct triple_reg_set *set;
12063                         int found;
12064                         found = 0;
12065                         rinfo = arch_reg_rhs(state, ins, j);
12066                         if (rinfo.reg != linfo.reg) {
12067                                 continue;
12068                         }
12069                         rhs = RHS(ins, j);
12070                         for(set = live; set && !found; set = set->next) {
12071                                 if (set->member == rhs) {
12072                                         found = 1;
12073                                 }
12074                         }
12075                         if (found) {
12076                                 struct triple *copy;
12077                                 copy = pre_copy(state, ins, j);
12078                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12079                         }
12080                 }
12081         }
12082         return;
12083 }
12084
12085 static void replace_set_use(struct compile_state *state,
12086         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12087 {
12088         struct triple_reg_set *set;
12089         for(set = head; set; set = set->next) {
12090                 if (set->member == orig) {
12091                         set->member = new;
12092                 }
12093         }
12094 }
12095
12096 static void replace_block_use(struct compile_state *state, 
12097         struct reg_block *blocks, struct triple *orig, struct triple *new)
12098 {
12099         int i;
12100 #warning "WISHLIST visit just those blocks that need it *"
12101         for(i = 1; i <= state->last_vertex; i++) {
12102                 struct reg_block *rb;
12103                 rb = &blocks[i];
12104                 replace_set_use(state, rb->in, orig, new);
12105                 replace_set_use(state, rb->out, orig, new);
12106         }
12107 }
12108
12109 static void color_instructions(struct compile_state *state)
12110 {
12111         struct triple *ins, *first;
12112         first = RHS(state->main_function, 0);
12113         ins = first;
12114         do {
12115                 if (triple_is_def(state, ins)) {
12116                         struct reg_info info;
12117                         info = find_lhs_color(state, ins, 0);
12118                         if (info.reg >= MAX_REGISTERS) {
12119                                 info.reg = REG_UNSET;
12120                         }
12121                         SET_INFO(ins->id, info);
12122                 }
12123                 ins = ins->next;
12124         } while(ins != first);
12125 }
12126
12127 static struct reg_info read_lhs_color(
12128         struct compile_state *state, struct triple *ins, int index)
12129 {
12130         struct reg_info info;
12131         if ((index == 0) && triple_is_def(state, ins)) {
12132                 info.reg   = ID_REG(ins->id);
12133                 info.regcm = ID_REGCM(ins->id);
12134         }
12135         else if (index < TRIPLE_LHS(ins->sizes)) {
12136                 info = read_lhs_color(state, LHS(ins, index), 0);
12137         }
12138         else {
12139                 internal_error(state, ins, "Bad lhs %d", index);
12140                 info.reg = REG_UNSET;
12141                 info.regcm = 0;
12142         }
12143         return info;
12144 }
12145
12146 static struct triple *resolve_tangle(
12147         struct compile_state *state, struct triple *tangle)
12148 {
12149         struct reg_info info, uinfo;
12150         struct triple_set *set, *next;
12151         struct triple *copy;
12152
12153 #warning "WISHLIST recalculate all affected instructions colors"
12154         info = find_lhs_color(state, tangle, 0);
12155         for(set = tangle->use; set; set = next) {
12156                 struct triple *user;
12157                 int i, zrhs;
12158                 next = set->next;
12159                 user = set->member;
12160                 zrhs = TRIPLE_RHS(user->sizes);
12161                 for(i = 0; i < zrhs; i++) {
12162                         if (RHS(user, i) != tangle) {
12163                                 continue;
12164                         }
12165                         uinfo = find_rhs_post_color(state, user, i);
12166                         if (uinfo.reg == info.reg) {
12167                                 copy = pre_copy(state, user, i);
12168                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12169                                 SET_INFO(copy->id, uinfo);
12170                         }
12171                 }
12172         }
12173         copy = 0;
12174         uinfo = find_lhs_pre_color(state, tangle, 0);
12175         if (uinfo.reg == info.reg) {
12176                 struct reg_info linfo;
12177                 copy = post_copy(state, tangle);
12178                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12179                 linfo = find_lhs_color(state, copy, 0);
12180                 SET_INFO(copy->id, linfo);
12181         }
12182         info = find_lhs_color(state, tangle, 0);
12183         SET_INFO(tangle->id, info);
12184         
12185         return copy;
12186 }
12187
12188
12189 static void fix_tangles(struct compile_state *state,
12190         struct reg_block *blocks, struct triple_reg_set *live,
12191         struct reg_block *rb, struct triple *ins, void *arg)
12192 {
12193         struct triple *tangle;
12194         do {
12195                 char used[MAX_REGISTERS];
12196                 struct triple_reg_set *set;
12197                 tangle = 0;
12198
12199                 /* Find out which registers have multiple uses at this point */
12200                 memset(used, 0, sizeof(used));
12201                 for(set = live; set; set = set->next) {
12202                         struct reg_info info;
12203                         info = read_lhs_color(state, set->member, 0);
12204                         if (info.reg == REG_UNSET) {
12205                                 continue;
12206                         }
12207                         reg_inc_used(state, used, info.reg);
12208                 }
12209                 
12210                 /* Now find the least dominated definition of a register in
12211                  * conflict I have seen so far.
12212                  */
12213                 for(set = live; set; set = set->next) {
12214                         struct reg_info info;
12215                         info = read_lhs_color(state, set->member, 0);
12216                         if (used[info.reg] < 2) {
12217                                 continue;
12218                         }
12219                         if (!tangle || tdominates(state, set->member, tangle)) {
12220                                 tangle = set->member;
12221                         }
12222                 }
12223                 /* If I have found a tangle resolve it */
12224                 if (tangle) {
12225                         struct triple *post_copy;
12226                         post_copy = resolve_tangle(state, tangle);
12227                         if (post_copy) {
12228                                 replace_block_use(state, blocks, tangle, post_copy);
12229                         }
12230                         if (post_copy && (tangle != ins)) {
12231                                 replace_set_use(state, live, tangle, post_copy);
12232                         }
12233                 }
12234         } while(tangle);
12235         return;
12236 }
12237
12238 static void correct_tangles(
12239         struct compile_state *state, struct reg_block *blocks)
12240 {
12241         color_instructions(state);
12242         walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12243 }
12244
12245 struct least_conflict {
12246         struct reg_state *rstate;
12247         struct live_range *ref_range;
12248         struct triple *ins;
12249         struct triple_reg_set *live;
12250         size_t count;
12251 };
12252 static void least_conflict(struct compile_state *state,
12253         struct reg_block *blocks, struct triple_reg_set *live,
12254         struct reg_block *rb, struct triple *ins, void *arg)
12255 {
12256         struct least_conflict *conflict = arg;
12257         struct live_range_edge *edge;
12258         struct triple_reg_set *set;
12259         size_t count;
12260
12261 #if 0
12262 #define HI() fprintf(stderr, "%-10p(%-15s) %d\n", ins, tops(ins->op), __LINE__)
12263 #else
12264 #define HI()
12265 #endif
12266
12267 #warning "FIXME handle instructions with left hand sides..."
12268         /* Only instructions that introduce a new definition
12269          * can be the conflict instruction.
12270          */
12271         if (!triple_is_def(state, ins)) {
12272 HI();
12273                 return;
12274         }
12275
12276         /* See if live ranges at this instruction are a
12277          * strict subset of the live ranges that are in conflict.
12278          */
12279         count = 0;
12280         for(set = live; set; set = set->next) {
12281                 struct live_range *lr;
12282                 lr = conflict->rstate->lrd[set->member->id].lr;
12283                 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12284                         if (edge->node == lr) {
12285                                 break;
12286                         }
12287                 }
12288                 if (!edge && (lr != conflict->ref_range)) {
12289 HI();
12290                         return;
12291                 }
12292                 count++;
12293         }
12294         if (count <= 1) {
12295 HI();
12296                 return;
12297         }
12298
12299         /* See if there is an uncolored member in this subset. 
12300          */
12301          for(set = live; set; set = set->next) {
12302                 struct live_range *lr;
12303                 lr = conflict->rstate->lrd[set->member->id].lr;
12304                 if (lr->color == REG_UNSET) {
12305                         break;
12306                 }
12307         }
12308         if (!set && (conflict->ref_range != REG_UNSET)) {
12309 HI();
12310                 return;
12311         }
12312
12313
12314         /* Find the instruction with the largest possible subset of
12315          * conflict ranges and that dominates any other instruction
12316          * with an equal sized set of conflicting ranges.
12317          */
12318         if ((count > conflict->count) ||
12319                 ((count == conflict->count) &&
12320                         tdominates(state, ins, conflict->ins))) {
12321                 struct triple_reg_set *next;
12322                 /* Remember the canidate instruction */
12323                 conflict->ins = ins;
12324                 conflict->count = count;
12325                 /* Free the old collection of live registers */
12326                 for(set = conflict->live; set; set = next) {
12327                         next = set->next;
12328                         do_triple_unset(&conflict->live, set->member);
12329                 }
12330                 conflict->live = 0;
12331                 /* Rember the registers that are alive but do not feed
12332                  * into or out of conflict->ins.
12333                  */
12334                 for(set = live; set; set = set->next) {
12335                         struct triple **expr;
12336                         if (set->member == ins) {
12337                                 goto next;
12338                         }
12339                         expr = triple_rhs(state, ins, 0);
12340                         for(;expr; expr = triple_rhs(state, ins, expr)) {
12341                                 if (*expr == set->member) {
12342                                         goto next;
12343                                 }
12344                         }
12345                         expr = triple_lhs(state, ins, 0);
12346                         for(; expr; expr = triple_lhs(state, ins, expr)) {
12347                                 if (*expr == set->member) {
12348                                         goto next;
12349                                 }
12350                         }
12351                         do_triple_set(&conflict->live, set->member, set->new);
12352                 next:
12353                         ;
12354                 }
12355         }
12356 HI();
12357         return;
12358 }
12359
12360 static void find_range_conflict(struct compile_state *state,
12361         struct reg_state *rstate, char *used, struct live_range *ref_range,
12362         struct least_conflict *conflict)
12363 {
12364
12365 #if 0
12366         static void verify_blocks(struct compile_state *stae);
12367         verify_blocks(state);
12368         print_blocks(state, stderr);
12369         print_dominators(state, stderr);
12370 #endif
12371         /* there are 3 kinds ways conflicts can occure.
12372          * 1) the life time of 2 values simply overlap.
12373          * 2) the 2 values feed into the same instruction.
12374          * 3) the 2 values feed into a phi function.
12375          */
12376
12377         /* find the instruction where the problematic conflict comes
12378          * into existance.  that the instruction where all of
12379          * the values are alive, and among such instructions it is
12380          * the least dominated one.
12381          *
12382          * a value is alive an an instruction if either;
12383          * 1) the value defintion dominates the instruction and there
12384          *    is a use at or after that instrction
12385          * 2) the value definition feeds into a phi function in the
12386          *    same block as the instruction.  and the phi function
12387          *    is at or after the instruction.
12388          */
12389         memset(conflict, 0, sizeof(*conflict));
12390         conflict->rstate    = rstate;
12391         conflict->ref_range = ref_range;
12392         conflict->ins       = 0;
12393         conflict->count     = 0;
12394         conflict->live      = 0;
12395         walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12396
12397         if (!conflict->ins) {
12398                 struct live_range_edge *edge;
12399                 struct live_range_def *lrd;
12400                 fprintf(stderr, "edges:\n");
12401                 for(edge = ref_range->edges; edge; edge = edge->next) {
12402                         lrd = edge->node->defs;
12403                         do {
12404                                 fprintf(stderr, " %-10p(%s)", lrd->def, tops(lrd->def->op));
12405                                 lrd = lrd->next;
12406                         } while(lrd != edge->node->defs);
12407                         fprintf(stderr, "|\n");
12408                 }
12409                 fprintf(stderr, "range:\n");
12410                 lrd = ref_range->defs;
12411                 do {
12412                         fprintf(stderr, " %-10p(%s)", lrd->def, tops(lrd->def->op));
12413                         lrd = lrd->next;
12414                 } while(lrd != ref_range->defs);
12415                 fprintf(stderr,"\n");
12416                 internal_error(state, ref_range->defs->def, "No conflict ins?");
12417         }
12418         if (!conflict->live) {
12419                 internal_error(state, ref_range->defs->def, "No conflict live?");
12420         }
12421         return;
12422 }
12423
12424 static struct triple *split_constrained_range(struct compile_state *state, 
12425         struct reg_state *rstate, char *used, struct least_conflict *conflict)
12426 {
12427         unsigned constrained_size;
12428         struct triple *new, *constrained;
12429         struct triple_reg_set *cset;
12430         /* Find a range that is having problems because it is
12431          * artificially constrained.
12432          */
12433         constrained_size = ~0;
12434         constrained = 0;
12435         new = 0;
12436         for(cset = conflict->live; cset; cset = cset->next) {
12437                 struct triple_set *set;
12438                 struct reg_info info;
12439                 unsigned classes;
12440                 unsigned cur_size, size;
12441                 /* Skip the live range that starts with conflict->ins */
12442                 if (cset->member == conflict->ins) {
12443                         continue;
12444                 }
12445                 /* Find how many registers this value can potentially
12446                  * be assigned to.
12447                  */
12448                 classes = arch_type_to_regcm(state, cset->member->type);
12449                 size = regc_max_size(state, classes);
12450
12451                 /* Find how many registers we allow this value to
12452                  * be assigned to.
12453                  */
12454                 info = arch_reg_lhs(state, cset->member, 0);
12455 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12456                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12457                         cur_size = regc_max_size(state, info.regcm);
12458                 } else {
12459                         cur_size = 1;
12460                 }
12461                 /* If this live_range feeds into conflict->ins
12462                  * splitting it is unlikely to help.
12463                  */
12464                 for(set = cset->member->use; set; set = set->next) {
12465                         if (set->member == conflict->ins) {
12466                                 goto next;
12467                         }
12468                 }
12469
12470                 /* If there is no difference between potential and
12471                  * actual register count there is nothing to do.
12472                  */
12473                 if (cur_size >= size) {
12474                         continue;
12475                 }
12476                 /* Of the constrained registers deal with the
12477                  * most constrained one first.
12478                  */
12479                 if (!constrained ||
12480                         (size < constrained_size)) {
12481                         constrained = cset->member;
12482                         constrained_size = size;
12483                 }
12484         next:
12485                 ;
12486         }
12487         if (constrained) {
12488                 new = post_copy(state, constrained);
12489                 new->id |= TRIPLE_FLAG_POST_SPLIT;
12490         }
12491         return new;
12492 }
12493
12494 static int split_ranges(
12495         struct compile_state *state, struct reg_state *rstate, 
12496         char *used, struct live_range *range)
12497 {
12498         struct triple *new;
12499
12500         if ((range->color == REG_UNNEEDED) ||
12501                 (rstate->passes >= rstate->max_passes)) {
12502                 return 0;
12503         }
12504         new = 0;
12505         /* If I can't allocate a register something needs to be split */
12506         if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12507                 struct least_conflict conflict;
12508
12509                 /* Find where in the set of registers the conflict
12510                  * actually occurs.
12511                  */
12512                 find_range_conflict(state, rstate, used, range, &conflict);
12513
12514                 /* If a range has been artifically constrained split it */
12515                 new = split_constrained_range(state, rstate, used, &conflict);
12516                 
12517                 if (!new) {
12518                 /* Ideally I would split the live range that will not be used
12519                  * for the longest period of time in hopes that this will 
12520                  * (a) allow me to spill a register or
12521                  * (b) allow me to place a value in another register.
12522                  *
12523                  * So far I don't have a test case for this, the resolving
12524                  * of mandatory constraints has solved all of my
12525                  * know issues.  So I have choosen not to write any
12526                  * code until I cat get a better feel for cases where
12527                  * it would be useful to have.
12528                  *
12529                  */
12530 #warning "WISHLIST implement live range splitting..."
12531                         return 0;
12532                 }
12533         }
12534         if (new) {
12535                 rstate->lrd[rstate->defs].orig_id = new->id;
12536                 new->id = rstate->defs;
12537                 rstate->defs++;
12538 #if 0
12539                 fprintf(stderr, "new: %p\n", new);
12540 #endif
12541                 return 1;
12542         }
12543         return 0;
12544 }
12545
12546 #if DEBUG_COLOR_GRAPH > 1
12547 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12548 #define cgdebug_flush() fflush(stdout)
12549 #elif DEBUG_COLOR_GRAPH == 1
12550 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12551 #define cgdebug_flush() fflush(stderr)
12552 #else
12553 #define cgdebug_printf(...)
12554 #define cgdebug_flush()
12555 #endif
12556
12557         
12558 static int select_free_color(struct compile_state *state, 
12559         struct reg_state *rstate, struct live_range *range)
12560 {
12561         struct triple_set *entry;
12562         struct live_range_def *lrd;
12563         struct live_range_def *phi;
12564         struct live_range_edge *edge;
12565         char used[MAX_REGISTERS];
12566         struct triple **expr;
12567
12568         /* Instead of doing just the trivial color select here I try
12569          * a few extra things because a good color selection will help reduce
12570          * copies.
12571          */
12572
12573         /* Find the registers currently in use */
12574         memset(used, 0, sizeof(used));
12575         for(edge = range->edges; edge; edge = edge->next) {
12576                 if (edge->node->color == REG_UNSET) {
12577                         continue;
12578                 }
12579                 reg_fill_used(state, used, edge->node->color);
12580         }
12581 #if DEBUG_COLOR_GRAPH > 1
12582         {
12583                 int i;
12584                 i = 0;
12585                 for(edge = range->edges; edge; edge = edge->next) {
12586                         i++;
12587                 }
12588                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
12589                         tops(range->def->op), i, 
12590                         range->def->filename, range->def->line, range->def->col);
12591                 for(i = 0; i < MAX_REGISTERS; i++) {
12592                         if (used[i]) {
12593                                 cgdebug_printf("used: %s\n",
12594                                         arch_reg_str(i));
12595                         }
12596                 }
12597         }       
12598 #endif
12599
12600 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12601
12602         /* If a color is already assigned see if it will work */
12603         if (range->color != REG_UNSET) {
12604                 struct live_range_def *lrd;
12605                 if (!used[range->color]) {
12606                         return 1;
12607                 }
12608                 for(edge = range->edges; edge; edge = edge->next) {
12609                         if (edge->node->color != range->color) {
12610                                 continue;
12611                         }
12612                         warning(state, edge->node->defs->def, "edge: ");
12613                         lrd = edge->node->defs;
12614                         do {
12615                                 warning(state, lrd->def, " %p %s",
12616                                         lrd->def, tops(lrd->def->op));
12617                                 lrd = lrd->next;
12618                         } while(lrd != edge->node->defs);
12619                 }
12620                 lrd = range->defs;
12621                 warning(state, range->defs->def, "def: ");
12622                 do {
12623                         warning(state, lrd->def, " %p %s",
12624                                 lrd->def, tops(lrd->def->op));
12625                         lrd = lrd->next;
12626                 } while(lrd != range->defs);
12627                 internal_error(state, range->defs->def,
12628                         "live range with already used color %s",
12629                         arch_reg_str(range->color));
12630         }
12631
12632         /* If I feed into an expression reuse it's color.
12633          * This should help remove copies in the case of 2 register instructions
12634          * and phi functions.
12635          */
12636         phi = 0;
12637         lrd = live_range_end(state, range, 0);
12638         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12639                 entry = lrd->def->use;
12640                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12641                         struct live_range_def *insd;
12642                         insd = &rstate->lrd[entry->member->id];
12643                         if (insd->lr->defs == 0) {
12644                                 continue;
12645                         }
12646                         if (!phi && (insd->def->op == OP_PHI) &&
12647                                 !interfere(rstate, range, insd->lr)) {
12648                                 phi = insd;
12649                         }
12650                         if ((insd->lr->color == REG_UNSET) ||
12651                                 ((insd->lr->classes & range->classes) == 0) ||
12652                                 (used[insd->lr->color])) {
12653                                 continue;
12654                         }
12655                         if (interfere(rstate, range, insd->lr)) {
12656                                 continue;
12657                         }
12658                         range->color = insd->lr->color;
12659                 }
12660         }
12661         /* If I feed into a phi function reuse it's color or the color
12662          * of something else that feeds into the phi function.
12663          */
12664         if (phi) {
12665                 if (phi->lr->color != REG_UNSET) {
12666                         if (used[phi->lr->color]) {
12667                                 range->color = phi->lr->color;
12668                         }
12669                 }
12670                 else {
12671                         expr = triple_rhs(state, phi->def, 0);
12672                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12673                                 struct live_range *lr;
12674                                 if (!*expr) {
12675                                         continue;
12676                                 }
12677                                 lr = rstate->lrd[(*expr)->id].lr;
12678                                 if ((lr->color == REG_UNSET) || 
12679                                         ((lr->classes & range->classes) == 0) ||
12680                                         (used[lr->color])) {
12681                                         continue;
12682                                 }
12683                                 if (interfere(rstate, range, lr)) {
12684                                         continue;
12685                                 }
12686                                 range->color = lr->color;
12687                         }
12688                 }
12689         }
12690         /* If I don't interfere with a rhs node reuse it's color */
12691         lrd = live_range_head(state, range, 0);
12692         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12693                 expr = triple_rhs(state, lrd->def, 0);
12694                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12695                         struct live_range *lr;
12696                         if (!*expr) {
12697                                 continue;
12698                         }
12699                         lr = rstate->lrd[(*expr)->id].lr;
12700                         if ((lr->color == -1) || 
12701                                 ((lr->classes & range->classes) == 0) ||
12702                                 (used[lr->color])) {
12703                                 continue;
12704                         }
12705                         if (interfere(rstate, range, lr)) {
12706                                 continue;
12707                         }
12708                         range->color = lr->color;
12709                         break;
12710                 }
12711         }
12712         /* If I have not opportunitically picked a useful color
12713          * pick the first color that is free.
12714          */
12715         if (range->color == REG_UNSET) {
12716                 range->color = 
12717                         arch_select_free_register(state, used, range->classes);
12718         }
12719         if (range->color == REG_UNSET) {
12720                 int i;
12721                 if (split_ranges(state, rstate, used, range)) {
12722                         return 0;
12723                 }
12724                 for(edge = range->edges; edge; edge = edge->next) {
12725                         if (edge->node->color == REG_UNSET) {
12726                                 continue;
12727                         }
12728                         warning(state, edge->node->defs->def, "reg %s", 
12729                                 arch_reg_str(edge->node->color));
12730                 }
12731                 warning(state, range->defs->def, "classes: %x",
12732                         range->classes);
12733                 for(i = 0; i < MAX_REGISTERS; i++) {
12734                         if (used[i]) {
12735                                 warning(state, range->defs->def, "used: %s",
12736                                         arch_reg_str(i));
12737                         }
12738                 }
12739 #if DEBUG_COLOR_GRAPH < 2
12740                 error(state, range->defs->def, "too few registers");
12741 #else
12742                 internal_error(state, range->defs->def, "too few registers");
12743 #endif
12744         }
12745         range->classes = arch_reg_regcm(state, range->color);
12746         if (range->color == -1) {
12747                 internal_error(state, range->defs->def, "select_free_color did not?");
12748         }
12749         return 1;
12750 }
12751
12752 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12753 {
12754         int colored;
12755         struct live_range_edge *edge;
12756         struct live_range *range;
12757         if (rstate->low) {
12758                 cgdebug_printf("Lo: ");
12759                 range = rstate->low;
12760                 if (*range->group_prev != range) {
12761                         internal_error(state, 0, "lo: *prev != range?");
12762                 }
12763                 *range->group_prev = range->group_next;
12764                 if (range->group_next) {
12765                         range->group_next->group_prev = range->group_prev;
12766                 }
12767                 if (&range->group_next == rstate->low_tail) {
12768                         rstate->low_tail = range->group_prev;
12769                 }
12770                 if (rstate->low == range) {
12771                         internal_error(state, 0, "low: next != prev?");
12772                 }
12773         }
12774         else if (rstate->high) {
12775                 cgdebug_printf("Hi: ");
12776                 range = rstate->high;
12777                 if (*range->group_prev != range) {
12778                         internal_error(state, 0, "hi: *prev != range?");
12779                 }
12780                 *range->group_prev = range->group_next;
12781                 if (range->group_next) {
12782                         range->group_next->group_prev = range->group_prev;
12783                 }
12784                 if (&range->group_next == rstate->high_tail) {
12785                         rstate->high_tail = range->group_prev;
12786                 }
12787                 if (rstate->high == range) {
12788                         internal_error(state, 0, "high: next != prev?");
12789                 }
12790         }
12791         else {
12792                 return 1;
12793         }
12794         cgdebug_printf(" %d\n", range - rstate->lr);
12795         range->group_prev = 0;
12796         for(edge = range->edges; edge; edge = edge->next) {
12797                 struct live_range *node;
12798                 node = edge->node;
12799                 /* Move nodes from the high to the low list */
12800                 if (node->group_prev && (node->color == REG_UNSET) &&
12801                         (node->degree == regc_max_size(state, node->classes))) {
12802                         if (*node->group_prev != node) {
12803                                 internal_error(state, 0, "move: *prev != node?");
12804                         }
12805                         *node->group_prev = node->group_next;
12806                         if (node->group_next) {
12807                                 node->group_next->group_prev = node->group_prev;
12808                         }
12809                         if (&node->group_next == rstate->high_tail) {
12810                                 rstate->high_tail = node->group_prev;
12811                         }
12812                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12813                         node->group_prev  = rstate->low_tail;
12814                         node->group_next  = 0;
12815                         *rstate->low_tail = node;
12816                         rstate->low_tail  = &node->group_next;
12817                         if (*node->group_prev != node) {
12818                                 internal_error(state, 0, "move2: *prev != node?");
12819                         }
12820                 }
12821                 node->degree -= 1;
12822         }
12823         colored = color_graph(state, rstate);
12824         if (colored) {
12825                 cgdebug_printf("Coloring %d @%s:%d.%d:", 
12826                         range - rstate->lr,
12827                         range->def->filename, range->def->line, range->def->col);
12828                 cgdebug_flush();
12829                 colored = select_free_color(state, rstate, range);
12830                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12831         }
12832         return colored;
12833 }
12834
12835 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12836 {
12837         struct live_range *lr;
12838         struct live_range_edge *edge;
12839         struct triple *ins, *first;
12840         char used[MAX_REGISTERS];
12841         first = RHS(state->main_function, 0);
12842         ins = first;
12843         do {
12844                 if (triple_is_def(state, ins)) {
12845                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12846                                 internal_error(state, ins, 
12847                                         "triple without a live range def");
12848                         }
12849                         lr = rstate->lrd[ins->id].lr;
12850                         if (lr->color == REG_UNSET) {
12851                                 internal_error(state, ins,
12852                                         "triple without a color");
12853                         }
12854                         /* Find the registers used by the edges */
12855                         memset(used, 0, sizeof(used));
12856                         for(edge = lr->edges; edge; edge = edge->next) {
12857                                 if (edge->node->color == REG_UNSET) {
12858                                         internal_error(state, 0,
12859                                                 "live range without a color");
12860                         }
12861                                 reg_fill_used(state, used, edge->node->color);
12862                         }
12863                         if (used[lr->color]) {
12864                                 internal_error(state, ins,
12865                                         "triple with already used color");
12866                         }
12867                 }
12868                 ins = ins->next;
12869         } while(ins != first);
12870 }
12871
12872 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12873 {
12874         struct live_range *lr;
12875         struct triple *first, *ins;
12876         first = RHS(state->main_function, 0);
12877         ins = first;
12878         do {
12879                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12880                         internal_error(state, ins, 
12881                                 "triple without a live range");
12882                 }
12883                 lr = rstate->lrd[ins->id].lr;
12884                 SET_REG(ins->id, lr->color);
12885                 ins = ins->next;
12886         } while (ins != first);
12887 }
12888
12889 static void print_interference_block(
12890         struct compile_state *state, struct block *block, void *arg)
12891
12892 {
12893         struct reg_state *rstate = arg;
12894         struct reg_block *rb;
12895         struct triple *ptr;
12896         int phi_present;
12897         int done;
12898         rb = &rstate->blocks[block->vertex];
12899
12900         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
12901                 block, 
12902                 block->vertex,
12903                 block->left, 
12904                 block->left && block->left->use?block->left->use->member : 0,
12905                 block->right, 
12906                 block->right && block->right->use?block->right->use->member : 0);
12907         if (rb->in) {
12908                 struct triple_reg_set *in_set;
12909                 printf("        in:");
12910                 for(in_set = rb->in; in_set; in_set = in_set->next) {
12911                         printf(" %-10p", in_set->member);
12912                 }
12913                 printf("\n");
12914         }
12915         phi_present = 0;
12916         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12917                 done = (ptr == block->last);
12918                 if (ptr->op == OP_PHI) {
12919                         phi_present = 1;
12920                         break;
12921                 }
12922         }
12923         if (phi_present) {
12924                 int edge;
12925                 for(edge = 0; edge < block->users; edge++) {
12926                         printf("     in(%d):", edge);
12927                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12928                                 struct triple **slot;
12929                                 done = (ptr == block->last);
12930                                 if (ptr->op != OP_PHI) {
12931                                         continue;
12932                                 }
12933                                 slot = &RHS(ptr, 0);
12934                                 printf(" %-10p", slot[edge]);
12935                         }
12936                         printf("\n");
12937                 }
12938         }
12939         if (block->first->op == OP_LABEL) {
12940                 printf("%p:\n", block->first);
12941         }
12942         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12943                 struct triple_set *user;
12944                 struct live_range *lr;
12945                 unsigned id;
12946                 int op;
12947                 op = ptr->op;
12948                 done = (ptr == block->last);
12949                 lr = rstate->lrd[ptr->id].lr;
12950                 
12951                 if (triple_stores_block(state, ptr)) {
12952                         if (ptr->u.block != block) {
12953                                 internal_error(state, ptr, 
12954                                         "Wrong block pointer: %p",
12955                                         ptr->u.block);
12956                         }
12957                 }
12958                 if (op == OP_ADECL) {
12959                         for(user = ptr->use; user; user = user->next) {
12960                                 if (!user->member->u.block) {
12961                                         internal_error(state, user->member, 
12962                                                 "Use %p not in a block?",
12963                                                 user->member);
12964                                 }
12965                                 
12966                         }
12967                 }
12968                 id = ptr->id;
12969                 SET_REG(ptr->id, lr->color);
12970                 display_triple(stdout, ptr);
12971                 ptr->id = id;
12972
12973                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12974                         internal_error(state, ptr, "lr has no defs!");
12975                 }
12976
12977                 if (lr->defs) {
12978                         struct live_range_def *lrd;
12979                         printf("       range:");
12980                         lrd = lr->defs;
12981                         do {
12982                                 printf(" %-10p", lrd->def);
12983                                 lrd = lrd->next;
12984                         } while(lrd != lr->defs);
12985                         printf("\n");
12986                 }
12987                 if (lr->edges > 0) {
12988                         struct live_range_edge *edge;
12989                         printf("       edges:");
12990                         for(edge = lr->edges; edge; edge = edge->next) {
12991                                 struct live_range_def *lrd;
12992                                 lrd = edge->node->defs;
12993                                 do {
12994                                         printf(" %-10p", lrd->def);
12995                                         lrd = lrd->next;
12996                                 } while(lrd != edge->node->defs);
12997                                 printf("|");
12998                         }
12999                         printf("\n");
13000                 }
13001                 /* Do a bunch of sanity checks */
13002                 valid_ins(state, ptr);
13003                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13004                         internal_error(state, ptr, "Invalid triple id: %d",
13005                                 ptr->id);
13006                 }
13007                 for(user = ptr->use; user; user = user->next) {
13008                         struct triple *use;
13009                         struct live_range *ulr;
13010                         use = user->member;
13011                         valid_ins(state, use);
13012                         if ((use->id < 0) || (use->id > rstate->defs)) {
13013                                 internal_error(state, use, "Invalid triple id: %d",
13014                                         use->id);
13015                         }
13016                         ulr = rstate->lrd[user->member->id].lr;
13017                         if (triple_stores_block(state, user->member) &&
13018                                 !user->member->u.block) {
13019                                 internal_error(state, user->member,
13020                                         "Use %p not in a block?",
13021                                         user->member);
13022                         }
13023                 }
13024         }
13025         if (rb->out) {
13026                 struct triple_reg_set *out_set;
13027                 printf("       out:");
13028                 for(out_set = rb->out; out_set; out_set = out_set->next) {
13029                         printf(" %-10p", out_set->member);
13030                 }
13031                 printf("\n");
13032         }
13033         printf("\n");
13034 }
13035
13036 static struct live_range *merge_sort_lr(
13037         struct live_range *first, struct live_range *last)
13038 {
13039         struct live_range *mid, *join, **join_tail, *pick;
13040         size_t size;
13041         size = (last - first) + 1;
13042         if (size >= 2) {
13043                 mid = first + size/2;
13044                 first = merge_sort_lr(first, mid -1);
13045                 mid   = merge_sort_lr(mid, last);
13046                 
13047                 join = 0;
13048                 join_tail = &join;
13049                 /* merge the two lists */
13050                 while(first && mid) {
13051                         if ((first->degree < mid->degree) ||
13052                                 ((first->degree == mid->degree) &&
13053                                         (first->length < mid->length))) {
13054                                 pick = first;
13055                                 first = first->group_next;
13056                                 if (first) {
13057                                         first->group_prev = 0;
13058                                 }
13059                         }
13060                         else {
13061                                 pick = mid;
13062                                 mid = mid->group_next;
13063                                 if (mid) {
13064                                         mid->group_prev = 0;
13065                                 }
13066                         }
13067                         pick->group_next = 0;
13068                         pick->group_prev = join_tail;
13069                         *join_tail = pick;
13070                         join_tail = &pick->group_next;
13071                 }
13072                 /* Splice the remaining list */
13073                 pick = (first)? first : mid;
13074                 *join_tail = pick;
13075                 if (pick) { 
13076                         pick->group_prev = join_tail;
13077                 }
13078         }
13079         else {
13080                 if (!first->defs) {
13081                         first = 0;
13082                 }
13083                 join = first;
13084         }
13085         return join;
13086 }
13087
13088 static void ids_from_rstate(struct compile_state *state, 
13089         struct reg_state *rstate)
13090 {
13091         struct triple *ins, *first;
13092         if (!rstate->defs) {
13093                 return;
13094         }
13095         /* Display the graph if desired */
13096         if (state->debug & DEBUG_INTERFERENCE) {
13097                 print_blocks(state, stdout);
13098                 print_control_flow(state);
13099         }
13100         first = RHS(state->main_function, 0);
13101         ins = first;
13102         do {
13103                 if (ins->id) {
13104                         struct live_range_def *lrd;
13105                         lrd = &rstate->lrd[ins->id];
13106                         ins->id = lrd->orig_id;
13107                 }
13108                 ins = ins->next;
13109         } while(ins != first);
13110 }
13111
13112 static void cleanup_live_edges(struct reg_state *rstate)
13113 {
13114         int i;
13115         /* Free the edges on each node */
13116         for(i = 1; i <= rstate->ranges; i++) {
13117                 remove_live_edges(rstate, &rstate->lr[i]);
13118         }
13119 }
13120
13121 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13122 {
13123         cleanup_live_edges(rstate);
13124         xfree(rstate->lrd);
13125         xfree(rstate->lr);
13126
13127         /* Free the variable lifetime information */
13128         if (rstate->blocks) {
13129                 free_variable_lifetimes(state, rstate->blocks);
13130         }
13131         rstate->defs = 0;
13132         rstate->ranges = 0;
13133         rstate->lrd = 0;
13134         rstate->lr = 0;
13135         rstate->blocks = 0;
13136 }
13137
13138 static void allocate_registers(struct compile_state *state)
13139 {
13140         struct reg_state rstate;
13141         int colored;
13142
13143         /* Clear out the reg_state */
13144         memset(&rstate, 0, sizeof(rstate));
13145         rstate.max_passes = MAX_ALLOCATION_PASSES;
13146
13147         do {
13148                 struct live_range **point, **next;
13149                 int coalesced;
13150
13151                 /* Restore ids */
13152                 ids_from_rstate(state, &rstate);
13153
13154                 /* Cleanup the temporary data structures */
13155                 cleanup_rstate(state, &rstate);
13156
13157                 /* Compute the variable lifetimes */
13158                 rstate.blocks = compute_variable_lifetimes(state);
13159
13160                 /* Fix invalid mandatory live range coalesce conflicts */
13161                 walk_variable_lifetimes(
13162                         state, rstate.blocks, fix_coalesce_conflicts, 0);
13163
13164                 /* Fix two simultaneous uses of the same register */
13165                 correct_tangles(state, rstate.blocks);
13166
13167                 if (state->debug & DEBUG_INSERTED_COPIES) {
13168                         printf("After resolve_tangles\n");
13169                         print_blocks(state, stdout);
13170                         print_control_flow(state);
13171                 }
13172
13173                 
13174                 /* Allocate and initialize the live ranges */
13175                 initialize_live_ranges(state, &rstate);
13176                 
13177                 do {
13178                         /* Forget previous live range edge calculations */
13179                         cleanup_live_edges(&rstate);
13180
13181                         /* Compute the interference graph */
13182                         walk_variable_lifetimes(
13183                                 state, rstate.blocks, graph_ins, &rstate);
13184                 
13185                         /* Display the interference graph if desired */
13186                         if (state->debug & DEBUG_INTERFERENCE) {
13187                                 printf("\nlive variables by block\n");
13188                                 walk_blocks(state, print_interference_block, &rstate);
13189                                 printf("\nlive variables by instruction\n");
13190                                 walk_variable_lifetimes(
13191                                         state, rstate.blocks, 
13192                                         print_interference_ins, &rstate);
13193                         }
13194                         
13195                         coalesced = coalesce_live_ranges(state, &rstate);
13196                 } while(coalesced);
13197                         
13198                 /* Build the groups low and high.  But with the nodes
13199                  * first sorted by degree order.
13200                  */
13201                 rstate.low_tail  = &rstate.low;
13202                 rstate.high_tail = &rstate.high;
13203                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13204                 if (rstate.high) {
13205                         rstate.high->group_prev = &rstate.high;
13206                 }
13207                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13208                         ;
13209                 rstate.high_tail = point;
13210                 /* Walk through the high list and move everything that needs
13211                  * to be onto low.
13212                  */
13213                 for(point = &rstate.high; *point; point = next) {
13214                         struct live_range *range;
13215                         next = &(*point)->group_next;
13216                         range = *point;
13217                         
13218                         /* If it has a low degree or it already has a color
13219                          * place the node in low.
13220                          */
13221                         if ((range->degree < regc_max_size(state, range->classes)) ||
13222                                 (range->color != REG_UNSET)) {
13223                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13224                                         range - rstate.lr, range->degree,
13225                                         (range->color != REG_UNSET) ? " (colored)": "");
13226                                 *range->group_prev = range->group_next;
13227                                 if (range->group_next) {
13228                                         range->group_next->group_prev = range->group_prev;
13229                                 }
13230                                 if (&range->group_next == rstate.high_tail) {
13231                                         rstate.high_tail = range->group_prev;
13232                                 }
13233                                 range->group_prev  = rstate.low_tail;
13234                                 range->group_next  = 0;
13235                                 *rstate.low_tail   = range;
13236                                 rstate.low_tail    = &range->group_next;
13237                                 next = point;
13238                         }
13239                         else {
13240                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13241                                         range - rstate.lr, range->degree,
13242                                         (range->color != REG_UNSET) ? " (colored)": "");
13243                         }
13244                 }
13245                 /* Color the live_ranges */
13246                 colored = color_graph(state, &rstate);
13247                 rstate.passes++;
13248         } while (!colored);
13249
13250         /* Verify the graph was properly colored */
13251         verify_colors(state, &rstate);
13252
13253         /* Move the colors from the graph to the triples */
13254         color_triples(state, &rstate);
13255
13256         /* Cleanup the temporary data structures */
13257         cleanup_rstate(state, &rstate);
13258 }
13259
13260 /* Sparce Conditional Constant Propogation
13261  * =========================================
13262  */
13263 struct ssa_edge;
13264 struct flow_block;
13265 struct lattice_node {
13266         unsigned old_id;
13267         struct triple *def;
13268         struct ssa_edge *out;
13269         struct flow_block *fblock;
13270         struct triple *val;
13271         /* lattice high   val && !is_const(val) 
13272          * lattice const  is_const(val)
13273          * lattice low    val == 0
13274          */
13275 };
13276 struct ssa_edge {
13277         struct lattice_node *src;
13278         struct lattice_node *dst;
13279         struct ssa_edge *work_next;
13280         struct ssa_edge *work_prev;
13281         struct ssa_edge *out_next;
13282 };
13283 struct flow_edge {
13284         struct flow_block *src;
13285         struct flow_block *dst;
13286         struct flow_edge *work_next;
13287         struct flow_edge *work_prev;
13288         struct flow_edge *in_next;
13289         struct flow_edge *out_next;
13290         int executable;
13291 };
13292 struct flow_block {
13293         struct block *block;
13294         struct flow_edge *in;
13295         struct flow_edge *out;
13296         struct flow_edge left, right;
13297 };
13298
13299 struct scc_state {
13300         int ins_count;
13301         struct lattice_node *lattice;
13302         struct ssa_edge     *ssa_edges;
13303         struct flow_block   *flow_blocks;
13304         struct flow_edge    *flow_work_list;
13305         struct ssa_edge     *ssa_work_list;
13306 };
13307
13308
13309 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13310         struct flow_edge *fedge)
13311 {
13312         if (!scc->flow_work_list) {
13313                 scc->flow_work_list = fedge;
13314                 fedge->work_next = fedge->work_prev = fedge;
13315         }
13316         else {
13317                 struct flow_edge *ftail;
13318                 ftail = scc->flow_work_list->work_prev;
13319                 fedge->work_next = ftail->work_next;
13320                 fedge->work_prev = ftail;
13321                 fedge->work_next->work_prev = fedge;
13322                 fedge->work_prev->work_next = fedge;
13323         }
13324 }
13325
13326 static struct flow_edge *scc_next_fedge(
13327         struct compile_state *state, struct scc_state *scc)
13328 {
13329         struct flow_edge *fedge;
13330         fedge = scc->flow_work_list;
13331         if (fedge) {
13332                 fedge->work_next->work_prev = fedge->work_prev;
13333                 fedge->work_prev->work_next = fedge->work_next;
13334                 if (fedge->work_next != fedge) {
13335                         scc->flow_work_list = fedge->work_next;
13336                 } else {
13337                         scc->flow_work_list = 0;
13338                 }
13339         }
13340         return fedge;
13341 }
13342
13343 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13344         struct ssa_edge *sedge)
13345 {
13346         if (!scc->ssa_work_list) {
13347                 scc->ssa_work_list = sedge;
13348                 sedge->work_next = sedge->work_prev = sedge;
13349         }
13350         else {
13351                 struct ssa_edge *stail;
13352                 stail = scc->ssa_work_list->work_prev;
13353                 sedge->work_next = stail->work_next;
13354                 sedge->work_prev = stail;
13355                 sedge->work_next->work_prev = sedge;
13356                 sedge->work_prev->work_next = sedge;
13357         }
13358 }
13359
13360 static struct ssa_edge *scc_next_sedge(
13361         struct compile_state *state, struct scc_state *scc)
13362 {
13363         struct ssa_edge *sedge;
13364         sedge = scc->ssa_work_list;
13365         if (sedge) {
13366                 sedge->work_next->work_prev = sedge->work_prev;
13367                 sedge->work_prev->work_next = sedge->work_next;
13368                 if (sedge->work_next != sedge) {
13369                         scc->ssa_work_list = sedge->work_next;
13370                 } else {
13371                         scc->ssa_work_list = 0;
13372                 }
13373         }
13374         return sedge;
13375 }
13376
13377 static void initialize_scc_state(
13378         struct compile_state *state, struct scc_state *scc)
13379 {
13380         int ins_count, ssa_edge_count;
13381         int ins_index, ssa_edge_index, fblock_index;
13382         struct triple *first, *ins;
13383         struct block *block;
13384         struct flow_block *fblock;
13385
13386         memset(scc, 0, sizeof(*scc));
13387
13388         /* Inialize pass zero find out how much memory we need */
13389         first = RHS(state->main_function, 0);
13390         ins = first;
13391         ins_count = ssa_edge_count = 0;
13392         do {
13393                 struct triple_set *edge;
13394                 ins_count += 1;
13395                 for(edge = ins->use; edge; edge = edge->next) {
13396                         ssa_edge_count++;
13397                 }
13398                 ins = ins->next;
13399         } while(ins != first);
13400 #if DEBUG_SCC
13401         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13402                 ins_count, ssa_edge_count, state->last_vertex);
13403 #endif
13404         scc->ins_count   = ins_count;
13405         scc->lattice     = 
13406                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13407         scc->ssa_edges   = 
13408                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13409         scc->flow_blocks = 
13410                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
13411                         "flow_blocks");
13412
13413         /* Initialize pass one collect up the nodes */
13414         fblock = 0;
13415         block = 0;
13416         ins_index = ssa_edge_index = fblock_index = 0;
13417         ins = first;
13418         do {
13419                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13420                         block = ins->u.block;
13421                         if (!block) {
13422                                 internal_error(state, ins, "label without block");
13423                         }
13424                         fblock_index += 1;
13425                         block->vertex = fblock_index;
13426                         fblock = &scc->flow_blocks[fblock_index];
13427                         fblock->block = block;
13428                 }
13429                 {
13430                         struct lattice_node *lnode;
13431                         ins_index += 1;
13432                         lnode = &scc->lattice[ins_index];
13433                         lnode->def = ins;
13434                         lnode->out = 0;
13435                         lnode->fblock = fblock;
13436                         lnode->val = ins; /* LATTICE HIGH */
13437                         lnode->old_id = ins->id;
13438                         ins->id = ins_index;
13439                 }
13440                 ins = ins->next;
13441         } while(ins != first);
13442         /* Initialize pass two collect up the edges */
13443         block = 0;
13444         fblock = 0;
13445         ins = first;
13446         do {
13447                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13448                         struct flow_edge *fedge, **ftail;
13449                         struct block_set *bedge;
13450                         block = ins->u.block;
13451                         fblock = &scc->flow_blocks[block->vertex];
13452                         fblock->in = 0;
13453                         fblock->out = 0;
13454                         ftail = &fblock->out;
13455                         if (block->left) {
13456                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13457                                 if (fblock->left.dst->block != block->left) {
13458                                         internal_error(state, 0, "block mismatch");
13459                                 }
13460                                 fblock->left.out_next = 0;
13461                                 *ftail = &fblock->left;
13462                                 ftail = &fblock->left.out_next;
13463                         }
13464                         if (block->right) {
13465                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13466                                 if (fblock->right.dst->block != block->right) {
13467                                         internal_error(state, 0, "block mismatch");
13468                                 }
13469                                 fblock->right.out_next = 0;
13470                                 *ftail = &fblock->right;
13471                                 ftail = &fblock->right.out_next;
13472                         }
13473                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13474                                 fedge->src = fblock;
13475                                 fedge->work_next = fedge->work_prev = fedge;
13476                                 fedge->executable = 0;
13477                         }
13478                         ftail = &fblock->in;
13479                         for(bedge = block->use; bedge; bedge = bedge->next) {
13480                                 struct block *src_block;
13481                                 struct flow_block *sfblock;
13482                                 struct flow_edge *sfedge;
13483                                 src_block = bedge->member;
13484                                 sfblock = &scc->flow_blocks[src_block->vertex];
13485                                 sfedge = 0;
13486                                 if (src_block->left == block) {
13487                                         sfedge = &sfblock->left;
13488                                 } else {
13489                                         sfedge = &sfblock->right;
13490                                 }
13491                                 *ftail = sfedge;
13492                                 ftail = &sfedge->in_next;
13493                                 sfedge->in_next = 0;
13494                         }
13495                 }
13496                 {
13497                         struct triple_set *edge;
13498                         struct ssa_edge **stail;
13499                         struct lattice_node *lnode;
13500                         lnode = &scc->lattice[ins->id];
13501                         lnode->out = 0;
13502                         stail = &lnode->out;
13503                         for(edge = ins->use; edge; edge = edge->next) {
13504                                 struct ssa_edge *sedge;
13505                                 ssa_edge_index += 1;
13506                                 sedge = &scc->ssa_edges[ssa_edge_index];
13507                                 *stail = sedge;
13508                                 stail = &sedge->out_next;
13509                                 sedge->src = lnode;
13510                                 sedge->dst = &scc->lattice[edge->member->id];
13511                                 sedge->work_next = sedge->work_prev = sedge;
13512                                 sedge->out_next = 0;
13513                         }
13514                 }
13515                 ins = ins->next;
13516         } while(ins != first);
13517         /* Setup a dummy block 0 as a node above the start node */
13518         {
13519                 struct flow_block *fblock, *dst;
13520                 struct flow_edge *fedge;
13521                 fblock = &scc->flow_blocks[0];
13522                 fblock->block = 0;
13523                 fblock->in = 0;
13524                 fblock->out = &fblock->left;
13525                 dst = &scc->flow_blocks[state->first_block->vertex];
13526                 fedge = &fblock->left;
13527                 fedge->src        = fblock;
13528                 fedge->dst        = dst;
13529                 fedge->work_next  = fedge;
13530                 fedge->work_prev  = fedge;
13531                 fedge->in_next    = fedge->dst->in;
13532                 fedge->out_next   = 0;
13533                 fedge->executable = 0;
13534                 fedge->dst->in = fedge;
13535                 
13536                 /* Initialize the work lists */
13537                 scc->flow_work_list = 0;
13538                 scc->ssa_work_list  = 0;
13539                 scc_add_fedge(state, scc, fedge);
13540         }
13541 #if DEBUG_SCC
13542         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13543                 ins_index, ssa_edge_index, fblock_index);
13544 #endif
13545 }
13546
13547         
13548 static void free_scc_state(
13549         struct compile_state *state, struct scc_state *scc)
13550 {
13551         xfree(scc->flow_blocks);
13552         xfree(scc->ssa_edges);
13553         xfree(scc->lattice);
13554         
13555 }
13556
13557 static struct lattice_node *triple_to_lattice(
13558         struct compile_state *state, struct scc_state *scc, struct triple *ins)
13559 {
13560         if (ins->id <= 0) {
13561                 internal_error(state, ins, "bad id");
13562         }
13563         return &scc->lattice[ins->id];
13564 }
13565
13566 static struct triple *preserve_lval(
13567         struct compile_state *state, struct lattice_node *lnode)
13568 {
13569         struct triple *old;
13570         /* Preserve the original value */
13571         if (lnode->val) {
13572                 old = dup_triple(state, lnode->val);
13573                 if (lnode->val != lnode->def) {
13574                         xfree(lnode->val);
13575                 }
13576                 lnode->val = 0;
13577         } else {
13578                 old = 0;
13579         }
13580         return old;
13581 }
13582
13583 static int lval_changed(struct compile_state *state, 
13584         struct triple *old, struct lattice_node *lnode)
13585 {
13586         int changed;
13587         /* See if the lattice value has changed */
13588         changed = 1;
13589         if (!old && !lnode->val) {
13590                 changed = 0;
13591         }
13592         if (changed && lnode->val && !is_const(lnode->val)) {
13593                 changed = 0;
13594         }
13595         if (changed &&
13596                 lnode->val && old &&
13597                 (memcmp(lnode->val->param, old->param,
13598                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13599                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13600                 changed = 0;
13601         }
13602         if (old) {
13603                 xfree(old);
13604         }
13605         return changed;
13606
13607 }
13608
13609 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
13610         struct lattice_node *lnode)
13611 {
13612         struct lattice_node *tmp;
13613         struct triple **slot, *old;
13614         struct flow_edge *fedge;
13615         int index;
13616         if (lnode->def->op != OP_PHI) {
13617                 internal_error(state, lnode->def, "not phi");
13618         }
13619         /* Store the original value */
13620         old = preserve_lval(state, lnode);
13621
13622         /* default to lattice high */
13623         lnode->val = lnode->def;
13624         slot = &RHS(lnode->def, 0);
13625         index = 0;
13626         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13627                 if (!fedge->executable) {
13628                         continue;
13629                 }
13630                 if (!slot[index]) {
13631                         internal_error(state, lnode->def, "no phi value");
13632                 }
13633                 tmp = triple_to_lattice(state, scc, slot[index]);
13634                 /* meet(X, lattice low) = lattice low */
13635                 if (!tmp->val) {
13636                         lnode->val = 0;
13637                 }
13638                 /* meet(X, lattice high) = X */
13639                 else if (!tmp->val) {
13640                         lnode->val = lnode->val;
13641                 }
13642                 /* meet(lattice high, X) = X */
13643                 else if (!is_const(lnode->val)) {
13644                         lnode->val = dup_triple(state, tmp->val);
13645                         lnode->val->type = lnode->def->type;
13646                 }
13647                 /* meet(const, const) = const or lattice low */
13648                 else if (!constants_equal(state, lnode->val, tmp->val)) {
13649                         lnode->val = 0;
13650                 }
13651                 if (!lnode->val) {
13652                         break;
13653                 }
13654         }
13655 #if DEBUG_SCC
13656         fprintf(stderr, "phi: %d -> %s\n",
13657                 lnode->def->id,
13658                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13659 #endif
13660         /* If the lattice value has changed update the work lists. */
13661         if (lval_changed(state, old, lnode)) {
13662                 struct ssa_edge *sedge;
13663                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13664                         scc_add_sedge(state, scc, sedge);
13665                 }
13666         }
13667 }
13668
13669 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13670         struct lattice_node *lnode)
13671 {
13672         int changed;
13673         struct triple *old, *scratch;
13674         struct triple **dexpr, **vexpr;
13675         int count, i;
13676         
13677         /* Store the original value */
13678         old = preserve_lval(state, lnode);
13679
13680         /* Reinitialize the value */
13681         lnode->val = scratch = dup_triple(state, lnode->def);
13682         scratch->id = lnode->old_id;
13683         scratch->next     = scratch;
13684         scratch->prev     = scratch;
13685         scratch->use      = 0;
13686
13687         count = TRIPLE_SIZE(scratch->sizes);
13688         for(i = 0; i < count; i++) {
13689                 dexpr = &lnode->def->param[i];
13690                 vexpr = &scratch->param[i];
13691                 *vexpr = *dexpr;
13692                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13693                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13694                         *dexpr) {
13695                         struct lattice_node *tmp;
13696                         tmp = triple_to_lattice(state, scc, *dexpr);
13697                         *vexpr = (tmp->val)? tmp->val : tmp->def;
13698                 }
13699         }
13700         if (scratch->op == OP_BRANCH) {
13701                 scratch->next = lnode->def->next;
13702         }
13703         /* Recompute the value */
13704 #warning "FIXME see if simplify does anything bad"
13705         /* So far it looks like only the strength reduction
13706          * optimization are things I need to worry about.
13707          */
13708         simplify(state, scratch);
13709         /* Cleanup my value */
13710         if (scratch->use) {
13711                 internal_error(state, lnode->def, "scratch used?");
13712         }
13713         if ((scratch->prev != scratch) ||
13714                 ((scratch->next != scratch) &&
13715                         ((lnode->def->op != OP_BRANCH) ||
13716                                 (scratch->next != lnode->def->next)))) {
13717                 internal_error(state, lnode->def, "scratch in list?");
13718         }
13719         /* undo any uses... */
13720         count = TRIPLE_SIZE(scratch->sizes);
13721         for(i = 0; i < count; i++) {
13722                 vexpr = &scratch->param[i];
13723                 if (*vexpr) {
13724                         unuse_triple(*vexpr, scratch);
13725                 }
13726         }
13727         if (!is_const(scratch)) {
13728                 for(i = 0; i < count; i++) {
13729                         dexpr = &lnode->def->param[i];
13730                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13731                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13732                                 *dexpr) {
13733                                 struct lattice_node *tmp;
13734                                 tmp = triple_to_lattice(state, scc, *dexpr);
13735                                 if (!tmp->val) {
13736                                         lnode->val = 0;
13737                                 }
13738                         }
13739                 }
13740         }
13741         if (lnode->val && 
13742                 (lnode->val->op == lnode->def->op) &&
13743                 (memcmp(lnode->val->param, lnode->def->param, 
13744                         count * sizeof(lnode->val->param[0])) == 0) &&
13745                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13746                 lnode->val = lnode->def;
13747         }
13748         /* Find the cases that are always lattice lo */
13749         if (lnode->val && 
13750                 triple_is_def(state, lnode->val) &&
13751                 !triple_is_pure(state, lnode->val)) {
13752                 lnode->val = 0;
13753         }
13754         if (lnode->val && 
13755                 (lnode->val->op == OP_SDECL) && 
13756                 (lnode->val != lnode->def)) {
13757                 internal_error(state, lnode->def, "bad sdecl");
13758         }
13759         /* See if the lattice value has changed */
13760         changed = lval_changed(state, old, lnode);
13761         if (lnode->val != scratch) {
13762                 xfree(scratch);
13763         }
13764         return changed;
13765 }
13766
13767 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13768         struct lattice_node *lnode)
13769 {
13770         struct lattice_node *cond;
13771 #if DEBUG_SCC
13772         {
13773                 struct flow_edge *fedge;
13774                 fprintf(stderr, "branch: %d (",
13775                         lnode->def->id);
13776                 
13777                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13778                         fprintf(stderr, " %d", fedge->dst->block->vertex);
13779                 }
13780                 fprintf(stderr, " )");
13781                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13782                         fprintf(stderr, " <- %d",
13783                                 RHS(lnode->def, 0)->id);
13784                 }
13785                 fprintf(stderr, "\n");
13786         }
13787 #endif
13788         if (lnode->def->op != OP_BRANCH) {
13789                 internal_error(state, lnode->def, "not branch");
13790         }
13791         /* This only applies to conditional branches */
13792         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13793                 return;
13794         }
13795         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13796         if (cond->val && !is_const(cond->val)) {
13797 #warning "FIXME do I need to do something here?"
13798                 warning(state, cond->def, "condition not constant?");
13799                 return;
13800         }
13801         if (cond->val == 0) {
13802                 scc_add_fedge(state, scc, cond->fblock->out);
13803                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13804         }
13805         else if (cond->val->u.cval) {
13806                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13807                 
13808         } else {
13809                 scc_add_fedge(state, scc, cond->fblock->out);
13810         }
13811
13812 }
13813
13814 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13815         struct lattice_node *lnode)
13816 {
13817         int changed;
13818
13819         changed = compute_lnode_val(state, scc, lnode);
13820 #if DEBUG_SCC
13821         {
13822                 struct triple **expr;
13823                 fprintf(stderr, "expr: %3d %10s (",
13824                         lnode->def->id, tops(lnode->def->op));
13825                 expr = triple_rhs(state, lnode->def, 0);
13826                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13827                         if (*expr) {
13828                                 fprintf(stderr, " %d", (*expr)->id);
13829                         }
13830                 }
13831                 fprintf(stderr, " ) -> %s\n",
13832                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13833         }
13834 #endif
13835         if (lnode->def->op == OP_BRANCH) {
13836                 scc_visit_branch(state, scc, lnode);
13837
13838         }
13839         else if (changed) {
13840                 struct ssa_edge *sedge;
13841                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13842                         scc_add_sedge(state, scc, sedge);
13843                 }
13844         }
13845 }
13846
13847 static void scc_writeback_values(
13848         struct compile_state *state, struct scc_state *scc)
13849 {
13850         struct triple *first, *ins;
13851         first = RHS(state->main_function, 0);
13852         ins = first;
13853         do {
13854                 struct lattice_node *lnode;
13855                 lnode = triple_to_lattice(state, scc, ins);
13856                 /* Restore id */
13857                 ins->id = lnode->old_id;
13858 #if DEBUG_SCC
13859                 if (lnode->val && !is_const(lnode->val)) {
13860                         warning(state, lnode->def, 
13861                                 "lattice node still high?");
13862                 }
13863 #endif
13864                 if (lnode->val && (lnode->val != ins)) {
13865                         /* See if it something I know how to write back */
13866                         switch(lnode->val->op) {
13867                         case OP_INTCONST:
13868                                 mkconst(state, ins, lnode->val->u.cval);
13869                                 break;
13870                         case OP_ADDRCONST:
13871                                 mkaddr_const(state, ins, 
13872                                         MISC(lnode->val, 0), lnode->val->u.cval);
13873                                 break;
13874                         default:
13875                                 /* By default don't copy the changes,
13876                                  * recompute them in place instead.
13877                                  */
13878                                 simplify(state, ins);
13879                                 break;
13880                         }
13881                         if (is_const(lnode->val) &&
13882                                 !constants_equal(state, lnode->val, ins)) {
13883                                 internal_error(state, 0, "constants not equal");
13884                         }
13885                         /* Free the lattice nodes */
13886                         xfree(lnode->val);
13887                         lnode->val = 0;
13888                 }
13889                 ins = ins->next;
13890         } while(ins != first);
13891 }
13892
13893 static void scc_transform(struct compile_state *state)
13894 {
13895         struct scc_state scc;
13896
13897         initialize_scc_state(state, &scc);
13898
13899         while(scc.flow_work_list || scc.ssa_work_list) {
13900                 struct flow_edge *fedge;
13901                 struct ssa_edge *sedge;
13902                 struct flow_edge *fptr;
13903                 while((fedge = scc_next_fedge(state, &scc))) {
13904                         struct block *block;
13905                         struct triple *ptr;
13906                         struct flow_block *fblock;
13907                         int time;
13908                         int done;
13909                         if (fedge->executable) {
13910                                 continue;
13911                         }
13912                         if (!fedge->dst) {
13913                                 internal_error(state, 0, "fedge without dst");
13914                         }
13915                         if (!fedge->src) {
13916                                 internal_error(state, 0, "fedge without src");
13917                         }
13918                         fedge->executable = 1;
13919                         fblock = fedge->dst;
13920                         block = fblock->block;
13921                         time = 0;
13922                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13923                                 if (fptr->executable) {
13924                                         time++;
13925                                 }
13926                         }
13927 #if DEBUG_SCC
13928                         fprintf(stderr, "vertex: %d time: %d\n", 
13929                                 block->vertex, time);
13930                         
13931 #endif
13932                         done = 0;
13933                         for(ptr = block->first; !done; ptr = ptr->next) {
13934                                 struct lattice_node *lnode;
13935                                 done = (ptr == block->last);
13936                                 lnode = &scc.lattice[ptr->id];
13937                                 if (ptr->op == OP_PHI) {
13938                                         scc_visit_phi(state, &scc, lnode);
13939                                 }
13940                                 else if (time == 1) {
13941                                         scc_visit_expr(state, &scc, lnode);
13942                                 }
13943                         }
13944                         if (fblock->out && !fblock->out->out_next) {
13945                                 scc_add_fedge(state, &scc, fblock->out);
13946                         }
13947                 }
13948                 while((sedge = scc_next_sedge(state, &scc))) {
13949                         struct lattice_node *lnode;
13950                         struct flow_block *fblock;
13951                         lnode = sedge->dst;
13952                         fblock = lnode->fblock;
13953 #if DEBUG_SCC
13954                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
13955                                 sedge - scc.ssa_edges,
13956                                 sedge->src->def->id,
13957                                 sedge->dst->def->id);
13958 #endif
13959                         if (lnode->def->op == OP_PHI) {
13960                                 scc_visit_phi(state, &scc, lnode);
13961                         }
13962                         else {
13963                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13964                                         if (fptr->executable) {
13965                                                 break;
13966                                         }
13967                                 }
13968                                 if (fptr) {
13969                                         scc_visit_expr(state, &scc, lnode);
13970                                 }
13971                         }
13972                 }
13973         }
13974         
13975         scc_writeback_values(state, &scc);
13976         free_scc_state(state, &scc);
13977 }
13978
13979
13980 static void transform_to_arch_instructions(struct compile_state *state)
13981 {
13982         struct triple *ins, *first;
13983         first = RHS(state->main_function, 0);
13984         ins = first;
13985         do {
13986                 ins = transform_to_arch_instruction(state, ins);
13987         } while(ins != first);
13988 }
13989
13990 #if DEBUG_CONSISTENCY
13991 static void verify_uses(struct compile_state *state)
13992 {
13993         struct triple *first, *ins;
13994         struct triple_set *set;
13995         first = RHS(state->main_function, 0);
13996         ins = first;
13997         do {
13998                 struct triple **expr;
13999                 expr = triple_rhs(state, ins, 0);
14000                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14001                         struct triple *rhs;
14002                         rhs = *expr;
14003                         for(set = rhs?rhs->use:0; set; set = set->next) {
14004                                 if (set->member == ins) {
14005                                         break;
14006                                 }
14007                         }
14008                         if (!set) {
14009                                 internal_error(state, ins, "rhs not used");
14010                         }
14011                 }
14012                 expr = triple_lhs(state, ins, 0);
14013                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14014                         struct triple *lhs;
14015                         lhs = *expr;
14016                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14017                                 if (set->member == ins) {
14018                                         break;
14019                                 }
14020                         }
14021                         if (!set) {
14022                                 internal_error(state, ins, "lhs not used");
14023                         }
14024                 }
14025                 ins = ins->next;
14026         } while(ins != first);
14027         
14028 }
14029 static void verify_blocks(struct compile_state *state)
14030 {
14031         struct triple *ins;
14032         struct block *block;
14033         block = state->first_block;
14034         if (!block) {
14035                 return;
14036         }
14037         do {
14038                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14039                         if (!triple_stores_block(state, ins)) {
14040                                 continue;
14041                         }
14042                         if (ins->u.block != block) {
14043                                 internal_error(state, ins, "inconsitent block specified");
14044                         }
14045                 }
14046                 if (!triple_stores_block(state, block->last->next)) {
14047                         internal_error(state, block->last->next, 
14048                                 "cannot find next block");
14049                 }
14050                 block = block->last->next->u.block;
14051                 if (!block) {
14052                         internal_error(state, block->last->next,
14053                                 "bad next block");
14054                 }
14055         } while(block != state->first_block);
14056 }
14057
14058 static void verify_domination(struct compile_state *state)
14059 {
14060         struct triple *first, *ins;
14061         struct triple_set *set;
14062         if (!state->first_block) {
14063                 return;
14064         }
14065         
14066         first = RHS(state->main_function, 0);
14067         ins = first;
14068         do {
14069                 for(set = ins->use; set; set = set->next) {
14070                         struct triple **expr;
14071                         if (set->member->op == OP_PHI) {
14072                                 continue;
14073                         }
14074                         /* See if the use is on the righ hand side */
14075                         expr = triple_rhs(state, set->member, 0);
14076                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14077                                 if (*expr == ins) {
14078                                         break;
14079                                 }
14080                         }
14081                         if (expr &&
14082                                 !tdominates(state, ins, set->member)) {
14083                                 internal_error(state, set->member, 
14084                                         "non dominated rhs use?");
14085                         }
14086                 }
14087                 ins = ins->next;
14088         } while(ins != first);
14089 }
14090
14091 static void verify_piece(struct compile_state *state)
14092 {
14093         struct triple *first, *ins;
14094         first = RHS(state->main_function, 0);
14095         ins = first;
14096         do {
14097                 struct triple *ptr;
14098                 int lhs, i;
14099                 lhs = TRIPLE_LHS(ins->sizes);
14100                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14101                         lhs = 0;
14102                 }
14103                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14104                         if (ptr != LHS(ins, i)) {
14105                                 internal_error(state, ins, "malformed lhs on %s",
14106                                         tops(ins->op));
14107                         }
14108                         if (ptr->op != OP_PIECE) {
14109                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14110                                         tops(ptr->op), i, tops(ins->op));
14111                         }
14112                         if (ptr->u.cval != i) {
14113                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14114                                         ptr->u.cval, i);
14115                         }
14116                 }
14117                 ins = ins->next;
14118         } while(ins != first);
14119 }
14120 static void verify_ins_colors(struct compile_state *state)
14121 {
14122         struct triple *first, *ins;
14123         
14124         first = RHS(state->main_function, 0);
14125         ins = first;
14126         do {
14127                 ins = ins->next;
14128         } while(ins != first);
14129 }
14130 static void verify_consistency(struct compile_state *state)
14131 {
14132         verify_uses(state);
14133         verify_blocks(state);
14134         verify_domination(state);
14135         verify_piece(state);
14136         verify_ins_colors(state);
14137 }
14138 #else 
14139 #define verify_consistency(state) do {} while(0)
14140 #endif /* DEBUG_USES */
14141
14142 static void optimize(struct compile_state *state)
14143 {
14144         if (state->debug & DEBUG_TRIPLES) {
14145                 print_triples(state);
14146         }
14147         /* Replace structures with simpler data types */
14148         flatten_structures(state);
14149         if (state->debug & DEBUG_TRIPLES) {
14150                 print_triples(state);
14151         }
14152         verify_consistency(state);
14153         /* Analize the intermediate code */
14154         setup_basic_blocks(state);
14155         analyze_idominators(state);
14156         analyze_ipdominators(state);
14157         /* Transform the code to ssa form */
14158         transform_to_ssa_form(state);
14159         verify_consistency(state);
14160         if (state->debug & DEBUG_CODE_ELIMINATION) {
14161                 fprintf(stdout, "After transform_to_ssa_form\n");
14162                 print_blocks(state, stdout);
14163         }
14164         /* Do strength reduction and simple constant optimizations */
14165         if (state->optimize >= 1) {
14166                 simplify_all(state);
14167         }
14168         verify_consistency(state);
14169         /* Propogate constants throughout the code */
14170         if (state->optimize >= 2) {
14171 #warning "FIXME fix scc_transform"
14172                 scc_transform(state);
14173                 transform_from_ssa_form(state);
14174                 free_basic_blocks(state);
14175                 setup_basic_blocks(state);
14176                 analyze_idominators(state);
14177                 analyze_ipdominators(state);
14178                 transform_to_ssa_form(state);
14179         }
14180         verify_consistency(state);
14181 #warning "WISHLIST implement single use constants (least possible register pressure)"
14182 #warning "WISHLIST implement induction variable elimination"
14183         /* Select architecture instructions and an initial partial
14184          * coloring based on architecture constraints.
14185          */
14186         transform_to_arch_instructions(state);
14187         verify_consistency(state);
14188         if (state->debug & DEBUG_ARCH_CODE) {
14189                 printf("After transform_to_arch_instructions\n");
14190                 print_blocks(state, stdout);
14191                 print_control_flow(state);
14192         }
14193         eliminate_inefectual_code(state);
14194         verify_consistency(state);
14195         if (state->debug & DEBUG_CODE_ELIMINATION) {
14196                 printf("After eliminate_inefectual_code\n");
14197                 print_blocks(state, stdout);
14198                 print_control_flow(state);
14199         }
14200         verify_consistency(state);
14201         /* Color all of the variables to see if they will fit in registers */
14202         insert_copies_to_phi(state);
14203         if (state->debug & DEBUG_INSERTED_COPIES) {
14204                 printf("After insert_copies_to_phi\n");
14205                 print_blocks(state, stdout);
14206                 print_control_flow(state);
14207         }
14208         verify_consistency(state);
14209         insert_mandatory_copies(state);
14210         if (state->debug & DEBUG_INSERTED_COPIES) {
14211                 printf("After insert_mandatory_copies\n");
14212                 print_blocks(state, stdout);
14213                 print_control_flow(state);
14214         }
14215         verify_consistency(state);
14216         allocate_registers(state);
14217         verify_consistency(state);
14218         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14219                 print_blocks(state, stdout);
14220         }
14221         if (state->debug & DEBUG_CONTROL_FLOW) {
14222                 print_control_flow(state);
14223         }
14224         /* Remove the optimization information.
14225          * This is more to check for memory consistency than to free memory.
14226          */
14227         free_basic_blocks(state);
14228 }
14229
14230 static void print_op_asm(struct compile_state *state,
14231         struct triple *ins, FILE *fp)
14232 {
14233         struct asm_info *info;
14234         const char *ptr;
14235         unsigned lhs, rhs, i;
14236         info = ins->u.ainfo;
14237         lhs = TRIPLE_LHS(ins->sizes);
14238         rhs = TRIPLE_RHS(ins->sizes);
14239         /* Don't count the clobbers in lhs */
14240         for(i = 0; i < lhs; i++) {
14241                 if (LHS(ins, i)->type == &void_type) {
14242                         break;
14243                 }
14244         }
14245         lhs = i;
14246         fprintf(fp, "#ASM\n");
14247         fputc('\t', fp);
14248         for(ptr = info->str; *ptr; ptr++) {
14249                 char *next;
14250                 unsigned long param;
14251                 struct triple *piece;
14252                 if (*ptr != '%') {
14253                         fputc(*ptr, fp);
14254                         continue;
14255                 }
14256                 ptr++;
14257                 if (*ptr == '%') {
14258                         fputc('%', fp);
14259                         continue;
14260                 }
14261                 param = strtoul(ptr, &next, 10);
14262                 if (ptr == next) {
14263                         error(state, ins, "Invalid asm template");
14264                 }
14265                 if (param >= (lhs + rhs)) {
14266                         error(state, ins, "Invalid param %%%u in asm template",
14267                                 param);
14268                 }
14269                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14270                 fprintf(fp, "%s", 
14271                         arch_reg_str(ID_REG(piece->id)));
14272                 ptr = next -1;
14273         }
14274         fprintf(fp, "\n#NOT ASM\n");
14275 }
14276
14277
14278 /* Only use the low x86 byte registers.  This allows me
14279  * allocate the entire register when a byte register is used.
14280  */
14281 #define X86_4_8BIT_GPRS 1
14282
14283 /* Recognized x86 cpu variants */
14284 #define BAD_CPU      0
14285 #define CPU_I386     1
14286 #define CPU_P3       2
14287 #define CPU_P4       3
14288 #define CPU_K7       4
14289 #define CPU_K8       5
14290
14291 #define CPU_DEFAULT  CPU_I386
14292
14293 /* The x86 register classes */
14294 #define REGC_FLAGS    0
14295 #define REGC_GPR8     1
14296 #define REGC_GPR16    2
14297 #define REGC_GPR32    3
14298 #define REGC_GPR64    4
14299 #define REGC_MMX      5
14300 #define REGC_XMM      6
14301 #define REGC_GPR32_8  7
14302 #define REGC_GPR16_8  8
14303 #define REGC_IMM32    9
14304 #define REGC_IMM16   10
14305 #define REGC_IMM8    11
14306 #define LAST_REGC  REGC_IMM8
14307 #if LAST_REGC >= MAX_REGC
14308 #error "MAX_REGC is to low"
14309 #endif
14310
14311 /* Register class masks */
14312 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14313 #define REGCM_GPR8    (1 << REGC_GPR8)
14314 #define REGCM_GPR16   (1 << REGC_GPR16)
14315 #define REGCM_GPR32   (1 << REGC_GPR32)
14316 #define REGCM_GPR64   (1 << REGC_GPR64)
14317 #define REGCM_MMX     (1 << REGC_MMX)
14318 #define REGCM_XMM     (1 << REGC_XMM)
14319 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14320 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14321 #define REGCM_IMM32   (1 << REGC_IMM32)
14322 #define REGCM_IMM16   (1 << REGC_IMM16)
14323 #define REGCM_IMM8    (1 << REGC_IMM8)
14324 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14325
14326 /* The x86 registers */
14327 #define REG_EFLAGS  2
14328 #define REGC_FLAGS_FIRST REG_EFLAGS
14329 #define REGC_FLAGS_LAST  REG_EFLAGS
14330 #define REG_AL      3
14331 #define REG_BL      4
14332 #define REG_CL      5
14333 #define REG_DL      6
14334 #define REG_AH      7
14335 #define REG_BH      8
14336 #define REG_CH      9
14337 #define REG_DH      10
14338 #define REGC_GPR8_FIRST  REG_AL
14339 #if X86_4_8BIT_GPRS
14340 #define REGC_GPR8_LAST   REG_DL
14341 #else 
14342 #define REGC_GPR8_LAST   REG_DH
14343 #endif
14344 #define REG_AX     11
14345 #define REG_BX     12
14346 #define REG_CX     13
14347 #define REG_DX     14
14348 #define REG_SI     15
14349 #define REG_DI     16
14350 #define REG_BP     17
14351 #define REG_SP     18
14352 #define REGC_GPR16_FIRST REG_AX
14353 #define REGC_GPR16_LAST  REG_SP
14354 #define REG_EAX    19
14355 #define REG_EBX    20
14356 #define REG_ECX    21
14357 #define REG_EDX    22
14358 #define REG_ESI    23
14359 #define REG_EDI    24
14360 #define REG_EBP    25
14361 #define REG_ESP    26
14362 #define REGC_GPR32_FIRST REG_EAX
14363 #define REGC_GPR32_LAST  REG_ESP
14364 #define REG_EDXEAX 27
14365 #define REGC_GPR64_FIRST REG_EDXEAX
14366 #define REGC_GPR64_LAST  REG_EDXEAX
14367 #define REG_MMX0   28
14368 #define REG_MMX1   29
14369 #define REG_MMX2   30
14370 #define REG_MMX3   31
14371 #define REG_MMX4   32
14372 #define REG_MMX5   33
14373 #define REG_MMX6   34
14374 #define REG_MMX7   35
14375 #define REGC_MMX_FIRST REG_MMX0
14376 #define REGC_MMX_LAST  REG_MMX7
14377 #define REG_XMM0   36
14378 #define REG_XMM1   37
14379 #define REG_XMM2   38
14380 #define REG_XMM3   39
14381 #define REG_XMM4   40
14382 #define REG_XMM5   41
14383 #define REG_XMM6   42
14384 #define REG_XMM7   43
14385 #define REGC_XMM_FIRST REG_XMM0
14386 #define REGC_XMM_LAST  REG_XMM7
14387 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14388 #define LAST_REG   REG_XMM7
14389
14390 #define REGC_GPR32_8_FIRST REG_EAX
14391 #define REGC_GPR32_8_LAST  REG_EDX
14392 #define REGC_GPR16_8_FIRST REG_AX
14393 #define REGC_GPR16_8_LAST  REG_DX
14394
14395 #define REGC_IMM8_FIRST    -1
14396 #define REGC_IMM8_LAST     -1
14397 #define REGC_IMM16_FIRST   -2
14398 #define REGC_IMM16_LAST    -1
14399 #define REGC_IMM32_FIRST   -4
14400 #define REGC_IMM32_LAST    -1
14401
14402 #if LAST_REG >= MAX_REGISTERS
14403 #error "MAX_REGISTERS to low"
14404 #endif
14405
14406
14407 static unsigned regc_size[LAST_REGC +1] = {
14408         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
14409         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
14410         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
14411         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
14412         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
14413         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
14414         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
14415         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14416         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14417         [REGC_IMM32]   = 0,
14418         [REGC_IMM16]   = 0,
14419         [REGC_IMM8]    = 0,
14420 };
14421
14422 static const struct {
14423         int first, last;
14424 } regcm_bound[LAST_REGC + 1] = {
14425         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
14426         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
14427         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
14428         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
14429         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
14430         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
14431         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
14432         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14433         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14434         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
14435         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
14436         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
14437 };
14438
14439 static int arch_encode_cpu(const char *cpu)
14440 {
14441         struct cpu {
14442                 const char *name;
14443                 int cpu;
14444         } cpus[] = {
14445                 { "i386", CPU_I386 },
14446                 { "p3",   CPU_P3 },
14447                 { "p4",   CPU_P4 },
14448                 { "k7",   CPU_K7 },
14449                 { "k8",   CPU_K8 },
14450                 {  0,     BAD_CPU }
14451         };
14452         struct cpu *ptr;
14453         for(ptr = cpus; ptr->name; ptr++) {
14454                 if (strcmp(ptr->name, cpu) == 0) {
14455                         break;
14456                 }
14457         }
14458         return ptr->cpu;
14459 }
14460
14461 static unsigned arch_regc_size(struct compile_state *state, int class)
14462 {
14463         if ((class < 0) || (class > LAST_REGC)) {
14464                 return 0;
14465         }
14466         return regc_size[class];
14467 }
14468 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14469 {
14470         /* See if two register classes may have overlapping registers */
14471         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14472                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14473
14474         /* Special case for the immediates */
14475         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14476                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14477                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14478                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
14479                 return 0;
14480         }
14481         return (regcm1 & regcm2) ||
14482                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14483 }
14484
14485 static void arch_reg_equivs(
14486         struct compile_state *state, unsigned *equiv, int reg)
14487 {
14488         if ((reg < 0) || (reg > LAST_REG)) {
14489                 internal_error(state, 0, "invalid register");
14490         }
14491         *equiv++ = reg;
14492         switch(reg) {
14493         case REG_AL:
14494 #if X86_4_8BIT_GPRS
14495                 *equiv++ = REG_AH;
14496 #endif
14497                 *equiv++ = REG_AX;
14498                 *equiv++ = REG_EAX;
14499                 *equiv++ = REG_EDXEAX;
14500                 break;
14501         case REG_AH:
14502 #if X86_4_8BIT_GPRS
14503                 *equiv++ = REG_AL;
14504 #endif
14505                 *equiv++ = REG_AX;
14506                 *equiv++ = REG_EAX;
14507                 *equiv++ = REG_EDXEAX;
14508                 break;
14509         case REG_BL:  
14510 #if X86_4_8BIT_GPRS
14511                 *equiv++ = REG_BH;
14512 #endif
14513                 *equiv++ = REG_BX;
14514                 *equiv++ = REG_EBX;
14515                 break;
14516
14517         case REG_BH:
14518 #if X86_4_8BIT_GPRS
14519                 *equiv++ = REG_BL;
14520 #endif
14521                 *equiv++ = REG_BX;
14522                 *equiv++ = REG_EBX;
14523                 break;
14524         case REG_CL:
14525 #if X86_4_8BIT_GPRS
14526                 *equiv++ = REG_CH;
14527 #endif
14528                 *equiv++ = REG_CX;
14529                 *equiv++ = REG_ECX;
14530                 break;
14531
14532         case REG_CH:
14533 #if X86_4_8BIT_GPRS
14534                 *equiv++ = REG_CL;
14535 #endif
14536                 *equiv++ = REG_CX;
14537                 *equiv++ = REG_ECX;
14538                 break;
14539         case REG_DL:
14540 #if X86_4_8BIT_GPRS
14541                 *equiv++ = REG_DH;
14542 #endif
14543                 *equiv++ = REG_DX;
14544                 *equiv++ = REG_EDX;
14545                 *equiv++ = REG_EDXEAX;
14546                 break;
14547         case REG_DH:
14548 #if X86_4_8BIT_GPRS
14549                 *equiv++ = REG_DL;
14550 #endif
14551                 *equiv++ = REG_DX;
14552                 *equiv++ = REG_EDX;
14553                 *equiv++ = REG_EDXEAX;
14554                 break;
14555         case REG_AX:
14556                 *equiv++ = REG_AL;
14557                 *equiv++ = REG_AH;
14558                 *equiv++ = REG_EAX;
14559                 *equiv++ = REG_EDXEAX;
14560                 break;
14561         case REG_BX:
14562                 *equiv++ = REG_BL;
14563                 *equiv++ = REG_BH;
14564                 *equiv++ = REG_EBX;
14565                 break;
14566         case REG_CX:  
14567                 *equiv++ = REG_CL;
14568                 *equiv++ = REG_CH;
14569                 *equiv++ = REG_ECX;
14570                 break;
14571         case REG_DX:  
14572                 *equiv++ = REG_DL;
14573                 *equiv++ = REG_DH;
14574                 *equiv++ = REG_EDX;
14575                 *equiv++ = REG_EDXEAX;
14576                 break;
14577         case REG_SI:  
14578                 *equiv++ = REG_ESI;
14579                 break;
14580         case REG_DI:
14581                 *equiv++ = REG_EDI;
14582                 break;
14583         case REG_BP:
14584                 *equiv++ = REG_EBP;
14585                 break;
14586         case REG_SP:
14587                 *equiv++ = REG_ESP;
14588                 break;
14589         case REG_EAX:
14590                 *equiv++ = REG_AL;
14591                 *equiv++ = REG_AH;
14592                 *equiv++ = REG_AX;
14593                 *equiv++ = REG_EDXEAX;
14594                 break;
14595         case REG_EBX:
14596                 *equiv++ = REG_BL;
14597                 *equiv++ = REG_BH;
14598                 *equiv++ = REG_BX;
14599                 break;
14600         case REG_ECX:
14601                 *equiv++ = REG_CL;
14602                 *equiv++ = REG_CH;
14603                 *equiv++ = REG_CX;
14604                 break;
14605         case REG_EDX:
14606                 *equiv++ = REG_DL;
14607                 *equiv++ = REG_DH;
14608                 *equiv++ = REG_DX;
14609                 *equiv++ = REG_EDXEAX;
14610                 break;
14611         case REG_ESI: 
14612                 *equiv++ = REG_SI;
14613                 break;
14614         case REG_EDI: 
14615                 *equiv++ = REG_DI;
14616                 break;
14617         case REG_EBP: 
14618                 *equiv++ = REG_BP;
14619                 break;
14620         case REG_ESP: 
14621                 *equiv++ = REG_SP;
14622                 break;
14623         case REG_EDXEAX: 
14624                 *equiv++ = REG_AL;
14625                 *equiv++ = REG_AH;
14626                 *equiv++ = REG_DL;
14627                 *equiv++ = REG_DH;
14628                 *equiv++ = REG_AX;
14629                 *equiv++ = REG_DX;
14630                 *equiv++ = REG_EAX;
14631                 *equiv++ = REG_EDX;
14632                 break;
14633         }
14634         *equiv++ = REG_UNSET; 
14635 }
14636
14637 static unsigned arch_avail_mask(struct compile_state *state)
14638 {
14639         unsigned avail_mask;
14640         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
14641                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14642                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14643         switch(state->cpu) {
14644         case CPU_P3:
14645         case CPU_K7:
14646                 avail_mask |= REGCM_MMX;
14647                 break;
14648         case CPU_P4:
14649         case CPU_K8:
14650                 avail_mask |= REGCM_MMX | REGCM_XMM;
14651                 break;
14652         }
14653 #if 0
14654         /* Don't enable 8 bit values until I can force both operands
14655          * to be 8bits simultaneously.
14656          */
14657         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14658 #endif
14659         return avail_mask;
14660 }
14661
14662 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14663 {
14664         unsigned mask, result;
14665         int class, class2;
14666         result = regcm;
14667         result &= arch_avail_mask(state);
14668
14669         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14670                 if ((result & mask) == 0) {
14671                         continue;
14672                 }
14673                 if (class > LAST_REGC) {
14674                         result &= ~mask;
14675                 }
14676                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14677                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14678                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14679                                 result |= (1 << class2);
14680                         }
14681                 }
14682         }
14683         return result;
14684 }
14685
14686 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14687 {
14688         unsigned mask;
14689         int class;
14690         mask = 0;
14691         for(class = 0; class <= LAST_REGC; class++) {
14692                 if ((reg >= regcm_bound[class].first) &&
14693                         (reg <= regcm_bound[class].last)) {
14694                         mask |= (1 << class);
14695                 }
14696         }
14697         if (!mask) {
14698                 internal_error(state, 0, "reg %d not in any class", reg);
14699         }
14700         return mask;
14701 }
14702
14703 static struct reg_info arch_reg_constraint(
14704         struct compile_state *state, struct type *type, const char *constraint)
14705 {
14706         static const struct {
14707                 char class;
14708                 unsigned int mask;
14709                 unsigned int reg;
14710         } constraints[] = {
14711                 { 'r', REGCM_GPR32, REG_UNSET },
14712                 { 'g', REGCM_GPR32, REG_UNSET },
14713                 { 'p', REGCM_GPR32, REG_UNSET },
14714                 { 'q', REGCM_GPR8,  REG_UNSET },
14715                 { 'Q', REGCM_GPR32_8, REG_UNSET },
14716                 { 'x', REGCM_XMM,   REG_UNSET },
14717                 { 'y', REGCM_MMX,   REG_UNSET },
14718                 { 'a', REGCM_GPR32, REG_EAX },
14719                 { 'b', REGCM_GPR32, REG_EBX },
14720                 { 'c', REGCM_GPR32, REG_ECX },
14721                 { 'd', REGCM_GPR32, REG_EDX },
14722                 { 'D', REGCM_GPR32, REG_EDI },
14723                 { 'S', REGCM_GPR32, REG_ESI },
14724                 { '\0', 0, REG_UNSET },
14725         };
14726         unsigned int regcm;
14727         unsigned int mask, reg;
14728         struct reg_info result;
14729         const char *ptr;
14730         regcm = arch_type_to_regcm(state, type);
14731         reg = REG_UNSET;
14732         mask = 0;
14733         for(ptr = constraint; *ptr; ptr++) {
14734                 int i;
14735                 if (*ptr ==  ' ') {
14736                         continue;
14737                 }
14738                 for(i = 0; constraints[i].class != '\0'; i++) {
14739                         if (constraints[i].class == *ptr) {
14740                                 break;
14741                         }
14742                 }
14743                 if (constraints[i].class == '\0') {
14744                         error(state, 0, "invalid register constraint ``%c''", *ptr);
14745                         break;
14746                 }
14747                 if ((constraints[i].mask & regcm) == 0) {
14748                         error(state, 0, "invalid register class %c specified",
14749                                 *ptr);
14750                 }
14751                 mask |= constraints[i].mask;
14752                 if (constraints[i].reg != REG_UNSET) {
14753                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14754                                 error(state, 0, "Only one register may be specified");
14755                         }
14756                         reg = constraints[i].reg;
14757                 }
14758         }
14759         result.reg = reg;
14760         result.regcm = mask;
14761         return result;
14762 }
14763
14764 static struct reg_info arch_reg_clobber(
14765         struct compile_state *state, const char *clobber)
14766 {
14767         struct reg_info result;
14768         if (strcmp(clobber, "memory") == 0) {
14769                 result.reg = REG_UNSET;
14770                 result.regcm = 0;
14771         }
14772         else if (strcmp(clobber, "%eax") == 0) {
14773                 result.reg = REG_EAX;
14774                 result.regcm = REGCM_GPR32;
14775         }
14776         else if (strcmp(clobber, "%ebx") == 0) {
14777                 result.reg = REG_EBX;
14778                 result.regcm = REGCM_GPR32;
14779         }
14780         else if (strcmp(clobber, "%ecx") == 0) {
14781                 result.reg = REG_ECX;
14782                 result.regcm = REGCM_GPR32;
14783         }
14784         else if (strcmp(clobber, "%edx") == 0) {
14785                 result.reg = REG_EDX;
14786                 result.regcm = REGCM_GPR32;
14787         }
14788         else if (strcmp(clobber, "%esi") == 0) {
14789                 result.reg = REG_ESI;
14790                 result.regcm = REGCM_GPR32;
14791         }
14792         else if (strcmp(clobber, "%edi") == 0) {
14793                 result.reg = REG_EDI;
14794                 result.regcm = REGCM_GPR32;
14795         }
14796         else if (strcmp(clobber, "%ebp") == 0) {
14797                 result.reg = REG_EBP;
14798                 result.regcm = REGCM_GPR32;
14799         }
14800         else if (strcmp(clobber, "%esp") == 0) {
14801                 result.reg = REG_ESP;
14802                 result.regcm = REGCM_GPR32;
14803         }
14804         else if (strcmp(clobber, "cc") == 0) {
14805                 result.reg = REG_EFLAGS;
14806                 result.regcm = REGCM_FLAGS;
14807         }
14808         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
14809                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14810                 result.reg = REG_XMM0 + octdigval(clobber[3]);
14811                 result.regcm = REGCM_XMM;
14812         }
14813         else if ((strncmp(clobber, "mmx", 3) == 0) &&
14814                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14815                 result.reg = REG_MMX0 + octdigval(clobber[3]);
14816                 result.regcm = REGCM_MMX;
14817         }
14818         else {
14819                 error(state, 0, "Invalid register clobber");
14820                 result.reg = REG_UNSET;
14821                 result.regcm = 0;
14822         }
14823         return result;
14824 }
14825
14826 static int do_select_reg(struct compile_state *state, 
14827         char *used, int reg, unsigned classes)
14828 {
14829         unsigned mask;
14830         if (used[reg]) {
14831                 return REG_UNSET;
14832         }
14833         mask = arch_reg_regcm(state, reg);
14834         return (classes & mask) ? reg : REG_UNSET;
14835 }
14836
14837 static int arch_select_free_register(
14838         struct compile_state *state, char *used, int classes)
14839 {
14840         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14841          * other types of registers.
14842          */
14843         int i, reg;
14844         reg = REG_UNSET;
14845         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14846                 reg = do_select_reg(state, used, i, classes);
14847         }
14848         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14849                 reg = do_select_reg(state, used, i, classes);
14850         }
14851         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14852                 reg = do_select_reg(state, used, i, classes);
14853         }
14854         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14855                 reg = do_select_reg(state, used, i, classes);
14856         }
14857         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14858                 reg = do_select_reg(state, used, i, classes);
14859         }
14860         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14861                 reg = do_select_reg(state, used, i, classes);
14862         }
14863         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14864                 reg = do_select_reg(state, used, i, classes);
14865         }
14866         return reg;
14867 }
14868
14869
14870 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
14871 {
14872 #warning "FIXME force types smaller (if legal) before I get here"
14873         unsigned avail_mask;
14874         unsigned mask;
14875         mask = 0;
14876         avail_mask = arch_avail_mask(state);
14877         switch(type->type & TYPE_MASK) {
14878         case TYPE_ARRAY:
14879         case TYPE_VOID: 
14880                 mask = 0; 
14881                 break;
14882         case TYPE_CHAR:
14883         case TYPE_UCHAR:
14884                 mask = REGCM_GPR8 | 
14885                         REGCM_GPR16 | REGCM_GPR16_8 | 
14886                         REGCM_GPR32 | REGCM_GPR32_8 |
14887                         REGCM_GPR64 |
14888                         REGCM_MMX | REGCM_XMM |
14889                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14890                 break;
14891         case TYPE_SHORT:
14892         case TYPE_USHORT:
14893                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
14894                         REGCM_GPR32 | REGCM_GPR32_8 |
14895                         REGCM_GPR64 |
14896                         REGCM_MMX | REGCM_XMM |
14897                         REGCM_IMM32 | REGCM_IMM16;
14898                 break;
14899         case TYPE_INT:
14900         case TYPE_UINT:
14901         case TYPE_LONG:
14902         case TYPE_ULONG:
14903         case TYPE_POINTER:
14904                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
14905                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
14906                         REGCM_IMM32;
14907                 break;
14908         default:
14909                 internal_error(state, 0, "no register class for type");
14910                 break;
14911         }
14912         mask &= avail_mask;
14913         return mask;
14914 }
14915
14916 static int is_imm32(struct triple *imm)
14917 {
14918         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
14919                 (imm->op == OP_ADDRCONST);
14920         
14921 }
14922 static int is_imm16(struct triple *imm)
14923 {
14924         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
14925 }
14926 static int is_imm8(struct triple *imm)
14927 {
14928         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
14929 }
14930
14931 static int get_imm32(struct triple *ins, struct triple **expr)
14932 {
14933         struct triple *imm;
14934         imm = *expr;
14935         while(imm->op == OP_COPY) {
14936                 imm = RHS(imm, 0);
14937         }
14938         if (!is_imm32(imm)) {
14939                 return 0;
14940         }
14941         unuse_triple(*expr, ins);
14942         use_triple(imm, ins);
14943         *expr = imm;
14944         return 1;
14945 }
14946
14947 static int get_imm8(struct triple *ins, struct triple **expr)
14948 {
14949         struct triple *imm;
14950         imm = *expr;
14951         while(imm->op == OP_COPY) {
14952                 imm = RHS(imm, 0);
14953         }
14954         if (!is_imm8(imm)) {
14955                 return 0;
14956         }
14957         unuse_triple(*expr, ins);
14958         use_triple(imm, ins);
14959         *expr = imm;
14960         return 1;
14961 }
14962
14963 #define TEMPLATE_NOP         0
14964 #define TEMPLATE_INTCONST8   1
14965 #define TEMPLATE_INTCONST32  2
14966 #define TEMPLATE_COPY_REG    3
14967 #define TEMPLATE_COPY_IMM32  4
14968 #define TEMPLATE_COPY_IMM16  5
14969 #define TEMPLATE_COPY_IMM8   6
14970 #define TEMPLATE_PHI         7
14971 #define TEMPLATE_STORE8      8
14972 #define TEMPLATE_STORE16     9
14973 #define TEMPLATE_STORE32    10
14974 #define TEMPLATE_LOAD8      11
14975 #define TEMPLATE_LOAD16     12
14976 #define TEMPLATE_LOAD32     13
14977 #define TEMPLATE_BINARY_REG 14
14978 #define TEMPLATE_BINARY_IMM 15
14979 #define TEMPLATE_SL_CL      16
14980 #define TEMPLATE_SL_IMM     17
14981 #define TEMPLATE_UNARY      18
14982 #define TEMPLATE_CMP_REG    19
14983 #define TEMPLATE_CMP_IMM    20
14984 #define TEMPLATE_TEST       21
14985 #define TEMPLATE_SET        22
14986 #define TEMPLATE_JMP        23
14987 #define TEMPLATE_INB_DX     24
14988 #define TEMPLATE_INB_IMM    25
14989 #define TEMPLATE_INW_DX     26
14990 #define TEMPLATE_INW_IMM    27
14991 #define TEMPLATE_INL_DX     28
14992 #define TEMPLATE_INL_IMM    29
14993 #define TEMPLATE_OUTB_DX    30
14994 #define TEMPLATE_OUTB_IMM   31
14995 #define TEMPLATE_OUTW_DX    32
14996 #define TEMPLATE_OUTW_IMM   33
14997 #define TEMPLATE_OUTL_DX    34
14998 #define TEMPLATE_OUTL_IMM   35
14999 #define TEMPLATE_BSF        36
15000 #define TEMPLATE_RDMSR      37
15001 #define TEMPLATE_WRMSR      38
15002 #define LAST_TEMPLATE       TEMPLATE_WRMSR
15003 #if LAST_TEMPLATE >= MAX_TEMPLATES
15004 #error "MAX_TEMPLATES to low"
15005 #endif
15006
15007 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15008 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15009
15010 static struct ins_template templates[] = {
15011         [TEMPLATE_NOP]      = {},
15012         [TEMPLATE_INTCONST8] = { 
15013                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15014         },
15015         [TEMPLATE_INTCONST32] = { 
15016                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15017         },
15018         [TEMPLATE_COPY_REG] = {
15019                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15020                 .rhs = { [0] = { REG_UNSET, COPY_REGCM }  },
15021         },
15022         [TEMPLATE_COPY_IMM32] = {
15023                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15024                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15025         },
15026         [TEMPLATE_COPY_IMM16] = {
15027                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15028                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15029         },
15030         [TEMPLATE_COPY_IMM8] = {
15031                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15032                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15033         },
15034         [TEMPLATE_PHI] = { 
15035                 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15036                 .rhs = { 
15037                         [ 0] = { REG_VIRT0, COPY_REGCM },
15038                         [ 1] = { REG_VIRT0, COPY_REGCM },
15039                         [ 2] = { REG_VIRT0, COPY_REGCM },
15040                         [ 3] = { REG_VIRT0, COPY_REGCM },
15041                         [ 4] = { REG_VIRT0, COPY_REGCM },
15042                         [ 5] = { REG_VIRT0, COPY_REGCM },
15043                         [ 6] = { REG_VIRT0, COPY_REGCM },
15044                         [ 7] = { REG_VIRT0, COPY_REGCM },
15045                         [ 8] = { REG_VIRT0, COPY_REGCM },
15046                         [ 9] = { REG_VIRT0, COPY_REGCM },
15047                         [10] = { REG_VIRT0, COPY_REGCM },
15048                         [11] = { REG_VIRT0, COPY_REGCM },
15049                         [12] = { REG_VIRT0, COPY_REGCM },
15050                         [13] = { REG_VIRT0, COPY_REGCM },
15051                         [14] = { REG_VIRT0, COPY_REGCM },
15052                         [15] = { REG_VIRT0, COPY_REGCM },
15053                 }, },
15054         [TEMPLATE_STORE8] = {
15055                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15056                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15057         },
15058         [TEMPLATE_STORE16] = {
15059                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15060                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15061         },
15062         [TEMPLATE_STORE32] = {
15063                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15064                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15065         },
15066         [TEMPLATE_LOAD8] = {
15067                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15068                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15069         },
15070         [TEMPLATE_LOAD16] = {
15071                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15072                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15073         },
15074         [TEMPLATE_LOAD32] = {
15075                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15076                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15077         },
15078         [TEMPLATE_BINARY_REG] = {
15079                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15080                 .rhs = { 
15081                         [0] = { REG_VIRT0, REGCM_GPR32 },
15082                         [1] = { REG_UNSET, REGCM_GPR32 },
15083                 },
15084         },
15085         [TEMPLATE_BINARY_IMM] = {
15086                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15087                 .rhs = { 
15088                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15089                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15090                 },
15091         },
15092         [TEMPLATE_SL_CL] = {
15093                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15094                 .rhs = { 
15095                         [0] = { REG_VIRT0, REGCM_GPR32 },
15096                         [1] = { REG_CL, REGCM_GPR8 },
15097                 },
15098         },
15099         [TEMPLATE_SL_IMM] = {
15100                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15101                 .rhs = { 
15102                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15103                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15104                 },
15105         },
15106         [TEMPLATE_UNARY] = {
15107                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15108                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15109         },
15110         [TEMPLATE_CMP_REG] = {
15111                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15112                 .rhs = {
15113                         [0] = { REG_UNSET, REGCM_GPR32 },
15114                         [1] = { REG_UNSET, REGCM_GPR32 },
15115                 },
15116         },
15117         [TEMPLATE_CMP_IMM] = {
15118                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15119                 .rhs = {
15120                         [0] = { REG_UNSET, REGCM_GPR32 },
15121                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15122                 },
15123         },
15124         [TEMPLATE_TEST] = {
15125                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15126                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15127         },
15128         [TEMPLATE_SET] = {
15129                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15130                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15131         },
15132         [TEMPLATE_JMP] = {
15133                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15134         },
15135         [TEMPLATE_INB_DX] = {
15136                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15137                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15138         },
15139         [TEMPLATE_INB_IMM] = {
15140                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15141                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15142         },
15143         [TEMPLATE_INW_DX]  = { 
15144                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15145                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15146         },
15147         [TEMPLATE_INW_IMM] = { 
15148                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15149                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15150         },
15151         [TEMPLATE_INL_DX]  = {
15152                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15153                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15154         },
15155         [TEMPLATE_INL_IMM] = {
15156                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15157                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15158         },
15159         [TEMPLATE_OUTB_DX] = { 
15160                 .rhs = {
15161                         [0] = { REG_AL,  REGCM_GPR8 },
15162                         [1] = { REG_DX, REGCM_GPR16 },
15163                 },
15164         },
15165         [TEMPLATE_OUTB_IMM] = { 
15166                 .rhs = {
15167                         [0] = { REG_AL,  REGCM_GPR8 },  
15168                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15169                 },
15170         },
15171         [TEMPLATE_OUTW_DX] = { 
15172                 .rhs = {
15173                         [0] = { REG_AX,  REGCM_GPR16 },
15174                         [1] = { REG_DX, REGCM_GPR16 },
15175                 },
15176         },
15177         [TEMPLATE_OUTW_IMM] = {
15178                 .rhs = {
15179                         [0] = { REG_AX,  REGCM_GPR16 }, 
15180                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15181                 },
15182         },
15183         [TEMPLATE_OUTL_DX] = { 
15184                 .rhs = {
15185                         [0] = { REG_EAX, REGCM_GPR32 },
15186                         [1] = { REG_DX, REGCM_GPR16 },
15187                 },
15188         },
15189         [TEMPLATE_OUTL_IMM] = { 
15190                 .rhs = {
15191                         [0] = { REG_EAX, REGCM_GPR32 }, 
15192                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15193                 },
15194         },
15195         [TEMPLATE_BSF] = {
15196                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15197                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15198         },
15199         [TEMPLATE_RDMSR] = {
15200                 .lhs = { 
15201                         [0] = { REG_EAX, REGCM_GPR32 },
15202                         [1] = { REG_EDX, REGCM_GPR32 },
15203                 },
15204                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15205         },
15206         [TEMPLATE_WRMSR] = {
15207                 .rhs = {
15208                         [0] = { REG_ECX, REGCM_GPR32 },
15209                         [1] = { REG_EAX, REGCM_GPR32 },
15210                         [2] = { REG_EDX, REGCM_GPR32 },
15211                 },
15212         },
15213 };
15214
15215 static void fixup_branches(struct compile_state *state,
15216         struct triple *cmp, struct triple *use, int jmp_op)
15217 {
15218         struct triple_set *entry, *next;
15219         for(entry = use->use; entry; entry = next) {
15220                 next = entry->next;
15221                 if (entry->member->op == OP_COPY) {
15222                         fixup_branches(state, cmp, entry->member, jmp_op);
15223                 }
15224                 else if (entry->member->op == OP_BRANCH) {
15225                         struct triple *branch, *test;
15226                         struct triple *left, *right;
15227                         left = right = 0;
15228                         left = RHS(cmp, 0);
15229                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15230                                 right = RHS(cmp, 1);
15231                         }
15232                         branch = entry->member;
15233                         test = pre_triple(state, branch,
15234                                 cmp->op, cmp->type, left, right);
15235                         test->template_id = TEMPLATE_TEST; 
15236                         if (cmp->op == OP_CMP) {
15237                                 test->template_id = TEMPLATE_CMP_REG;
15238                                 if (get_imm32(test, &RHS(test, 1))) {
15239                                         test->template_id = TEMPLATE_CMP_IMM;
15240                                 }
15241                         }
15242                         use_triple(RHS(test, 0), test);
15243                         use_triple(RHS(test, 1), test);
15244                         unuse_triple(RHS(branch, 0), branch);
15245                         RHS(branch, 0) = test;
15246                         branch->op = jmp_op;
15247                         branch->template_id = TEMPLATE_JMP;
15248                         use_triple(RHS(branch, 0), branch);
15249                 }
15250         }
15251 }
15252
15253 static void bool_cmp(struct compile_state *state, 
15254         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15255 {
15256         struct triple_set *entry, *next;
15257         struct triple *set;
15258
15259         /* Put a barrier up before the cmp which preceeds the
15260          * copy instruction.  If a set actually occurs this gives
15261          * us a chance to move variables in registers out of the way.
15262          */
15263
15264         /* Modify the comparison operator */
15265         ins->op = cmp_op;
15266         ins->template_id = TEMPLATE_TEST;
15267         if (cmp_op == OP_CMP) {
15268                 ins->template_id = TEMPLATE_CMP_REG;
15269                 if (get_imm32(ins, &RHS(ins, 1))) {
15270                         ins->template_id =  TEMPLATE_CMP_IMM;
15271                 }
15272         }
15273         /* Generate the instruction sequence that will transform the
15274          * result of the comparison into a logical value.
15275          */
15276         set = post_triple(state, ins, set_op, ins->type, ins, 0);
15277         use_triple(ins, set);
15278         set->template_id = TEMPLATE_SET;
15279
15280         for(entry = ins->use; entry; entry = next) {
15281                 next = entry->next;
15282                 if (entry->member == set) {
15283                         continue;
15284                 }
15285                 replace_rhs_use(state, ins, set, entry->member);
15286         }
15287         fixup_branches(state, ins, set, jmp_op);
15288 }
15289
15290 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15291 {
15292         struct triple *next;
15293         int lhs, i;
15294         lhs = TRIPLE_LHS(ins->sizes);
15295         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15296                 if (next != LHS(ins, i)) {
15297                         internal_error(state, ins, "malformed lhs on %s",
15298                                 tops(ins->op));
15299                 }
15300                 if (next->op != OP_PIECE) {
15301                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15302                                 tops(next->op), i, tops(ins->op));
15303                 }
15304                 if (next->u.cval != i) {
15305                         internal_error(state, ins, "bad u.cval of %d %d expected",
15306                                 next->u.cval, i);
15307                 }
15308         }
15309         return next;
15310 }
15311
15312 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15313 {
15314         struct ins_template *template;
15315         struct reg_info result;
15316         int zlhs;
15317         if (ins->op == OP_PIECE) {
15318                 index = ins->u.cval;
15319                 ins = MISC(ins, 0);
15320         }
15321         zlhs = TRIPLE_LHS(ins->sizes);
15322         if (triple_is_def(state, ins)) {
15323                 zlhs = 1;
15324         }
15325         if (index >= zlhs) {
15326                 internal_error(state, ins, "index %d out of range for %s\n",
15327                         index, tops(ins->op));
15328         }
15329         switch(ins->op) {
15330         case OP_ASM:
15331                 template = &ins->u.ainfo->tmpl;
15332                 break;
15333         default:
15334                 if (ins->template_id > LAST_TEMPLATE) {
15335                         internal_error(state, ins, "bad template number %d", 
15336                                 ins->template_id);
15337                 }
15338                 template = &templates[ins->template_id];
15339                 break;
15340         }
15341         result = template->lhs[index];
15342         result.regcm = arch_regcm_normalize(state, result.regcm);
15343         if (result.reg != REG_UNNEEDED) {
15344                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15345         }
15346         if (result.regcm == 0) {
15347                 internal_error(state, ins, "lhs %d regcm == 0", index);
15348         }
15349         return result;
15350 }
15351
15352 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15353 {
15354         struct reg_info result;
15355         struct ins_template *template;
15356         if ((index > TRIPLE_RHS(ins->sizes)) ||
15357                 (ins->op == OP_PIECE)) {
15358                 internal_error(state, ins, "index %d out of range for %s\n",
15359                         index, tops(ins->op));
15360         }
15361         switch(ins->op) {
15362         case OP_ASM:
15363                 template = &ins->u.ainfo->tmpl;
15364                 break;
15365         default:
15366                 if (ins->template_id > LAST_TEMPLATE) {
15367                         internal_error(state, ins, "bad template number %d", 
15368                                 ins->template_id);
15369                 }
15370                 template = &templates[ins->template_id];
15371                 break;
15372         }
15373         result = template->rhs[index];
15374         result.regcm = arch_regcm_normalize(state, result.regcm);
15375         if (result.regcm == 0) {
15376                 internal_error(state, ins, "rhs %d regcm == 0", index);
15377         }
15378         return result;
15379 }
15380
15381 static struct triple *transform_to_arch_instruction(
15382         struct compile_state *state, struct triple *ins)
15383 {
15384         /* Transform from generic 3 address instructions
15385          * to archtecture specific instructions.
15386          * And apply architecture specific constrains to instructions.
15387          * Copies are inserted to preserve the register flexibility
15388          * of 3 address instructions.
15389          */
15390         struct triple *next;
15391         next = ins->next;
15392         switch(ins->op) {
15393         case OP_INTCONST:
15394                 ins->template_id = TEMPLATE_INTCONST32;
15395                 if (ins->u.cval < 256) {
15396                         ins->template_id = TEMPLATE_INTCONST8;
15397                 }
15398                 break;
15399         case OP_ADDRCONST:
15400                 ins->template_id = TEMPLATE_INTCONST32;
15401                 break;
15402         case OP_NOOP:
15403         case OP_SDECL:
15404         case OP_BLOBCONST:
15405         case OP_LABEL:
15406                 ins->template_id = TEMPLATE_NOP;
15407                 break;
15408         case OP_COPY:
15409                 ins->template_id = TEMPLATE_COPY_REG;
15410                 if (is_imm8(RHS(ins, 0))) {
15411                         ins->template_id = TEMPLATE_COPY_IMM8;
15412                 }
15413                 else if (is_imm16(RHS(ins, 0))) {
15414                         ins->template_id = TEMPLATE_COPY_IMM16;
15415                 }
15416                 else if (is_imm32(RHS(ins, 0))) {
15417                         ins->template_id = TEMPLATE_COPY_IMM32;
15418                 }
15419                 else if (is_const(RHS(ins, 0))) {
15420                         internal_error(state, ins, "bad constant passed to copy");
15421                 }
15422                 break;
15423         case OP_PHI:
15424                 ins->template_id = TEMPLATE_PHI;
15425                 break;
15426         case OP_STORE:
15427                 switch(ins->type->type & TYPE_MASK) {
15428                 case TYPE_CHAR:    case TYPE_UCHAR:
15429                         ins->template_id = TEMPLATE_STORE8;
15430                         break;
15431                 case TYPE_SHORT:   case TYPE_USHORT:
15432                         ins->template_id = TEMPLATE_STORE16;
15433                         break;
15434                 case TYPE_INT:     case TYPE_UINT:
15435                 case TYPE_LONG:    case TYPE_ULONG:
15436                 case TYPE_POINTER:
15437                         ins->template_id = TEMPLATE_STORE32;
15438                         break;
15439                 default:
15440                         internal_error(state, ins, "unknown type in store");
15441                         break;
15442                 }
15443                 break;
15444         case OP_LOAD:
15445                 switch(ins->type->type & TYPE_MASK) {
15446                 case TYPE_CHAR:   case TYPE_UCHAR:
15447                         ins->template_id = TEMPLATE_LOAD8;
15448                         break;
15449                 case TYPE_SHORT:
15450                 case TYPE_USHORT:
15451                         ins->template_id = TEMPLATE_LOAD16;
15452                         break;
15453                 case TYPE_INT:
15454                 case TYPE_UINT:
15455                 case TYPE_LONG:
15456                 case TYPE_ULONG:
15457                 case TYPE_POINTER:
15458                         ins->template_id = TEMPLATE_LOAD32;
15459                         break;
15460                 default:
15461                         internal_error(state, ins, "unknown type in load");
15462                         break;
15463                 }
15464                 break;
15465         case OP_ADD:
15466         case OP_SUB:
15467         case OP_AND:
15468         case OP_XOR:
15469         case OP_OR:
15470         case OP_SMUL:
15471                 ins->template_id = TEMPLATE_BINARY_REG;
15472                 if (get_imm32(ins, &RHS(ins, 1))) {
15473                         ins->template_id = TEMPLATE_BINARY_IMM;
15474                 }
15475                 break;
15476         case OP_SL:
15477         case OP_SSR:
15478         case OP_USR:
15479                 ins->template_id = TEMPLATE_SL_CL;
15480                 if (get_imm8(ins, &RHS(ins, 1))) {
15481                         ins->template_id = TEMPLATE_SL_IMM;
15482                 }
15483                 break;
15484         case OP_INVERT:
15485         case OP_NEG:
15486                 ins->template_id = TEMPLATE_UNARY;
15487                 break;
15488         case OP_EQ: 
15489                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
15490                 break;
15491         case OP_NOTEQ:
15492                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15493                 break;
15494         case OP_SLESS:
15495                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15496                 break;
15497         case OP_ULESS:
15498                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15499                 break;
15500         case OP_SMORE:
15501                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15502                 break;
15503         case OP_UMORE:
15504                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15505                 break;
15506         case OP_SLESSEQ:
15507                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15508                 break;
15509         case OP_ULESSEQ:
15510                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15511                 break;
15512         case OP_SMOREEQ:
15513                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15514                 break;
15515         case OP_UMOREEQ:
15516                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15517                 break;
15518         case OP_LTRUE:
15519                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15520                 break;
15521         case OP_LFALSE:
15522                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15523                 break;
15524         case OP_BRANCH:
15525                 if (TRIPLE_RHS(ins->sizes) > 0) {
15526                         internal_error(state, ins, "bad branch test");
15527                 }
15528                 ins->op = OP_JMP;
15529                 ins->template_id = TEMPLATE_NOP;
15530                 break;
15531         case OP_INB:
15532         case OP_INW:
15533         case OP_INL:
15534                 switch(ins->op) {
15535                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15536                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15537                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15538                 }
15539                 if (get_imm8(ins, &RHS(ins, 0))) {
15540                         ins->template_id += 1;
15541                 }
15542                 break;
15543         case OP_OUTB:
15544         case OP_OUTW:
15545         case OP_OUTL:
15546                 switch(ins->op) {
15547                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15548                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15549                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15550                 }
15551                 if (get_imm8(ins, &RHS(ins, 1))) {
15552                         ins->template_id += 1;
15553                 }
15554                 break;
15555         case OP_BSF:
15556         case OP_BSR:
15557                 ins->template_id = TEMPLATE_BSF;
15558                 break;
15559         case OP_RDMSR:
15560                 ins->template_id = TEMPLATE_RDMSR;
15561                 next = after_lhs(state, ins);
15562                 break;
15563         case OP_WRMSR:
15564                 ins->template_id = TEMPLATE_WRMSR;
15565                 break;
15566         case OP_HLT:
15567                 ins->template_id = TEMPLATE_NOP;
15568                 break;
15569         case OP_ASM:
15570                 ins->template_id = TEMPLATE_NOP;
15571                 next = after_lhs(state, ins);
15572                 break;
15573                 /* Already transformed instructions */
15574         case OP_TEST:
15575                 ins->template_id = TEMPLATE_TEST;
15576                 break;
15577         case OP_CMP:
15578                 ins->template_id = TEMPLATE_CMP_REG;
15579                 if (get_imm32(ins, &RHS(ins, 1))) {
15580                         ins->template_id = TEMPLATE_CMP_IMM;
15581                 }
15582                 break;
15583         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
15584         case OP_JMP_SLESS:   case OP_JMP_ULESS:
15585         case OP_JMP_SMORE:   case OP_JMP_UMORE:
15586         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15587         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15588                 ins->template_id = TEMPLATE_JMP;
15589                 break;
15590         case OP_SET_EQ:      case OP_SET_NOTEQ:
15591         case OP_SET_SLESS:   case OP_SET_ULESS:
15592         case OP_SET_SMORE:   case OP_SET_UMORE:
15593         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15594         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15595                 ins->template_id = TEMPLATE_SET;
15596                 break;
15597                 /* Unhandled instructions */
15598         case OP_PIECE:
15599         default:
15600                 internal_error(state, ins, "unhandled ins: %d %s\n",
15601                         ins->op, tops(ins->op));
15602                 break;
15603         }
15604         return next;
15605 }
15606
15607 static void generate_local_labels(struct compile_state *state)
15608 {
15609         struct triple *first, *label;
15610         int label_counter;
15611         label_counter = 0;
15612         first = RHS(state->main_function, 0);
15613         label = first;
15614         do {
15615                 if ((label->op == OP_LABEL) || 
15616                         (label->op == OP_SDECL)) {
15617                         if (label->use) {
15618                                 label->u.cval = ++label_counter;
15619                         } else {
15620                                 label->u.cval = 0;
15621                         }
15622                         
15623                 }
15624                 label = label->next;
15625         } while(label != first);
15626 }
15627
15628 static int check_reg(struct compile_state *state, 
15629         struct triple *triple, int classes)
15630 {
15631         unsigned mask;
15632         int reg;
15633         reg = ID_REG(triple->id);
15634         if (reg == REG_UNSET) {
15635                 internal_error(state, triple, "register not set");
15636         }
15637         mask = arch_reg_regcm(state, reg);
15638         if (!(classes & mask)) {
15639                 internal_error(state, triple, "reg %d in wrong class",
15640                         reg);
15641         }
15642         return reg;
15643 }
15644
15645 static const char *arch_reg_str(int reg)
15646 {
15647         static const char *regs[] = {
15648                 "%bad_register",
15649                 "%bad_register2",
15650                 "%eflags",
15651                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15652                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15653                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15654                 "%edx:%eax",
15655                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15656                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
15657                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15658         };
15659         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15660                 reg = 0;
15661         }
15662         return regs[reg];
15663 }
15664
15665
15666 static const char *reg(struct compile_state *state, struct triple *triple,
15667         int classes)
15668 {
15669         int reg;
15670         reg = check_reg(state, triple, classes);
15671         return arch_reg_str(reg);
15672 }
15673
15674 const char *type_suffix(struct compile_state *state, struct type *type)
15675 {
15676         const char *suffix;
15677         switch(size_of(state, type)) {
15678         case 1: suffix = "b"; break;
15679         case 2: suffix = "w"; break;
15680         case 4: suffix = "l"; break;
15681         default:
15682                 internal_error(state, 0, "unknown suffix");
15683                 suffix = 0;
15684                 break;
15685         }
15686         return suffix;
15687 }
15688
15689 static void print_const_val(
15690         struct compile_state *state, struct triple *ins, FILE *fp)
15691 {
15692         switch(ins->op) {
15693         case OP_INTCONST:
15694                 fprintf(fp, " $%ld ", 
15695                         (long_t)(ins->u.cval));
15696                 break;
15697         case OP_ADDRCONST:
15698                 fprintf(fp, " $L%s%lu+%lu ",
15699                         state->label_prefix, 
15700                         MISC(ins, 0)->u.cval,
15701                         ins->u.cval);
15702                 break;
15703         default:
15704                 internal_error(state, ins, "unknown constant type");
15705                 break;
15706         }
15707 }
15708
15709 static void print_binary_op(struct compile_state *state,
15710         const char *op, struct triple *ins, FILE *fp) 
15711 {
15712         unsigned mask;
15713         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15714         if (RHS(ins, 0)->id != ins->id) {
15715                 internal_error(state, ins, "invalid register assignment");
15716         }
15717         if (is_const(RHS(ins, 1))) {
15718                 fprintf(fp, "\t%s ", op);
15719                 print_const_val(state, RHS(ins, 1), fp);
15720                 fprintf(fp, ", %s\n",
15721                         reg(state, RHS(ins, 0), mask));
15722         }
15723         else {
15724                 unsigned lmask, rmask;
15725                 int lreg, rreg;
15726                 lreg = check_reg(state, RHS(ins, 0), mask);
15727                 rreg = check_reg(state, RHS(ins, 1), mask);
15728                 lmask = arch_reg_regcm(state, lreg);
15729                 rmask = arch_reg_regcm(state, rreg);
15730                 mask = lmask & rmask;
15731                 fprintf(fp, "\t%s %s, %s\n",
15732                         op,
15733                         reg(state, RHS(ins, 1), mask),
15734                         reg(state, RHS(ins, 0), mask));
15735         }
15736 }
15737 static void print_unary_op(struct compile_state *state, 
15738         const char *op, struct triple *ins, FILE *fp)
15739 {
15740         unsigned mask;
15741         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15742         fprintf(fp, "\t%s %s\n",
15743                 op,
15744                 reg(state, RHS(ins, 0), mask));
15745 }
15746
15747 static void print_op_shift(struct compile_state *state,
15748         const char *op, struct triple *ins, FILE *fp)
15749 {
15750         unsigned mask;
15751         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15752         if (RHS(ins, 0)->id != ins->id) {
15753                 internal_error(state, ins, "invalid register assignment");
15754         }
15755         if (is_const(RHS(ins, 1))) {
15756                 fprintf(fp, "\t%s ", op);
15757                 print_const_val(state, RHS(ins, 1), fp);
15758                 fprintf(fp, ", %s\n",
15759                         reg(state, RHS(ins, 0), mask));
15760         }
15761         else {
15762                 fprintf(fp, "\t%s %s, %s\n",
15763                         op,
15764                         reg(state, RHS(ins, 1), REGCM_GPR8),
15765                         reg(state, RHS(ins, 0), mask));
15766         }
15767 }
15768
15769 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15770 {
15771         const char *op;
15772         int mask;
15773         int dreg;
15774         mask = 0;
15775         switch(ins->op) {
15776         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15777         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15778         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15779         default:
15780                 internal_error(state, ins, "not an in operation");
15781                 op = 0;
15782                 break;
15783         }
15784         dreg = check_reg(state, ins, mask);
15785         if (!reg_is_reg(state, dreg, REG_EAX)) {
15786                 internal_error(state, ins, "dst != %%eax");
15787         }
15788         if (is_const(RHS(ins, 0))) {
15789                 fprintf(fp, "\t%s ", op);
15790                 print_const_val(state, RHS(ins, 0), fp);
15791                 fprintf(fp, ", %s\n",
15792                         reg(state, ins, mask));
15793         }
15794         else {
15795                 int addr_reg;
15796                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15797                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15798                         internal_error(state, ins, "src != %%dx");
15799                 }
15800                 fprintf(fp, "\t%s %s, %s\n",
15801                         op, 
15802                         reg(state, RHS(ins, 0), REGCM_GPR16),
15803                         reg(state, ins, mask));
15804         }
15805 }
15806
15807 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15808 {
15809         const char *op;
15810         int mask;
15811         int lreg;
15812         mask = 0;
15813         switch(ins->op) {
15814         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15815         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15816         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15817         default:
15818                 internal_error(state, ins, "not an out operation");
15819                 op = 0;
15820                 break;
15821         }
15822         lreg = check_reg(state, RHS(ins, 0), mask);
15823         if (!reg_is_reg(state, lreg, REG_EAX)) {
15824                 internal_error(state, ins, "src != %%eax");
15825         }
15826         if (is_const(RHS(ins, 1))) {
15827                 fprintf(fp, "\t%s %s,", 
15828                         op, reg(state, RHS(ins, 0), mask));
15829                 print_const_val(state, RHS(ins, 1), fp);
15830                 fprintf(fp, "\n");
15831         }
15832         else {
15833                 int addr_reg;
15834                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15835                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15836                         internal_error(state, ins, "dst != %%dx");
15837                 }
15838                 fprintf(fp, "\t%s %s, %s\n",
15839                         op, 
15840                         reg(state, RHS(ins, 0), mask),
15841                         reg(state, RHS(ins, 1), REGCM_GPR16));
15842         }
15843 }
15844
15845 static void print_op_move(struct compile_state *state,
15846         struct triple *ins, FILE *fp)
15847 {
15848         /* op_move is complex because there are many types
15849          * of registers we can move between.
15850          * Because OP_COPY will be introduced in arbitrary locations
15851          * OP_COPY must not affect flags.
15852          */
15853         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15854         struct triple *dst, *src;
15855         if (ins->op == OP_COPY) {
15856                 src = RHS(ins, 0);
15857                 dst = ins;
15858         }
15859         else if (ins->op == OP_WRITE) {
15860                 dst = LHS(ins, 0);
15861                 src = RHS(ins, 0);
15862         }
15863         else {
15864                 internal_error(state, ins, "unknown move operation");
15865                 src = dst = 0;
15866         }
15867         if (!is_const(src)) {
15868                 int src_reg, dst_reg;
15869                 int src_regcm, dst_regcm;
15870                 src_reg = ID_REG(src->id);
15871                 dst_reg   = ID_REG(dst->id);
15872                 src_regcm = arch_reg_regcm(state, src_reg);
15873                 dst_regcm   = arch_reg_regcm(state, dst_reg);
15874                 /* If the class is the same just move the register */
15875                 if (src_regcm & dst_regcm & 
15876                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15877                         if ((src_reg != dst_reg) || !omit_copy) {
15878                                 fprintf(fp, "\tmov %s, %s\n",
15879                                         reg(state, src, src_regcm),
15880                                         reg(state, dst, dst_regcm));
15881                         }
15882                 }
15883                 /* Move 32bit to 16bit */
15884                 else if ((src_regcm & REGCM_GPR32) &&
15885                         (dst_regcm & REGCM_GPR16)) {
15886                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15887                         if ((src_reg != dst_reg) || !omit_copy) {
15888                                 fprintf(fp, "\tmovw %s, %s\n",
15889                                         arch_reg_str(src_reg), 
15890                                         arch_reg_str(dst_reg));
15891                         }
15892                 }
15893                 /* Move 32bit to 8bit */
15894                 else if ((src_regcm & REGCM_GPR32_8) &&
15895                         (dst_regcm & REGCM_GPR8))
15896                 {
15897                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15898                         if ((src_reg != dst_reg) || !omit_copy) {
15899                                 fprintf(fp, "\tmovb %s, %s\n",
15900                                         arch_reg_str(src_reg),
15901                                         arch_reg_str(dst_reg));
15902                         }
15903                 }
15904                 /* Move 16bit to 8bit */
15905                 else if ((src_regcm & REGCM_GPR16_8) &&
15906                         (dst_regcm & REGCM_GPR8))
15907                 {
15908                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
15909                         if ((src_reg != dst_reg) || !omit_copy) {
15910                                 fprintf(fp, "\tmovb %s, %s\n",
15911                                         arch_reg_str(src_reg),
15912                                         arch_reg_str(dst_reg));
15913                         }
15914                 }
15915                 /* Move 8/16bit to 16/32bit */
15916                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
15917                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
15918                         const char *op;
15919                         op = is_signed(src->type)? "movsx": "movzx";
15920                         fprintf(fp, "\t%s %s, %s\n",
15921                                 op,
15922                                 reg(state, src, src_regcm),
15923                                 reg(state, dst, dst_regcm));
15924                 }
15925                 /* Move between sse registers */
15926                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
15927                         if ((src_reg != dst_reg) || !omit_copy) {
15928                                 fprintf(fp, "\tmovdqa %s, %s\n",
15929                                         reg(state, src, src_regcm),
15930                                         reg(state, dst, dst_regcm));
15931                         }
15932                 }
15933                 /* Move between mmx registers or mmx & sse  registers */
15934                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15935                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15936                         if ((src_reg != dst_reg) || !omit_copy) {
15937                                 fprintf(fp, "\tmovq %s, %s\n",
15938                                         reg(state, src, src_regcm),
15939                                         reg(state, dst, dst_regcm));
15940                         }
15941                 }
15942                 /* Move between 32bit gprs & mmx/sse registers */
15943                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
15944                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
15945                         fprintf(fp, "\tmovd %s, %s\n",
15946                                 reg(state, src, src_regcm),
15947                                 reg(state, dst, dst_regcm));
15948                 }
15949 #if X86_4_8BIT_GPRS
15950                 /* Move from 8bit gprs to  mmx/sse registers */
15951                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
15952                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15953                         const char *op;
15954                         int mid_reg;
15955                         op = is_signed(src->type)? "movsx":"movzx";
15956                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15957                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
15958                                 op,
15959                                 reg(state, src, src_regcm),
15960                                 arch_reg_str(mid_reg),
15961                                 arch_reg_str(mid_reg),
15962                                 reg(state, dst, dst_regcm));
15963                 }
15964                 /* Move from mmx/sse registers and 8bit gprs */
15965                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15966                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
15967                         int mid_reg;
15968                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15969                         fprintf(fp, "\tmovd %s, %s\n",
15970                                 reg(state, src, src_regcm),
15971                                 arch_reg_str(mid_reg));
15972                 }
15973                 /* Move from 32bit gprs to 16bit gprs */
15974                 else if ((src_regcm & REGCM_GPR32) &&
15975                         (dst_regcm & REGCM_GPR16)) {
15976                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
15977                         if ((src_reg != dst_reg) || !omit_copy) {
15978                                 fprintf(fp, "\tmov %s, %s\n",
15979                                         arch_reg_str(src_reg),
15980                                         arch_reg_str(dst_reg));
15981                         }
15982                 }
15983                 /* Move from 32bit gprs to 8bit gprs */
15984                 else if ((src_regcm & REGCM_GPR32) &&
15985                         (dst_regcm & REGCM_GPR8)) {
15986                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15987                         if ((src_reg != dst_reg) || !omit_copy) {
15988                                 fprintf(fp, "\tmov %s, %s\n",
15989                                         arch_reg_str(src_reg),
15990                                         arch_reg_str(dst_reg));
15991                         }
15992                 }
15993                 /* Move from 16bit gprs to 8bit gprs */
15994                 else if ((src_regcm & REGCM_GPR16) &&
15995                         (dst_regcm & REGCM_GPR8)) {
15996                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
15997                         if ((src_reg != dst_reg) || !omit_copy) {
15998                                 fprintf(fp, "\tmov %s, %s\n",
15999                                         arch_reg_str(src_reg),
16000                                         arch_reg_str(dst_reg));
16001                         }
16002                 }
16003 #endif /* X86_4_8BIT_GPRS */
16004                 else {
16005                         internal_error(state, ins, "unknown copy type");
16006                 }
16007         }
16008         else {
16009                 fprintf(fp, "\tmov ");
16010                 print_const_val(state, src, fp);
16011                 fprintf(fp, ", %s\n",
16012                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16013         }
16014 }
16015
16016 static void print_op_load(struct compile_state *state,
16017         struct triple *ins, FILE *fp)
16018 {
16019         struct triple *dst, *src;
16020         dst = ins;
16021         src = RHS(ins, 0);
16022         if (is_const(src) || is_const(dst)) {
16023                 internal_error(state, ins, "unknown load operation");
16024         }
16025         fprintf(fp, "\tmov (%s), %s\n",
16026                 reg(state, src, REGCM_GPR32),
16027                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16028 }
16029
16030
16031 static void print_op_store(struct compile_state *state,
16032         struct triple *ins, FILE *fp)
16033 {
16034         struct triple *dst, *src;
16035         dst = LHS(ins, 0);
16036         src = RHS(ins, 0);
16037         if (is_const(src) && (src->op == OP_INTCONST)) {
16038                 long_t value;
16039                 value = (long_t)(src->u.cval);
16040                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16041                         type_suffix(state, src->type),
16042                         value,
16043                         reg(state, dst, REGCM_GPR32));
16044         }
16045         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16046                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16047                         type_suffix(state, src->type),
16048                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16049                         dst->u.cval);
16050         }
16051         else {
16052                 if (is_const(src) || is_const(dst)) {
16053                         internal_error(state, ins, "unknown store operation");
16054                 }
16055                 fprintf(fp, "\tmov%s %s, (%s)\n",
16056                         type_suffix(state, src->type),
16057                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16058                         reg(state, dst, REGCM_GPR32));
16059         }
16060         
16061         
16062 }
16063
16064 static void print_op_smul(struct compile_state *state,
16065         struct triple *ins, FILE *fp)
16066 {
16067         if (!is_const(RHS(ins, 1))) {
16068                 fprintf(fp, "\timul %s, %s\n",
16069                         reg(state, RHS(ins, 1), REGCM_GPR32),
16070                         reg(state, RHS(ins, 0), REGCM_GPR32));
16071         }
16072         else {
16073                 fprintf(fp, "\timul ");
16074                 print_const_val(state, RHS(ins, 1), fp);
16075                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16076         }
16077 }
16078
16079 static void print_op_cmp(struct compile_state *state,
16080         struct triple *ins, FILE *fp)
16081 {
16082         unsigned mask;
16083         int dreg;
16084         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16085         dreg = check_reg(state, ins, REGCM_FLAGS);
16086         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16087                 internal_error(state, ins, "bad dest register for cmp");
16088         }
16089         if (is_const(RHS(ins, 1))) {
16090                 fprintf(fp, "\tcmp ");
16091                 print_const_val(state, RHS(ins, 1), fp);
16092                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16093         }
16094         else {
16095                 unsigned lmask, rmask;
16096                 int lreg, rreg;
16097                 lreg = check_reg(state, RHS(ins, 0), mask);
16098                 rreg = check_reg(state, RHS(ins, 1), mask);
16099                 lmask = arch_reg_regcm(state, lreg);
16100                 rmask = arch_reg_regcm(state, rreg);
16101                 mask = lmask & rmask;
16102                 fprintf(fp, "\tcmp %s, %s\n",
16103                         reg(state, RHS(ins, 1), mask),
16104                         reg(state, RHS(ins, 0), mask));
16105         }
16106 }
16107
16108 static void print_op_test(struct compile_state *state,
16109         struct triple *ins, FILE *fp)
16110 {
16111         unsigned mask;
16112         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16113         fprintf(fp, "\ttest %s, %s\n",
16114                 reg(state, RHS(ins, 0), mask),
16115                 reg(state, RHS(ins, 0), mask));
16116 }
16117
16118 static void print_op_branch(struct compile_state *state,
16119         struct triple *branch, FILE *fp)
16120 {
16121         const char *bop = "j";
16122         if (branch->op == OP_JMP) {
16123                 if (TRIPLE_RHS(branch->sizes) != 0) {
16124                         internal_error(state, branch, "jmp with condition?");
16125                 }
16126                 bop = "jmp";
16127         }
16128         else {
16129                 struct triple *ptr;
16130                 if (TRIPLE_RHS(branch->sizes) != 1) {
16131                         internal_error(state, branch, "jmpcc without condition?");
16132                 }
16133                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16134                 if ((RHS(branch, 0)->op != OP_CMP) &&
16135                         (RHS(branch, 0)->op != OP_TEST)) {
16136                         internal_error(state, branch, "bad branch test");
16137                 }
16138 #warning "FIXME I have observed instructions between the test and branch instructions"
16139                 ptr = RHS(branch, 0);
16140                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16141                         if (ptr->op != OP_COPY) {
16142                                 internal_error(state, branch, "branch does not follow test");
16143                         }
16144                 }
16145                 switch(branch->op) {
16146                 case OP_JMP_EQ:       bop = "jz";  break;
16147                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16148                 case OP_JMP_SLESS:    bop = "jl";  break;
16149                 case OP_JMP_ULESS:    bop = "jb";  break;
16150                 case OP_JMP_SMORE:    bop = "jg";  break;
16151                 case OP_JMP_UMORE:    bop = "ja";  break;
16152                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16153                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16154                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16155                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16156                 default:
16157                         internal_error(state, branch, "Invalid branch op");
16158                         break;
16159                 }
16160                 
16161         }
16162         fprintf(fp, "\t%s L%s%lu\n",
16163                 bop, 
16164                 state->label_prefix,
16165                 TARG(branch, 0)->u.cval);
16166 }
16167
16168 static void print_op_set(struct compile_state *state,
16169         struct triple *set, FILE *fp)
16170 {
16171         const char *sop = "set";
16172         if (TRIPLE_RHS(set->sizes) != 1) {
16173                 internal_error(state, set, "setcc without condition?");
16174         }
16175         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16176         if ((RHS(set, 0)->op != OP_CMP) &&
16177                 (RHS(set, 0)->op != OP_TEST)) {
16178                 internal_error(state, set, "bad set test");
16179         }
16180         if (RHS(set, 0)->next != set) {
16181                 internal_error(state, set, "set does not follow test");
16182         }
16183         switch(set->op) {
16184         case OP_SET_EQ:       sop = "setz";  break;
16185         case OP_SET_NOTEQ:    sop = "setnz"; break;
16186         case OP_SET_SLESS:    sop = "setl";  break;
16187         case OP_SET_ULESS:    sop = "setb";  break;
16188         case OP_SET_SMORE:    sop = "setg";  break;
16189         case OP_SET_UMORE:    sop = "seta";  break;
16190         case OP_SET_SLESSEQ:  sop = "setle"; break;
16191         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16192         case OP_SET_SMOREEQ:  sop = "setge"; break;
16193         case OP_SET_UMOREEQ:  sop = "setae"; break;
16194         default:
16195                 internal_error(state, set, "Invalid set op");
16196                 break;
16197         }
16198         fprintf(fp, "\t%s %s\n",
16199                 sop, reg(state, set, REGCM_GPR8));
16200 }
16201
16202 static void print_op_bit_scan(struct compile_state *state, 
16203         struct triple *ins, FILE *fp) 
16204 {
16205         const char *op;
16206         switch(ins->op) {
16207         case OP_BSF: op = "bsf"; break;
16208         case OP_BSR: op = "bsr"; break;
16209         default: 
16210                 internal_error(state, ins, "unknown bit scan");
16211                 op = 0;
16212                 break;
16213         }
16214         fprintf(fp, 
16215                 "\t%s %s, %s\n"
16216                 "\tjnz 1f\n"
16217                 "\tmovl $-1, %s\n"
16218                 "1:\n",
16219                 op,
16220                 reg(state, RHS(ins, 0), REGCM_GPR32),
16221                 reg(state, ins, REGCM_GPR32),
16222                 reg(state, ins, REGCM_GPR32));
16223 }
16224
16225 static void print_const(struct compile_state *state,
16226         struct triple *ins, FILE *fp)
16227 {
16228         switch(ins->op) {
16229         case OP_INTCONST:
16230                 switch(ins->type->type & TYPE_MASK) {
16231                 case TYPE_CHAR:
16232                 case TYPE_UCHAR:
16233                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16234                         break;
16235                 case TYPE_SHORT:
16236                 case TYPE_USHORT:
16237                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16238                         break;
16239                 case TYPE_INT:
16240                 case TYPE_UINT:
16241                 case TYPE_LONG:
16242                 case TYPE_ULONG:
16243                         fprintf(fp, ".int %lu\n", ins->u.cval);
16244                         break;
16245                 default:
16246                         internal_error(state, ins, "Unknown constant type");
16247                 }
16248                 break;
16249         case OP_BLOBCONST:
16250         {
16251                 unsigned char *blob;
16252                 size_t size, i;
16253                 size = size_of(state, ins->type);
16254                 blob = ins->u.blob;
16255                 for(i = 0; i < size; i++) {
16256                         fprintf(fp, ".byte 0x%02x\n",
16257                                 blob[i]);
16258                 }
16259                 break;
16260         }
16261         default:
16262                 internal_error(state, ins, "Unknown constant type");
16263                 break;
16264         }
16265 }
16266
16267 #define TEXT_SECTION ".rom.text"
16268 #define DATA_SECTION ".rom.data"
16269
16270 static void print_sdecl(struct compile_state *state,
16271         struct triple *ins, FILE *fp)
16272 {
16273         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16274         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16275         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16276         print_const(state, MISC(ins, 0), fp);
16277         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16278                 
16279 }
16280
16281 static void print_instruction(struct compile_state *state,
16282         struct triple *ins, FILE *fp)
16283 {
16284         /* Assumption: after I have exted the register allocator
16285          * everything is in a valid register. 
16286          */
16287         switch(ins->op) {
16288         case OP_ASM:
16289                 print_op_asm(state, ins, fp);
16290                 break;
16291         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16292         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16293         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16294         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16295         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16296         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16297         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16298         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16299         case OP_POS:    break;
16300         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16301         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16302         case OP_INTCONST:
16303         case OP_ADDRCONST:
16304         case OP_BLOBCONST:
16305                 /* Don't generate anything here for constants */
16306         case OP_PHI:
16307                 /* Don't generate anything for variable declarations. */
16308                 break;
16309         case OP_SDECL:
16310                 print_sdecl(state, ins, fp);
16311                 break;
16312         case OP_WRITE: 
16313         case OP_COPY:   
16314                 print_op_move(state, ins, fp);
16315                 break;
16316         case OP_LOAD:
16317                 print_op_load(state, ins, fp);
16318                 break;
16319         case OP_STORE:
16320                 print_op_store(state, ins, fp);
16321                 break;
16322         case OP_SMUL:
16323                 print_op_smul(state, ins, fp);
16324                 break;
16325         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16326         case OP_TEST:   print_op_test(state, ins, fp); break;
16327         case OP_JMP:
16328         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16329         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16330         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16331         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16332         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16333                 print_op_branch(state, ins, fp);
16334                 break;
16335         case OP_SET_EQ:      case OP_SET_NOTEQ:
16336         case OP_SET_SLESS:   case OP_SET_ULESS:
16337         case OP_SET_SMORE:   case OP_SET_UMORE:
16338         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16339         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16340                 print_op_set(state, ins, fp);
16341                 break;
16342         case OP_INB:  case OP_INW:  case OP_INL:
16343                 print_op_in(state, ins, fp); 
16344                 break;
16345         case OP_OUTB: case OP_OUTW: case OP_OUTL:
16346                 print_op_out(state, ins, fp); 
16347                 break;
16348         case OP_BSF:
16349         case OP_BSR:
16350                 print_op_bit_scan(state, ins, fp);
16351                 break;
16352         case OP_RDMSR:
16353                 after_lhs(state, ins);
16354                 fprintf(fp, "\trdmsr\n");
16355                 break;
16356         case OP_WRMSR:
16357                 fprintf(fp, "\twrmsr\n");
16358                 break;
16359         case OP_HLT:
16360                 fprintf(fp, "\thlt\n");
16361                 break;
16362         case OP_LABEL:
16363                 if (!ins->use) {
16364                         return;
16365                 }
16366                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16367                 break;
16368                 /* Ignore OP_PIECE */
16369         case OP_PIECE:
16370                 break;
16371                 /* Operations I am not yet certain how to handle */
16372         case OP_UMUL:
16373         case OP_SDIV: case OP_UDIV:
16374         case OP_SMOD: case OP_UMOD:
16375                 /* Operations that should never get here */
16376         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
16377         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
16378         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16379         default:
16380                 internal_error(state, ins, "unknown op: %d %s",
16381                         ins->op, tops(ins->op));
16382                 break;
16383         }
16384 }
16385
16386 static void print_instructions(struct compile_state *state)
16387 {
16388         struct triple *first, *ins;
16389         int print_location;
16390         int last_line;
16391         int last_col;
16392         const char *last_filename;
16393         FILE *fp;
16394         print_location = 1;
16395         last_line = -1;
16396         last_col  = -1;
16397         last_filename = 0;
16398         fp = state->output;
16399         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16400         first = RHS(state->main_function, 0);
16401         ins = first;
16402         do {
16403                 if (print_location &&
16404                         ((last_filename != ins->filename) ||
16405                                 (last_line != ins->line) ||
16406                                 (last_col  != ins->col))) {
16407                         fprintf(fp, "\t/* %s:%d */\n",
16408                                 ins->filename, ins->line);
16409                         last_filename = ins->filename;
16410                         last_line = ins->line;
16411                         last_col  = ins->col;
16412                 }
16413
16414                 print_instruction(state, ins, fp);
16415                 ins = ins->next;
16416         } while(ins != first);
16417         
16418 }
16419 static void generate_code(struct compile_state *state)
16420 {
16421         generate_local_labels(state);
16422         print_instructions(state);
16423         
16424 }
16425
16426 static void print_tokens(struct compile_state *state)
16427 {
16428         struct token *tk;
16429         tk = &state->token[0];
16430         do {
16431 #if 1
16432                 token(state, 0);
16433 #else
16434                 next_token(state, 0);
16435 #endif
16436                 loc(stdout, state, 0);
16437                 printf("%s <- `%s'\n",
16438                         tokens[tk->tok],
16439                         tk->ident ? tk->ident->name :
16440                         tk->str_len ? tk->val.str : "");
16441                 
16442         } while(tk->tok != TOK_EOF);
16443 }
16444
16445 static void compile(const char *filename, const char *ofilename, 
16446         int cpu, int debug, int opt, const char *label_prefix)
16447 {
16448         int i;
16449         struct compile_state state;
16450         memset(&state, 0, sizeof(state));
16451         state.file = 0;
16452         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16453                 memset(&state.token[i], 0, sizeof(state.token[i]));
16454                 state.token[i].tok = -1;
16455         }
16456         /* Remember the debug settings */
16457         state.cpu      = cpu;
16458         state.debug    = debug;
16459         state.optimize = opt;
16460         /* Remember the output filename */
16461         state.ofilename = ofilename;
16462         state.output    = fopen(state.ofilename, "w");
16463         if (!state.output) {
16464                 error(&state, 0, "Cannot open output file %s\n",
16465                         ofilename);
16466         }
16467         /* Remember the label prefix */
16468         state.label_prefix = label_prefix;
16469         /* Prep the preprocessor */
16470         state.if_depth = 0;
16471         state.if_value = 0;
16472         /* register the C keywords */
16473         register_keywords(&state);
16474         /* register the keywords the macro preprocessor knows */
16475         register_macro_keywords(&state);
16476         /* Memorize where some special keywords are. */
16477         state.i_continue = lookup(&state, "continue", 8);
16478         state.i_break    = lookup(&state, "break", 5);
16479         /* Enter the globl definition scope */
16480         start_scope(&state);
16481         register_builtins(&state);
16482         compile_file(&state, filename, 1);
16483 #if 0
16484         print_tokens(&state);
16485 #endif  
16486         decls(&state);
16487         /* Exit the global definition scope */
16488         end_scope(&state);
16489
16490         /* Now that basic compilation has happened 
16491          * optimize the intermediate code 
16492          */
16493         optimize(&state);
16494
16495         generate_code(&state);
16496         if (state.debug) {
16497                 fprintf(stderr, "done\n");
16498         }
16499 }
16500
16501 static void version(void)
16502 {
16503         printf("romcc " VERSION " released " RELEASE_DATE "\n");
16504 }
16505
16506 static void usage(void)
16507 {
16508         version();
16509         printf(
16510                 "Usage: romcc <source>.c\n"
16511                 "Compile a C source file without using ram\n"
16512         );
16513 }
16514
16515 static void arg_error(char *fmt, ...)
16516 {
16517         va_list args;
16518         va_start(args, fmt);
16519         vfprintf(stderr, fmt, args);
16520         va_end(args);
16521         usage();
16522         exit(1);
16523 }
16524
16525 int main(int argc, char **argv)
16526 {
16527         const char *filename;
16528         const char *ofilename;
16529         const char *label_prefix;
16530         int cpu;
16531         int last_argc;
16532         int debug;
16533         int optimize;
16534         cpu = CPU_DEFAULT;
16535         label_prefix = "";
16536         ofilename = "auto.inc";
16537         optimize = 0;
16538         debug = 0;
16539         last_argc = -1;
16540         while((argc > 1) && (argc != last_argc)) {
16541                 last_argc = argc;
16542                 if (strncmp(argv[1], "--debug=", 8) == 0) {
16543                         debug = atoi(argv[1] + 8);
16544                         argv++;
16545                         argc--;
16546                 }
16547                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16548                         label_prefix= argv[1] + 15;
16549                         argv++;
16550                         argc--;
16551                 }
16552                 else if ((strcmp(argv[1],"-O") == 0) ||
16553                         (strcmp(argv[1], "-O1") == 0)) {
16554                         optimize = 1;
16555                         argv++;
16556                         argc--;
16557                 }
16558                 else if (strcmp(argv[1],"-O2") == 0) {
16559                         optimize = 2;
16560                         argv++;
16561                         argc--;
16562                 }
16563                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16564                         ofilename = argv[2];
16565                         argv += 2;
16566                         argc -= 2;
16567                 }
16568                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16569                         cpu = arch_encode_cpu(argv[1] + 6);
16570                         if (cpu == BAD_CPU) {
16571                                 arg_error("Invalid cpu specified: %s\n",
16572                                         argv[1] + 6);
16573                         }
16574                         argv++;
16575                         argc--;
16576                 }
16577         }
16578         if (argc != 2) {
16579                 arg_error("Wrong argument count %d\n", argc);
16580         }
16581         filename = argv[1];
16582         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
16583
16584         return 0;
16585 }