- Reduce the algorithmic complexity of parts of the register allocator
[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 <ctype.h>
13 #include <limits.h>
14
15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_SCC 0
18 #define DEBUG_CONSISTENCY 1
19
20 #warning "FIXME boundary cases with small types in larger registers"
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
868 /* Provision for 8 register classes */
869 #if 1
870 #define REG_SHIFT  0
871 #define REGC_SHIFT REGISTER_BITS
872 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
873 #define REG_MASK (MAX_VIRT_REGISTERS -1)
874 #define ID_REG(ID)              ((ID) & REG_MASK)
875 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
876 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
877 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
878 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
879                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
880 #else
881 #define REG_MASK (MAX_VIRT_REGISTERS -1)
882 #define ID_REG(ID)              ((ID) & REG_MASK)
883 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
884 #endif
885
886 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
887 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
888 static void arch_reg_equivs(
889         struct compile_state *state, unsigned *equiv, int reg);
890 static int arch_select_free_register(
891         struct compile_state *state, char *used, int classes);
892 static unsigned arch_regc_size(struct compile_state *state, int class);
893 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
894 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
895 static const char *arch_reg_str(int reg);
896 static struct reg_info arch_reg_constraint(
897         struct compile_state *state, struct type *type, const char *constraint);
898 static struct reg_info arch_reg_clobber(
899         struct compile_state *state, const char *clobber);
900 static struct reg_info arch_reg_lhs(struct compile_state *state, 
901         struct triple *ins, int index);
902 static struct reg_info arch_reg_rhs(struct compile_state *state, 
903         struct triple *ins, int index);
904 static struct triple *transform_to_arch_instruction(
905         struct compile_state *state, struct triple *ins);
906
907
908
909 #define DEBUG_ABORT_ON_ERROR    0x0001
910 #define DEBUG_INTERMEDIATE_CODE 0x0002
911 #define DEBUG_CONTROL_FLOW      0x0004
912 #define DEBUG_BASIC_BLOCKS      0x0008
913 #define DEBUG_FDOMINATORS       0x0010
914 #define DEBUG_RDOMINATORS       0x0020
915 #define DEBUG_TRIPLES           0x0040
916 #define DEBUG_INTERFERENCE      0x0080
917 #define DEBUG_ARCH_CODE         0x0100
918 #define DEBUG_CODE_ELIMINATION  0x0200
919 #define DEBUG_INSERTED_COPIES   0x0400
920
921 #define GLOBAL_SCOPE_DEPTH 1
922
923 static void compile_file(struct compile_state *old_state, const char *filename, int local);
924
925 static void do_cleanup(struct compile_state *state)
926 {
927         if (state->output) {
928                 fclose(state->output);
929                 unlink(state->ofilename);
930         }
931 }
932
933 static int get_col(struct file_state *file)
934 {
935         int col;
936         char *ptr, *end;
937         ptr = file->line_start;
938         end = file->pos;
939         for(col = 0; ptr < end; ptr++) {
940                 if (*ptr != '\t') {
941                         col++;
942                 } 
943                 else {
944                         col = (col & ~7) + 8;
945                 }
946         }
947         return col;
948 }
949
950 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
951 {
952         int col;
953         if (triple) {
954                 fprintf(fp, "%s:%d.%d: ", 
955                         triple->filename, triple->line, triple->col);
956                 return;
957         }
958         if (!state->file) {
959                 return;
960         }
961         col = get_col(state->file);
962         fprintf(fp, "%s:%d.%d: ", 
963                 state->file->basename, state->file->line, col);
964 }
965
966 static void __internal_error(struct compile_state *state, struct triple *ptr, 
967         char *fmt, ...)
968 {
969         va_list args;
970         va_start(args, fmt);
971         loc(stderr, state, ptr);
972         if (ptr) {
973                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
974         }
975         fprintf(stderr, "Internal compiler error: ");
976         vfprintf(stderr, fmt, args);
977         fprintf(stderr, "\n");
978         va_end(args);
979         do_cleanup(state);
980         abort();
981 }
982
983
984 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
985         char *fmt, ...)
986 {
987         va_list args;
988         va_start(args, fmt);
989         loc(stderr, state, ptr);
990         fprintf(stderr, "Internal compiler warning: ");
991         vfprintf(stderr, fmt, args);
992         fprintf(stderr, "\n");
993         va_end(args);
994 }
995
996
997
998 static void __error(struct compile_state *state, struct triple *ptr, 
999         char *fmt, ...)
1000 {
1001         va_list args;
1002         va_start(args, fmt);
1003         loc(stderr, state, ptr);
1004         vfprintf(stderr, fmt, args);
1005         va_end(args);
1006         fprintf(stderr, "\n");
1007         do_cleanup(state);
1008         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1009                 abort();
1010         }
1011         exit(1);
1012 }
1013
1014 static void __warning(struct compile_state *state, struct triple *ptr, 
1015         char *fmt, ...)
1016 {
1017         va_list args;
1018         va_start(args, fmt);
1019         loc(stderr, state, ptr);
1020         fprintf(stderr, "warning: "); 
1021         vfprintf(stderr, fmt, args);
1022         fprintf(stderr, "\n");
1023         va_end(args);
1024 }
1025
1026 #if DEBUG_ERROR_MESSAGES 
1027 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1028 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1029 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1030 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1031 #else
1032 #  define internal_error __internal_error
1033 #  define internal_warning __internal_warning
1034 #  define error __error
1035 #  define warning __warning
1036 #endif
1037 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1038
1039 static void valid_op(struct compile_state *state, int op)
1040 {
1041         char *fmt = "invalid op: %d";
1042         if (op >= OP_MAX) {
1043                 internal_error(state, 0, fmt, op);
1044         }
1045         if (op < 0) {
1046                 internal_error(state, 0, fmt, op);
1047         }
1048 }
1049
1050 static void valid_ins(struct compile_state *state, struct triple *ptr)
1051 {
1052         valid_op(state, ptr->op);
1053 }
1054
1055 static void process_trigraphs(struct compile_state *state)
1056 {
1057         char *src, *dest, *end;
1058         struct file_state *file;
1059         file = state->file;
1060         src = dest = file->buf;
1061         end = file->buf + file->size;
1062         while((end - src) >= 3) {
1063                 if ((src[0] == '?') && (src[1] == '?')) {
1064                         int c = -1;
1065                         switch(src[2]) {
1066                         case '=': c = '#'; break;
1067                         case '/': c = '\\'; break;
1068                         case '\'': c = '^'; break;
1069                         case '(': c = '['; break;
1070                         case ')': c = ']'; break;
1071                         case '!': c = '!'; break;
1072                         case '<': c = '{'; break;
1073                         case '>': c = '}'; break;
1074                         case '-': c = '~'; break;
1075                         }
1076                         if (c != -1) {
1077                                 *dest++ = c;
1078                                 src += 3;
1079                         }
1080                         else {
1081                                 *dest++ = *src++;
1082                         }
1083                 }
1084                 else {
1085                         *dest++ = *src++;
1086                 }
1087         }
1088         while(src != end) {
1089                 *dest++ = *src++;
1090         }
1091         file->size = dest - file->buf;
1092 }
1093
1094 static void splice_lines(struct compile_state *state)
1095 {
1096         char *src, *dest, *end;
1097         struct file_state *file;
1098         file = state->file;
1099         src = dest = file->buf;
1100         end = file->buf + file->size;
1101         while((end - src) >= 2) {
1102                 if ((src[0] == '\\') && (src[1] == '\n')) {
1103                         src += 2;
1104                 }
1105                 else {
1106                         *dest++ = *src++;
1107                 }
1108         }
1109         while(src != end) {
1110                 *dest++ = *src++;
1111         }
1112         file->size = dest - file->buf;
1113 }
1114
1115 static struct type void_type;
1116 static void use_triple(struct triple *used, struct triple *user)
1117 {
1118         struct triple_set **ptr, *new;
1119         if (!used)
1120                 return;
1121         if (!user)
1122                 return;
1123         ptr = &used->use;
1124         while(*ptr) {
1125                 if ((*ptr)->member == user) {
1126                         return;
1127                 }
1128                 ptr = &(*ptr)->next;
1129         }
1130         /* Append new to the head of the list, 
1131          * copy_func and rename_block_variables
1132          * depends on this.
1133          */
1134         new = xcmalloc(sizeof(*new), "triple_set");
1135         new->member = user;
1136         new->next   = used->use;
1137         used->use   = new;
1138 }
1139
1140 static void unuse_triple(struct triple *used, struct triple *unuser)
1141 {
1142         struct triple_set *use, **ptr;
1143         if (!used) {
1144                 return;
1145         }
1146         ptr = &used->use;
1147         while(*ptr) {
1148                 use = *ptr;
1149                 if (use->member == unuser) {
1150                         *ptr = use->next;
1151                         xfree(use);
1152                 }
1153                 else {
1154                         ptr = &use->next;
1155                 }
1156         }
1157 }
1158
1159 static void push_triple(struct triple *used, struct triple *user)
1160 {
1161         struct triple_set *new;
1162         if (!used)
1163                 return;
1164         if (!user)
1165                 return;
1166         /* Append new to the head of the list,
1167          * it's the only sensible behavoir for a stack.
1168          */
1169         new = xcmalloc(sizeof(*new), "triple_set");
1170         new->member = user;
1171         new->next   = used->use;
1172         used->use   = new;
1173 }
1174
1175 static void pop_triple(struct triple *used, struct triple *unuser)
1176 {
1177         struct triple_set *use, **ptr;
1178         ptr = &used->use;
1179         while(*ptr) {
1180                 use = *ptr;
1181                 if (use->member == unuser) {
1182                         *ptr = use->next;
1183                         xfree(use);
1184                         /* Only free one occurance from the stack */
1185                         return;
1186                 }
1187                 else {
1188                         ptr = &use->next;
1189                 }
1190         }
1191 }
1192
1193
1194 /* The zero triple is used as a place holder when we are removing pointers
1195  * from a triple.  Having allows certain sanity checks to pass even
1196  * when the original triple that was pointed to is gone.
1197  */
1198 static struct triple zero_triple = {
1199         .next     = &zero_triple,
1200         .prev     = &zero_triple,
1201         .use      = 0,
1202         .op       = OP_INTCONST,
1203         .sizes    = TRIPLE_SIZES(0, 0, 0, 0),
1204         .id       = -1, /* An invalid id */
1205         .u = { .cval   = 0, },
1206         .filename = __FILE__,
1207         .line     = __LINE__,
1208         .col      = 0,
1209         .param { [0] = 0, [1] = 0, },
1210 };
1211
1212
1213 static unsigned short triple_sizes(struct compile_state *state,
1214         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1215 {
1216         int lhs, rhs, misc, targ;
1217         valid_op(state, op);
1218         lhs = table_ops[op].lhs;
1219         rhs = table_ops[op].rhs;
1220         misc = table_ops[op].misc;
1221         targ = table_ops[op].targ;
1222         
1223         
1224         if (op == OP_CALL) {
1225                 struct type *param;
1226                 rhs = 0;
1227                 param = type->right;
1228                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1229                         rhs++;
1230                         param = param->right;
1231                 }
1232                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1233                         rhs++;
1234                 }
1235                 lhs = 0;
1236                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1237                         lhs = type->left->elements;
1238                 }
1239         }
1240         else if (op == OP_VAL_VEC) {
1241                 rhs = type->elements;
1242         }
1243         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1244                 rhs = rhs_wanted;
1245         }
1246         else if (op == OP_ASM) {
1247                 rhs = rhs_wanted;
1248                 lhs = lhs_wanted;
1249         }
1250         if ((rhs < 0) || (rhs > MAX_RHS)) {
1251                 internal_error(state, 0, "bad rhs");
1252         }
1253         if ((lhs < 0) || (lhs > MAX_LHS)) {
1254                 internal_error(state, 0, "bad lhs");
1255         }
1256         if ((misc < 0) || (misc > MAX_MISC)) {
1257                 internal_error(state, 0, "bad misc");
1258         }
1259         if ((targ < 0) || (targ > MAX_TARG)) {
1260                 internal_error(state, 0, "bad targs");
1261         }
1262         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1263 }
1264
1265 static struct triple *alloc_triple(struct compile_state *state, 
1266         int op, struct type *type, int lhs, int rhs,
1267         const char *filename, int line, int col)
1268 {
1269         size_t size, sizes, extra_count, min_count;
1270         struct triple *ret;
1271         sizes = triple_sizes(state, op, type, lhs, rhs);
1272
1273         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1274         extra_count = TRIPLE_SIZE(sizes);
1275         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1276
1277         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1278         ret = xcmalloc(size, "tripple");
1279         ret->op       = op;
1280         ret->sizes    = sizes;
1281         ret->type     = type;
1282         ret->next     = ret;
1283         ret->prev     = ret;
1284         ret->filename = filename;
1285         ret->line     = line;
1286         ret->col      = col;
1287         return ret;
1288 }
1289
1290 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1291 {
1292         struct triple *dup;
1293         int src_lhs, src_rhs, src_size;
1294         src_lhs = TRIPLE_LHS(src->sizes);
1295         src_rhs = TRIPLE_RHS(src->sizes);
1296         src_size = TRIPLE_SIZE(src->sizes);
1297         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1298                 src->filename, src->line, src->col);
1299         memcpy(dup, src, sizeof(*src));
1300         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1301         return dup;
1302 }
1303
1304 static struct triple *new_triple(struct compile_state *state, 
1305         int op, struct type *type, int lhs, int rhs)
1306 {
1307         struct triple *ret;
1308         const char *filename;
1309         int line, col;
1310         filename = 0;
1311         line = 0;
1312         col  = 0;
1313         if (state->file) {
1314                 filename = state->file->basename;
1315                 line     = state->file->line;
1316                 col      = get_col(state->file);
1317         }
1318         ret = alloc_triple(state, op, type, lhs, rhs,
1319                 filename, line, col);
1320         return ret;
1321 }
1322
1323 static struct triple *build_triple(struct compile_state *state, 
1324         int op, struct type *type, struct triple *left, struct triple *right,
1325         const char *filename, int line, int col)
1326 {
1327         struct triple *ret;
1328         size_t count;
1329         ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1330         count = TRIPLE_SIZE(ret->sizes);
1331         if (count > 0) {
1332                 ret->param[0] = left;
1333         }
1334         if (count > 1) {
1335                 ret->param[1] = right;
1336         }
1337         return ret;
1338 }
1339
1340 static struct triple *triple(struct compile_state *state, 
1341         int op, struct type *type, struct triple *left, struct triple *right)
1342 {
1343         struct triple *ret;
1344         size_t count;
1345         ret = new_triple(state, op, type, -1, -1);
1346         count = TRIPLE_SIZE(ret->sizes);
1347         if (count >= 1) {
1348                 ret->param[0] = left;
1349         }
1350         if (count >= 2) {
1351                 ret->param[1] = right;
1352         }
1353         return ret;
1354 }
1355
1356 static struct triple *branch(struct compile_state *state, 
1357         struct triple *targ, struct triple *test)
1358 {
1359         struct triple *ret;
1360         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1361         if (test) {
1362                 RHS(ret, 0) = test;
1363         }
1364         TARG(ret, 0) = targ;
1365         /* record the branch target was used */
1366         if (!targ || (targ->op != OP_LABEL)) {
1367                 internal_error(state, 0, "branch not to label");
1368                 use_triple(targ, ret);
1369         }
1370         return ret;
1371 }
1372
1373
1374 static void insert_triple(struct compile_state *state,
1375         struct triple *first, struct triple *ptr)
1376 {
1377         if (ptr) {
1378                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1379                         internal_error(state, ptr, "expression already used");
1380                 }
1381                 ptr->next       = first;
1382                 ptr->prev       = first->prev;
1383                 ptr->prev->next = ptr;
1384                 ptr->next->prev = ptr;
1385                 if ((ptr->prev->op == OP_BRANCH) && 
1386                         TRIPLE_RHS(ptr->prev->sizes)) {
1387                         unuse_triple(first, ptr->prev);
1388                         use_triple(ptr, ptr->prev);
1389                 }
1390         }
1391 }
1392
1393 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1394 {
1395         /* This function is used to determine if u.block 
1396          * is utilized to store the current block number.
1397          */
1398         int stores_block;
1399         valid_ins(state, ins);
1400         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1401         return stores_block;
1402 }
1403
1404 static struct block *block_of_triple(struct compile_state *state, 
1405         struct triple *ins)
1406 {
1407         struct triple *first;
1408         first = RHS(state->main_function, 0);
1409         while(ins != first && !triple_stores_block(state, ins)) {
1410                 if (ins == ins->prev) {
1411                         internal_error(state, 0, "ins == ins->prev?");
1412                 }
1413                 ins = ins->prev;
1414         }
1415         if (!triple_stores_block(state, ins)) {
1416                 internal_error(state, ins, "Cannot find block");
1417         }
1418         return ins->u.block;
1419 }
1420
1421 static struct triple *pre_triple(struct compile_state *state,
1422         struct triple *base,
1423         int op, struct type *type, struct triple *left, struct triple *right)
1424 {
1425         struct block *block;
1426         struct triple *ret;
1427         block = block_of_triple(state, base);
1428         ret = build_triple(state, op, type, left, right, 
1429                 base->filename, base->line, base->col);
1430         if (triple_stores_block(state, ret)) {
1431                 ret->u.block = block;
1432         }
1433         insert_triple(state, base, ret);
1434         if (block->first == base) {
1435                 block->first = ret;
1436         }
1437         return ret;
1438 }
1439
1440 static struct triple *post_triple(struct compile_state *state,
1441         struct triple *base,
1442         int op, struct type *type, struct triple *left, struct triple *right)
1443 {
1444         struct block *block;
1445         struct triple *ret;
1446         block = block_of_triple(state, base);
1447         ret = build_triple(state, op, type, left, right, 
1448                 base->filename, base->line, base->col);
1449         if (triple_stores_block(state, ret)) {
1450                 ret->u.block = block;
1451         }
1452         insert_triple(state, base->next, ret);
1453         if (block->last == base) {
1454                 block->last = ret;
1455         }
1456         return ret;
1457 }
1458
1459 static struct triple *label(struct compile_state *state)
1460 {
1461         /* Labels don't get a type */
1462         struct triple *result;
1463         result = triple(state, OP_LABEL, &void_type, 0, 0);
1464         return result;
1465 }
1466
1467 static void display_triple(FILE *fp, struct triple *ins)
1468 {
1469         if (ins->op == OP_INTCONST) {
1470                 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx>          @ %s:%d.%d\n",
1471                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1472                         ins->u.cval,
1473                         ins->filename, ins->line, ins->col);
1474         }
1475         else if (ins->op == OP_ADDRCONST) {
1476                 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1477                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1478                         MISC(ins, 0), ins->u.cval,
1479                         ins->filename, ins->line, ins->col);
1480         }
1481         else {
1482                 int i, count;
1483                 fprintf(fp, "(%p) %3d %-2d %-10s", 
1484                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1485                 count = TRIPLE_SIZE(ins->sizes);
1486                 for(i = 0; i < count; i++) {
1487                         fprintf(fp, " %-10p", ins->param[i]);
1488                 }
1489                 for(; i < 2; i++) {
1490                         printf("           ");
1491                 }
1492                 fprintf(fp, " @ %s:%d.%d\n", 
1493                         ins->filename, ins->line, ins->col);
1494         }
1495         fflush(fp);
1496 }
1497
1498 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1499 {
1500         /* Does the triple have no side effects.
1501          * I.e. Rexecuting the triple with the same arguments 
1502          * gives the same value.
1503          */
1504         unsigned pure;
1505         valid_ins(state, ins);
1506         pure = PURE_BITS(table_ops[ins->op].flags);
1507         if ((pure != PURE) && (pure != IMPURE)) {
1508                 internal_error(state, 0, "Purity of %s not known\n",
1509                         tops(ins->op));
1510         }
1511         return pure == PURE;
1512 }
1513
1514 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1515 {
1516         /* This function is used to determine which triples need
1517          * a register.
1518          */
1519         int is_branch;
1520         valid_ins(state, ins);
1521         is_branch = (table_ops[ins->op].targ != 0);
1522         return is_branch;
1523 }
1524
1525 static int triple_is_def(struct compile_state *state, struct triple *ins)
1526 {
1527         /* This function is used to determine which triples need
1528          * a register.
1529          */
1530         int is_def;
1531         valid_ins(state, ins);
1532         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1533         return is_def;
1534 }
1535
1536 static struct triple **triple_iter(struct compile_state *state,
1537         size_t count, struct triple **vector,
1538         struct triple *ins, struct triple **last)
1539 {
1540         struct triple **ret;
1541         ret = 0;
1542         if (count) {
1543                 if (!last) {
1544                         ret = vector;
1545                 }
1546                 else if ((last >= vector) && (last < (vector + count - 1))) {
1547                         ret = last + 1;
1548                 }
1549         }
1550         return ret;
1551         
1552 }
1553
1554 static struct triple **triple_lhs(struct compile_state *state,
1555         struct triple *ins, struct triple **last)
1556 {
1557         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1558                 ins, last);
1559 }
1560
1561 static struct triple **triple_rhs(struct compile_state *state,
1562         struct triple *ins, struct triple **last)
1563 {
1564         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1565                 ins, last);
1566 }
1567
1568 static struct triple **triple_misc(struct compile_state *state,
1569         struct triple *ins, struct triple **last)
1570 {
1571         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1572                 ins, last);
1573 }
1574
1575 static struct triple **triple_targ(struct compile_state *state,
1576         struct triple *ins, struct triple **last)
1577 {
1578         size_t count;
1579         struct triple **ret, **vector;
1580         ret = 0;
1581         count = TRIPLE_TARG(ins->sizes);
1582         vector = &TARG(ins, 0);
1583         if (count) {
1584                 if (!last) {
1585                         ret = vector;
1586                 }
1587                 else if ((last >= vector) && (last < (vector + count - 1))) {
1588                         ret = last + 1;
1589                 }
1590                 else if ((last == (vector + count - 1)) && 
1591                         TRIPLE_RHS(ins->sizes)) {
1592                         ret = &ins->next;
1593                 }
1594         }
1595         return ret;
1596 }
1597
1598
1599 static void verify_use(struct compile_state *state,
1600         struct triple *user, struct triple *used)
1601 {
1602         int size, i;
1603         size = TRIPLE_SIZE(user->sizes);
1604         for(i = 0; i < size; i++) {
1605                 if (user->param[i] == used) {
1606                         break;
1607                 }
1608         }
1609         if (triple_is_branch(state, user)) {
1610                 if (user->next == used) {
1611                         i = -1;
1612                 }
1613         }
1614         if (i == size) {
1615                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1616                         tops(user->op), user, tops(used->op), used);
1617         }
1618 }
1619
1620 static int find_rhs_use(struct compile_state *state, 
1621         struct triple *user, struct triple *used)
1622 {
1623         struct triple **param;
1624         int size, i;
1625         verify_use(state, user, used);
1626         size = TRIPLE_RHS(user->sizes);
1627         param = &RHS(user, 0);
1628         for(i = 0; i < size; i++) {
1629                 if (param[i] == used) {
1630                         return i;
1631                 }
1632         }
1633         return -1;
1634 }
1635
1636 static void free_triple(struct compile_state *state, struct triple *ptr)
1637 {
1638         size_t size;
1639         size = sizeof(*ptr) - sizeof(ptr->param) +
1640                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1641         ptr->prev->next = ptr->next;
1642         ptr->next->prev = ptr->prev;
1643         if (ptr->use) {
1644                 internal_error(state, ptr, "ptr->use != 0");
1645         }
1646         memset(ptr, -1, size);
1647         xfree(ptr);
1648 }
1649
1650 static void release_triple(struct compile_state *state, struct triple *ptr)
1651 {
1652         struct triple_set *set, *next;
1653         struct triple **expr;
1654         /* Remove ptr from use chains where it is the user */
1655         expr = triple_rhs(state, ptr, 0);
1656         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1657                 if (*expr) {
1658                         unuse_triple(*expr, ptr);
1659                 }
1660         }
1661         expr = triple_lhs(state, ptr, 0);
1662         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1663                 if (*expr) {
1664                         unuse_triple(*expr, ptr);
1665                 }
1666         }
1667         expr = triple_misc(state, ptr, 0);
1668         for(; expr; expr = triple_misc(state, ptr, expr)) {
1669                 if (*expr) {
1670                         unuse_triple(*expr, ptr);
1671                 }
1672         }
1673         expr = triple_targ(state, ptr, 0);
1674         for(; expr; expr = triple_targ(state, ptr, expr)) {
1675                 if (*expr) {
1676                         unuse_triple(*expr, ptr);
1677                 }
1678         }
1679         /* Reomve ptr from use chains where it is used */
1680         for(set = ptr->use; set; set = next) {
1681                 next = set->next;
1682                 expr = triple_rhs(state, set->member, 0);
1683                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1684                         if (*expr == ptr) {
1685                                 *expr = &zero_triple;
1686                         }
1687                 }
1688                 expr = triple_lhs(state, set->member, 0);
1689                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1690                         if (*expr == ptr) {
1691                                 *expr = &zero_triple;
1692                         }
1693                 }
1694                 expr = triple_misc(state, set->member, 0);
1695                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1696                         if (*expr == ptr) {
1697                                 *expr = &zero_triple;
1698                         }
1699                 }
1700                 expr = triple_targ(state, set->member, 0);
1701                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1702                         if (*expr == ptr) {
1703                                 *expr = &zero_triple;
1704                         }
1705                 }
1706                 unuse_triple(ptr, set->member);
1707         }
1708         free_triple(state, ptr);
1709 }
1710
1711 static void print_triple(struct compile_state *state, struct triple *ptr);
1712
1713 #define TOK_UNKNOWN     0
1714 #define TOK_SPACE       1
1715 #define TOK_SEMI        2
1716 #define TOK_LBRACE      3
1717 #define TOK_RBRACE      4
1718 #define TOK_COMMA       5
1719 #define TOK_EQ          6
1720 #define TOK_COLON       7
1721 #define TOK_LBRACKET    8
1722 #define TOK_RBRACKET    9
1723 #define TOK_LPAREN      10
1724 #define TOK_RPAREN      11
1725 #define TOK_STAR        12
1726 #define TOK_DOTS        13
1727 #define TOK_MORE        14
1728 #define TOK_LESS        15
1729 #define TOK_TIMESEQ     16
1730 #define TOK_DIVEQ       17
1731 #define TOK_MODEQ       18
1732 #define TOK_PLUSEQ      19
1733 #define TOK_MINUSEQ     20
1734 #define TOK_SLEQ        21
1735 #define TOK_SREQ        22
1736 #define TOK_ANDEQ       23
1737 #define TOK_XOREQ       24
1738 #define TOK_OREQ        25
1739 #define TOK_EQEQ        26
1740 #define TOK_NOTEQ       27
1741 #define TOK_QUEST       28
1742 #define TOK_LOGOR       29
1743 #define TOK_LOGAND      30
1744 #define TOK_OR          31
1745 #define TOK_AND         32
1746 #define TOK_XOR         33
1747 #define TOK_LESSEQ      34
1748 #define TOK_MOREEQ      35
1749 #define TOK_SL          36
1750 #define TOK_SR          37
1751 #define TOK_PLUS        38
1752 #define TOK_MINUS       39
1753 #define TOK_DIV         40
1754 #define TOK_MOD         41
1755 #define TOK_PLUSPLUS    42
1756 #define TOK_MINUSMINUS  43
1757 #define TOK_BANG        44
1758 #define TOK_ARROW       45
1759 #define TOK_DOT         46
1760 #define TOK_TILDE       47
1761 #define TOK_LIT_STRING  48
1762 #define TOK_LIT_CHAR    49
1763 #define TOK_LIT_INT     50
1764 #define TOK_LIT_FLOAT   51
1765 #define TOK_MACRO       52
1766 #define TOK_CONCATENATE 53
1767
1768 #define TOK_IDENT       54
1769 #define TOK_STRUCT_NAME 55
1770 #define TOK_ENUM_CONST  56
1771 #define TOK_TYPE_NAME   57
1772
1773 #define TOK_AUTO        58
1774 #define TOK_BREAK       59
1775 #define TOK_CASE        60
1776 #define TOK_CHAR        61
1777 #define TOK_CONST       62
1778 #define TOK_CONTINUE    63
1779 #define TOK_DEFAULT     64
1780 #define TOK_DO          65
1781 #define TOK_DOUBLE      66
1782 #define TOK_ELSE        67
1783 #define TOK_ENUM        68
1784 #define TOK_EXTERN      69
1785 #define TOK_FLOAT       70
1786 #define TOK_FOR         71
1787 #define TOK_GOTO        72
1788 #define TOK_IF          73
1789 #define TOK_INLINE      74
1790 #define TOK_INT         75
1791 #define TOK_LONG        76
1792 #define TOK_REGISTER    77
1793 #define TOK_RESTRICT    78
1794 #define TOK_RETURN      79
1795 #define TOK_SHORT       80
1796 #define TOK_SIGNED      81
1797 #define TOK_SIZEOF      82
1798 #define TOK_STATIC      83
1799 #define TOK_STRUCT      84
1800 #define TOK_SWITCH      85
1801 #define TOK_TYPEDEF     86
1802 #define TOK_UNION       87
1803 #define TOK_UNSIGNED    88
1804 #define TOK_VOID        89
1805 #define TOK_VOLATILE    90
1806 #define TOK_WHILE       91
1807 #define TOK_ASM         92
1808 #define TOK_ATTRIBUTE   93
1809 #define TOK_ALIGNOF     94
1810 #define TOK_FIRST_KEYWORD TOK_AUTO
1811 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1812
1813 #define TOK_DEFINE      100
1814 #define TOK_UNDEF       101
1815 #define TOK_INCLUDE     102
1816 #define TOK_LINE        103
1817 #define TOK_ERROR       104
1818 #define TOK_WARNING     105
1819 #define TOK_PRAGMA      106
1820 #define TOK_IFDEF       107
1821 #define TOK_IFNDEF      108
1822 #define TOK_ELIF        109
1823 #define TOK_ENDIF       110
1824
1825 #define TOK_FIRST_MACRO TOK_DEFINE
1826 #define TOK_LAST_MACRO  TOK_ENDIF
1827          
1828 #define TOK_EOF         111
1829
1830 static const char *tokens[] = {
1831 [TOK_UNKNOWN     ] = "unknown",
1832 [TOK_SPACE       ] = ":space:",
1833 [TOK_SEMI        ] = ";",
1834 [TOK_LBRACE      ] = "{",
1835 [TOK_RBRACE      ] = "}",
1836 [TOK_COMMA       ] = ",",
1837 [TOK_EQ          ] = "=",
1838 [TOK_COLON       ] = ":",
1839 [TOK_LBRACKET    ] = "[",
1840 [TOK_RBRACKET    ] = "]",
1841 [TOK_LPAREN      ] = "(",
1842 [TOK_RPAREN      ] = ")",
1843 [TOK_STAR        ] = "*",
1844 [TOK_DOTS        ] = "...",
1845 [TOK_MORE        ] = ">",
1846 [TOK_LESS        ] = "<",
1847 [TOK_TIMESEQ     ] = "*=",
1848 [TOK_DIVEQ       ] = "/=",
1849 [TOK_MODEQ       ] = "%=",
1850 [TOK_PLUSEQ      ] = "+=",
1851 [TOK_MINUSEQ     ] = "-=",
1852 [TOK_SLEQ        ] = "<<=",
1853 [TOK_SREQ        ] = ">>=",
1854 [TOK_ANDEQ       ] = "&=",
1855 [TOK_XOREQ       ] = "^=",
1856 [TOK_OREQ        ] = "|=",
1857 [TOK_EQEQ        ] = "==",
1858 [TOK_NOTEQ       ] = "!=",
1859 [TOK_QUEST       ] = "?",
1860 [TOK_LOGOR       ] = "||",
1861 [TOK_LOGAND      ] = "&&",
1862 [TOK_OR          ] = "|",
1863 [TOK_AND         ] = "&",
1864 [TOK_XOR         ] = "^",
1865 [TOK_LESSEQ      ] = "<=",
1866 [TOK_MOREEQ      ] = ">=",
1867 [TOK_SL          ] = "<<",
1868 [TOK_SR          ] = ">>",
1869 [TOK_PLUS        ] = "+",
1870 [TOK_MINUS       ] = "-",
1871 [TOK_DIV         ] = "/",
1872 [TOK_MOD         ] = "%",
1873 [TOK_PLUSPLUS    ] = "++",
1874 [TOK_MINUSMINUS  ] = "--",
1875 [TOK_BANG        ] = "!",
1876 [TOK_ARROW       ] = "->",
1877 [TOK_DOT         ] = ".",
1878 [TOK_TILDE       ] = "~",
1879 [TOK_LIT_STRING  ] = ":string:",
1880 [TOK_IDENT       ] = ":ident:",
1881 [TOK_TYPE_NAME   ] = ":typename:",
1882 [TOK_LIT_CHAR    ] = ":char:",
1883 [TOK_LIT_INT     ] = ":integer:",
1884 [TOK_LIT_FLOAT   ] = ":float:",
1885 [TOK_MACRO       ] = "#",
1886 [TOK_CONCATENATE ] = "##",
1887
1888 [TOK_AUTO        ] = "auto",
1889 [TOK_BREAK       ] = "break",
1890 [TOK_CASE        ] = "case",
1891 [TOK_CHAR        ] = "char",
1892 [TOK_CONST       ] = "const",
1893 [TOK_CONTINUE    ] = "continue",
1894 [TOK_DEFAULT     ] = "default",
1895 [TOK_DO          ] = "do",
1896 [TOK_DOUBLE      ] = "double",
1897 [TOK_ELSE        ] = "else",
1898 [TOK_ENUM        ] = "enum",
1899 [TOK_EXTERN      ] = "extern",
1900 [TOK_FLOAT       ] = "float",
1901 [TOK_FOR         ] = "for",
1902 [TOK_GOTO        ] = "goto",
1903 [TOK_IF          ] = "if",
1904 [TOK_INLINE      ] = "inline",
1905 [TOK_INT         ] = "int",
1906 [TOK_LONG        ] = "long",
1907 [TOK_REGISTER    ] = "register",
1908 [TOK_RESTRICT    ] = "restrict",
1909 [TOK_RETURN      ] = "return",
1910 [TOK_SHORT       ] = "short",
1911 [TOK_SIGNED      ] = "signed",
1912 [TOK_SIZEOF      ] = "sizeof",
1913 [TOK_STATIC      ] = "static",
1914 [TOK_STRUCT      ] = "struct",
1915 [TOK_SWITCH      ] = "switch",
1916 [TOK_TYPEDEF     ] = "typedef",
1917 [TOK_UNION       ] = "union",
1918 [TOK_UNSIGNED    ] = "unsigned",
1919 [TOK_VOID        ] = "void",
1920 [TOK_VOLATILE    ] = "volatile",
1921 [TOK_WHILE       ] = "while",
1922 [TOK_ASM         ] = "asm",
1923 [TOK_ATTRIBUTE   ] = "__attribute__",
1924 [TOK_ALIGNOF     ] = "__alignof__",
1925
1926 [TOK_DEFINE      ] = "define",
1927 [TOK_UNDEF       ] = "undef",
1928 [TOK_INCLUDE     ] = "include",
1929 [TOK_LINE        ] = "line",
1930 [TOK_ERROR       ] = "error",
1931 [TOK_WARNING     ] = "warning",
1932 [TOK_PRAGMA      ] = "pragma",
1933 [TOK_IFDEF       ] = "ifdef",
1934 [TOK_IFNDEF      ] = "ifndef",
1935 [TOK_ELIF        ] = "elif",
1936 [TOK_ENDIF       ] = "endif",
1937
1938 [TOK_EOF         ] = "EOF",
1939 };
1940
1941 static unsigned int hash(const char *str, int str_len)
1942 {
1943         unsigned int hash;
1944         const char *end;
1945         end = str + str_len;
1946         hash = 0;
1947         for(; str < end; str++) {
1948                 hash = (hash *263) + *str;
1949         }
1950         hash = hash & (HASH_TABLE_SIZE -1);
1951         return hash;
1952 }
1953
1954 static struct hash_entry *lookup(
1955         struct compile_state *state, const char *name, int name_len)
1956 {
1957         struct hash_entry *entry;
1958         unsigned int index;
1959         index = hash(name, name_len);
1960         entry = state->hash_table[index];
1961         while(entry && 
1962                 ((entry->name_len != name_len) ||
1963                         (memcmp(entry->name, name, name_len) != 0))) {
1964                 entry = entry->next;
1965         }
1966         if (!entry) {
1967                 char *new_name;
1968                 /* Get a private copy of the name */
1969                 new_name = xmalloc(name_len + 1, "hash_name");
1970                 memcpy(new_name, name, name_len);
1971                 new_name[name_len] = '\0';
1972
1973                 /* Create a new hash entry */
1974                 entry = xcmalloc(sizeof(*entry), "hash_entry");
1975                 entry->next = state->hash_table[index];
1976                 entry->name = new_name;
1977                 entry->name_len = name_len;
1978
1979                 /* Place the new entry in the hash table */
1980                 state->hash_table[index] = entry;
1981         }
1982         return entry;
1983 }
1984
1985 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1986 {
1987         struct hash_entry *entry;
1988         entry = tk->ident;
1989         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1990                 (entry->tok == TOK_ENUM_CONST) ||
1991                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
1992                         (entry->tok <= TOK_LAST_KEYWORD)))) {
1993                 tk->tok = entry->tok;
1994         }
1995 }
1996
1997 static void ident_to_macro(struct compile_state *state, struct token *tk)
1998 {
1999         struct hash_entry *entry;
2000         entry = tk->ident;
2001         if (entry && 
2002                 (entry->tok >= TOK_FIRST_MACRO) &&
2003                 (entry->tok <= TOK_LAST_MACRO)) {
2004                 tk->tok = entry->tok;
2005         }
2006 }
2007
2008 static void hash_keyword(
2009         struct compile_state *state, const char *keyword, int tok)
2010 {
2011         struct hash_entry *entry;
2012         entry = lookup(state, keyword, strlen(keyword));
2013         if (entry && entry->tok != TOK_UNKNOWN) {
2014                 die("keyword %s already hashed", keyword);
2015         }
2016         entry->tok  = tok;
2017 }
2018
2019 static void symbol(
2020         struct compile_state *state, struct hash_entry *ident,
2021         struct symbol **chain, struct triple *def, struct type *type)
2022 {
2023         struct symbol *sym;
2024         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2025                 error(state, 0, "%s already defined", ident->name);
2026         }
2027         sym = xcmalloc(sizeof(*sym), "symbol");
2028         sym->ident = ident;
2029         sym->def   = def;
2030         sym->type  = type;
2031         sym->scope_depth = state->scope_depth;
2032         sym->next = *chain;
2033         *chain    = sym;
2034 }
2035
2036 static void start_scope(struct compile_state *state)
2037 {
2038         state->scope_depth++;
2039 }
2040
2041 static void end_scope_syms(struct symbol **chain, int depth)
2042 {
2043         struct symbol *sym, *next;
2044         sym = *chain;
2045         while(sym && (sym->scope_depth == depth)) {
2046                 next = sym->next;
2047                 xfree(sym);
2048                 sym = next;
2049         }
2050         *chain = sym;
2051 }
2052
2053 static void end_scope(struct compile_state *state)
2054 {
2055         int i;
2056         int depth;
2057         /* Walk through the hash table and remove all symbols
2058          * in the current scope. 
2059          */
2060         depth = state->scope_depth;
2061         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2062                 struct hash_entry *entry;
2063                 entry = state->hash_table[i];
2064                 while(entry) {
2065                         end_scope_syms(&entry->sym_label,  depth);
2066                         end_scope_syms(&entry->sym_struct, depth);
2067                         end_scope_syms(&entry->sym_ident,  depth);
2068                         entry = entry->next;
2069                 }
2070         }
2071         state->scope_depth = depth - 1;
2072 }
2073
2074 static void register_keywords(struct compile_state *state)
2075 {
2076         hash_keyword(state, "auto",          TOK_AUTO);
2077         hash_keyword(state, "break",         TOK_BREAK);
2078         hash_keyword(state, "case",          TOK_CASE);
2079         hash_keyword(state, "char",          TOK_CHAR);
2080         hash_keyword(state, "const",         TOK_CONST);
2081         hash_keyword(state, "continue",      TOK_CONTINUE);
2082         hash_keyword(state, "default",       TOK_DEFAULT);
2083         hash_keyword(state, "do",            TOK_DO);
2084         hash_keyword(state, "double",        TOK_DOUBLE);
2085         hash_keyword(state, "else",          TOK_ELSE);
2086         hash_keyword(state, "enum",          TOK_ENUM);
2087         hash_keyword(state, "extern",        TOK_EXTERN);
2088         hash_keyword(state, "float",         TOK_FLOAT);
2089         hash_keyword(state, "for",           TOK_FOR);
2090         hash_keyword(state, "goto",          TOK_GOTO);
2091         hash_keyword(state, "if",            TOK_IF);
2092         hash_keyword(state, "inline",        TOK_INLINE);
2093         hash_keyword(state, "int",           TOK_INT);
2094         hash_keyword(state, "long",          TOK_LONG);
2095         hash_keyword(state, "register",      TOK_REGISTER);
2096         hash_keyword(state, "restrict",      TOK_RESTRICT);
2097         hash_keyword(state, "return",        TOK_RETURN);
2098         hash_keyword(state, "short",         TOK_SHORT);
2099         hash_keyword(state, "signed",        TOK_SIGNED);
2100         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2101         hash_keyword(state, "static",        TOK_STATIC);
2102         hash_keyword(state, "struct",        TOK_STRUCT);
2103         hash_keyword(state, "switch",        TOK_SWITCH);
2104         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2105         hash_keyword(state, "union",         TOK_UNION);
2106         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2107         hash_keyword(state, "void",          TOK_VOID);
2108         hash_keyword(state, "volatile",      TOK_VOLATILE);
2109         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2110         hash_keyword(state, "while",         TOK_WHILE);
2111         hash_keyword(state, "asm",           TOK_ASM);
2112         hash_keyword(state, "__asm__",       TOK_ASM);
2113         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2114         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2115 }
2116
2117 static void register_macro_keywords(struct compile_state *state)
2118 {
2119         hash_keyword(state, "define",        TOK_DEFINE);
2120         hash_keyword(state, "undef",         TOK_UNDEF);
2121         hash_keyword(state, "include",       TOK_INCLUDE);
2122         hash_keyword(state, "line",          TOK_LINE);
2123         hash_keyword(state, "error",         TOK_ERROR);
2124         hash_keyword(state, "warning",       TOK_WARNING);
2125         hash_keyword(state, "pragma",        TOK_PRAGMA);
2126         hash_keyword(state, "ifdef",         TOK_IFDEF);
2127         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2128         hash_keyword(state, "elif",          TOK_ELIF);
2129         hash_keyword(state, "endif",         TOK_ENDIF);
2130 }
2131
2132 static int spacep(int c)
2133 {
2134         int ret = 0;
2135         switch(c) {
2136         case ' ':
2137         case '\t':
2138         case '\f':
2139         case '\v':
2140         case '\r':
2141         case '\n':
2142                 ret = 1;
2143                 break;
2144         }
2145         return ret;
2146 }
2147
2148 static int digitp(int c)
2149 {
2150         int ret = 0;
2151         switch(c) {
2152         case '0': case '1': case '2': case '3': case '4': 
2153         case '5': case '6': case '7': case '8': case '9':
2154                 ret = 1;
2155                 break;
2156         }
2157         return ret;
2158 }
2159
2160 static int hexdigitp(int c)
2161 {
2162         int ret = 0;
2163         switch(c) {
2164         case '0': case '1': case '2': case '3': case '4': 
2165         case '5': case '6': case '7': case '8': case '9':
2166         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2167         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2168                 ret = 1;
2169                 break;
2170         }
2171         return ret;
2172 }
2173 static int hexdigval(int c) 
2174 {
2175         int val = -1;
2176         if ((c >= '0') && (c <= '9')) {
2177                 val = c - '0';
2178         }
2179         else if ((c >= 'A') && (c <= 'F')) {
2180                 val = 10 + (c - 'A');
2181         }
2182         else if ((c >= 'a') && (c <= 'f')) {
2183                 val = 10 + (c - 'a');
2184         }
2185         return val;
2186 }
2187
2188 static int octdigitp(int c)
2189 {
2190         int ret = 0;
2191         switch(c) {
2192         case '0': case '1': case '2': case '3': 
2193         case '4': case '5': case '6': case '7':
2194                 ret = 1;
2195                 break;
2196         }
2197         return ret;
2198 }
2199 static int octdigval(int c)
2200 {
2201         int val = -1;
2202         if ((c >= '0') && (c <= '7')) {
2203                 val = c - '0';
2204         }
2205         return val;
2206 }
2207
2208 static int letterp(int c)
2209 {
2210         int ret = 0;
2211         switch(c) {
2212         case 'a': case 'b': case 'c': case 'd': case 'e':
2213         case 'f': case 'g': case 'h': case 'i': case 'j':
2214         case 'k': case 'l': case 'm': case 'n': case 'o':
2215         case 'p': case 'q': case 'r': case 's': case 't':
2216         case 'u': case 'v': case 'w': case 'x': case 'y':
2217         case 'z':
2218         case 'A': case 'B': case 'C': case 'D': case 'E':
2219         case 'F': case 'G': case 'H': case 'I': case 'J':
2220         case 'K': case 'L': case 'M': case 'N': case 'O':
2221         case 'P': case 'Q': case 'R': case 'S': case 'T':
2222         case 'U': case 'V': case 'W': case 'X': case 'Y':
2223         case 'Z':
2224         case '_':
2225                 ret = 1;
2226                 break;
2227         }
2228         return ret;
2229 }
2230
2231 static int char_value(struct compile_state *state,
2232         const signed char **strp, const signed char *end)
2233 {
2234         const signed char *str;
2235         int c;
2236         str = *strp;
2237         c = *str++;
2238         if ((c == '\\') && (str < end)) {
2239                 switch(*str) {
2240                 case 'n':  c = '\n'; str++; break;
2241                 case 't':  c = '\t'; str++; break;
2242                 case 'v':  c = '\v'; str++; break;
2243                 case 'b':  c = '\b'; str++; break;
2244                 case 'r':  c = '\r'; str++; break;
2245                 case 'f':  c = '\f'; str++; break;
2246                 case 'a':  c = '\a'; str++; break;
2247                 case '\\': c = '\\'; str++; break;
2248                 case '?':  c = '?';  str++; break;
2249                 case '\'': c = '\''; str++; break;
2250                 case '"':  c = '"';  break;
2251                 case 'x': 
2252                         c = 0;
2253                         str++;
2254                         while((str < end) && hexdigitp(*str)) {
2255                                 c <<= 4;
2256                                 c += hexdigval(*str);
2257                                 str++;
2258                         }
2259                         break;
2260                 case '0': case '1': case '2': case '3': 
2261                 case '4': case '5': case '6': case '7':
2262                         c = 0;
2263                         while((str < end) && octdigitp(*str)) {
2264                                 c <<= 3;
2265                                 c += octdigval(*str);
2266                                 str++;
2267                         }
2268                         break;
2269                 default:
2270                         error(state, 0, "Invalid character constant");
2271                         break;
2272                 }
2273         }
2274         *strp = str;
2275         return c;
2276 }
2277
2278 static char *after_digits(char *ptr, char *end)
2279 {
2280         while((ptr < end) && digitp(*ptr)) {
2281                 ptr++;
2282         }
2283         return ptr;
2284 }
2285
2286 static char *after_octdigits(char *ptr, char *end)
2287 {
2288         while((ptr < end) && octdigitp(*ptr)) {
2289                 ptr++;
2290         }
2291         return ptr;
2292 }
2293
2294 static char *after_hexdigits(char *ptr, char *end)
2295 {
2296         while((ptr < end) && hexdigitp(*ptr)) {
2297                 ptr++;
2298         }
2299         return ptr;
2300 }
2301
2302 static void save_string(struct compile_state *state, 
2303         struct token *tk, char *start, char *end, const char *id)
2304 {
2305         char *str;
2306         int str_len;
2307         /* Create a private copy of the string */
2308         str_len = end - start + 1;
2309         str = xmalloc(str_len + 1, id);
2310         memcpy(str, start, str_len);
2311         str[str_len] = '\0';
2312
2313         /* Store the copy in the token */
2314         tk->val.str = str;
2315         tk->str_len = str_len;
2316 }
2317 static void next_token(struct compile_state *state, int index)
2318 {
2319         struct file_state *file;
2320         struct token *tk;
2321         char *token;
2322         int c, c1, c2, c3;
2323         char *tokp, *end;
2324         int tok;
2325 next_token:
2326         file = state->file;
2327         tk = &state->token[index];
2328         tk->str_len = 0;
2329         tk->ident = 0;
2330         token = tokp = file->pos;
2331         end = file->buf + file->size;
2332         tok = TOK_UNKNOWN;
2333         c = -1;
2334         if (tokp < end) {
2335                 c = *tokp;
2336         }
2337         c1 = -1;
2338         if ((tokp + 1) < end) {
2339                 c1 = tokp[1];
2340         }
2341         c2 = -1;
2342         if ((tokp + 2) < end) {
2343                 c2 = tokp[2];
2344         }
2345         c3 = -1;
2346         if ((tokp + 3) < end) {
2347                 c3 = tokp[3];
2348         }
2349         if (tokp >= end) {
2350                 tok = TOK_EOF;
2351                 tokp = end;
2352         }
2353         /* Whitespace */
2354         else if (spacep(c)) {
2355                 tok = TOK_SPACE;
2356                 while ((tokp < end) && spacep(c)) {
2357                         if (c == '\n') {
2358                                 file->line++;
2359                                 file->line_start = tokp + 1;
2360                         }
2361                         c = *(++tokp);
2362                 }
2363                 if (!spacep(c)) {
2364                         tokp--;
2365                 }
2366         }
2367         /* EOL Comments */
2368         else if ((c == '/') && (c1 == '/')) {
2369                 tok = TOK_SPACE;
2370                 for(tokp += 2; tokp < end; tokp++) {
2371                         c = *tokp;
2372                         if (c == '\n') {
2373                                 file->line++;
2374                                 file->line_start = tokp +1;
2375                                 break;
2376                         }
2377                 }
2378         }
2379         /* Comments */
2380         else if ((c == '/') && (c1 == '*')) {
2381                 int line;
2382                 char *line_start;
2383                 line = file->line;
2384                 line_start = file->line_start;
2385                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2386                         c = *tokp;
2387                         if (c == '\n') {
2388                                 line++;
2389                                 line_start = tokp +1;
2390                         }
2391                         else if ((c == '*') && (tokp[1] == '/')) {
2392                                 tok = TOK_SPACE;
2393                                 tokp += 1;
2394                                 break;
2395                         }
2396                 }
2397                 if (tok == TOK_UNKNOWN) {
2398                         error(state, 0, "unterminated comment");
2399                 }
2400                 file->line = line;
2401                 file->line_start = line_start;
2402         }
2403         /* string constants */
2404         else if ((c == '"') ||
2405                 ((c == 'L') && (c1 == '"'))) {
2406                 int line;
2407                 char *line_start;
2408                 int wchar;
2409                 line = file->line;
2410                 line_start = file->line_start;
2411                 wchar = 0;
2412                 if (c == 'L') {
2413                         wchar = 1;
2414                         tokp++;
2415                 }
2416                 for(tokp += 1; tokp < end; tokp++) {
2417                         c = *tokp;
2418                         if (c == '\n') {
2419                                 line++;
2420                                 line_start = tokp + 1;
2421                         }
2422                         else if ((c == '\\') && (tokp +1 < end)) {
2423                                 tokp++;
2424                         }
2425                         else if (c == '"') {
2426                                 tok = TOK_LIT_STRING;
2427                                 break;
2428                         }
2429                 }
2430                 if (tok == TOK_UNKNOWN) {
2431                         error(state, 0, "unterminated string constant");
2432                 }
2433                 if (line != file->line) {
2434                         warning(state, 0, "multiline string constant");
2435                 }
2436                 file->line = line;
2437                 file->line_start = line_start;
2438
2439                 /* Save the string value */
2440                 save_string(state, tk, token, tokp, "literal string");
2441         }
2442         /* character constants */
2443         else if ((c == '\'') ||
2444                 ((c == 'L') && (c1 == '\''))) {
2445                 int line;
2446                 char *line_start;
2447                 int wchar;
2448                 line = file->line;
2449                 line_start = file->line_start;
2450                 wchar = 0;
2451                 if (c == 'L') {
2452                         wchar = 1;
2453                         tokp++;
2454                 }
2455                 for(tokp += 1; tokp < end; tokp++) {
2456                         c = *tokp;
2457                         if (c == '\n') {
2458                                 line++;
2459                                 line_start = tokp + 1;
2460                         }
2461                         else if ((c == '\\') && (tokp +1 < end)) {
2462                                 tokp++;
2463                         }
2464                         else if (c == '\'') {
2465                                 tok = TOK_LIT_CHAR;
2466                                 break;
2467                         }
2468                 }
2469                 if (tok == TOK_UNKNOWN) {
2470                         error(state, 0, "unterminated character constant");
2471                 }
2472                 if (line != file->line) {
2473                         warning(state, 0, "multiline character constant");
2474                 }
2475                 file->line = line;
2476                 file->line_start = line_start;
2477
2478                 /* Save the character value */
2479                 save_string(state, tk, token, tokp, "literal character");
2480         }
2481         /* integer and floating constants 
2482          * Integer Constants
2483          * {digits}
2484          * 0[Xx]{hexdigits}
2485          * 0{octdigit}+
2486          * 
2487          * Floating constants
2488          * {digits}.{digits}[Ee][+-]?{digits}
2489          * {digits}.{digits}
2490          * {digits}[Ee][+-]?{digits}
2491          * .{digits}[Ee][+-]?{digits}
2492          * .{digits}
2493          */
2494         
2495         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2496                 char *next, *new;
2497                 int is_float;
2498                 is_float = 0;
2499                 if (c != '.') {
2500                         next = after_digits(tokp, end);
2501                 }
2502                 else {
2503                         next = tokp;
2504                 }
2505                 if (next[0] == '.') {
2506                         new = after_digits(next, end);
2507                         is_float = (new != next);
2508                         next = new;
2509                 }
2510                 if ((next[0] == 'e') || (next[0] == 'E')) {
2511                         if (((next + 1) < end) && 
2512                                 ((next[1] == '+') || (next[1] == '-'))) {
2513                                 next++;
2514                         }
2515                         new = after_digits(next, end);
2516                         is_float = (new != next);
2517                         next = new;
2518                 }
2519                 if (is_float) {
2520                         tok = TOK_LIT_FLOAT;
2521                         if ((next < end) && (
2522                                 (next[0] == 'f') ||
2523                                 (next[0] == 'F') ||
2524                                 (next[0] == 'l') ||
2525                                 (next[0] == 'L'))
2526                                 ) {
2527                                 next++;
2528                         }
2529                 }
2530                 if (!is_float && digitp(c)) {
2531                         tok = TOK_LIT_INT;
2532                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2533                                 next = after_hexdigits(tokp + 2, end);
2534                         }
2535                         else if (c == '0') {
2536                                 next = after_octdigits(tokp, end);
2537                         }
2538                         else {
2539                                 next = after_digits(tokp, end);
2540                         }
2541                         /* crazy integer suffixes */
2542                         if ((next < end) && 
2543                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2544                                 next++;
2545                                 if ((next < end) &&
2546                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2547                                         next++;
2548                                 }
2549                         }
2550                         else if ((next < end) &&
2551                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2552                                 next++;
2553                                 if ((next < end) && 
2554                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2555                                         next++;
2556                                 }
2557                         }
2558                 }
2559                 tokp = next - 1;
2560
2561                 /* Save the integer/floating point value */
2562                 save_string(state, tk, token, tokp, "literal number");
2563         }
2564         /* identifiers */
2565         else if (letterp(c)) {
2566                 tok = TOK_IDENT;
2567                 for(tokp += 1; tokp < end; tokp++) {
2568                         c = *tokp;
2569                         if (!letterp(c) && !digitp(c)) {
2570                                 break;
2571                         }
2572                 }
2573                 tokp -= 1;
2574                 tk->ident = lookup(state, token, tokp +1 - token);
2575         }
2576         /* C99 alternate macro characters */
2577         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2578                 tokp += 3; 
2579                 tok = TOK_CONCATENATE; 
2580         }
2581         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2582         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2583         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2584         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2585         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2586         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2587         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2588         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2589         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2590         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2591         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2592         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2593         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2594         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2595         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2596         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2597         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2598         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2599         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2600         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2601         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2602         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2603         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2604         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2605         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2606         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2607         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2608         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2609         else if (c == ';') { tok = TOK_SEMI; }
2610         else if (c == '{') { tok = TOK_LBRACE; }
2611         else if (c == '}') { tok = TOK_RBRACE; }
2612         else if (c == ',') { tok = TOK_COMMA; }
2613         else if (c == '=') { tok = TOK_EQ; }
2614         else if (c == ':') { tok = TOK_COLON; }
2615         else if (c == '[') { tok = TOK_LBRACKET; }
2616         else if (c == ']') { tok = TOK_RBRACKET; }
2617         else if (c == '(') { tok = TOK_LPAREN; }
2618         else if (c == ')') { tok = TOK_RPAREN; }
2619         else if (c == '*') { tok = TOK_STAR; }
2620         else if (c == '>') { tok = TOK_MORE; }
2621         else if (c == '<') { tok = TOK_LESS; }
2622         else if (c == '?') { tok = TOK_QUEST; }
2623         else if (c == '|') { tok = TOK_OR; }
2624         else if (c == '&') { tok = TOK_AND; }
2625         else if (c == '^') { tok = TOK_XOR; }
2626         else if (c == '+') { tok = TOK_PLUS; }
2627         else if (c == '-') { tok = TOK_MINUS; }
2628         else if (c == '/') { tok = TOK_DIV; }
2629         else if (c == '%') { tok = TOK_MOD; }
2630         else if (c == '!') { tok = TOK_BANG; }
2631         else if (c == '.') { tok = TOK_DOT; }
2632         else if (c == '~') { tok = TOK_TILDE; }
2633         else if (c == '#') { tok = TOK_MACRO; }
2634         if (tok == TOK_MACRO) {
2635                 /* Only match preprocessor directives at the start of a line */
2636                 char *ptr;
2637                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2638                         ;
2639                 if (ptr != tokp) {
2640                         tok = TOK_UNKNOWN;
2641                 }
2642         }
2643         if (tok == TOK_UNKNOWN) {
2644                 error(state, 0, "unknown token");
2645         }
2646
2647         file->pos = tokp + 1;
2648         tk->tok = tok;
2649         if (tok == TOK_IDENT) {
2650                 ident_to_keyword(state, tk);
2651         }
2652         /* Don't return space tokens. */
2653         if (tok == TOK_SPACE) {
2654                 goto next_token;
2655         }
2656 }
2657
2658 static void compile_macro(struct compile_state *state, struct token *tk)
2659 {
2660         struct file_state *file;
2661         struct hash_entry *ident;
2662         ident = tk->ident;
2663         file = xmalloc(sizeof(*file), "file_state");
2664         file->basename = xstrdup(tk->ident->name);
2665         file->dirname = xstrdup("");
2666         file->size = ident->sym_define->buf_len;
2667         file->buf = xmalloc(file->size +2,  file->basename);
2668         memcpy(file->buf, ident->sym_define->buf, file->size);
2669         file->buf[file->size] = '\n';
2670         file->buf[file->size + 1] = '\0';
2671         file->pos = file->buf;
2672         file->line_start = file->pos;
2673         file->line = 1;
2674         file->prev = state->file;
2675         state->file = file;
2676 }
2677
2678
2679 static int mpeek(struct compile_state *state, int index)
2680 {
2681         struct token *tk;
2682         int rescan;
2683         tk = &state->token[index + 1];
2684         if (tk->tok == -1) {
2685                 next_token(state, index + 1);
2686         }
2687         do {
2688                 rescan = 0;
2689                 if ((tk->tok == TOK_EOF) && 
2690                         (state->file != state->macro_file) &&
2691                         (state->file->prev)) {
2692                         struct file_state *file = state->file;
2693                         state->file = file->prev;
2694                         /* file->basename is used keep it */
2695                         xfree(file->dirname);
2696                         xfree(file->buf);
2697                         xfree(file);
2698                         next_token(state, index + 1);
2699                         rescan = 1;
2700                 }
2701                 else if (tk->ident && tk->ident->sym_define) {
2702                         compile_macro(state, tk);
2703                         next_token(state, index + 1);
2704                         rescan = 1;
2705                 }
2706         } while(rescan);
2707         /* Don't show the token on the next line */
2708         if (state->macro_line < state->macro_file->line) {
2709                 return TOK_EOF;
2710         }
2711         return state->token[index +1].tok;
2712 }
2713
2714 static void meat(struct compile_state *state, int index, int tok)
2715 {
2716         int next_tok;
2717         int i;
2718         next_tok = mpeek(state, index);
2719         if (next_tok != tok) {
2720                 const char *name1, *name2;
2721                 name1 = tokens[next_tok];
2722                 name2 = "";
2723                 if (next_tok == TOK_IDENT) {
2724                         name2 = state->token[index + 1].ident->name;
2725                 }
2726                 error(state, 0, "found %s %s expected %s", 
2727                         name1, name2, tokens[tok]);
2728         }
2729         /* Free the old token value */
2730         if (state->token[index].str_len) {
2731                 memset((void *)(state->token[index].val.str), -1, 
2732                         state->token[index].str_len);
2733                 xfree(state->token[index].val.str);
2734         }
2735         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2736                 state->token[i] = state->token[i + 1];
2737         }
2738         memset(&state->token[i], 0, sizeof(state->token[i]));
2739         state->token[i].tok = -1;
2740 }
2741
2742 static long_t mcexpr(struct compile_state *state, int index);
2743
2744 static long_t mprimary_expr(struct compile_state *state, int index)
2745 {
2746         long_t val;
2747         int tok;
2748         tok = mpeek(state, index);
2749         while(state->token[index + 1].ident && 
2750                 state->token[index + 1].ident->sym_define) {
2751                 meat(state, index, tok);
2752                 compile_macro(state, &state->token[index]);
2753                 tok = mpeek(state, index);
2754         }
2755         switch(tok) {
2756         case TOK_LPAREN:
2757                 meat(state, index, TOK_LPAREN);
2758                 val = mcexpr(state, index);
2759                 meat(state, index, TOK_RPAREN);
2760                 break;
2761         case TOK_LIT_INT:
2762         {
2763                 char *end;
2764                 meat(state, index, TOK_LIT_INT);
2765                 errno = 0;
2766                 val = strtol(state->token[index].val.str, &end, 0);
2767                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2768                         (errno == ERANGE)) {
2769                         error(state, 0, "Integer constant to large");
2770                 }
2771                 break;
2772         }
2773         default:
2774                 meat(state, index, TOK_LIT_INT);
2775                 val = 0;
2776         }
2777         return val;
2778 }
2779 static long_t munary_expr(struct compile_state *state, int index)
2780 {
2781         long_t val;
2782         switch(mpeek(state, index)) {
2783         case TOK_PLUS:
2784                 meat(state, index, TOK_PLUS);
2785                 val = munary_expr(state, index);
2786                 val = + val;
2787                 break;
2788         case TOK_MINUS:
2789                 meat(state, index, TOK_MINUS);
2790                 val = munary_expr(state, index);
2791                 val = - val;
2792                 break;
2793         case TOK_TILDE:
2794                 meat(state, index, TOK_BANG);
2795                 val = munary_expr(state, index);
2796                 val = ~ val;
2797                 break;
2798         case TOK_BANG:
2799                 meat(state, index, TOK_BANG);
2800                 val = munary_expr(state, index);
2801                 val = ! val;
2802                 break;
2803         default:
2804                 val = mprimary_expr(state, index);
2805                 break;
2806         }
2807         return val;
2808         
2809 }
2810 static long_t mmul_expr(struct compile_state *state, int index)
2811 {
2812         long_t val;
2813         int done;
2814         val = munary_expr(state, index);
2815         do {
2816                 long_t right;
2817                 done = 0;
2818                 switch(mpeek(state, index)) {
2819                 case TOK_STAR:
2820                         meat(state, index, TOK_STAR);
2821                         right = munary_expr(state, index);
2822                         val = val * right;
2823                         break;
2824                 case TOK_DIV:
2825                         meat(state, index, TOK_DIV);
2826                         right = munary_expr(state, index);
2827                         val = val / right;
2828                         break;
2829                 case TOK_MOD:
2830                         meat(state, index, TOK_MOD);
2831                         right = munary_expr(state, index);
2832                         val = val % right;
2833                         break;
2834                 default:
2835                         done = 1;
2836                         break;
2837                 }
2838         } while(!done);
2839
2840         return val;
2841 }
2842
2843 static long_t madd_expr(struct compile_state *state, int index)
2844 {
2845         long_t val;
2846         int done;
2847         val = mmul_expr(state, index);
2848         do {
2849                 long_t right;
2850                 done = 0;
2851                 switch(mpeek(state, index)) {
2852                 case TOK_PLUS:
2853                         meat(state, index, TOK_PLUS);
2854                         right = mmul_expr(state, index);
2855                         val = val + right;
2856                         break;
2857                 case TOK_MINUS:
2858                         meat(state, index, TOK_MINUS);
2859                         right = mmul_expr(state, index);
2860                         val = val - right;
2861                         break;
2862                 default:
2863                         done = 1;
2864                         break;
2865                 }
2866         } while(!done);
2867
2868         return val;
2869 }
2870
2871 static long_t mshift_expr(struct compile_state *state, int index)
2872 {
2873         long_t val;
2874         int done;
2875         val = madd_expr(state, index);
2876         do {
2877                 long_t right;
2878                 done = 0;
2879                 switch(mpeek(state, index)) {
2880                 case TOK_SL:
2881                         meat(state, index, TOK_SL);
2882                         right = madd_expr(state, index);
2883                         val = val << right;
2884                         break;
2885                 case TOK_SR:
2886                         meat(state, index, TOK_SR);
2887                         right = madd_expr(state, index);
2888                         val = val >> right;
2889                         break;
2890                 default:
2891                         done = 1;
2892                         break;
2893                 }
2894         } while(!done);
2895
2896         return val;
2897 }
2898
2899 static long_t mrel_expr(struct compile_state *state, int index)
2900 {
2901         long_t val;
2902         int done;
2903         val = mshift_expr(state, index);
2904         do {
2905                 long_t right;
2906                 done = 0;
2907                 switch(mpeek(state, index)) {
2908                 case TOK_LESS:
2909                         meat(state, index, TOK_LESS);
2910                         right = mshift_expr(state, index);
2911                         val = val < right;
2912                         break;
2913                 case TOK_MORE:
2914                         meat(state, index, TOK_MORE);
2915                         right = mshift_expr(state, index);
2916                         val = val > right;
2917                         break;
2918                 case TOK_LESSEQ:
2919                         meat(state, index, TOK_LESSEQ);
2920                         right = mshift_expr(state, index);
2921                         val = val <= right;
2922                         break;
2923                 case TOK_MOREEQ:
2924                         meat(state, index, TOK_MOREEQ);
2925                         right = mshift_expr(state, index);
2926                         val = val >= right;
2927                         break;
2928                 default:
2929                         done = 1;
2930                         break;
2931                 }
2932         } while(!done);
2933         return val;
2934 }
2935
2936 static long_t meq_expr(struct compile_state *state, int index)
2937 {
2938         long_t val;
2939         int done;
2940         val = mrel_expr(state, index);
2941         do {
2942                 long_t right;
2943                 done = 0;
2944                 switch(mpeek(state, index)) {
2945                 case TOK_EQEQ:
2946                         meat(state, index, TOK_EQEQ);
2947                         right = mrel_expr(state, index);
2948                         val = val == right;
2949                         break;
2950                 case TOK_NOTEQ:
2951                         meat(state, index, TOK_NOTEQ);
2952                         right = mrel_expr(state, index);
2953                         val = val != right;
2954                         break;
2955                 default:
2956                         done = 1;
2957                         break;
2958                 }
2959         } while(!done);
2960         return val;
2961 }
2962
2963 static long_t mand_expr(struct compile_state *state, int index)
2964 {
2965         long_t val;
2966         val = meq_expr(state, index);
2967         if (mpeek(state, index) == TOK_AND) {
2968                 long_t right;
2969                 meat(state, index, TOK_AND);
2970                 right = meq_expr(state, index);
2971                 val = val & right;
2972         }
2973         return val;
2974 }
2975
2976 static long_t mxor_expr(struct compile_state *state, int index)
2977 {
2978         long_t val;
2979         val = mand_expr(state, index);
2980         if (mpeek(state, index) == TOK_XOR) {
2981                 long_t right;
2982                 meat(state, index, TOK_XOR);
2983                 right = mand_expr(state, index);
2984                 val = val ^ right;
2985         }
2986         return val;
2987 }
2988
2989 static long_t mor_expr(struct compile_state *state, int index)
2990 {
2991         long_t val;
2992         val = mxor_expr(state, index);
2993         if (mpeek(state, index) == TOK_OR) {
2994                 long_t right;
2995                 meat(state, index, TOK_OR);
2996                 right = mxor_expr(state, index);
2997                 val = val | right;
2998         }
2999         return val;
3000 }
3001
3002 static long_t mland_expr(struct compile_state *state, int index)
3003 {
3004         long_t val;
3005         val = mor_expr(state, index);
3006         if (mpeek(state, index) == TOK_LOGAND) {
3007                 long_t right;
3008                 meat(state, index, TOK_LOGAND);
3009                 right = mor_expr(state, index);
3010                 val = val && right;
3011         }
3012         return val;
3013 }
3014 static long_t mlor_expr(struct compile_state *state, int index)
3015 {
3016         long_t val;
3017         val = mland_expr(state, index);
3018         if (mpeek(state, index) == TOK_LOGOR) {
3019                 long_t right;
3020                 meat(state, index, TOK_LOGOR);
3021                 right = mland_expr(state, index);
3022                 val = val || right;
3023         }
3024         return val;
3025 }
3026
3027 static long_t mcexpr(struct compile_state *state, int index)
3028 {
3029         return mlor_expr(state, index);
3030 }
3031 static void preprocess(struct compile_state *state, int index)
3032 {
3033         /* Doing much more with the preprocessor would require
3034          * a parser and a major restructuring.
3035          * Postpone that for later.
3036          */
3037         struct file_state *file;
3038         struct token *tk;
3039         int line;
3040         int tok;
3041         
3042         file = state->file;
3043         tk = &state->token[index];
3044         state->macro_line = line = file->line;
3045         state->macro_file = file;
3046
3047         next_token(state, index);
3048         ident_to_macro(state, tk);
3049         if (tk->tok == TOK_IDENT) {
3050                 error(state, 0, "undefined preprocessing directive `%s'",
3051                         tk->ident->name);
3052         }
3053         switch(tk->tok) {
3054         case TOK_UNDEF:
3055         case TOK_LINE:
3056         case TOK_PRAGMA:
3057                 if (state->if_value < 0) {
3058                         break;
3059                 }
3060                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3061                         tk->ident->name);
3062                 break;
3063         case TOK_ELIF:
3064                 error(state, 0, "#elif not supported");
3065 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3066                 if (state->if_depth == 0) {
3067                         error(state, 0, "#elif without #if");
3068                 }
3069                 /* If the #if was taken the #elif just disables the following code */
3070                 if (state->if_value >= 0) {
3071                         state->if_value = - state->if_value;
3072                 }
3073                 /* If the previous #if was not taken see if the #elif enables the 
3074                  * trailing code.
3075                  */
3076                 else if ((state->if_value < 0) && 
3077                         (state->if_depth == - state->if_value))
3078                 {
3079                         if (mcexpr(state, index) != 0) {
3080                                 state->if_value = state->if_depth;
3081                         }
3082                         else {
3083                                 state->if_value = - state->if_depth;
3084                         }
3085                 }
3086                 break;
3087         case TOK_IF:
3088                 state->if_depth++;
3089                 if (state->if_value < 0) {
3090                         break;
3091                 }
3092                 if (mcexpr(state, index) != 0) {
3093                         state->if_value = state->if_depth;
3094                 }
3095                 else {
3096                         state->if_value = - state->if_depth;
3097                 }
3098                 break;
3099         case TOK_IFNDEF:
3100                 state->if_depth++;
3101                 if (state->if_value < 0) {
3102                         break;
3103                 }
3104                 next_token(state, index);
3105                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3106                         error(state, 0, "Invalid macro name");
3107                 }
3108                 if (tk->ident->sym_define == 0) {
3109                         state->if_value = state->if_depth;
3110                 } 
3111                 else {
3112                         state->if_value = - state->if_depth;
3113                 }
3114                 break;
3115         case TOK_IFDEF:
3116                 state->if_depth++;
3117                 if (state->if_value < 0) {
3118                         break;
3119                 }
3120                 next_token(state, index);
3121                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3122                         error(state, 0, "Invalid macro name");
3123                 }
3124                 if (tk->ident->sym_define != 0) {
3125                         state->if_value = state->if_depth;
3126                 }
3127                 else {
3128                         state->if_value = - state->if_depth;
3129                 }
3130                 break;
3131         case TOK_ELSE:
3132                 if (state->if_depth == 0) {
3133                         error(state, 0, "#else without #if");
3134                 }
3135                 if ((state->if_value >= 0) ||
3136                         ((state->if_value < 0) && 
3137                                 (state->if_depth == -state->if_value)))
3138                 {
3139                         state->if_value = - state->if_value;
3140                 }
3141                 break;
3142         case TOK_ENDIF:
3143                 if (state->if_depth == 0) {
3144                         error(state, 0, "#endif without #if");
3145                 }
3146                 if ((state->if_value >= 0) ||
3147                         ((state->if_value < 0) &&
3148                                 (state->if_depth == -state->if_value))) 
3149                 {
3150                         state->if_value = state->if_depth - 1;
3151                 }
3152                 state->if_depth--;
3153                 break;
3154         case TOK_DEFINE:
3155         {
3156                 struct hash_entry *ident;
3157                 struct macro *macro;
3158                 char *ptr;
3159                 
3160                 if (state->if_value < 0) /* quit early when #if'd out */
3161                         break;
3162
3163                 meat(state, index, TOK_IDENT);
3164                 ident = tk->ident;
3165                 
3166
3167                 if (*file->pos == '(') {
3168 #warning "FIXME macros with arguments not supported"
3169                         error(state, 0, "Macros with arguments not supported");
3170                 }
3171
3172                 /* Find the end of the line to get an estimate of
3173                  * the macro's length.
3174                  */
3175                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3176                         ;
3177
3178                 if (ident->sym_define != 0) {
3179                         error(state, 0, "macro %s already defined\n", ident->name);
3180                 }
3181                 macro = xmalloc(sizeof(*macro), "macro");
3182                 macro->ident = ident;
3183                 macro->buf_len = ptr - file->pos +1;
3184                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3185
3186                 memcpy(macro->buf, file->pos, macro->buf_len);
3187                 macro->buf[macro->buf_len] = '\n';
3188                 macro->buf[macro->buf_len +1] = '\0';
3189
3190                 ident->sym_define = macro;
3191                 break;
3192         }
3193         case TOK_ERROR:
3194         {
3195                 char *end;
3196                 int len;
3197                 /* Find the end of the line */
3198                 for(end = file->pos; *end != '\n'; end++)
3199                         ;
3200                 len = (end - file->pos);
3201                 if (state->if_value >= 0) {
3202                         error(state, 0, "%*.*s", len, len, file->pos);
3203                 }
3204                 file->pos = end;
3205                 break;
3206         }
3207         case TOK_WARNING:
3208         {
3209                 char *end;
3210                 int len;
3211                 /* Find the end of the line */
3212                 for(end = file->pos; *end != '\n'; end++)
3213                         ;
3214                 len = (end - file->pos);
3215                 if (state->if_value >= 0) {
3216                         warning(state, 0, "%*.*s", len, len, file->pos);
3217                 }
3218                 file->pos = end;
3219                 break;
3220         }
3221         case TOK_INCLUDE:
3222         {
3223                 char *name;
3224                 char *ptr;
3225                 int local;
3226                 local = 0;
3227                 name = 0;
3228                 next_token(state, index);
3229                 if (tk->tok == TOK_LIT_STRING) {
3230                         const char *token;
3231                         int name_len;
3232                         name = xmalloc(tk->str_len, "include");
3233                         token = tk->val.str +1;
3234                         name_len = tk->str_len -2;
3235                         if (*token == '"') {
3236                                 token++;
3237                                 name_len--;
3238                         }
3239                         memcpy(name, token, name_len);
3240                         name[name_len] = '\0';
3241                         local = 1;
3242                 }
3243                 else if (tk->tok == TOK_LESS) {
3244                         char *start, *end;
3245                         start = file->pos;
3246                         for(end = start; *end != '\n'; end++) {
3247                                 if (*end == '>') {
3248                                         break;
3249                                 }
3250                         }
3251                         if (*end == '\n') {
3252                                 error(state, 0, "Unterminated included directive");
3253                         }
3254                         name = xmalloc(end - start + 1, "include");
3255                         memcpy(name, start, end - start);
3256                         name[end - start] = '\0';
3257                         file->pos = end +1;
3258                         local = 0;
3259                 }
3260                 else {
3261                         error(state, 0, "Invalid include directive");
3262                 }
3263                 /* Error if there are any characters after the include */
3264                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3265                         if (!isspace(*ptr)) {
3266                                 error(state, 0, "garbage after include directive");
3267                         }
3268                 }
3269                 if (state->if_value >= 0) {
3270                         compile_file(state, name, local);
3271                 }
3272                 xfree(name);
3273                 next_token(state, index);
3274                 return;
3275         }
3276         default:
3277                 /* Ignore # without a following ident */
3278                 if (tk->tok == TOK_IDENT) {
3279                         error(state, 0, "Invalid preprocessor directive: %s", 
3280                                 tk->ident->name);
3281                 }
3282                 break;
3283         }
3284         /* Consume the rest of the macro line */
3285         do {
3286                 tok = mpeek(state, index);
3287                 meat(state, index, tok);
3288         } while(tok != TOK_EOF);
3289         return;
3290 }
3291
3292 static void token(struct compile_state *state, int index)
3293 {
3294         struct file_state *file;
3295         struct token *tk;
3296         int rescan;
3297
3298         tk = &state->token[index];
3299         next_token(state, index);
3300         do {
3301                 rescan = 0;
3302                 file = state->file;
3303                 if (tk->tok == TOK_EOF && file->prev) {
3304                         state->file = file->prev;
3305                         /* file->basename is used keep it */
3306                         xfree(file->dirname);
3307                         xfree(file->buf);
3308                         xfree(file);
3309                         next_token(state, index);
3310                         rescan = 1;
3311                 }
3312                 else if (tk->tok == TOK_MACRO) {
3313                         preprocess(state, index);
3314                         rescan = 1;
3315                 }
3316                 else if (tk->ident && tk->ident->sym_define) {
3317                         compile_macro(state, tk);
3318                         next_token(state, index);
3319                         rescan = 1;
3320                 }
3321                 else if (state->if_value < 0) {
3322                         next_token(state, index);
3323                         rescan = 1;
3324                 }
3325         } while(rescan);
3326 }
3327
3328 static int peek(struct compile_state *state)
3329 {
3330         if (state->token[1].tok == -1) {
3331                 token(state, 1);
3332         }
3333         return state->token[1].tok;
3334 }
3335
3336 static int peek2(struct compile_state *state)
3337 {
3338         if (state->token[1].tok == -1) {
3339                 token(state, 1);
3340         }
3341         if (state->token[2].tok == -1) {
3342                 token(state, 2);
3343         }
3344         return state->token[2].tok;
3345 }
3346
3347 static void eat(struct compile_state *state, int tok)
3348 {
3349         int next_tok;
3350         int i;
3351         next_tok = peek(state);
3352         if (next_tok != tok) {
3353                 const char *name1, *name2;
3354                 name1 = tokens[next_tok];
3355                 name2 = "";
3356                 if (next_tok == TOK_IDENT) {
3357                         name2 = state->token[1].ident->name;
3358                 }
3359                 error(state, 0, "\tfound %s %s expected %s",
3360                         name1, name2 ,tokens[tok]);
3361         }
3362         /* Free the old token value */
3363         if (state->token[0].str_len) {
3364                 xfree((void *)(state->token[0].val.str));
3365         }
3366         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3367                 state->token[i] = state->token[i + 1];
3368         }
3369         memset(&state->token[i], 0, sizeof(state->token[i]));
3370         state->token[i].tok = -1;
3371 }
3372
3373 #warning "FIXME do not hardcode the include paths"
3374 static char *include_paths[] = {
3375         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3376         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3377         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3378         0
3379 };
3380
3381 static void compile_file(struct compile_state *state, const char *filename, int local)
3382 {
3383         char cwd[4096];
3384         const char *subdir, *base;
3385         int subdir_len;
3386         struct file_state *file;
3387         char *basename;
3388         file = xmalloc(sizeof(*file), "file_state");
3389
3390         base = strrchr(filename, '/');
3391         subdir = filename;
3392         if (base != 0) {
3393                 subdir_len = base - filename;
3394                 base++;
3395         }
3396         else {
3397                 base = filename;
3398                 subdir_len = 0;
3399         }
3400         basename = xmalloc(strlen(base) +1, "basename");
3401         strcpy(basename, base);
3402         file->basename = basename;
3403
3404         if (getcwd(cwd, sizeof(cwd)) == 0) {
3405                 die("cwd buffer to small");
3406         }
3407         
3408         if (subdir[0] == '/') {
3409                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3410                 memcpy(file->dirname, subdir, subdir_len);
3411                 file->dirname[subdir_len] = '\0';
3412         }
3413         else {
3414                 char *dir;
3415                 int dirlen;
3416                 char **path;
3417                 /* Find the appropriate directory... */
3418                 dir = 0;
3419                 if (!state->file && exists(cwd, filename)) {
3420                         dir = cwd;
3421                 }
3422                 if (local && state->file && exists(state->file->dirname, filename)) {
3423                         dir = state->file->dirname;
3424                 }
3425                 for(path = include_paths; !dir && *path; path++) {
3426                         if (exists(*path, filename)) {
3427                                 dir = *path;
3428                         }
3429                 }
3430                 if (!dir) {
3431                         error(state, 0, "Cannot find `%s'\n", filename);
3432                 }
3433                 dirlen = strlen(dir);
3434                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3435                 memcpy(file->dirname, dir, dirlen);
3436                 file->dirname[dirlen] = '/';
3437                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3438                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3439         }
3440         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3441         xchdir(cwd);
3442
3443         file->pos = file->buf;
3444         file->line_start = file->pos;
3445         file->line = 1;
3446
3447         file->prev = state->file;
3448         state->file = file;
3449         
3450         process_trigraphs(state);
3451         splice_lines(state);
3452 }
3453
3454 /* Type helper functions */
3455
3456 static struct type *new_type(
3457         unsigned int type, struct type *left, struct type *right)
3458 {
3459         struct type *result;
3460         result = xmalloc(sizeof(*result), "type");
3461         result->type = type;
3462         result->left = left;
3463         result->right = right;
3464         result->field_ident = 0;
3465         result->type_ident = 0;
3466         return result;
3467 }
3468
3469 static struct type *clone_type(unsigned int specifiers, struct type *old)
3470 {
3471         struct type *result;
3472         result = xmalloc(sizeof(*result), "type");
3473         memcpy(result, old, sizeof(*result));
3474         result->type &= TYPE_MASK;
3475         result->type |= specifiers;
3476         return result;
3477 }
3478
3479 #define SIZEOF_SHORT 2
3480 #define SIZEOF_INT   4
3481 #define SIZEOF_LONG  (sizeof(long_t))
3482
3483 #define ALIGNOF_SHORT 2
3484 #define ALIGNOF_INT   4
3485 #define ALIGNOF_LONG  (sizeof(long_t))
3486
3487 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3488 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3489 static inline ulong_t mask_uint(ulong_t x)
3490 {
3491         if (SIZEOF_INT < SIZEOF_LONG) {
3492                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3493                 x &= mask;
3494         }
3495         return x;
3496 }
3497 #define MASK_UINT(X)      (mask_uint(X))
3498 #define MASK_ULONG(X)    (X)
3499
3500 static struct type void_type   = { .type  = TYPE_VOID };
3501 static struct type char_type   = { .type  = TYPE_CHAR };
3502 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3503 static struct type short_type  = { .type  = TYPE_SHORT };
3504 static struct type ushort_type = { .type  = TYPE_USHORT };
3505 static struct type int_type    = { .type  = TYPE_INT };
3506 static struct type uint_type   = { .type  = TYPE_UINT };
3507 static struct type long_type   = { .type  = TYPE_LONG };
3508 static struct type ulong_type  = { .type  = TYPE_ULONG };
3509
3510 static struct triple *variable(struct compile_state *state, struct type *type)
3511 {
3512         struct triple *result;
3513         if ((type->type & STOR_MASK) != STOR_PERM) {
3514                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3515                         result = triple(state, OP_ADECL, type, 0, 0);
3516                 } else {
3517                         struct type *field;
3518                         struct triple **vector;
3519                         ulong_t index;
3520                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3521                         vector = &result->param[0];
3522
3523                         field = type->left;
3524                         index = 0;
3525                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3526                                 vector[index] = variable(state, field->left);
3527                                 field = field->right;
3528                                 index++;
3529                         }
3530                         vector[index] = variable(state, field);
3531                 }
3532         }
3533         else {
3534                 result = triple(state, OP_SDECL, type, 0, 0);
3535         }
3536         return result;
3537 }
3538
3539 static void stor_of(FILE *fp, struct type *type)
3540 {
3541         switch(type->type & STOR_MASK) {
3542         case STOR_AUTO:
3543                 fprintf(fp, "auto ");
3544                 break;
3545         case STOR_STATIC:
3546                 fprintf(fp, "static ");
3547                 break;
3548         case STOR_EXTERN:
3549                 fprintf(fp, "extern ");
3550                 break;
3551         case STOR_REGISTER:
3552                 fprintf(fp, "register ");
3553                 break;
3554         case STOR_TYPEDEF:
3555                 fprintf(fp, "typedef ");
3556                 break;
3557         case STOR_INLINE:
3558                 fprintf(fp, "inline ");
3559                 break;
3560         }
3561 }
3562 static void qual_of(FILE *fp, struct type *type)
3563 {
3564         if (type->type & QUAL_CONST) {
3565                 fprintf(fp, " const");
3566         }
3567         if (type->type & QUAL_VOLATILE) {
3568                 fprintf(fp, " volatile");
3569         }
3570         if (type->type & QUAL_RESTRICT) {
3571                 fprintf(fp, " restrict");
3572         }
3573 }
3574
3575 static void name_of(FILE *fp, struct type *type)
3576 {
3577         stor_of(fp, type);
3578         switch(type->type & TYPE_MASK) {
3579         case TYPE_VOID:
3580                 fprintf(fp, "void");
3581                 qual_of(fp, type);
3582                 break;
3583         case TYPE_CHAR:
3584                 fprintf(fp, "signed char");
3585                 qual_of(fp, type);
3586                 break;
3587         case TYPE_UCHAR:
3588                 fprintf(fp, "unsigned char");
3589                 qual_of(fp, type);
3590                 break;
3591         case TYPE_SHORT:
3592                 fprintf(fp, "signed short");
3593                 qual_of(fp, type);
3594                 break;
3595         case TYPE_USHORT:
3596                 fprintf(fp, "unsigned short");
3597                 qual_of(fp, type);
3598                 break;
3599         case TYPE_INT:
3600                 fprintf(fp, "signed int");
3601                 qual_of(fp, type);
3602                 break;
3603         case TYPE_UINT:
3604                 fprintf(fp, "unsigned int");
3605                 qual_of(fp, type);
3606                 break;
3607         case TYPE_LONG:
3608                 fprintf(fp, "signed long");
3609                 qual_of(fp, type);
3610                 break;
3611         case TYPE_ULONG:
3612                 fprintf(fp, "unsigned long");
3613                 qual_of(fp, type);
3614                 break;
3615         case TYPE_POINTER:
3616                 name_of(fp, type->left);
3617                 fprintf(fp, " * ");
3618                 qual_of(fp, type);
3619                 break;
3620         case TYPE_PRODUCT:
3621         case TYPE_OVERLAP:
3622                 name_of(fp, type->left);
3623                 fprintf(fp, ", ");
3624                 name_of(fp, type->right);
3625                 break;
3626         case TYPE_ENUM:
3627                 fprintf(fp, "enum %s", type->type_ident->name);
3628                 qual_of(fp, type);
3629                 break;
3630         case TYPE_STRUCT:
3631                 fprintf(fp, "struct %s", type->type_ident->name);
3632                 qual_of(fp, type);
3633                 break;
3634         case TYPE_FUNCTION:
3635         {
3636                 name_of(fp, type->left);
3637                 fprintf(fp, " (*)(");
3638                 name_of(fp, type->right);
3639                 fprintf(fp, ")");
3640                 break;
3641         }
3642         case TYPE_ARRAY:
3643                 name_of(fp, type->left);
3644                 fprintf(fp, " [%ld]", type->elements);
3645                 break;
3646         default:
3647                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3648                 break;
3649         }
3650 }
3651
3652 static size_t align_of(struct compile_state *state, struct type *type)
3653 {
3654         size_t align;
3655         align = 0;
3656         switch(type->type & TYPE_MASK) {
3657         case TYPE_VOID:
3658                 align = 1;
3659                 break;
3660         case TYPE_CHAR:
3661         case TYPE_UCHAR:
3662                 align = 1;
3663                 break;
3664         case TYPE_SHORT:
3665         case TYPE_USHORT:
3666                 align = ALIGNOF_SHORT;
3667                 break;
3668         case TYPE_INT:
3669         case TYPE_UINT:
3670         case TYPE_ENUM:
3671                 align = ALIGNOF_INT;
3672                 break;
3673         case TYPE_LONG:
3674         case TYPE_ULONG:
3675         case TYPE_POINTER:
3676                 align = ALIGNOF_LONG;
3677                 break;
3678         case TYPE_PRODUCT:
3679         case TYPE_OVERLAP:
3680         {
3681                 size_t left_align, right_align;
3682                 left_align  = align_of(state, type->left);
3683                 right_align = align_of(state, type->right);
3684                 align = (left_align >= right_align) ? left_align : right_align;
3685                 break;
3686         }
3687         case TYPE_ARRAY:
3688                 align = align_of(state, type->left);
3689                 break;
3690         case TYPE_STRUCT:
3691                 align = align_of(state, type->left);
3692                 break;
3693         default:
3694                 error(state, 0, "alignof not yet defined for type\n");
3695                 break;
3696         }
3697         return align;
3698 }
3699
3700 static size_t size_of(struct compile_state *state, struct type *type)
3701 {
3702         size_t size;
3703         size = 0;
3704         switch(type->type & TYPE_MASK) {
3705         case TYPE_VOID:
3706                 size = 0;
3707                 break;
3708         case TYPE_CHAR:
3709         case TYPE_UCHAR:
3710                 size = 1;
3711                 break;
3712         case TYPE_SHORT:
3713         case TYPE_USHORT:
3714                 size = SIZEOF_SHORT;
3715                 break;
3716         case TYPE_INT:
3717         case TYPE_UINT:
3718         case TYPE_ENUM:
3719                 size = SIZEOF_INT;
3720                 break;
3721         case TYPE_LONG:
3722         case TYPE_ULONG:
3723         case TYPE_POINTER:
3724                 size = SIZEOF_LONG;
3725                 break;
3726         case TYPE_PRODUCT:
3727         {
3728                 size_t align, pad;
3729                 size = size_of(state, type->left);
3730                 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3731                         type = type->right;
3732                         align = align_of(state, type->left);
3733                         pad = align - (size % align);
3734                         size = size + pad + size_of(state, type->left);
3735                 }
3736                 align = align_of(state, type->right);
3737                 pad = align - (size % align);
3738                 size = size + pad + sizeof(type->right);
3739                 break;
3740         }
3741         case TYPE_OVERLAP:
3742         {
3743                 size_t size_left, size_right;
3744                 size_left = size_of(state, type->left);
3745                 size_right = size_of(state, type->right);
3746                 size = (size_left >= size_right)? size_left : size_right;
3747                 break;
3748         }
3749         case TYPE_ARRAY:
3750                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3751                         internal_error(state, 0, "Invalid array type");
3752                 } else {
3753                         size = size_of(state, type->left) * type->elements;
3754                 }
3755                 break;
3756         case TYPE_STRUCT:
3757                 size = size_of(state, type->left);
3758                 break;
3759         default:
3760                 error(state, 0, "sizeof not yet defined for type\n");
3761                 break;
3762         }
3763         return size;
3764 }
3765
3766 static size_t field_offset(struct compile_state *state, 
3767         struct type *type, struct hash_entry *field)
3768 {
3769         size_t size, align, pad;
3770         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3771                 internal_error(state, 0, "field_offset only works on structures");
3772         }
3773         size = 0;
3774         type = type->left;
3775         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3776                 if (type->left->field_ident == field) {
3777                         type = type->left;
3778                 }
3779                 size += size_of(state, type->left);
3780                 type = type->right;
3781                 align = align_of(state, type->left);
3782                 pad = align - (size % align);
3783                 size += pad;
3784         }
3785         if (type->field_ident != field) {
3786                 internal_error(state, 0, "field_offset: member %s not present",
3787                         field->name);
3788         }
3789         return size;
3790 }
3791
3792 static struct type *field_type(struct compile_state *state, 
3793         struct type *type, struct hash_entry *field)
3794 {
3795         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3796                 internal_error(state, 0, "field_type only works on structures");
3797         }
3798         type = type->left;
3799         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3800                 if (type->left->field_ident == field) {
3801                         type = type->left;
3802                         break;
3803                 }
3804                 type = type->right;
3805         }
3806         if (type->field_ident != field) {
3807                 internal_error(state, 0, "field_type: member %s not present", 
3808                         field->name);
3809         }
3810         return type;
3811 }
3812
3813 static struct triple *struct_field(struct compile_state *state,
3814         struct triple *decl, struct hash_entry *field)
3815 {
3816         struct triple **vector;
3817         struct type *type;
3818         ulong_t index;
3819         type = decl->type;
3820         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3821                 return decl;
3822         }
3823         if (decl->op != OP_VAL_VEC) {
3824                 internal_error(state, 0, "Invalid struct variable");
3825         }
3826         if (!field) {
3827                 internal_error(state, 0, "Missing structure field");
3828         }
3829         type = type->left;
3830         vector = &RHS(decl, 0);
3831         index = 0;
3832         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3833                 if (type->left->field_ident == field) {
3834                         type = type->left;
3835                         break;
3836                 }
3837                 index += 1;
3838                 type = type->right;
3839         }
3840         if (type->field_ident != field) {
3841                 internal_error(state, 0, "field %s not found?", field->name);
3842         }
3843         return vector[index];
3844 }
3845
3846 static void arrays_complete(struct compile_state *state, struct type *type)
3847 {
3848         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3849                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3850                         error(state, 0, "array size not specified");
3851                 }
3852                 arrays_complete(state, type->left);
3853         }
3854 }
3855
3856 static unsigned int do_integral_promotion(unsigned int type)
3857 {
3858         type &= TYPE_MASK;
3859         if (TYPE_INTEGER(type) && 
3860                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3861                 type = TYPE_INT;
3862         }
3863         return type;
3864 }
3865
3866 static unsigned int do_arithmetic_conversion(
3867         unsigned int left, unsigned int right)
3868 {
3869         left &= TYPE_MASK;
3870         right &= TYPE_MASK;
3871         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3872                 return TYPE_LDOUBLE;
3873         }
3874         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3875                 return TYPE_DOUBLE;
3876         }
3877         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3878                 return TYPE_FLOAT;
3879         }
3880         left = do_integral_promotion(left);
3881         right = do_integral_promotion(right);
3882         /* If both operands have the same size done */
3883         if (left == right) {
3884                 return left;
3885         }
3886         /* If both operands have the same signedness pick the larger */
3887         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3888                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3889         }
3890         /* If the signed type can hold everything use it */
3891         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3892                 return left;
3893         }
3894         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3895                 return right;
3896         }
3897         /* Convert to the unsigned type with the same rank as the signed type */
3898         else if (TYPE_SIGNED(left)) {
3899                 return TYPE_MKUNSIGNED(left);
3900         }
3901         else {
3902                 return TYPE_MKUNSIGNED(right);
3903         }
3904 }
3905
3906 /* see if two types are the same except for qualifiers */
3907 static int equiv_types(struct type *left, struct type *right)
3908 {
3909         unsigned int type;
3910         /* Error if the basic types do not match */
3911         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3912                 return 0;
3913         }
3914         type = left->type & TYPE_MASK;
3915         /* if the basic types match and it is an arithmetic type we are done */
3916         if (TYPE_ARITHMETIC(type)) {
3917                 return 1;
3918         }
3919         /* If it is a pointer type recurse and keep testing */
3920         if (type == TYPE_POINTER) {
3921                 return equiv_types(left->left, right->left);
3922         }
3923         else if (type == TYPE_ARRAY) {
3924                 return (left->elements == right->elements) &&
3925                         equiv_types(left->left, right->left);
3926         }
3927         /* test for struct/union equality */
3928         else if (type == TYPE_STRUCT) {
3929                 return left->type_ident == right->type_ident;
3930         }
3931         /* Test for equivalent functions */
3932         else if (type == TYPE_FUNCTION) {
3933                 return equiv_types(left->left, right->left) &&
3934                         equiv_types(left->right, right->right);
3935         }
3936         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3937         else if (type == TYPE_PRODUCT) {
3938                 return equiv_types(left->left, right->left) &&
3939                         equiv_types(left->right, right->right);
3940         }
3941         /* We should see TYPE_OVERLAP */
3942         else {
3943                 return 0;
3944         }
3945 }
3946
3947 static int equiv_ptrs(struct type *left, struct type *right)
3948 {
3949         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3950                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3951                 return 0;
3952         }
3953         return equiv_types(left->left, right->left);
3954 }
3955
3956 static struct type *compatible_types(struct type *left, struct type *right)
3957 {
3958         struct type *result;
3959         unsigned int type, qual_type;
3960         /* Error if the basic types do not match */
3961         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3962                 return 0;
3963         }
3964         type = left->type & TYPE_MASK;
3965         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3966         result = 0;
3967         /* if the basic types match and it is an arithmetic type we are done */
3968         if (TYPE_ARITHMETIC(type)) {
3969                 result = new_type(qual_type, 0, 0);
3970         }
3971         /* If it is a pointer type recurse and keep testing */
3972         else if (type == TYPE_POINTER) {
3973                 result = compatible_types(left->left, right->left);
3974                 if (result) {
3975                         result = new_type(qual_type, result, 0);
3976                 }
3977         }
3978         /* test for struct/union equality */
3979         else if (type == TYPE_STRUCT) {
3980                 if (left->type_ident == right->type_ident) {
3981                         result = left;
3982                 }
3983         }
3984         /* Test for equivalent functions */
3985         else if (type == TYPE_FUNCTION) {
3986                 struct type *lf, *rf;
3987                 lf = compatible_types(left->left, right->left);
3988                 rf = compatible_types(left->right, right->right);
3989                 if (lf && rf) {
3990                         result = new_type(qual_type, lf, rf);
3991                 }
3992         }
3993         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3994         else if (type == TYPE_PRODUCT) {
3995                 struct type *lf, *rf;
3996                 lf = compatible_types(left->left, right->left);
3997                 rf = compatible_types(left->right, right->right);
3998                 if (lf && rf) {
3999                         result = new_type(qual_type, lf, rf);
4000                 }
4001         }
4002         else {
4003                 /* Nothing else is compatible */
4004         }
4005         return result;
4006 }
4007
4008 static struct type *compatible_ptrs(struct type *left, struct type *right)
4009 {
4010         struct type *result;
4011         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4012                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4013                 return 0;
4014         }
4015         result = compatible_types(left->left, right->left);
4016         if (result) {
4017                 unsigned int qual_type;
4018                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4019                 result = new_type(qual_type, result, 0);
4020         }
4021         return result;
4022         
4023 }
4024 static struct triple *integral_promotion(
4025         struct compile_state *state, struct triple *def)
4026 {
4027         struct type *type;
4028         type = def->type;
4029         /* As all operations are carried out in registers
4030          * the values are converted on load I just convert
4031          * logical type of the operand.
4032          */
4033         if (TYPE_INTEGER(type->type)) {
4034                 unsigned int int_type;
4035                 int_type = type->type & ~TYPE_MASK;
4036                 int_type |= do_integral_promotion(type->type);
4037                 if (int_type != type->type) {
4038                         def->type = new_type(int_type, 0, 0);
4039                 }
4040         }
4041         return def;
4042 }
4043
4044
4045 static void arithmetic(struct compile_state *state, struct triple *def)
4046 {
4047         if (!TYPE_ARITHMETIC(def->type->type)) {
4048                 error(state, 0, "arithmetic type expexted");
4049         }
4050 }
4051
4052 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4053 {
4054         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4055                 error(state, def, "pointer or arithmetic type expected");
4056         }
4057 }
4058
4059 static int is_integral(struct triple *ins)
4060 {
4061         return TYPE_INTEGER(ins->type->type);
4062 }
4063
4064 static void integral(struct compile_state *state, struct triple *def)
4065 {
4066         if (!is_integral(def)) {
4067                 error(state, 0, "integral type expected");
4068         }
4069 }
4070
4071
4072 static void bool(struct compile_state *state, struct triple *def)
4073 {
4074         if (!TYPE_ARITHMETIC(def->type->type) &&
4075                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4076                 error(state, 0, "arithmetic or pointer type expected");
4077         }
4078 }
4079
4080 static int is_signed(struct type *type)
4081 {
4082         return !!TYPE_SIGNED(type->type);
4083 }
4084
4085 /* Is this value located in a register otherwise it must be in memory */
4086 static int is_in_reg(struct compile_state *state, struct triple *def)
4087 {
4088         int in_reg;
4089         if (def->op == OP_ADECL) {
4090                 in_reg = 1;
4091         }
4092         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4093                 in_reg = 0;
4094         }
4095         else if (def->op == OP_VAL_VEC) {
4096                 in_reg = is_in_reg(state, RHS(def, 0));
4097         }
4098         else if (def->op == OP_DOT) {
4099                 in_reg = is_in_reg(state, RHS(def, 0));
4100         }
4101         else {
4102                 internal_error(state, 0, "unknown expr storage location");
4103                 in_reg = -1;
4104         }
4105         return in_reg;
4106 }
4107
4108 /* Is this a stable variable location otherwise it must be a temporary */
4109 static int is_stable(struct compile_state *state, struct triple *def)
4110 {
4111         int ret;
4112         ret = 0;
4113         if (!def) {
4114                 return 0;
4115         }
4116         if ((def->op == OP_ADECL) || 
4117                 (def->op == OP_SDECL) || 
4118                 (def->op == OP_DEREF) ||
4119                 (def->op == OP_BLOBCONST)) {
4120                 ret = 1;
4121         }
4122         else if (def->op == OP_DOT) {
4123                 ret = is_stable(state, RHS(def, 0));
4124         }
4125         else if (def->op == OP_VAL_VEC) {
4126                 struct triple **vector;
4127                 ulong_t i;
4128                 ret = 1;
4129                 vector = &RHS(def, 0);
4130                 for(i = 0; i < def->type->elements; i++) {
4131                         if (!is_stable(state, vector[i])) {
4132                                 ret = 0;
4133                                 break;
4134                         }
4135                 }
4136         }
4137         return ret;
4138 }
4139
4140 static int is_lvalue(struct compile_state *state, struct triple *def)
4141 {
4142         int ret;
4143         ret = 1;
4144         if (!def) {
4145                 return 0;
4146         }
4147         if (!is_stable(state, def)) {
4148                 return 0;
4149         }
4150         if (def->type->type & QUAL_CONST) {
4151                 ret = 0;
4152         }
4153         else if (def->op == OP_DOT) {
4154                 ret = is_lvalue(state, RHS(def, 0));
4155         }
4156         return ret;
4157 }
4158
4159 static void lvalue(struct compile_state *state, struct triple *def)
4160 {
4161         if (!def) {
4162                 internal_error(state, def, "nothing where lvalue expected?");
4163         }
4164         if (!is_lvalue(state, def)) { 
4165                 error(state, def, "lvalue expected");
4166         }
4167 }
4168
4169 static int is_pointer(struct triple *def)
4170 {
4171         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4172 }
4173
4174 static void pointer(struct compile_state *state, struct triple *def)
4175 {
4176         if (!is_pointer(def)) {
4177                 error(state, def, "pointer expected");
4178         }
4179 }
4180
4181 static struct triple *int_const(
4182         struct compile_state *state, struct type *type, ulong_t value)
4183 {
4184         struct triple *result;
4185         switch(type->type & TYPE_MASK) {
4186         case TYPE_CHAR:
4187         case TYPE_INT:   case TYPE_UINT:
4188         case TYPE_LONG:  case TYPE_ULONG:
4189                 break;
4190         default:
4191                 internal_error(state, 0, "constant for unkown type");
4192         }
4193         result = triple(state, OP_INTCONST, type, 0, 0);
4194         result->u.cval = value;
4195         return result;
4196 }
4197
4198
4199 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4200         struct triple *expr, struct type *type, ulong_t offset)
4201 {
4202         struct triple *result;
4203         lvalue(state, expr);
4204
4205         result = 0;
4206         if (expr->op == OP_ADECL) {
4207                 error(state, expr, "address of auto variables not supported");
4208         }
4209         else if (expr->op == OP_SDECL) {
4210                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4211                 MISC(result, 0) = expr;
4212                 result->u.cval = offset;
4213         }
4214         else if (expr->op == OP_DEREF) {
4215                 result = triple(state, OP_ADD, type,
4216                         RHS(expr, 0),
4217                         int_const(state, &ulong_type, offset));
4218         }
4219         return result;
4220 }
4221
4222 static struct triple *mk_addr_expr(
4223         struct compile_state *state, struct triple *expr, ulong_t offset)
4224 {
4225         struct type *type;
4226         
4227         type = new_type(
4228                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4229                 expr->type, 0);
4230
4231         return do_mk_addr_expr(state, expr, type, offset);
4232 }
4233
4234 static struct triple *mk_deref_expr(
4235         struct compile_state *state, struct triple *expr)
4236 {
4237         struct type *base_type;
4238         pointer(state, expr);
4239         base_type = expr->type->left;
4240         if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4241                 error(state, 0, 
4242                         "Only pointer and arithmetic values can be dereferenced");
4243         }
4244         return triple(state, OP_DEREF, base_type, expr, 0);
4245 }
4246
4247 static struct triple *deref_field(
4248         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4249 {
4250         struct triple *result;
4251         struct type *type, *member;
4252         if (!field) {
4253                 internal_error(state, 0, "No field passed to deref_field");
4254         }
4255         result = 0;
4256         type = expr->type;
4257         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4258                 error(state, 0, "request for member %s in something not a struct or union",
4259                         field->name);
4260         }
4261         member = type->left;
4262         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4263                 if (member->left->field_ident == field) {
4264                         member = member->left;
4265                         break;
4266                 }
4267                 member = member->right;
4268         }
4269         if (member->field_ident != field) {
4270                 error(state, 0, "%s is not a member", field->name);
4271         }
4272         if ((type->type & STOR_MASK) == STOR_PERM) {
4273                 /* Do the pointer arithmetic to get a deref the field */
4274                 ulong_t offset;
4275                 offset = field_offset(state, type, field);
4276                 result = do_mk_addr_expr(state, expr, member, offset);
4277                 result = mk_deref_expr(state, result);
4278         }
4279         else {
4280                 /* Find the variable for the field I want. */
4281                 result = triple(state, OP_DOT, 
4282                         field_type(state, type, field), expr, 0);
4283                 result->u.field = field;
4284         }
4285         return result;
4286 }
4287
4288 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4289 {
4290         int op;
4291         if  (!def) {
4292                 return 0;
4293         }
4294         if (!is_stable(state, def)) {
4295                 return def;
4296         }
4297         /* Tranform an array to a pointer to the first element */
4298 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4299         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4300                 struct type *type;
4301                 struct triple *result;
4302                 type = new_type(
4303                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4304                         def->type->left, 0);
4305                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4306                 MISC(result, 0) = def;
4307                 return result;
4308         }
4309         if (is_in_reg(state, def)) {
4310                 op = OP_READ;
4311         } else {
4312                 op = OP_LOAD;
4313         }
4314         return triple(state, op, def->type, def, 0);
4315 }
4316
4317 static void write_compatible(struct compile_state *state,
4318         struct type *dest, struct type *rval)
4319 {
4320         int compatible = 0;
4321         /* Both operands have arithmetic type */
4322         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4323                 compatible = 1;
4324         }
4325         /* One operand is a pointer and the other is a pointer to void */
4326         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4327                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4328                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4329                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4330                 compatible = 1;
4331         }
4332         /* If both types are the same without qualifiers we are good */
4333         else if (equiv_ptrs(dest, rval)) {
4334                 compatible = 1;
4335         }
4336         /* test for struct/union equality  */
4337         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4338                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4339                 (dest->type_ident == rval->type_ident)) {
4340                 compatible = 1;
4341         }
4342         if (!compatible) {
4343                 error(state, 0, "Incompatible types in assignment");
4344         }
4345 }
4346
4347 static struct triple *write_expr(
4348         struct compile_state *state, struct triple *dest, struct triple *rval)
4349 {
4350         struct triple *def;
4351         int op;
4352
4353         def = 0;
4354         if (!rval) {
4355                 internal_error(state, 0, "missing rval");
4356         }
4357
4358         if (rval->op == OP_LIST) {
4359                 internal_error(state, 0, "expression of type OP_LIST?");
4360         }
4361         if (!is_lvalue(state, dest)) {
4362                 internal_error(state, 0, "writing to a non lvalue?");
4363         }
4364
4365         write_compatible(state, dest->type, rval->type);
4366
4367         /* Now figure out which assignment operator to use */
4368         op = -1;
4369         if (is_in_reg(state, dest)) {
4370                 op = OP_WRITE;
4371         } else {
4372                 op = OP_STORE;
4373         }
4374         def = triple(state, op, dest->type, dest, rval);
4375         return def;
4376 }
4377
4378 static struct triple *init_expr(
4379         struct compile_state *state, struct triple *dest, struct triple *rval)
4380 {
4381         struct triple *def;
4382
4383         def = 0;
4384         if (!rval) {
4385                 internal_error(state, 0, "missing rval");
4386         }
4387         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4388                 rval = read_expr(state, rval);
4389                 def = write_expr(state, dest, rval);
4390         }
4391         else {
4392                 /* Fill in the array size if necessary */
4393                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4394                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4395                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4396                                 dest->type->elements = rval->type->elements;
4397                         }
4398                 }
4399                 if (!equiv_types(dest->type, rval->type)) {
4400                         error(state, 0, "Incompatible types in inializer");
4401                 }
4402                 MISC(dest, 0) = rval;
4403                 insert_triple(state, dest, rval);
4404                 rval->id |= TRIPLE_FLAG_FLATTENED;
4405                 use_triple(MISC(dest, 0), dest);
4406         }
4407         return def;
4408 }
4409
4410 struct type *arithmetic_result(
4411         struct compile_state *state, struct triple *left, struct triple *right)
4412 {
4413         struct type *type;
4414         /* Sanity checks to ensure I am working with arithmetic types */
4415         arithmetic(state, left);
4416         arithmetic(state, right);
4417         type = new_type(
4418                 do_arithmetic_conversion(
4419                         left->type->type, 
4420                         right->type->type), 0, 0);
4421         return type;
4422 }
4423
4424 struct type *ptr_arithmetic_result(
4425         struct compile_state *state, struct triple *left, struct triple *right)
4426 {
4427         struct type *type;
4428         /* Sanity checks to ensure I am working with the proper types */
4429         ptr_arithmetic(state, left);
4430         arithmetic(state, right);
4431         if (TYPE_ARITHMETIC(left->type->type) && 
4432                 TYPE_ARITHMETIC(right->type->type)) {
4433                 type = arithmetic_result(state, left, right);
4434         }
4435         else if (TYPE_PTR(left->type->type)) {
4436                 type = left->type;
4437         }
4438         else {
4439                 internal_error(state, 0, "huh?");
4440                 type = 0;
4441         }
4442         return type;
4443 }
4444
4445
4446 /* boolean helper function */
4447
4448 static struct triple *ltrue_expr(struct compile_state *state, 
4449         struct triple *expr)
4450 {
4451         switch(expr->op) {
4452         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4453         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4454         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4455                 /* If the expression is already boolean do nothing */
4456                 break;
4457         default:
4458                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4459                 break;
4460         }
4461         return expr;
4462 }
4463
4464 static struct triple *lfalse_expr(struct compile_state *state, 
4465         struct triple *expr)
4466 {
4467         return triple(state, OP_LFALSE, &int_type, expr, 0);
4468 }
4469
4470 static struct triple *cond_expr(
4471         struct compile_state *state, 
4472         struct triple *test, struct triple *left, struct triple *right)
4473 {
4474         struct triple *def;
4475         struct type *result_type;
4476         unsigned int left_type, right_type;
4477         bool(state, test);
4478         left_type = left->type->type;
4479         right_type = right->type->type;
4480         result_type = 0;
4481         /* Both operands have arithmetic type */
4482         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4483                 result_type = arithmetic_result(state, left, right);
4484         }
4485         /* Both operands have void type */
4486         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4487                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4488                 result_type = &void_type;
4489         }
4490         /* pointers to the same type... */
4491         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4492                 ;
4493         }
4494         /* Both operands are pointers and left is a pointer to void */
4495         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4496                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4497                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4498                 result_type = right->type;
4499         }
4500         /* Both operands are pointers and right is a pointer to void */
4501         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4502                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4503                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4504                 result_type = left->type;
4505         }
4506         if (!result_type) {
4507                 error(state, 0, "Incompatible types in conditional expression");
4508         }
4509         /* Cleanup and invert the test */
4510         test = lfalse_expr(state, read_expr(state, test));
4511         def = new_triple(state, OP_COND, result_type, 0, 3);
4512         def->param[0] = test;
4513         def->param[1] = left;
4514         def->param[2] = right;
4515         return def;
4516 }
4517
4518
4519 static int expr_depth(struct compile_state *state, struct triple *ins)
4520 {
4521         int count;
4522         count = 0;
4523         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4524                 count = 0;
4525         }
4526         else if (ins->op == OP_DEREF) {
4527                 count = expr_depth(state, RHS(ins, 0)) - 1;
4528         }
4529         else if (ins->op == OP_VAL) {
4530                 count = expr_depth(state, RHS(ins, 0)) - 1;
4531         }
4532         else if (ins->op == OP_COMMA) {
4533                 int ldepth, rdepth;
4534                 ldepth = expr_depth(state, RHS(ins, 0));
4535                 rdepth = expr_depth(state, RHS(ins, 1));
4536                 count = (ldepth >= rdepth)? ldepth : rdepth;
4537         }
4538         else if (ins->op == OP_CALL) {
4539                 /* Don't figure the depth of a call just guess it is huge */
4540                 count = 1000;
4541         }
4542         else {
4543                 struct triple **expr;
4544                 expr = triple_rhs(state, ins, 0);
4545                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4546                         if (*expr) {
4547                                 int depth;
4548                                 depth = expr_depth(state, *expr);
4549                                 if (depth > count) {
4550                                         count = depth;
4551                                 }
4552                         }
4553                 }
4554         }
4555         return count + 1;
4556 }
4557
4558 static struct triple *flatten(
4559         struct compile_state *state, struct triple *first, struct triple *ptr);
4560
4561 static struct triple *flatten_generic(
4562         struct compile_state *state, struct triple *first, struct triple *ptr)
4563 {
4564         struct rhs_vector {
4565                 int depth;
4566                 struct triple **ins;
4567         } vector[MAX_RHS];
4568         int i, rhs, lhs;
4569         /* Only operations with just a rhs should come here */
4570         rhs = TRIPLE_RHS(ptr->sizes);
4571         lhs = TRIPLE_LHS(ptr->sizes);
4572         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4573                 internal_error(state, ptr, "unexpected args for: %d %s",
4574                         ptr->op, tops(ptr->op));
4575         }
4576         /* Find the depth of the rhs elements */
4577         for(i = 0; i < rhs; i++) {
4578                 vector[i].ins = &RHS(ptr, i);
4579                 vector[i].depth = expr_depth(state, *vector[i].ins);
4580         }
4581         /* Selection sort the rhs */
4582         for(i = 0; i < rhs; i++) {
4583                 int j, max = i;
4584                 for(j = i + 1; j < rhs; j++ ) {
4585                         if (vector[j].depth > vector[max].depth) {
4586                                 max = j;
4587                         }
4588                 }
4589                 if (max != i) {
4590                         struct rhs_vector tmp;
4591                         tmp = vector[i];
4592                         vector[i] = vector[max];
4593                         vector[max] = tmp;
4594                 }
4595         }
4596         /* Now flatten the rhs elements */
4597         for(i = 0; i < rhs; i++) {
4598                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4599                 use_triple(*vector[i].ins, ptr);
4600         }
4601         
4602         /* Now flatten the lhs elements */
4603         for(i = 0; i < lhs; i++) {
4604                 struct triple **ins = &LHS(ptr, i);
4605                 *ins = flatten(state, first, *ins);
4606                 use_triple(*ins, ptr);
4607         }
4608         return ptr;
4609 }
4610
4611 static struct triple *flatten_land(
4612         struct compile_state *state, struct triple *first, struct triple *ptr)
4613 {
4614         struct triple *left, *right;
4615         struct triple *val, *test, *jmp, *label1, *end;
4616
4617         /* Find the triples */
4618         left = RHS(ptr, 0);
4619         right = RHS(ptr, 1);
4620
4621         /* Generate the needed triples */
4622         end = label(state);
4623
4624         /* Thread the triples together */
4625         val          = flatten(state, first, variable(state, ptr->type));
4626         left         = flatten(state, first, write_expr(state, val, left));
4627         test         = flatten(state, first, 
4628                 lfalse_expr(state, read_expr(state, val)));
4629         jmp          = flatten(state, first, branch(state, end, test));
4630         label1       = flatten(state, first, label(state));
4631         right        = flatten(state, first, write_expr(state, val, right));
4632         TARG(jmp, 0) = flatten(state, first, end); 
4633         
4634         /* Now give the caller something to chew on */
4635         return read_expr(state, val);
4636 }
4637
4638 static struct triple *flatten_lor(
4639         struct compile_state *state, struct triple *first, struct triple *ptr)
4640 {
4641         struct triple *left, *right;
4642         struct triple *val, *jmp, *label1, *end;
4643
4644         /* Find the triples */
4645         left = RHS(ptr, 0);
4646         right = RHS(ptr, 1);
4647
4648         /* Generate the needed triples */
4649         end = label(state);
4650
4651         /* Thread the triples together */
4652         val          = flatten(state, first, variable(state, ptr->type));
4653         left         = flatten(state, first, write_expr(state, val, left));
4654         jmp          = flatten(state, first, branch(state, end, left));
4655         label1       = flatten(state, first, label(state));
4656         right        = flatten(state, first, write_expr(state, val, right));
4657         TARG(jmp, 0) = flatten(state, first, end);
4658        
4659         
4660         /* Now give the caller something to chew on */
4661         return read_expr(state, val);
4662 }
4663
4664 static struct triple *flatten_cond(
4665         struct compile_state *state, struct triple *first, struct triple *ptr)
4666 {
4667         struct triple *test, *left, *right;
4668         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4669
4670         /* Find the triples */
4671         test = RHS(ptr, 0);
4672         left = RHS(ptr, 1);
4673         right = RHS(ptr, 2);
4674
4675         /* Generate the needed triples */
4676         end = label(state);
4677         middle = label(state);
4678
4679         /* Thread the triples together */
4680         val           = flatten(state, first, variable(state, ptr->type));
4681         test          = flatten(state, first, test);
4682         jmp1          = flatten(state, first, branch(state, middle, test));
4683         label1        = flatten(state, first, label(state));
4684         left          = flatten(state, first, left);
4685         mv1           = flatten(state, first, write_expr(state, val, left));
4686         jmp2          = flatten(state, first, branch(state, end, 0));
4687         TARG(jmp1, 0) = flatten(state, first, middle);
4688         right         = flatten(state, first, right);
4689         mv2           = flatten(state, first, write_expr(state, val, right));
4690         TARG(jmp2, 0) = flatten(state, first, end);
4691         
4692         /* Now give the caller something to chew on */
4693         return read_expr(state, val);
4694 }
4695
4696 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4697 {
4698         struct triple *nfunc;
4699         struct triple *nfirst, *ofirst;
4700         struct triple *new, *old;
4701
4702 #if 0
4703         fprintf(stdout, "\n");
4704         loc(stdout, state, 0);
4705         fprintf(stdout, "\n__________ copy_func _________\n");
4706         print_triple(state, ofunc);
4707         fprintf(stdout, "__________ copy_func _________ done\n\n");
4708 #endif
4709
4710         /* Make a new copy of the old function */
4711         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4712         nfirst = 0;
4713         ofirst = old = RHS(ofunc, 0);
4714         do {
4715                 struct triple *new;
4716                 int old_lhs, old_rhs;
4717                 old_lhs = TRIPLE_LHS(old->sizes);
4718                 old_rhs = TRIPLE_RHS(old->sizes);
4719                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4720                         old->filename, old->line, old->col);
4721                 if (!triple_stores_block(state, new)) {
4722                         memcpy(&new->u, &old->u, sizeof(new->u));
4723                 }
4724                 if (!nfirst) {
4725                         RHS(nfunc, 0) = nfirst = new;
4726                 }
4727                 else {
4728                         insert_triple(state, nfirst, new);
4729                 }
4730                 new->id |= TRIPLE_FLAG_FLATTENED;
4731                 
4732                 /* During the copy remember new as user of old */
4733                 use_triple(old, new);
4734
4735                 /* Populate the return type if present */
4736                 if (old == MISC(ofunc, 0)) {
4737                         MISC(nfunc, 0) = new;
4738                 }
4739                 old = old->next;
4740         } while(old != ofirst);
4741
4742         /* Make a second pass to fix up any unresolved references */
4743         old = ofirst;
4744         new = nfirst;
4745         do {
4746                 struct triple **oexpr, **nexpr;
4747                 int count, i;
4748                 /* Lookup where the copy is, to join pointers */
4749                 count = TRIPLE_SIZE(old->sizes);
4750                 for(i = 0; i < count; i++) {
4751                         oexpr = &old->param[i];
4752                         nexpr = &new->param[i];
4753                         if (!*nexpr && *oexpr && (*oexpr)->use) {
4754                                 *nexpr = (*oexpr)->use->member;
4755                                 if (*nexpr == old) {
4756                                         internal_error(state, 0, "new == old?");
4757                                 }
4758                                 use_triple(*nexpr, new);
4759                         }
4760                         if (!*nexpr && *oexpr) {
4761                                 internal_error(state, 0, "Could not copy %d\n", i);
4762                         }
4763                 }
4764                 old = old->next;
4765                 new = new->next;
4766         } while((old != ofirst) && (new != nfirst));
4767         
4768         /* Make a third pass to cleanup the extra useses */
4769         old = ofirst;
4770         new = nfirst;
4771         do {
4772                 unuse_triple(old, new);
4773                 old = old->next;
4774                 new = new->next;
4775         } while ((old != ofirst) && (new != nfirst));
4776         return nfunc;
4777 }
4778
4779 static struct triple *flatten_call(
4780         struct compile_state *state, struct triple *first, struct triple *ptr)
4781 {
4782         /* Inline the function call */
4783         struct type *ptype;
4784         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4785         struct triple *end, *nend;
4786         int pvals, i;
4787
4788         /* Find the triples */
4789         ofunc = MISC(ptr, 0);
4790         if (ofunc->op != OP_LIST) {
4791                 internal_error(state, 0, "improper function");
4792         }
4793         nfunc = copy_func(state, ofunc);
4794         nfirst = RHS(nfunc, 0)->next;
4795         /* Prepend the parameter reading into the new function list */
4796         ptype = nfunc->type->right;
4797         param = RHS(nfunc, 0)->next;
4798         pvals = TRIPLE_RHS(ptr->sizes);
4799         for(i = 0; i < pvals; i++) {
4800                 struct type *atype;
4801                 struct triple *arg;
4802                 atype = ptype;
4803                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4804                         atype = ptype->left;
4805                 }
4806                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4807                         param = param->next;
4808                 }
4809                 arg = RHS(ptr, i);
4810                 flatten(state, nfirst, write_expr(state, param, arg));
4811                 ptype = ptype->right;
4812                 param = param->next;
4813         }
4814         result = 0;
4815         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4816                 result = read_expr(state, MISC(nfunc,0));
4817         }
4818 #if 0
4819         fprintf(stdout, "\n");
4820         loc(stdout, state, 0);
4821         fprintf(stdout, "\n__________ flatten_call _________\n");
4822         print_triple(state, nfunc);
4823         fprintf(stdout, "__________ flatten_call _________ done\n\n");
4824 #endif
4825
4826         /* Get rid of the extra triples */
4827         nfirst = RHS(nfunc, 0)->next;
4828         free_triple(state, RHS(nfunc, 0));
4829         RHS(nfunc, 0) = 0;
4830         free_triple(state, nfunc);
4831
4832         /* Append the new function list onto the return list */
4833         end = first->prev;
4834         nend = nfirst->prev;
4835         end->next    = nfirst;
4836         nfirst->prev = end;
4837         nend->next   = first;
4838         first->prev  = nend;
4839
4840         return result;
4841 }
4842
4843 static struct triple *flatten(
4844         struct compile_state *state, struct triple *first, struct triple *ptr)
4845 {
4846         struct triple *orig_ptr;
4847         if (!ptr)
4848                 return 0;
4849         do {
4850                 orig_ptr = ptr;
4851                 /* Only flatten triples once */
4852                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4853                         return ptr;
4854                 }
4855                 switch(ptr->op) {
4856                 case OP_WRITE:
4857                 case OP_STORE:
4858                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4859                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4860                         use_triple(LHS(ptr, 0), ptr);
4861                         use_triple(RHS(ptr, 0), ptr);
4862                         break;
4863                 case OP_COMMA:
4864                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4865                         ptr = RHS(ptr, 1);
4866                         break;
4867                 case OP_VAL:
4868                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4869                         return MISC(ptr, 0);
4870                         break;
4871                 case OP_LAND:
4872                         ptr = flatten_land(state, first, ptr);
4873                         break;
4874                 case OP_LOR:
4875                         ptr = flatten_lor(state, first, ptr);
4876                         break;
4877                 case OP_COND:
4878                         ptr = flatten_cond(state, first, ptr);
4879                         break;
4880                 case OP_CALL:
4881                         ptr = flatten_call(state, first, ptr);
4882                         break;
4883                 case OP_READ:
4884                 case OP_LOAD:
4885                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4886                         use_triple(RHS(ptr, 0), ptr);
4887                         break;
4888                 case OP_BRANCH:
4889                         use_triple(TARG(ptr, 0), ptr);
4890                         if (TRIPLE_RHS(ptr->sizes)) {
4891                                 use_triple(RHS(ptr, 0), ptr);
4892                                 if (ptr->next != ptr) {
4893                                         use_triple(ptr->next, ptr);
4894                                 }
4895                         }
4896                         break;
4897                 case OP_BLOBCONST:
4898                         insert_triple(state, first, ptr);
4899                         ptr->id |= TRIPLE_FLAG_FLATTENED;
4900                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4901                         use_triple(MISC(ptr, 0), ptr);
4902                         break;
4903                 case OP_DEREF:
4904                         /* Since OP_DEREF is just a marker delete it when I flatten it */
4905                         ptr = RHS(ptr, 0);
4906                         RHS(orig_ptr, 0) = 0;
4907                         free_triple(state, orig_ptr);
4908                         break;
4909                 case OP_DOT:
4910                 {
4911                         struct triple *base;
4912                         base = RHS(ptr, 0);
4913                         base = flatten(state, first, base);
4914                         if (base->op == OP_VAL_VEC) {
4915                                 ptr = struct_field(state, base, ptr->u.field);
4916                         }
4917                         break;
4918                 }
4919                 case OP_ADDRCONST:
4920                 case OP_SDECL:
4921                 case OP_PIECE:
4922                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4923                         use_triple(MISC(ptr, 0), ptr);
4924                         break;
4925                 case OP_ADECL:
4926                         break;
4927                 default:
4928                         /* Flatten the easy cases we don't override */
4929                         ptr = flatten_generic(state, first, ptr);
4930                         break;
4931                 }
4932         } while(ptr && (ptr != orig_ptr));
4933         if (ptr) {
4934                 insert_triple(state, first, ptr);
4935                 ptr->id |= TRIPLE_FLAG_FLATTENED;
4936         }
4937         return ptr;
4938 }
4939
4940 static void release_expr(struct compile_state *state, struct triple *expr)
4941 {
4942         struct triple *head;
4943         head = label(state);
4944         flatten(state, head, expr);
4945         while(head->next != head) {
4946                 release_triple(state, head->next);
4947         }
4948         free_triple(state, head);
4949 }
4950
4951 static int replace_rhs_use(struct compile_state *state,
4952         struct triple *orig, struct triple *new, struct triple *use)
4953 {
4954         struct triple **expr;
4955         int found;
4956         found = 0;
4957         expr = triple_rhs(state, use, 0);
4958         for(;expr; expr = triple_rhs(state, use, expr)) {
4959                 if (*expr == orig) {
4960                         *expr = new;
4961                         found = 1;
4962                 }
4963         }
4964         if (found) {
4965                 unuse_triple(orig, use);
4966                 use_triple(new, use);
4967         }
4968         return found;
4969 }
4970
4971 static int replace_lhs_use(struct compile_state *state,
4972         struct triple *orig, struct triple *new, struct triple *use)
4973 {
4974         struct triple **expr;
4975         int found;
4976         found = 0;
4977         expr = triple_lhs(state, use, 0);
4978         for(;expr; expr = triple_lhs(state, use, expr)) {
4979                 if (*expr == orig) {
4980                         *expr = new;
4981                         found = 1;
4982                 }
4983         }
4984         if (found) {
4985                 unuse_triple(orig, use);
4986                 use_triple(new, use);
4987         }
4988         return found;
4989 }
4990
4991 static void propogate_use(struct compile_state *state,
4992         struct triple *orig, struct triple *new)
4993 {
4994         struct triple_set *user, *next;
4995         for(user = orig->use; user; user = next) {
4996                 struct triple *use;
4997                 int found;
4998                 next = user->next;
4999                 use = user->member;
5000                 found = 0;
5001                 found |= replace_rhs_use(state, orig, new, use);
5002                 found |= replace_lhs_use(state, orig, new, use);
5003                 if (!found) {
5004                         internal_error(state, use, "use without use");
5005                 }
5006         }
5007         if (orig->use) {
5008                 internal_error(state, orig, "used after propogate_use");
5009         }
5010 }
5011
5012 /*
5013  * Code generators
5014  * ===========================
5015  */
5016
5017 static struct triple *mk_add_expr(
5018         struct compile_state *state, struct triple *left, struct triple *right)
5019 {
5020         struct type *result_type;
5021         /* Put pointer operands on the left */
5022         if (is_pointer(right)) {
5023                 struct triple *tmp;
5024                 tmp = left;
5025                 left = right;
5026                 right = tmp;
5027         }
5028         left  = read_expr(state, left);
5029         right = read_expr(state, right);
5030         result_type = ptr_arithmetic_result(state, left, right);
5031         if (is_pointer(left)) {
5032                 right = triple(state, 
5033                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5034                         &ulong_type, 
5035                         right, 
5036                         int_const(state, &ulong_type, 
5037                                 size_of(state, left->type->left)));
5038         }
5039         return triple(state, OP_ADD, result_type, left, right);
5040 }
5041
5042 static struct triple *mk_sub_expr(
5043         struct compile_state *state, struct triple *left, struct triple *right)
5044 {
5045         struct type *result_type;
5046         result_type = ptr_arithmetic_result(state, left, right);
5047         left  = read_expr(state, left);
5048         right = read_expr(state, right);
5049         if (is_pointer(left)) {
5050                 right = triple(state, 
5051                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5052                         &ulong_type, 
5053                         right, 
5054                         int_const(state, &ulong_type, 
5055                                 size_of(state, left->type->left)));
5056         }
5057         return triple(state, OP_SUB, result_type, left, right);
5058 }
5059
5060 static struct triple *mk_pre_inc_expr(
5061         struct compile_state *state, struct triple *def)
5062 {
5063         struct triple *val;
5064         lvalue(state, def);
5065         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5066         return triple(state, OP_VAL, def->type,
5067                 write_expr(state, def, val),
5068                 val);
5069 }
5070
5071 static struct triple *mk_pre_dec_expr(
5072         struct compile_state *state, struct triple *def)
5073 {
5074         struct triple *val;
5075         lvalue(state, def);
5076         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5077         return triple(state, OP_VAL, def->type,
5078                 write_expr(state, def, val),
5079                 val);
5080 }
5081
5082 static struct triple *mk_post_inc_expr(
5083         struct compile_state *state, struct triple *def)
5084 {
5085         struct triple *val;
5086         lvalue(state, def);
5087         val = read_expr(state, def);
5088         return triple(state, OP_VAL, def->type,
5089                 write_expr(state, def,
5090                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5091                 , val);
5092 }
5093
5094 static struct triple *mk_post_dec_expr(
5095         struct compile_state *state, struct triple *def)
5096 {
5097         struct triple *val;
5098         lvalue(state, def);
5099         val = read_expr(state, def);
5100         return triple(state, OP_VAL, def->type, 
5101                 write_expr(state, def,
5102                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5103                 , val);
5104 }
5105
5106 static struct triple *mk_subscript_expr(
5107         struct compile_state *state, struct triple *left, struct triple *right)
5108 {
5109         left  = read_expr(state, left);
5110         right = read_expr(state, right);
5111         if (!is_pointer(left) && !is_pointer(right)) {
5112                 error(state, left, "subscripted value is not a pointer");
5113         }
5114         return mk_deref_expr(state, mk_add_expr(state, left, right));
5115 }
5116
5117 /*
5118  * Compile time evaluation
5119  * ===========================
5120  */
5121 static int is_const(struct triple *ins)
5122 {
5123         return IS_CONST_OP(ins->op);
5124 }
5125
5126 static int constants_equal(struct compile_state *state, 
5127         struct triple *left, struct triple *right)
5128 {
5129         int equal;
5130         if (!is_const(left) || !is_const(right)) {
5131                 equal = 0;
5132         }
5133         else if (left->op != right->op) {
5134                 equal = 0;
5135         }
5136         else if (!equiv_types(left->type, right->type)) {
5137                 equal = 0;
5138         }
5139         else {
5140                 equal = 0;
5141                 switch(left->op) {
5142                 case OP_INTCONST:
5143                         if (left->u.cval == right->u.cval) {
5144                                 equal = 1;
5145                         }
5146                         break;
5147                 case OP_BLOBCONST:
5148                 {
5149                         size_t lsize, rsize;
5150                         lsize = size_of(state, left->type);
5151                         rsize = size_of(state, right->type);
5152                         if (lsize != rsize) {
5153                                 break;
5154                         }
5155                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5156                                 equal = 1;
5157                         }
5158                         break;
5159                 }
5160                 case OP_ADDRCONST:
5161                         if ((MISC(left, 0) == MISC(right, 0)) &&
5162                                 (left->u.cval == right->u.cval)) {
5163                                 equal = 1;
5164                         }
5165                         break;
5166                 default:
5167                         internal_error(state, left, "uknown constant type");
5168                         break;
5169                 }
5170         }
5171         return equal;
5172 }
5173
5174 static int is_zero(struct triple *ins)
5175 {
5176         return is_const(ins) && (ins->u.cval == 0);
5177 }
5178
5179 static int is_one(struct triple *ins)
5180 {
5181         return is_const(ins) && (ins->u.cval == 1);
5182 }
5183
5184 static long_t bsr(ulong_t value)
5185 {
5186         int i;
5187         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5188                 ulong_t mask;
5189                 mask = 1;
5190                 mask <<= i;
5191                 if (value & mask) {
5192                         return i;
5193                 }
5194         }
5195         return -1;
5196 }
5197
5198 static long_t bsf(ulong_t value)
5199 {
5200         int i;
5201         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5202                 ulong_t mask;
5203                 mask = 1;
5204                 mask <<= 1;
5205                 if (value & mask) {
5206                         return i;
5207                 }
5208         }
5209         return -1;
5210 }
5211
5212 static long_t log2(ulong_t value)
5213 {
5214         return bsr(value);
5215 }
5216
5217 static long_t tlog2(struct triple *ins)
5218 {
5219         return log2(ins->u.cval);
5220 }
5221
5222 static int is_pow2(struct triple *ins)
5223 {
5224         ulong_t value, mask;
5225         long_t log;
5226         if (!is_const(ins)) {
5227                 return 0;
5228         }
5229         value = ins->u.cval;
5230         log = log2(value);
5231         if (log == -1) {
5232                 return 0;
5233         }
5234         mask = 1;
5235         mask <<= log;
5236         return  ((value & mask) == value);
5237 }
5238
5239 static ulong_t read_const(struct compile_state *state,
5240         struct triple *ins, struct triple **expr)
5241 {
5242         struct triple *rhs;
5243         rhs = *expr;
5244         switch(rhs->type->type &TYPE_MASK) {
5245         case TYPE_CHAR:   
5246         case TYPE_SHORT:
5247         case TYPE_INT:
5248         case TYPE_LONG:
5249         case TYPE_UCHAR:   
5250         case TYPE_USHORT:  
5251         case TYPE_UINT:
5252         case TYPE_ULONG:
5253         case TYPE_POINTER:
5254                 break;
5255         default:
5256                 internal_error(state, rhs, "bad type to read_const\n");
5257                 break;
5258         }
5259         return rhs->u.cval;
5260 }
5261
5262 static long_t read_sconst(struct triple *ins, struct triple **expr)
5263 {
5264         struct triple *rhs;
5265         rhs = *expr;
5266         return (long_t)(rhs->u.cval);
5267 }
5268
5269 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5270 {
5271         struct triple **expr;
5272         expr = triple_rhs(state, ins, 0);
5273         for(;expr;expr = triple_rhs(state, ins, expr)) {
5274                 if (*expr) {
5275                         unuse_triple(*expr, ins);
5276                         *expr = 0;
5277                 }
5278         }
5279 }
5280
5281 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5282 {
5283         struct triple **expr;
5284         expr = triple_lhs(state, ins, 0);
5285         for(;expr;expr = triple_lhs(state, ins, expr)) {
5286                 unuse_triple(*expr, ins);
5287                 *expr = 0;
5288         }
5289 }
5290
5291 static void check_lhs(struct compile_state *state, struct triple *ins)
5292 {
5293         struct triple **expr;
5294         expr = triple_lhs(state, ins, 0);
5295         for(;expr;expr = triple_lhs(state, ins, expr)) {
5296                 internal_error(state, ins, "unexpected lhs");
5297         }
5298         
5299 }
5300 static void check_targ(struct compile_state *state, struct triple *ins)
5301 {
5302         struct triple **expr;
5303         expr = triple_targ(state, ins, 0);
5304         for(;expr;expr = triple_targ(state, ins, expr)) {
5305                 internal_error(state, ins, "unexpected targ");
5306         }
5307 }
5308
5309 static void wipe_ins(struct compile_state *state, struct triple *ins)
5310 {
5311         /* Becareful which instructions you replace the wiped
5312          * instruction with, as there are not enough slots
5313          * in all instructions to hold all others.
5314          */
5315         check_targ(state, ins);
5316         unuse_rhs(state, ins);
5317         unuse_lhs(state, ins);
5318 }
5319
5320 static void mkcopy(struct compile_state *state, 
5321         struct triple *ins, struct triple *rhs)
5322 {
5323         wipe_ins(state, ins);
5324         ins->op = OP_COPY;
5325         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5326         RHS(ins, 0) = rhs;
5327         use_triple(RHS(ins, 0), ins);
5328 }
5329
5330 static void mkconst(struct compile_state *state, 
5331         struct triple *ins, ulong_t value)
5332 {
5333         if (!is_integral(ins) && !is_pointer(ins)) {
5334                 internal_error(state, ins, "unknown type to make constant\n");
5335         }
5336         wipe_ins(state, ins);
5337         ins->op = OP_INTCONST;
5338         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5339         ins->u.cval = value;
5340 }
5341
5342 static void mkaddr_const(struct compile_state *state,
5343         struct triple *ins, struct triple *sdecl, ulong_t value)
5344 {
5345         wipe_ins(state, ins);
5346         ins->op = OP_ADDRCONST;
5347         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5348         MISC(ins, 0) = sdecl;
5349         ins->u.cval = value;
5350         use_triple(sdecl, ins);
5351 }
5352
5353 /* Transform multicomponent variables into simple register variables */
5354 static void flatten_structures(struct compile_state *state)
5355 {
5356         struct triple *ins, *first;
5357         first = RHS(state->main_function, 0);
5358         ins = first;
5359         /* Pass one expand structure values into valvecs.
5360          */
5361         ins = first;
5362         do {
5363                 struct triple *next;
5364                 next = ins->next;
5365                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5366                         if (ins->op == OP_VAL_VEC) {
5367                                 /* Do nothing */
5368                         }
5369                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5370                                 struct triple *def, **vector;
5371                                 struct type *tptr;
5372                                 int op;
5373                                 ulong_t i;
5374
5375                                 op = ins->op;
5376                                 def = RHS(ins, 0);
5377                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5378                                         ins->filename, ins->line, ins->col);
5379
5380                                 vector = &RHS(next, 0);
5381                                 tptr = next->type->left;
5382                                 for(i = 0; i < next->type->elements; i++) {
5383                                         struct triple *sfield;
5384                                         struct type *mtype;
5385                                         mtype = tptr;
5386                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5387                                                 mtype = mtype->left;
5388                                         }
5389                                         sfield = deref_field(state, def, mtype->field_ident);
5390                                         
5391                                         vector[i] = triple(
5392                                                 state, op, mtype, sfield, 0);
5393                                         vector[i]->filename = next->filename;
5394                                         vector[i]->line = next->line;
5395                                         vector[i]->col = next->col;
5396                                         tptr = tptr->right;
5397                                 }
5398                                 propogate_use(state, ins, next);
5399                                 flatten(state, ins, next);
5400                                 free_triple(state, ins);
5401                         }
5402                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5403                                 struct triple *src, *dst, **vector;
5404                                 struct type *tptr;
5405                                 int op;
5406                                 ulong_t i;
5407
5408                                 op = ins->op;
5409                                 src = RHS(ins, 0);
5410                                 dst = LHS(ins, 0);
5411                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5412                                         ins->filename, ins->line, ins->col);
5413                                 
5414                                 vector = &RHS(next, 0);
5415                                 tptr = next->type->left;
5416                                 for(i = 0; i < ins->type->elements; i++) {
5417                                         struct triple *dfield, *sfield;
5418                                         struct type *mtype;
5419                                         mtype = tptr;
5420                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5421                                                 mtype = mtype->left;
5422                                         }
5423                                         sfield = deref_field(state, src, mtype->field_ident);
5424                                         dfield = deref_field(state, dst, mtype->field_ident);
5425                                         vector[i] = triple(
5426                                                 state, op, mtype, dfield, sfield);
5427                                         vector[i]->filename = next->filename;
5428                                         vector[i]->line = next->line;
5429                                         vector[i]->col = next->col;
5430                                         tptr = tptr->right;
5431                                 }
5432                                 propogate_use(state, ins, next);
5433                                 flatten(state, ins, next);
5434                                 free_triple(state, ins);
5435                         }
5436                 }
5437                 ins = next;
5438         } while(ins != first);
5439         /* Pass two flatten the valvecs.
5440          */
5441         ins = first;
5442         do {
5443                 struct triple *next;
5444                 next = ins->next;
5445                 if (ins->op == OP_VAL_VEC) {
5446                         release_triple(state, ins);
5447                 } 
5448                 ins = next;
5449         } while(ins != first);
5450         /* Pass three verify the state and set ->id to 0.
5451          */
5452         ins = first;
5453         do {
5454                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5455                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5456                         internal_error(state, 0, "STRUCT_TYPE remains?");
5457                 }
5458                 if (ins->op == OP_DOT) {
5459                         internal_error(state, 0, "OP_DOT remains?");
5460                 }
5461                 if (ins->op == OP_VAL_VEC) {
5462                         internal_error(state, 0, "OP_VAL_VEC remains?");
5463                 }
5464                 ins = ins->next;
5465         } while(ins != first);
5466 }
5467
5468 /* For those operations that cannot be simplified */
5469 static void simplify_noop(struct compile_state *state, struct triple *ins)
5470 {
5471         return;
5472 }
5473
5474 static void simplify_smul(struct compile_state *state, struct triple *ins)
5475 {
5476         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5477                 struct triple *tmp;
5478                 tmp = RHS(ins, 0);
5479                 RHS(ins, 0) = RHS(ins, 1);
5480                 RHS(ins, 1) = tmp;
5481         }
5482         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5483                 long_t left, right;
5484                 left  = read_sconst(ins, &RHS(ins, 0));
5485                 right = read_sconst(ins, &RHS(ins, 1));
5486                 mkconst(state, ins, left * right);
5487         }
5488         else if (is_zero(RHS(ins, 1))) {
5489                 mkconst(state, ins, 0);
5490         }
5491         else if (is_one(RHS(ins, 1))) {
5492                 mkcopy(state, ins, RHS(ins, 0));
5493         }
5494         else if (is_pow2(RHS(ins, 1))) {
5495                 struct triple *val;
5496                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5497                 ins->op = OP_SL;
5498                 insert_triple(state, ins, val);
5499                 unuse_triple(RHS(ins, 1), ins);
5500                 use_triple(val, ins);
5501                 RHS(ins, 1) = val;
5502         }
5503 }
5504
5505 static void simplify_umul(struct compile_state *state, struct triple *ins)
5506 {
5507         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5508                 struct triple *tmp;
5509                 tmp = RHS(ins, 0);
5510                 RHS(ins, 0) = RHS(ins, 1);
5511                 RHS(ins, 1) = tmp;
5512         }
5513         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5514                 ulong_t left, right;
5515                 left  = read_const(state, ins, &RHS(ins, 0));
5516                 right = read_const(state, ins, &RHS(ins, 1));
5517                 mkconst(state, ins, left * right);
5518         }
5519         else if (is_zero(RHS(ins, 1))) {
5520                 mkconst(state, ins, 0);
5521         }
5522         else if (is_one(RHS(ins, 1))) {
5523                 mkcopy(state, ins, RHS(ins, 0));
5524         }
5525         else if (is_pow2(RHS(ins, 1))) {
5526                 struct triple *val;
5527                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5528                 ins->op = OP_SL;
5529                 insert_triple(state, ins, val);
5530                 unuse_triple(RHS(ins, 1), ins);
5531                 use_triple(val, ins);
5532                 RHS(ins, 1) = val;
5533         }
5534 }
5535
5536 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5537 {
5538         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5539                 long_t left, right;
5540                 left  = read_sconst(ins, &RHS(ins, 0));
5541                 right = read_sconst(ins, &RHS(ins, 1));
5542                 mkconst(state, ins, left / right);
5543         }
5544         else if (is_zero(RHS(ins, 0))) {
5545                 mkconst(state, ins, 0);
5546         }
5547         else if (is_zero(RHS(ins, 1))) {
5548                 error(state, ins, "division by zero");
5549         }
5550         else if (is_one(RHS(ins, 1))) {
5551                 mkcopy(state, ins, RHS(ins, 0));
5552         }
5553         else if (is_pow2(RHS(ins, 1))) {
5554                 struct triple *val;
5555                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5556                 ins->op = OP_SSR;
5557                 insert_triple(state, ins, val);
5558                 unuse_triple(RHS(ins, 1), ins);
5559                 use_triple(val, ins);
5560                 RHS(ins, 1) = val;
5561         }
5562 }
5563
5564 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5565 {
5566         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5567                 ulong_t left, right;
5568                 left  = read_const(state, ins, &RHS(ins, 0));
5569                 right = read_const(state, ins, &RHS(ins, 1));
5570                 mkconst(state, ins, left / right);
5571         }
5572         else if (is_zero(RHS(ins, 0))) {
5573                 mkconst(state, ins, 0);
5574         }
5575         else if (is_zero(RHS(ins, 1))) {
5576                 error(state, ins, "division by zero");
5577         }
5578         else if (is_one(RHS(ins, 1))) {
5579                 mkcopy(state, ins, RHS(ins, 0));
5580         }
5581         else if (is_pow2(RHS(ins, 1))) {
5582                 struct triple *val;
5583                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5584                 ins->op = OP_USR;
5585                 insert_triple(state, ins, val);
5586                 unuse_triple(RHS(ins, 1), ins);
5587                 use_triple(val, ins);
5588                 RHS(ins, 1) = val;
5589         }
5590 }
5591
5592 static void simplify_smod(struct compile_state *state, struct triple *ins)
5593 {
5594         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5595                 long_t left, right;
5596                 left  = read_const(state, ins, &RHS(ins, 0));
5597                 right = read_const(state, ins, &RHS(ins, 1));
5598                 mkconst(state, ins, left % right);
5599         }
5600         else if (is_zero(RHS(ins, 0))) {
5601                 mkconst(state, ins, 0);
5602         }
5603         else if (is_zero(RHS(ins, 1))) {
5604                 error(state, ins, "division by zero");
5605         }
5606         else if (is_one(RHS(ins, 1))) {
5607                 mkconst(state, ins, 0);
5608         }
5609         else if (is_pow2(RHS(ins, 1))) {
5610                 struct triple *val;
5611                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5612                 ins->op = OP_AND;
5613                 insert_triple(state, ins, val);
5614                 unuse_triple(RHS(ins, 1), ins);
5615                 use_triple(val, ins);
5616                 RHS(ins, 1) = val;
5617         }
5618 }
5619 static void simplify_umod(struct compile_state *state, struct triple *ins)
5620 {
5621         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5622                 ulong_t left, right;
5623                 left  = read_const(state, ins, &RHS(ins, 0));
5624                 right = read_const(state, ins, &RHS(ins, 1));
5625                 mkconst(state, ins, left % right);
5626         }
5627         else if (is_zero(RHS(ins, 0))) {
5628                 mkconst(state, ins, 0);
5629         }
5630         else if (is_zero(RHS(ins, 1))) {
5631                 error(state, ins, "division by zero");
5632         }
5633         else if (is_one(RHS(ins, 1))) {
5634                 mkconst(state, ins, 0);
5635         }
5636         else if (is_pow2(RHS(ins, 1))) {
5637                 struct triple *val;
5638                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5639                 ins->op = OP_AND;
5640                 insert_triple(state, ins, val);
5641                 unuse_triple(RHS(ins, 1), ins);
5642                 use_triple(val, ins);
5643                 RHS(ins, 1) = val;
5644         }
5645 }
5646
5647 static void simplify_add(struct compile_state *state, struct triple *ins)
5648 {
5649         /* start with the pointer on the left */
5650         if (is_pointer(RHS(ins, 1))) {
5651                 struct triple *tmp;
5652                 tmp = RHS(ins, 0);
5653                 RHS(ins, 0) = RHS(ins, 1);
5654                 RHS(ins, 1) = tmp;
5655         }
5656         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5657                 if (!is_pointer(RHS(ins, 0))) {
5658                         ulong_t left, right;
5659                         left  = read_const(state, ins, &RHS(ins, 0));
5660                         right = read_const(state, ins, &RHS(ins, 1));
5661                         mkconst(state, ins, left + right);
5662                 }
5663                 else /* op == OP_ADDRCONST */ {
5664                         struct triple *sdecl;
5665                         ulong_t left, right;
5666                         sdecl = MISC(RHS(ins, 0), 0);
5667                         left  = RHS(ins, 0)->u.cval;
5668                         right = RHS(ins, 1)->u.cval;
5669                         mkaddr_const(state, ins, sdecl, left + right);
5670                 }
5671         }
5672         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5673                 struct triple *tmp;
5674                 tmp = RHS(ins, 1);
5675                 RHS(ins, 1) = RHS(ins, 0);
5676                 RHS(ins, 0) = tmp;
5677         }
5678 }
5679
5680 static void simplify_sub(struct compile_state *state, struct triple *ins)
5681 {
5682         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5683                 if (!is_pointer(RHS(ins, 0))) {
5684                         ulong_t left, right;
5685                         left  = read_const(state, ins, &RHS(ins, 0));
5686                         right = read_const(state, ins, &RHS(ins, 1));
5687                         mkconst(state, ins, left - right);
5688                 }
5689                 else /* op == OP_ADDRCONST */ {
5690                         struct triple *sdecl;
5691                         ulong_t left, right;
5692                         sdecl = MISC(RHS(ins, 0), 0);
5693                         left  = RHS(ins, 0)->u.cval;
5694                         right = RHS(ins, 1)->u.cval;
5695                         mkaddr_const(state, ins, sdecl, left - right);
5696                 }
5697         }
5698 }
5699
5700 static void simplify_sl(struct compile_state *state, struct triple *ins)
5701 {
5702         if (is_const(RHS(ins, 1))) {
5703                 ulong_t right;
5704                 right = read_const(state, ins, &RHS(ins, 1));
5705                 if (right >= (size_of(state, ins->type)*8)) {
5706                         warning(state, ins, "left shift count >= width of type");
5707                 }
5708         }
5709         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5710                 ulong_t left, right;
5711                 left  = read_const(state, ins, &RHS(ins, 0));
5712                 right = read_const(state, ins, &RHS(ins, 1));
5713                 mkconst(state, ins,  left << right);
5714         }
5715 }
5716
5717 static void simplify_usr(struct compile_state *state, struct triple *ins)
5718 {
5719         if (is_const(RHS(ins, 1))) {
5720                 ulong_t right;
5721                 right = read_const(state, ins, &RHS(ins, 1));
5722                 if (right >= (size_of(state, ins->type)*8)) {
5723                         warning(state, ins, "right shift count >= width of type");
5724                 }
5725         }
5726         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5727                 ulong_t left, right;
5728                 left  = read_const(state, ins, &RHS(ins, 0));
5729                 right = read_const(state, ins, &RHS(ins, 1));
5730                 mkconst(state, ins, left >> right);
5731         }
5732 }
5733
5734 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5735 {
5736         if (is_const(RHS(ins, 1))) {
5737                 ulong_t right;
5738                 right = read_const(state, ins, &RHS(ins, 1));
5739                 if (right >= (size_of(state, ins->type)*8)) {
5740                         warning(state, ins, "right shift count >= width of type");
5741                 }
5742         }
5743         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5744                 long_t left, right;
5745                 left  = read_sconst(ins, &RHS(ins, 0));
5746                 right = read_sconst(ins, &RHS(ins, 1));
5747                 mkconst(state, ins, left >> right);
5748         }
5749 }
5750
5751 static void simplify_and(struct compile_state *state, struct triple *ins)
5752 {
5753         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5754                 ulong_t left, right;
5755                 left  = read_const(state, ins, &RHS(ins, 0));
5756                 right = read_const(state, ins, &RHS(ins, 1));
5757                 mkconst(state, ins, left & right);
5758         }
5759 }
5760
5761 static void simplify_or(struct compile_state *state, struct triple *ins)
5762 {
5763         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5764                 ulong_t left, right;
5765                 left  = read_const(state, ins, &RHS(ins, 0));
5766                 right = read_const(state, ins, &RHS(ins, 1));
5767                 mkconst(state, ins, left | right);
5768         }
5769 }
5770
5771 static void simplify_xor(struct compile_state *state, struct triple *ins)
5772 {
5773         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5774                 ulong_t left, right;
5775                 left  = read_const(state, ins, &RHS(ins, 0));
5776                 right = read_const(state, ins, &RHS(ins, 1));
5777                 mkconst(state, ins, left ^ right);
5778         }
5779 }
5780
5781 static void simplify_pos(struct compile_state *state, struct triple *ins)
5782 {
5783         if (is_const(RHS(ins, 0))) {
5784                 mkconst(state, ins, RHS(ins, 0)->u.cval);
5785         }
5786         else {
5787                 mkcopy(state, ins, RHS(ins, 0));
5788         }
5789 }
5790
5791 static void simplify_neg(struct compile_state *state, struct triple *ins)
5792 {
5793         if (is_const(RHS(ins, 0))) {
5794                 ulong_t left;
5795                 left = read_const(state, ins, &RHS(ins, 0));
5796                 mkconst(state, ins, -left);
5797         }
5798         else if (RHS(ins, 0)->op == OP_NEG) {
5799                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5800         }
5801 }
5802
5803 static void simplify_invert(struct compile_state *state, struct triple *ins)
5804 {
5805         if (is_const(RHS(ins, 0))) {
5806                 ulong_t left;
5807                 left = read_const(state, ins, &RHS(ins, 0));
5808                 mkconst(state, ins, ~left);
5809         }
5810 }
5811
5812 static void simplify_eq(struct compile_state *state, struct triple *ins)
5813 {
5814         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5815                 ulong_t left, right;
5816                 left  = read_const(state, ins, &RHS(ins, 0));
5817                 right = read_const(state, ins, &RHS(ins, 1));
5818                 mkconst(state, ins, left == right);
5819         }
5820         else if (RHS(ins, 0) == RHS(ins, 1)) {
5821                 mkconst(state, ins, 1);
5822         }
5823 }
5824
5825 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5826 {
5827         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5828                 ulong_t left, right;
5829                 left  = read_const(state, ins, &RHS(ins, 0));
5830                 right = read_const(state, ins, &RHS(ins, 1));
5831                 mkconst(state, ins, left != right);
5832         }
5833         else if (RHS(ins, 0) == RHS(ins, 1)) {
5834                 mkconst(state, ins, 0);
5835         }
5836 }
5837
5838 static void simplify_sless(struct compile_state *state, struct triple *ins)
5839 {
5840         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5841                 long_t left, right;
5842                 left  = read_sconst(ins, &RHS(ins, 0));
5843                 right = read_sconst(ins, &RHS(ins, 1));
5844                 mkconst(state, ins, left < right);
5845         }
5846         else if (RHS(ins, 0) == RHS(ins, 1)) {
5847                 mkconst(state, ins, 0);
5848         }
5849 }
5850
5851 static void simplify_uless(struct compile_state *state, struct triple *ins)
5852 {
5853         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5854                 ulong_t left, right;
5855                 left  = read_const(state, ins, &RHS(ins, 0));
5856                 right = read_const(state, ins, &RHS(ins, 1));
5857                 mkconst(state, ins, left < right);
5858         }
5859         else if (is_zero(RHS(ins, 0))) {
5860                 mkconst(state, ins, 1);
5861         }
5862         else if (RHS(ins, 0) == RHS(ins, 1)) {
5863                 mkconst(state, ins, 0);
5864         }
5865 }
5866
5867 static void simplify_smore(struct compile_state *state, struct triple *ins)
5868 {
5869         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5870                 long_t left, right;
5871                 left  = read_sconst(ins, &RHS(ins, 0));
5872                 right = read_sconst(ins, &RHS(ins, 1));
5873                 mkconst(state, ins, left > right);
5874         }
5875         else if (RHS(ins, 0) == RHS(ins, 1)) {
5876                 mkconst(state, ins, 0);
5877         }
5878 }
5879
5880 static void simplify_umore(struct compile_state *state, struct triple *ins)
5881 {
5882         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5883                 ulong_t left, right;
5884                 left  = read_const(state, ins, &RHS(ins, 0));
5885                 right = read_const(state, ins, &RHS(ins, 1));
5886                 mkconst(state, ins, left > right);
5887         }
5888         else if (is_zero(RHS(ins, 1))) {
5889                 mkconst(state, ins, 1);
5890         }
5891         else if (RHS(ins, 0) == RHS(ins, 1)) {
5892                 mkconst(state, ins, 0);
5893         }
5894 }
5895
5896
5897 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5898 {
5899         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5900                 long_t left, right;
5901                 left  = read_sconst(ins, &RHS(ins, 0));
5902                 right = read_sconst(ins, &RHS(ins, 1));
5903                 mkconst(state, ins, left <= right);
5904         }
5905         else if (RHS(ins, 0) == RHS(ins, 1)) {
5906                 mkconst(state, ins, 1);
5907         }
5908 }
5909
5910 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5911 {
5912         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5913                 ulong_t left, right;
5914                 left  = read_const(state, ins, &RHS(ins, 0));
5915                 right = read_const(state, ins, &RHS(ins, 1));
5916                 mkconst(state, ins, left <= right);
5917         }
5918         else if (is_zero(RHS(ins, 0))) {
5919                 mkconst(state, ins, 1);
5920         }
5921         else if (RHS(ins, 0) == RHS(ins, 1)) {
5922                 mkconst(state, ins, 1);
5923         }
5924 }
5925
5926 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5927 {
5928         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5929                 long_t left, right;
5930                 left  = read_sconst(ins, &RHS(ins, 0));
5931                 right = read_sconst(ins, &RHS(ins, 1));
5932                 mkconst(state, ins, left >= right);
5933         }
5934         else if (RHS(ins, 0) == RHS(ins, 1)) {
5935                 mkconst(state, ins, 1);
5936         }
5937 }
5938
5939 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5940 {
5941         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5942                 ulong_t left, right;
5943                 left  = read_const(state, ins, &RHS(ins, 0));
5944                 right = read_const(state, ins, &RHS(ins, 1));
5945                 mkconst(state, ins, left >= right);
5946         }
5947         else if (is_zero(RHS(ins, 1))) {
5948                 mkconst(state, ins, 1);
5949         }
5950         else if (RHS(ins, 0) == RHS(ins, 1)) {
5951                 mkconst(state, ins, 1);
5952         }
5953 }
5954
5955 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5956 {
5957         if (is_const(RHS(ins, 0))) {
5958                 ulong_t left;
5959                 left = read_const(state, ins, &RHS(ins, 0));
5960                 mkconst(state, ins, left == 0);
5961         }
5962         /* Otherwise if I am the only user... */
5963         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5964                 int need_copy = 1;
5965                 /* Invert a boolean operation */
5966                 switch(RHS(ins, 0)->op) {
5967                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
5968                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
5969                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
5970                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
5971                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
5972                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
5973                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
5974                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
5975                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
5976                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
5977                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
5978                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
5979                 default:
5980                         need_copy = 0;
5981                         break;
5982                 }
5983                 if (need_copy) {
5984                         mkcopy(state, ins, RHS(ins, 0));
5985                 }
5986         }
5987 }
5988
5989 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5990 {
5991         if (is_const(RHS(ins, 0))) {
5992                 ulong_t left;
5993                 left = read_const(state, ins, &RHS(ins, 0));
5994                 mkconst(state, ins, left != 0);
5995         }
5996         else switch(RHS(ins, 0)->op) {
5997         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
5998         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
5999         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6000                 mkcopy(state, ins, RHS(ins, 0));
6001         }
6002
6003 }
6004
6005 static void simplify_copy(struct compile_state *state, struct triple *ins)
6006 {
6007         if (is_const(RHS(ins, 0))) {
6008                 switch(RHS(ins, 0)->op) {
6009                 case OP_INTCONST:
6010                 {
6011                         ulong_t left;
6012                         left = read_const(state, ins, &RHS(ins, 0));
6013                         mkconst(state, ins, left);
6014                         break;
6015                 }
6016                 case OP_ADDRCONST:
6017                 {
6018                         struct triple *sdecl;
6019                         ulong_t offset;
6020                         sdecl  = MISC(RHS(ins, 0), 0);
6021                         offset = RHS(ins, 0)->u.cval;
6022                         mkaddr_const(state, ins, sdecl, offset);
6023                         break;
6024                 }
6025                 default:
6026                         internal_error(state, ins, "uknown constant");
6027                         break;
6028                 }
6029         }
6030 }
6031
6032 static void simplify_branch(struct compile_state *state, struct triple *ins)
6033 {
6034         struct block *block;
6035         if (ins->op != OP_BRANCH) {
6036                 internal_error(state, ins, "not branch");
6037         }
6038         if (ins->use != 0) {
6039                 internal_error(state, ins, "branch use");
6040         }
6041 #warning "FIXME implement simplify branch."
6042         /* The challenge here with simplify branch is that I need to 
6043          * make modifications to the control flow graph as well
6044          * as to the branch instruction itself.
6045          */
6046         block = ins->u.block;
6047         
6048         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6049                 struct triple *targ;
6050                 ulong_t value;
6051                 value = read_const(state, ins, &RHS(ins, 0));
6052                 unuse_triple(RHS(ins, 0), ins);
6053                 targ = TARG(ins, 0);
6054                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6055                 if (value) {
6056                         unuse_triple(ins->next, ins);
6057                         TARG(ins, 0) = targ;
6058                 }
6059                 else {
6060                         unuse_triple(targ, ins);
6061                         TARG(ins, 0) = ins->next;
6062                 }
6063 #warning "FIXME handle the case of making a branch unconditional"
6064         }
6065         if (TARG(ins, 0) == ins->next) {
6066                 unuse_triple(ins->next, ins);
6067                 if (TRIPLE_RHS(ins->sizes)) {
6068                         unuse_triple(RHS(ins, 0), ins);
6069                         unuse_triple(ins->next, ins);
6070                 }
6071                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6072                 ins->op = OP_NOOP;
6073                 if (ins->use) {
6074                         internal_error(state, ins, "noop use != 0");
6075                 }
6076 #warning "FIXME handle the case of killing a branch"
6077         }
6078 }
6079
6080 static void simplify_phi(struct compile_state *state, struct triple *ins)
6081 {
6082         struct triple **expr;
6083         ulong_t value;
6084         expr = triple_rhs(state, ins, 0);
6085         if (!*expr || !is_const(*expr)) {
6086                 return;
6087         }
6088         value = read_const(state, ins, expr);
6089         for(;expr;expr = triple_rhs(state, ins, expr)) {
6090                 if (!*expr || !is_const(*expr)) {
6091                         return;
6092                 }
6093                 if (value != read_const(state, ins, expr)) {
6094                         return;
6095                 }
6096         }
6097         mkconst(state, ins, value);
6098 }
6099
6100
6101 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6102 {
6103         if (is_const(RHS(ins, 0))) {
6104                 ulong_t left;
6105                 left = read_const(state, ins, &RHS(ins, 0));
6106                 mkconst(state, ins, bsf(left));
6107         }
6108 }
6109
6110 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6111 {
6112         if (is_const(RHS(ins, 0))) {
6113                 ulong_t left;
6114                 left = read_const(state, ins, &RHS(ins, 0));
6115                 mkconst(state, ins, bsr(left));
6116         }
6117 }
6118
6119
6120 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6121 static const simplify_t table_simplify[] = {
6122 #if 0
6123 #define simplify_smul     simplify_noop
6124 #define simplify_umul     simplify_noop
6125 #define simplify_sdiv     simplify_noop
6126 #define simplify_udiv     simplify_noop
6127 #define simplify_smod     simplify_noop
6128 #define simplify_umod     simplify_noop
6129 #endif
6130 #if 0
6131 #define simplify_add      simplify_noop
6132 #define simplify_sub      simplify_noop
6133 #endif
6134 #if 0
6135 #define simplify_sl       simplify_noop
6136 #define simplify_usr      simplify_noop
6137 #define simplify_ssr      simplify_noop
6138 #endif
6139 #if 0
6140 #define simplify_and      simplify_noop
6141 #define simplify_xor      simplify_noop
6142 #define simplify_or       simplify_noop
6143 #endif
6144 #if 0
6145 #define simplify_pos      simplify_noop
6146 #define simplify_neg      simplify_noop
6147 #define simplify_invert   simplify_noop
6148 #endif
6149
6150 #if 0
6151 #define simplify_eq       simplify_noop
6152 #define simplify_noteq    simplify_noop
6153 #endif
6154 #if 0
6155 #define simplify_sless    simplify_noop
6156 #define simplify_uless    simplify_noop
6157 #define simplify_smore    simplify_noop
6158 #define simplify_umore    simplify_noop
6159 #endif
6160 #if 0
6161 #define simplify_slesseq  simplify_noop
6162 #define simplify_ulesseq  simplify_noop
6163 #define simplify_smoreeq  simplify_noop
6164 #define simplify_umoreeq  simplify_noop
6165 #endif
6166 #if 0
6167 #define simplify_lfalse   simplify_noop
6168 #endif
6169 #if 0
6170 #define simplify_ltrue    simplify_noop
6171 #endif
6172
6173 #if 0
6174 #define simplify_copy     simplify_noop
6175 #endif
6176
6177 #if 0
6178 #define simplify_branch   simplify_noop
6179 #endif
6180
6181 #if 0
6182 #define simplify_phi      simplify_noop
6183 #endif
6184
6185 #if 0
6186 #define simplify_bsf      simplify_noop
6187 #define simplify_bsr      simplify_noop
6188 #endif
6189
6190 [OP_SMUL       ] = simplify_smul,
6191 [OP_UMUL       ] = simplify_umul,
6192 [OP_SDIV       ] = simplify_sdiv,
6193 [OP_UDIV       ] = simplify_udiv,
6194 [OP_SMOD       ] = simplify_smod,
6195 [OP_UMOD       ] = simplify_umod,
6196 [OP_ADD        ] = simplify_add,
6197 [OP_SUB        ] = simplify_sub,
6198 [OP_SL         ] = simplify_sl,
6199 [OP_USR        ] = simplify_usr,
6200 [OP_SSR        ] = simplify_ssr,
6201 [OP_AND        ] = simplify_and,
6202 [OP_XOR        ] = simplify_xor,
6203 [OP_OR         ] = simplify_or,
6204 [OP_POS        ] = simplify_pos,
6205 [OP_NEG        ] = simplify_neg,
6206 [OP_INVERT     ] = simplify_invert,
6207
6208 [OP_EQ         ] = simplify_eq,
6209 [OP_NOTEQ      ] = simplify_noteq,
6210 [OP_SLESS      ] = simplify_sless,
6211 [OP_ULESS      ] = simplify_uless,
6212 [OP_SMORE      ] = simplify_smore,
6213 [OP_UMORE      ] = simplify_umore,
6214 [OP_SLESSEQ    ] = simplify_slesseq,
6215 [OP_ULESSEQ    ] = simplify_ulesseq,
6216 [OP_SMOREEQ    ] = simplify_smoreeq,
6217 [OP_UMOREEQ    ] = simplify_umoreeq,
6218 [OP_LFALSE     ] = simplify_lfalse,
6219 [OP_LTRUE      ] = simplify_ltrue,
6220
6221 [OP_LOAD       ] = simplify_noop,
6222 [OP_STORE      ] = simplify_noop,
6223
6224 [OP_NOOP       ] = simplify_noop,
6225
6226 [OP_INTCONST   ] = simplify_noop,
6227 [OP_BLOBCONST  ] = simplify_noop,
6228 [OP_ADDRCONST  ] = simplify_noop,
6229
6230 [OP_WRITE      ] = simplify_noop,
6231 [OP_READ       ] = simplify_noop,
6232 [OP_COPY       ] = simplify_copy,
6233 [OP_PIECE      ] = simplify_noop,
6234 [OP_ASM        ] = simplify_noop,
6235
6236 [OP_DOT        ] = simplify_noop,
6237 [OP_VAL_VEC    ] = simplify_noop,
6238
6239 [OP_LIST       ] = simplify_noop,
6240 [OP_BRANCH     ] = simplify_branch,
6241 [OP_LABEL      ] = simplify_noop,
6242 [OP_ADECL      ] = simplify_noop,
6243 [OP_SDECL      ] = simplify_noop,
6244 [OP_PHI        ] = simplify_phi,
6245
6246 [OP_INB        ] = simplify_noop,
6247 [OP_INW        ] = simplify_noop,
6248 [OP_INL        ] = simplify_noop,
6249 [OP_OUTB       ] = simplify_noop,
6250 [OP_OUTW       ] = simplify_noop,
6251 [OP_OUTL       ] = simplify_noop,
6252 [OP_BSF        ] = simplify_bsf,
6253 [OP_BSR        ] = simplify_bsr,
6254 [OP_RDMSR      ] = simplify_noop,
6255 [OP_WRMSR      ] = simplify_noop,                    
6256 [OP_HLT        ] = simplify_noop,
6257 };
6258
6259 static void simplify(struct compile_state *state, struct triple *ins)
6260 {
6261         int op;
6262         simplify_t do_simplify;
6263         do {
6264                 op = ins->op;
6265                 do_simplify = 0;
6266                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6267                         do_simplify = 0;
6268                 }
6269                 else {
6270                         do_simplify = table_simplify[op];
6271                 }
6272                 if (!do_simplify) {
6273                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6274                                 op, tops(op));
6275                         return;
6276                 }
6277                 do_simplify(state, ins);
6278         } while(ins->op != op);
6279 }
6280
6281 static void simplify_all(struct compile_state *state)
6282 {
6283         struct triple *ins, *first;
6284         first = RHS(state->main_function, 0);
6285         ins = first;
6286         do {
6287                 simplify(state, ins);
6288                 ins = ins->next;
6289         } while(ins != first);
6290 }
6291
6292 /*
6293  * Builtins....
6294  * ============================
6295  */
6296
6297 static void register_builtin_function(struct compile_state *state,
6298         const char *name, int op, struct type *rtype, ...)
6299 {
6300         struct type *ftype, *atype, *param, **next;
6301         struct triple *def, *arg, *result, *work, *last, *first;
6302         struct hash_entry *ident;
6303         struct file_state file;
6304         int parameters;
6305         int name_len;
6306         va_list args;
6307         int i;
6308
6309         /* Dummy file state to get debug handling right */
6310         memset(&file, 0, sizeof(file));
6311         file.basename = name;
6312         file.line = 1;
6313         file.prev = state->file;
6314         state->file = &file;
6315
6316         /* Find the Parameter count */
6317         valid_op(state, op);
6318         parameters = table_ops[op].rhs;
6319         if (parameters < 0 ) {
6320                 internal_error(state, 0, "Invalid builtin parameter count");
6321         }
6322
6323         /* Find the function type */
6324         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6325         next = &ftype->right;
6326         va_start(args, rtype);
6327         for(i = 0; i < parameters; i++) {
6328                 atype = va_arg(args, struct type *);
6329                 if (!*next) {
6330                         *next = atype;
6331                 } else {
6332                         *next = new_type(TYPE_PRODUCT, *next, atype);
6333                         next = &((*next)->right);
6334                 }
6335         }
6336         if (!*next) {
6337                 *next = &void_type;
6338         }
6339         va_end(args);
6340
6341         /* Generate the needed triples */
6342         def = triple(state, OP_LIST, ftype, 0, 0);
6343         first = label(state);
6344         RHS(def, 0) = first;
6345
6346         /* Now string them together */
6347         param = ftype->right;
6348         for(i = 0; i < parameters; i++) {
6349                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6350                         atype = param->left;
6351                 } else {
6352                         atype = param;
6353                 }
6354                 arg = flatten(state, first, variable(state, atype));
6355                 param = param->right;
6356         }
6357         result = 0;
6358         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6359                 result = flatten(state, first, variable(state, rtype));
6360         }
6361         MISC(def, 0) = result;
6362         work = new_triple(state, op, rtype, -1, parameters);
6363         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6364                 RHS(work, i) = read_expr(state, arg);
6365         }
6366         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6367                 struct triple *val;
6368                 /* Populate the LHS with the target registers */
6369                 work = flatten(state, first, work);
6370                 work->type = &void_type;
6371                 param = rtype->left;
6372                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6373                         internal_error(state, 0, "Invalid result type");
6374                 }
6375                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6376                 for(i = 0; i < rtype->elements; i++) {
6377                         struct triple *piece;
6378                         atype = param;
6379                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6380                                 atype = param->left;
6381                         }
6382                         if (!TYPE_ARITHMETIC(atype->type) &&
6383                                 !TYPE_PTR(atype->type)) {
6384                                 internal_error(state, 0, "Invalid lhs type");
6385                         }
6386                         piece = triple(state, OP_PIECE, atype, work, 0);
6387                         piece->u.cval = i;
6388                         LHS(work, i) = piece;
6389                         RHS(val, i) = piece;
6390                 }
6391                 work = val;
6392         }
6393         if (result) {
6394                 work = write_expr(state, result, work);
6395         }
6396         work = flatten(state, first, work);
6397         last = flatten(state, first, label(state));
6398         name_len = strlen(name);
6399         ident = lookup(state, name, name_len);
6400         symbol(state, ident, &ident->sym_ident, def, ftype);
6401         
6402         state->file = file.prev;
6403 #if 0
6404         fprintf(stdout, "\n");
6405         loc(stdout, state, 0);
6406         fprintf(stdout, "\n__________ builtin_function _________\n");
6407         print_triple(state, def);
6408         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6409 #endif
6410 }
6411
6412 static struct type *partial_struct(struct compile_state *state,
6413         const char *field_name, struct type *type, struct type *rest)
6414 {
6415         struct hash_entry *field_ident;
6416         struct type *result;
6417         int field_name_len;
6418
6419         field_name_len = strlen(field_name);
6420         field_ident = lookup(state, field_name, field_name_len);
6421
6422         result = clone_type(0, type);
6423         result->field_ident = field_ident;
6424
6425         if (rest) {
6426                 result = new_type(TYPE_PRODUCT, result, rest);
6427         }
6428         return result;
6429 }
6430
6431 static struct type *register_builtin_type(struct compile_state *state,
6432         const char *name, struct type *type)
6433 {
6434         struct hash_entry *ident;
6435         int name_len;
6436
6437         name_len = strlen(name);
6438         ident = lookup(state, name, name_len);
6439         
6440         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6441                 ulong_t elements = 0;
6442                 struct type *field;
6443                 type = new_type(TYPE_STRUCT, type, 0);
6444                 field = type->left;
6445                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6446                         elements++;
6447                         field = field->right;
6448                 }
6449                 elements++;
6450                 symbol(state, ident, &ident->sym_struct, 0, type);
6451                 type->type_ident = ident;
6452                 type->elements = elements;
6453         }
6454         symbol(state, ident, &ident->sym_ident, 0, type);
6455         ident->tok = TOK_TYPE_NAME;
6456         return type;
6457 }
6458
6459
6460 static void register_builtins(struct compile_state *state)
6461 {
6462         struct type *msr_type;
6463
6464         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6465                 &ushort_type);
6466         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6467                 &ushort_type);
6468         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6469                 &ushort_type);
6470
6471         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6472                 &uchar_type, &ushort_type);
6473         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6474                 &ushort_type, &ushort_type);
6475         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6476                 &uint_type, &ushort_type);
6477         
6478         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6479                 &int_type);
6480         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6481                 &int_type);
6482
6483         msr_type = register_builtin_type(state, "__builtin_msr_t",
6484                 partial_struct(state, "lo", &ulong_type,
6485                 partial_struct(state, "hi", &ulong_type, 0)));
6486
6487         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6488                 &ulong_type);
6489         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6490                 &ulong_type, &ulong_type, &ulong_type);
6491         
6492         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6493                 &void_type);
6494 }
6495
6496 static struct type *declarator(
6497         struct compile_state *state, struct type *type, 
6498         struct hash_entry **ident, int need_ident);
6499 static void decl(struct compile_state *state, struct triple *first);
6500 static struct type *specifier_qualifier_list(struct compile_state *state);
6501 static int isdecl_specifier(int tok);
6502 static struct type *decl_specifiers(struct compile_state *state);
6503 static int istype(int tok);
6504 static struct triple *expr(struct compile_state *state);
6505 static struct triple *assignment_expr(struct compile_state *state);
6506 static struct type *type_name(struct compile_state *state);
6507 static void statement(struct compile_state *state, struct triple *fist);
6508
6509 static struct triple *call_expr(
6510         struct compile_state *state, struct triple *func)
6511 {
6512         struct triple *def;
6513         struct type *param, *type;
6514         ulong_t pvals, index;
6515
6516         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6517                 error(state, 0, "Called object is not a function");
6518         }
6519         if (func->op != OP_LIST) {
6520                 internal_error(state, 0, "improper function");
6521         }
6522         eat(state, TOK_LPAREN);
6523         /* Find the return type without any specifiers */
6524         type = clone_type(0, func->type->left);
6525         def = new_triple(state, OP_CALL, func->type, -1, -1);
6526         def->type = type;
6527
6528         pvals = TRIPLE_RHS(def->sizes);
6529         MISC(def, 0) = func;
6530
6531         param = func->type->right;
6532         for(index = 0; index < pvals; index++) {
6533                 struct triple *val;
6534                 struct type *arg_type;
6535                 val = read_expr(state, assignment_expr(state));
6536                 arg_type = param;
6537                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6538                         arg_type = param->left;
6539                 }
6540                 write_compatible(state, arg_type, val->type);
6541                 RHS(def, index) = val;
6542                 if (index != (pvals - 1)) {
6543                         eat(state, TOK_COMMA);
6544                         param = param->right;
6545                 }
6546         }
6547         eat(state, TOK_RPAREN);
6548         return def;
6549 }
6550
6551
6552 static struct triple *character_constant(struct compile_state *state)
6553 {
6554         struct triple *def;
6555         struct token *tk;
6556         const signed char *str, *end;
6557         int c;
6558         int str_len;
6559         eat(state, TOK_LIT_CHAR);
6560         tk = &state->token[0];
6561         str = tk->val.str + 1;
6562         str_len = tk->str_len - 2;
6563         if (str_len <= 0) {
6564                 error(state, 0, "empty character constant");
6565         }
6566         end = str + str_len;
6567         c = char_value(state, &str, end);
6568         if (str != end) {
6569                 error(state, 0, "multibyte character constant not supported");
6570         }
6571         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6572         return def;
6573 }
6574
6575 static struct triple *string_constant(struct compile_state *state)
6576 {
6577         struct triple *def;
6578         struct token *tk;
6579         struct type *type;
6580         const signed char *str, *end;
6581         signed char *buf, *ptr;
6582         int str_len;
6583
6584         buf = 0;
6585         type = new_type(TYPE_ARRAY, &char_type, 0);
6586         type->elements = 0;
6587         /* The while loop handles string concatenation */
6588         do {
6589                 eat(state, TOK_LIT_STRING);
6590                 tk = &state->token[0];
6591                 str = tk->val.str + 1;
6592                 str_len = tk->str_len - 2;
6593                 if (str_len < 0) {
6594                         error(state, 0, "negative string constant length");
6595                 }
6596                 end = str + str_len;
6597                 ptr = buf;
6598                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6599                 memcpy(buf, ptr, type->elements);
6600                 ptr = buf + type->elements;
6601                 do {
6602                         *ptr++ = char_value(state, &str, end);
6603                 } while(str < end);
6604                 type->elements = ptr - buf;
6605         } while(peek(state) == TOK_LIT_STRING);
6606         *ptr = '\0';
6607         type->elements += 1;
6608         def = triple(state, OP_BLOBCONST, type, 0, 0);
6609         def->u.blob = buf;
6610         return def;
6611 }
6612
6613
6614 static struct triple *integer_constant(struct compile_state *state)
6615 {
6616         struct triple *def;
6617         unsigned long val;
6618         struct token *tk;
6619         char *end;
6620         int u, l, decimal;
6621         struct type *type;
6622
6623         eat(state, TOK_LIT_INT);
6624         tk = &state->token[0];
6625         errno = 0;
6626         decimal = (tk->val.str[0] != '0');
6627         val = strtoul(tk->val.str, &end, 0);
6628         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6629                 error(state, 0, "Integer constant to large");
6630         }
6631         u = l = 0;
6632         if ((*end == 'u') || (*end == 'U')) {
6633                 u = 1;
6634                         end++;
6635         }
6636         if ((*end == 'l') || (*end == 'L')) {
6637                 l = 1;
6638                 end++;
6639         }
6640         if ((*end == 'u') || (*end == 'U')) {
6641                 u = 1;
6642                 end++;
6643         }
6644         if (*end) {
6645                 error(state, 0, "Junk at end of integer constant");
6646         }
6647         if (u && l)  {
6648                 type = &ulong_type;
6649         }
6650         else if (l) {
6651                 type = &long_type;
6652                 if (!decimal && (val > LONG_MAX)) {
6653                         type = &ulong_type;
6654                 }
6655         }
6656         else if (u) {
6657                 type = &uint_type;
6658                 if (val > UINT_MAX) {
6659                         type = &ulong_type;
6660                 }
6661         }
6662         else {
6663                 type = &int_type;
6664                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6665                         type = &uint_type;
6666                 }
6667                 else if (!decimal && (val > LONG_MAX)) {
6668                         type = &ulong_type;
6669                 }
6670                 else if (val > INT_MAX) {
6671                         type = &long_type;
6672                 }
6673         }
6674         def = int_const(state, type, val);
6675         return def;
6676 }
6677
6678 static struct triple *primary_expr(struct compile_state *state)
6679 {
6680         struct triple *def;
6681         int tok;
6682         tok = peek(state);
6683         switch(tok) {
6684         case TOK_IDENT:
6685         {
6686                 struct hash_entry *ident;
6687                 /* Here ident is either:
6688                  * a varable name
6689                  * a function name
6690                  * an enumeration constant.
6691                  */
6692                 eat(state, TOK_IDENT);
6693                 ident = state->token[0].ident;
6694                 if (!ident->sym_ident) {
6695                         error(state, 0, "%s undeclared", ident->name);
6696                 }
6697                 def = ident->sym_ident->def;
6698                 break;
6699         }
6700         case TOK_ENUM_CONST:
6701                 /* Here ident is an enumeration constant */
6702                 eat(state, TOK_ENUM_CONST);
6703                 def = 0;
6704                 FINISHME();
6705                 break;
6706         case TOK_LPAREN:
6707                 eat(state, TOK_LPAREN);
6708                 def = expr(state);
6709                 eat(state, TOK_RPAREN);
6710                 break;
6711         case TOK_LIT_INT:
6712                 def = integer_constant(state);
6713                 break;
6714         case TOK_LIT_FLOAT:
6715                 eat(state, TOK_LIT_FLOAT);
6716                 error(state, 0, "Floating point constants not supported");
6717                 def = 0;
6718                 FINISHME();
6719                 break;
6720         case TOK_LIT_CHAR:
6721                 def = character_constant(state);
6722                 break;
6723         case TOK_LIT_STRING:
6724                 def = string_constant(state);
6725                 break;
6726         default:
6727                 def = 0;
6728                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6729         }
6730         return def;
6731 }
6732
6733 static struct triple *postfix_expr(struct compile_state *state)
6734 {
6735         struct triple *def;
6736         int postfix;
6737         def = primary_expr(state);
6738         do {
6739                 struct triple *left;
6740                 int tok;
6741                 postfix = 1;
6742                 left = def;
6743                 switch((tok = peek(state))) {
6744                 case TOK_LBRACKET:
6745                         eat(state, TOK_LBRACKET);
6746                         def = mk_subscript_expr(state, left, expr(state));
6747                         eat(state, TOK_RBRACKET);
6748                         break;
6749                 case TOK_LPAREN:
6750                         def = call_expr(state, def);
6751                         break;
6752                 case TOK_DOT:
6753                 {
6754                         struct hash_entry *field;
6755                         eat(state, TOK_DOT);
6756                         eat(state, TOK_IDENT);
6757                         field = state->token[0].ident;
6758                         def = deref_field(state, def, field);
6759                         break;
6760                 }
6761                 case TOK_ARROW:
6762                 {
6763                         struct hash_entry *field;
6764                         eat(state, TOK_ARROW);
6765                         eat(state, TOK_IDENT);
6766                         field = state->token[0].ident;
6767                         def = mk_deref_expr(state, read_expr(state, def));
6768                         def = deref_field(state, def, field);
6769                         break;
6770                 }
6771                 case TOK_PLUSPLUS:
6772                         eat(state, TOK_PLUSPLUS);
6773                         def = mk_post_inc_expr(state, left);
6774                         break;
6775                 case TOK_MINUSMINUS:
6776                         eat(state, TOK_MINUSMINUS);
6777                         def = mk_post_dec_expr(state, left);
6778                         break;
6779                 default:
6780                         postfix = 0;
6781                         break;
6782                 }
6783         } while(postfix);
6784         return def;
6785 }
6786
6787 static struct triple *cast_expr(struct compile_state *state);
6788
6789 static struct triple *unary_expr(struct compile_state *state)
6790 {
6791         struct triple *def, *right;
6792         int tok;
6793         switch((tok = peek(state))) {
6794         case TOK_PLUSPLUS:
6795                 eat(state, TOK_PLUSPLUS);
6796                 def = mk_pre_inc_expr(state, unary_expr(state));
6797                 break;
6798         case TOK_MINUSMINUS:
6799                 eat(state, TOK_MINUSMINUS);
6800                 def = mk_pre_dec_expr(state, unary_expr(state));
6801                 break;
6802         case TOK_AND:
6803                 eat(state, TOK_AND);
6804                 def = mk_addr_expr(state, cast_expr(state), 0);
6805                 break;
6806         case TOK_STAR:
6807                 eat(state, TOK_STAR);
6808                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6809                 break;
6810         case TOK_PLUS:
6811                 eat(state, TOK_PLUS);
6812                 right = read_expr(state, cast_expr(state));
6813                 arithmetic(state, right);
6814                 def = integral_promotion(state, right);
6815                 break;
6816         case TOK_MINUS:
6817                 eat(state, TOK_MINUS);
6818                 right = read_expr(state, cast_expr(state));
6819                 arithmetic(state, right);
6820                 def = integral_promotion(state, right);
6821                 def = triple(state, OP_NEG, def->type, def, 0);
6822                 break;
6823         case TOK_TILDE:
6824                 eat(state, TOK_TILDE);
6825                 right = read_expr(state, cast_expr(state));
6826                 integral(state, right);
6827                 def = integral_promotion(state, right);
6828                 def = triple(state, OP_INVERT, def->type, def, 0);
6829                 break;
6830         case TOK_BANG:
6831                 eat(state, TOK_BANG);
6832                 right = read_expr(state, cast_expr(state));
6833                 bool(state, right);
6834                 def = lfalse_expr(state, right);
6835                 break;
6836         case TOK_SIZEOF:
6837         {
6838                 struct type *type;
6839                 int tok1, tok2;
6840                 eat(state, TOK_SIZEOF);
6841                 tok1 = peek(state);
6842                 tok2 = peek2(state);
6843                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6844                         eat(state, TOK_LPAREN);
6845                         type = type_name(state);
6846                         eat(state, TOK_RPAREN);
6847                 }
6848                 else {
6849                         struct triple *expr;
6850                         expr = unary_expr(state);
6851                         type = expr->type;
6852                         release_expr(state, expr);
6853                 }
6854                 def = int_const(state, &ulong_type, size_of(state, type));
6855                 break;
6856         }
6857         case TOK_ALIGNOF:
6858         {
6859                 struct type *type;
6860                 int tok1, tok2;
6861                 eat(state, TOK_ALIGNOF);
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, align_of(state, type));
6876                 break;
6877         }
6878         default:
6879                 def = postfix_expr(state);
6880                 break;
6881         }
6882         return def;
6883 }
6884
6885 static struct triple *cast_expr(struct compile_state *state)
6886 {
6887         struct triple *def;
6888         int tok1, tok2;
6889         tok1 = peek(state);
6890         tok2 = peek2(state);
6891         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6892                 struct type *type;
6893                 eat(state, TOK_LPAREN);
6894                 type = type_name(state);
6895                 eat(state, TOK_RPAREN);
6896                 def = read_expr(state, cast_expr(state));
6897                 def = triple(state, OP_COPY, type, def, 0);
6898         }
6899         else {
6900                 def = unary_expr(state);
6901         }
6902         return def;
6903 }
6904
6905 static struct triple *mult_expr(struct compile_state *state)
6906 {
6907         struct triple *def;
6908         int done;
6909         def = cast_expr(state);
6910         do {
6911                 struct triple *left, *right;
6912                 struct type *result_type;
6913                 int tok, op, sign;
6914                 done = 0;
6915                 switch(tok = (peek(state))) {
6916                 case TOK_STAR:
6917                 case TOK_DIV:
6918                 case TOK_MOD:
6919                         left = read_expr(state, def);
6920                         arithmetic(state, left);
6921
6922                         eat(state, tok);
6923
6924                         right = read_expr(state, cast_expr(state));
6925                         arithmetic(state, right);
6926
6927                         result_type = arithmetic_result(state, left, right);
6928                         sign = is_signed(result_type);
6929                         op = -1;
6930                         switch(tok) {
6931                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6932                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
6933                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
6934                         }
6935                         def = triple(state, op, result_type, left, right);
6936                         break;
6937                 default:
6938                         done = 1;
6939                         break;
6940                 }
6941         } while(!done);
6942         return def;
6943 }
6944
6945 static struct triple *add_expr(struct compile_state *state)
6946 {
6947         struct triple *def;
6948         int done;
6949         def = mult_expr(state);
6950         do {
6951                 done = 0;
6952                 switch( peek(state)) {
6953                 case TOK_PLUS:
6954                         eat(state, TOK_PLUS);
6955                         def = mk_add_expr(state, def, mult_expr(state));
6956                         break;
6957                 case TOK_MINUS:
6958                         eat(state, TOK_MINUS);
6959                         def = mk_sub_expr(state, def, mult_expr(state));
6960                         break;
6961                 default:
6962                         done = 1;
6963                         break;
6964                 }
6965         } while(!done);
6966         return def;
6967 }
6968
6969 static struct triple *shift_expr(struct compile_state *state)
6970 {
6971         struct triple *def;
6972         int done;
6973         def = add_expr(state);
6974         do {
6975                 struct triple *left, *right;
6976                 int tok, op;
6977                 done = 0;
6978                 switch((tok = peek(state))) {
6979                 case TOK_SL:
6980                 case TOK_SR:
6981                         left = read_expr(state, def);
6982                         integral(state, left);
6983                         left = integral_promotion(state, left);
6984
6985                         eat(state, tok);
6986
6987                         right = read_expr(state, add_expr(state));
6988                         integral(state, right);
6989                         right = integral_promotion(state, right);
6990                         
6991                         op = (tok == TOK_SL)? OP_SL : 
6992                                 is_signed(left->type)? OP_SSR: OP_USR;
6993
6994                         def = triple(state, op, left->type, left, right);
6995                         break;
6996                 default:
6997                         done = 1;
6998                         break;
6999                 }
7000         } while(!done);
7001         return def;
7002 }
7003
7004 static struct triple *relational_expr(struct compile_state *state)
7005 {
7006 #warning "Extend relational exprs to work on more than arithmetic types"
7007         struct triple *def;
7008         int done;
7009         def = shift_expr(state);
7010         do {
7011                 struct triple *left, *right;
7012                 struct type *arg_type;
7013                 int tok, op, sign;
7014                 done = 0;
7015                 switch((tok = peek(state))) {
7016                 case TOK_LESS:
7017                 case TOK_MORE:
7018                 case TOK_LESSEQ:
7019                 case TOK_MOREEQ:
7020                         left = read_expr(state, def);
7021                         arithmetic(state, left);
7022
7023                         eat(state, tok);
7024
7025                         right = read_expr(state, shift_expr(state));
7026                         arithmetic(state, right);
7027
7028                         arg_type = arithmetic_result(state, left, right);
7029                         sign = is_signed(arg_type);
7030                         op = -1;
7031                         switch(tok) {
7032                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7033                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7034                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7035                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7036                         }
7037                         def = triple(state, op, &int_type, left, right);
7038                         break;
7039                 default:
7040                         done = 1;
7041                         break;
7042                 }
7043         } while(!done);
7044         return def;
7045 }
7046
7047 static struct triple *equality_expr(struct compile_state *state)
7048 {
7049 #warning "Extend equality exprs to work on more than arithmetic types"
7050         struct triple *def;
7051         int done;
7052         def = relational_expr(state);
7053         do {
7054                 struct triple *left, *right;
7055                 int tok, op;
7056                 done = 0;
7057                 switch((tok = peek(state))) {
7058                 case TOK_EQEQ:
7059                 case TOK_NOTEQ:
7060                         left = read_expr(state, def);
7061                         arithmetic(state, left);
7062                         eat(state, tok);
7063                         right = read_expr(state, relational_expr(state));
7064                         arithmetic(state, right);
7065                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7066                         def = triple(state, op, &int_type, left, right);
7067                         break;
7068                 default:
7069                         done = 1;
7070                         break;
7071                 }
7072         } while(!done);
7073         return def;
7074 }
7075
7076 static struct triple *and_expr(struct compile_state *state)
7077 {
7078         struct triple *def;
7079         def = equality_expr(state);
7080         while(peek(state) == TOK_AND) {
7081                 struct triple *left, *right;
7082                 struct type *result_type;
7083                 left = read_expr(state, def);
7084                 integral(state, left);
7085                 eat(state, TOK_AND);
7086                 right = read_expr(state, equality_expr(state));
7087                 integral(state, right);
7088                 result_type = arithmetic_result(state, left, right);
7089                 def = triple(state, OP_AND, result_type, left, right);
7090         }
7091         return def;
7092 }
7093
7094 static struct triple *xor_expr(struct compile_state *state)
7095 {
7096         struct triple *def;
7097         def = and_expr(state);
7098         while(peek(state) == TOK_XOR) {
7099                 struct triple *left, *right;
7100                 struct type *result_type;
7101                 left = read_expr(state, def);
7102                 integral(state, left);
7103                 eat(state, TOK_XOR);
7104                 right = read_expr(state, and_expr(state));
7105                 integral(state, right);
7106                 result_type = arithmetic_result(state, left, right);
7107                 def = triple(state, OP_XOR, result_type, left, right);
7108         }
7109         return def;
7110 }
7111
7112 static struct triple *or_expr(struct compile_state *state)
7113 {
7114         struct triple *def;
7115         def = xor_expr(state);
7116         while(peek(state) == TOK_OR) {
7117                 struct triple *left, *right;
7118                 struct type *result_type;
7119                 left = read_expr(state, def);
7120                 integral(state, left);
7121                 eat(state, TOK_OR);
7122                 right = read_expr(state, xor_expr(state));
7123                 integral(state, right);
7124                 result_type = arithmetic_result(state, left, right);
7125                 def = triple(state, OP_OR, result_type, left, right);
7126         }
7127         return def;
7128 }
7129
7130 static struct triple *land_expr(struct compile_state *state)
7131 {
7132         struct triple *def;
7133         def = or_expr(state);
7134         while(peek(state) == TOK_LOGAND) {
7135                 struct triple *left, *right;
7136                 left = read_expr(state, def);
7137                 bool(state, left);
7138                 eat(state, TOK_LOGAND);
7139                 right = read_expr(state, or_expr(state));
7140                 bool(state, right);
7141
7142                 def = triple(state, OP_LAND, &int_type,
7143                         ltrue_expr(state, left),
7144                         ltrue_expr(state, right));
7145         }
7146         return def;
7147 }
7148
7149 static struct triple *lor_expr(struct compile_state *state)
7150 {
7151         struct triple *def;
7152         def = land_expr(state);
7153         while(peek(state) == TOK_LOGOR) {
7154                 struct triple *left, *right;
7155                 left = read_expr(state, def);
7156                 bool(state, left);
7157                 eat(state, TOK_LOGOR);
7158                 right = read_expr(state, land_expr(state));
7159                 bool(state, right);
7160                 
7161                 def = triple(state, OP_LOR, &int_type,
7162                         ltrue_expr(state, left),
7163                         ltrue_expr(state, right));
7164         }
7165         return def;
7166 }
7167
7168 static struct triple *conditional_expr(struct compile_state *state)
7169 {
7170         struct triple *def;
7171         def = lor_expr(state);
7172         if (peek(state) == TOK_QUEST) {
7173                 struct triple *test, *left, *right;
7174                 bool(state, def);
7175                 test = ltrue_expr(state, read_expr(state, def));
7176                 eat(state, TOK_QUEST);
7177                 left = read_expr(state, expr(state));
7178                 eat(state, TOK_COLON);
7179                 right = read_expr(state, conditional_expr(state));
7180
7181                 def = cond_expr(state, test, left, right);
7182         }
7183         return def;
7184 }
7185
7186 static struct triple *eval_const_expr(
7187         struct compile_state *state, struct triple *expr)
7188 {
7189         struct triple *def;
7190         struct triple *head, *ptr;
7191         head = label(state); /* dummy initial triple */
7192         flatten(state, head, expr);
7193         for(ptr = head->next; ptr != head; ptr = ptr->next) {
7194                 simplify(state, ptr);
7195         }
7196         /* Remove the constant value the tail of the list */
7197         def = head->prev;
7198         def->prev->next = def->next;
7199         def->next->prev = def->prev;
7200         def->next = def->prev = def;
7201         if (!is_const(def)) {
7202                 internal_error(state, 0, "Not a constant expression");
7203         }
7204         /* Free the intermediate expressions */
7205         while(head->next != head) {
7206                 release_triple(state, head->next);
7207         }
7208         free_triple(state, head);
7209         return def;
7210 }
7211
7212 static struct triple *constant_expr(struct compile_state *state)
7213 {
7214         return eval_const_expr(state, conditional_expr(state));
7215 }
7216
7217 static struct triple *assignment_expr(struct compile_state *state)
7218 {
7219         struct triple *def, *left, *right;
7220         int tok, op, sign;
7221         /* The C grammer in K&R shows assignment expressions
7222          * only taking unary expressions as input on their
7223          * left hand side.  But specifies the precedence of
7224          * assignemnt as the lowest operator except for comma.
7225          *
7226          * Allowing conditional expressions on the left hand side
7227          * of an assignement results in a grammar that accepts
7228          * a larger set of statements than standard C.   As long
7229          * as the subset of the grammar that is standard C behaves
7230          * correctly this should cause no problems.
7231          * 
7232          * For the extra token strings accepted by the grammar
7233          * none of them should produce a valid lvalue, so they
7234          * should not produce functioning programs.
7235          *
7236          * GCC has this bug as well, so surprises should be minimal.
7237          */
7238         def = conditional_expr(state);
7239         left = def;
7240         switch((tok = peek(state))) {
7241         case TOK_EQ:
7242                 lvalue(state, left);
7243                 eat(state, TOK_EQ);
7244                 def = write_expr(state, left, 
7245                         read_expr(state, assignment_expr(state)));
7246                 break;
7247         case TOK_TIMESEQ:
7248         case TOK_DIVEQ:
7249         case TOK_MODEQ:
7250                 lvalue(state, left);
7251                 arithmetic(state, left);
7252                 eat(state, tok);
7253                 right = read_expr(state, assignment_expr(state));
7254                 arithmetic(state, right);
7255
7256                 sign = is_signed(left->type);
7257                 op = -1;
7258                 switch(tok) {
7259                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7260                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7261                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7262                 }
7263                 def = write_expr(state, left,
7264                         triple(state, op, left->type, 
7265                                 read_expr(state, left), right));
7266                 break;
7267         case TOK_PLUSEQ:
7268                 lvalue(state, left);
7269                 eat(state, TOK_PLUSEQ);
7270                 def = write_expr(state, left,
7271                         mk_add_expr(state, left, assignment_expr(state)));
7272                 break;
7273         case TOK_MINUSEQ:
7274                 lvalue(state, left);
7275                 eat(state, TOK_MINUSEQ);
7276                 def = write_expr(state, left,
7277                         mk_sub_expr(state, left, assignment_expr(state)));
7278                 break;
7279         case TOK_SLEQ:
7280         case TOK_SREQ:
7281         case TOK_ANDEQ:
7282         case TOK_XOREQ:
7283         case TOK_OREQ:
7284                 lvalue(state, left);
7285                 integral(state, left);
7286                 eat(state, tok);
7287                 right = read_expr(state, assignment_expr(state));
7288                 integral(state, right);
7289                 right = integral_promotion(state, right);
7290                 sign = is_signed(left->type);
7291                 op = -1;
7292                 switch(tok) {
7293                 case TOK_SLEQ:  op = OP_SL; break;
7294                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7295                 case TOK_ANDEQ: op = OP_AND; break;
7296                 case TOK_XOREQ: op = OP_XOR; break;
7297                 case TOK_OREQ:  op = OP_OR; break;
7298                 }
7299                 def = write_expr(state, left,
7300                         triple(state, op, left->type, 
7301                                 read_expr(state, left), right));
7302                 break;
7303         }
7304         return def;
7305 }
7306
7307 static struct triple *expr(struct compile_state *state)
7308 {
7309         struct triple *def;
7310         def = assignment_expr(state);
7311         while(peek(state) == TOK_COMMA) {
7312                 struct triple *left, *right;
7313                 left = def;
7314                 eat(state, TOK_COMMA);
7315                 right = assignment_expr(state);
7316                 def = triple(state, OP_COMMA, right->type, left, right);
7317         }
7318         return def;
7319 }
7320
7321 static void expr_statement(struct compile_state *state, struct triple *first)
7322 {
7323         if (peek(state) != TOK_SEMI) {
7324                 flatten(state, first, expr(state));
7325         }
7326         eat(state, TOK_SEMI);
7327 }
7328
7329 static void if_statement(struct compile_state *state, struct triple *first)
7330 {
7331         struct triple *test, *jmp1, *jmp2, *middle, *end;
7332
7333         jmp1 = jmp2 = middle = 0;
7334         eat(state, TOK_IF);
7335         eat(state, TOK_LPAREN);
7336         test = expr(state);
7337         bool(state, test);
7338         /* Cleanup and invert the test */
7339         test = lfalse_expr(state, read_expr(state, test));
7340         eat(state, TOK_RPAREN);
7341         /* Generate the needed pieces */
7342         middle = label(state);
7343         jmp1 = branch(state, middle, test);
7344         /* Thread the pieces together */
7345         flatten(state, first, test);
7346         flatten(state, first, jmp1);
7347         flatten(state, first, label(state));
7348         statement(state, first);
7349         if (peek(state) == TOK_ELSE) {
7350                 eat(state, TOK_ELSE);
7351                 /* Generate the rest of the pieces */
7352                 end = label(state);
7353                 jmp2 = branch(state, end, 0);
7354                 /* Thread them together */
7355                 flatten(state, first, jmp2);
7356                 flatten(state, first, middle);
7357                 statement(state, first);
7358                 flatten(state, first, end);
7359         }
7360         else {
7361                 flatten(state, first, middle);
7362         }
7363 }
7364
7365 static void for_statement(struct compile_state *state, struct triple *first)
7366 {
7367         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7368         struct triple *label1, *label2, *label3;
7369         struct hash_entry *ident;
7370
7371         eat(state, TOK_FOR);
7372         eat(state, TOK_LPAREN);
7373         head = test = tail = jmp1 = jmp2 = 0;
7374         if (peek(state) != TOK_SEMI) {
7375                 head = expr(state);
7376         } 
7377         eat(state, TOK_SEMI);
7378         if (peek(state) != TOK_SEMI) {
7379                 test = expr(state);
7380                 bool(state, test);
7381                 test = ltrue_expr(state, read_expr(state, test));
7382         }
7383         eat(state, TOK_SEMI);
7384         if (peek(state) != TOK_RPAREN) {
7385                 tail = expr(state);
7386         }
7387         eat(state, TOK_RPAREN);
7388         /* Generate the needed pieces */
7389         label1 = label(state);
7390         label2 = label(state);
7391         label3 = label(state);
7392         if (test) {
7393                 jmp1 = branch(state, label3, 0);
7394                 jmp2 = branch(state, label1, test);
7395         }
7396         else {
7397                 jmp2 = branch(state, label1, 0);
7398         }
7399         end = label(state);
7400         /* Remember where break and continue go */
7401         start_scope(state);
7402         ident = state->i_break;
7403         symbol(state, ident, &ident->sym_ident, end, end->type);
7404         ident = state->i_continue;
7405         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7406         /* Now include the body */
7407         flatten(state, first, head);
7408         flatten(state, first, jmp1);
7409         flatten(state, first, label1);
7410         statement(state, first);
7411         flatten(state, first, label2);
7412         flatten(state, first, tail);
7413         flatten(state, first, label3);
7414         flatten(state, first, test);
7415         flatten(state, first, jmp2);
7416         flatten(state, first, end);
7417         /* Cleanup the break/continue scope */
7418         end_scope(state);
7419 }
7420
7421 static void while_statement(struct compile_state *state, struct triple *first)
7422 {
7423         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7424         struct hash_entry *ident;
7425         eat(state, TOK_WHILE);
7426         eat(state, TOK_LPAREN);
7427         test = expr(state);
7428         bool(state, test);
7429         test = ltrue_expr(state, read_expr(state, test));
7430         eat(state, TOK_RPAREN);
7431         /* Generate the needed pieces */
7432         label1 = label(state);
7433         label2 = label(state);
7434         jmp1 = branch(state, label2, 0);
7435         jmp2 = branch(state, label1, test);
7436         end = label(state);
7437         /* Remember where break and continue go */
7438         start_scope(state);
7439         ident = state->i_break;
7440         symbol(state, ident, &ident->sym_ident, end, end->type);
7441         ident = state->i_continue;
7442         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7443         /* Thread them together */
7444         flatten(state, first, jmp1);
7445         flatten(state, first, label1);
7446         statement(state, first);
7447         flatten(state, first, label2);
7448         flatten(state, first, test);
7449         flatten(state, first, jmp2);
7450         flatten(state, first, end);
7451         /* Cleanup the break/continue scope */
7452         end_scope(state);
7453 }
7454
7455 static void do_statement(struct compile_state *state, struct triple *first)
7456 {
7457         struct triple *label1, *label2, *test, *end;
7458         struct hash_entry *ident;
7459         eat(state, TOK_DO);
7460         /* Generate the needed pieces */
7461         label1 = label(state);
7462         label2 = label(state);
7463         end = label(state);
7464         /* Remember where break and continue go */
7465         start_scope(state);
7466         ident = state->i_break;
7467         symbol(state, ident, &ident->sym_ident, end, end->type);
7468         ident = state->i_continue;
7469         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7470         /* Now include the body */
7471         flatten(state, first, label1);
7472         statement(state, first);
7473         /* Cleanup the break/continue scope */
7474         end_scope(state);
7475         /* Eat the rest of the loop */
7476         eat(state, TOK_WHILE);
7477         eat(state, TOK_LPAREN);
7478         test = read_expr(state, expr(state));
7479         bool(state, test);
7480         eat(state, TOK_RPAREN);
7481         eat(state, TOK_SEMI);
7482         /* Thread the pieces together */
7483         test = ltrue_expr(state, test);
7484         flatten(state, first, label2);
7485         flatten(state, first, test);
7486         flatten(state, first, branch(state, label1, test));
7487         flatten(state, first, end);
7488 }
7489
7490
7491 static void return_statement(struct compile_state *state, struct triple *first)
7492 {
7493         struct triple *jmp, *mv, *dest, *var, *val;
7494         int last;
7495         eat(state, TOK_RETURN);
7496
7497 #warning "FIXME implement a more general excess branch elimination"
7498         val = 0;
7499         /* If we have a return value do some more work */
7500         if (peek(state) != TOK_SEMI) {
7501                 val = read_expr(state, expr(state));
7502         }
7503         eat(state, TOK_SEMI);
7504
7505         /* See if this last statement in a function */
7506         last = ((peek(state) == TOK_RBRACE) && 
7507                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7508
7509         /* Find the return variable */
7510         var = MISC(state->main_function, 0);
7511         /* Find the return destination */
7512         dest = RHS(state->main_function, 0)->prev;
7513         mv = jmp = 0;
7514         /* If needed generate a jump instruction */
7515         if (!last) {
7516                 jmp = branch(state, dest, 0);
7517         }
7518         /* If needed generate an assignment instruction */
7519         if (val) {
7520                 mv = write_expr(state, var, val);
7521         }
7522         /* Now put the code together */
7523         if (mv) {
7524                 flatten(state, first, mv);
7525                 flatten(state, first, jmp);
7526         }
7527         else if (jmp) {
7528                 flatten(state, first, jmp);
7529         }
7530 }
7531
7532 static void break_statement(struct compile_state *state, struct triple *first)
7533 {
7534         struct triple *dest;
7535         eat(state, TOK_BREAK);
7536         eat(state, TOK_SEMI);
7537         if (!state->i_break->sym_ident) {
7538                 error(state, 0, "break statement not within loop or switch");
7539         }
7540         dest = state->i_break->sym_ident->def;
7541         flatten(state, first, branch(state, dest, 0));
7542 }
7543
7544 static void continue_statement(struct compile_state *state, struct triple *first)
7545 {
7546         struct triple *dest;
7547         eat(state, TOK_CONTINUE);
7548         eat(state, TOK_SEMI);
7549         if (!state->i_continue->sym_ident) {
7550                 error(state, 0, "continue statement outside of a loop");
7551         }
7552         dest = state->i_continue->sym_ident->def;
7553         flatten(state, first, branch(state, dest, 0));
7554 }
7555
7556 static void goto_statement(struct compile_state *state, struct triple *first)
7557 {
7558         FINISHME();
7559         eat(state, TOK_GOTO);
7560         eat(state, TOK_IDENT);
7561         eat(state, TOK_SEMI);
7562         error(state, 0, "goto is not implemeted");
7563         FINISHME();
7564 }
7565
7566 static void labeled_statement(struct compile_state *state, struct triple *first)
7567 {
7568         FINISHME();
7569         eat(state, TOK_IDENT);
7570         eat(state, TOK_COLON);
7571         statement(state, first);
7572         error(state, 0, "labeled statements are not implemented");
7573         FINISHME();
7574 }
7575
7576 static void switch_statement(struct compile_state *state, struct triple *first)
7577 {
7578         FINISHME();
7579         eat(state, TOK_SWITCH);
7580         eat(state, TOK_LPAREN);
7581         expr(state);
7582         eat(state, TOK_RPAREN);
7583         statement(state, first);
7584         error(state, 0, "switch statements are not implemented");
7585         FINISHME();
7586 }
7587
7588 static void case_statement(struct compile_state *state, struct triple *first)
7589 {
7590         FINISHME();
7591         eat(state, TOK_CASE);
7592         constant_expr(state);
7593         eat(state, TOK_COLON);
7594         statement(state, first);
7595         error(state, 0, "case statements are not implemented");
7596         FINISHME();
7597 }
7598
7599 static void default_statement(struct compile_state *state, struct triple *first)
7600 {
7601         FINISHME();
7602         eat(state, TOK_DEFAULT);
7603         eat(state, TOK_COLON);
7604         statement(state, first);
7605         error(state, 0, "default statements are not implemented");
7606         FINISHME();
7607 }
7608
7609 static void asm_statement(struct compile_state *state, struct triple *first)
7610 {
7611         struct asm_info *info;
7612         struct {
7613                 struct triple *constraint;
7614                 struct triple *expr;
7615         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7616         struct triple *def, *asm_str;
7617         int out, in, clobbers, more, colons, i;
7618
7619         eat(state, TOK_ASM);
7620         /* For now ignore the qualifiers */
7621         switch(peek(state)) {
7622         case TOK_CONST:
7623                 eat(state, TOK_CONST);
7624                 break;
7625         case TOK_VOLATILE:
7626                 eat(state, TOK_VOLATILE);
7627                 break;
7628         }
7629         eat(state, TOK_LPAREN);
7630         asm_str = string_constant(state);
7631
7632         colons = 0;
7633         out = in = clobbers = 0;
7634         /* Outputs */
7635         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7636                 eat(state, TOK_COLON);
7637                 colons++;
7638                 more = (peek(state) == TOK_LIT_STRING);
7639                 while(more) {
7640                         struct triple *var;
7641                         struct triple *constraint;
7642                         more = 0;
7643                         if (out > MAX_LHS) {
7644                                 error(state, 0, "Maximum output count exceeded.");
7645                         }
7646                         constraint = string_constant(state);
7647                         eat(state, TOK_LPAREN);
7648                         var = conditional_expr(state);
7649                         eat(state, TOK_RPAREN);
7650
7651                         lvalue(state, var);
7652                         out_param[out].constraint = constraint;
7653                         out_param[out].expr       = var;
7654                         if (peek(state) == TOK_COMMA) {
7655                                 eat(state, TOK_COMMA);
7656                                 more = 1;
7657                         }
7658                         out++;
7659                 }
7660         }
7661         /* Inputs */
7662         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7663                 eat(state, TOK_COLON);
7664                 colons++;
7665                 more = (peek(state) == TOK_LIT_STRING);
7666                 while(more) {
7667                         struct triple *val;
7668                         struct triple *constraint;
7669                         more = 0;
7670                         if (in > MAX_RHS) {
7671                                 error(state, 0, "Maximum input count exceeded.");
7672                         }
7673                         constraint = string_constant(state);
7674                         eat(state, TOK_LPAREN);
7675                         val = conditional_expr(state);
7676                         eat(state, TOK_RPAREN);
7677
7678                         in_param[in].constraint = constraint;
7679                         in_param[in].expr       = val;
7680                         if (peek(state) == TOK_COMMA) {
7681                                 eat(state, TOK_COMMA);
7682                                 more = 1;
7683                         }
7684                         in++;
7685                 }
7686         }
7687
7688         /* Clobber */
7689         if ((colons == 2) && (peek(state) == TOK_COLON)) {
7690                 eat(state, TOK_COLON);
7691                 colons++;
7692                 more = (peek(state) == TOK_LIT_STRING);
7693                 while(more) {
7694                         struct triple *clobber;
7695                         more = 0;
7696                         if ((clobbers + out) > MAX_LHS) {
7697                                 error(state, 0, "Maximum clobber limit exceeded.");
7698                         }
7699                         clobber = string_constant(state);
7700                         eat(state, TOK_RPAREN);
7701
7702                         clob_param[clobbers].constraint = clobber;
7703                         if (peek(state) == TOK_COMMA) {
7704                                 eat(state, TOK_COMMA);
7705                                 more = 1;
7706                         }
7707                         clobbers++;
7708                 }
7709         }
7710         eat(state, TOK_RPAREN);
7711         eat(state, TOK_SEMI);
7712
7713
7714         info = xcmalloc(sizeof(*info), "asm_info");
7715         info->str = asm_str->u.blob;
7716         free_triple(state, asm_str);
7717
7718         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7719         def->u.ainfo = info;
7720         for(i = 0; i < in; i++) {
7721                 struct triple *constraint;
7722                 constraint = in_param[i].constraint;
7723                 info->tmpl.rhs[i] = arch_reg_constraint(state, 
7724                         in_param[i].expr->type, constraint->u.blob);
7725
7726                 RHS(def, i) = read_expr(state,in_param[i].expr);
7727                 free_triple(state, constraint);
7728         }
7729         flatten(state, first, def);
7730         for(i = 0; i < out; i++) {
7731                 struct triple *piece;
7732                 struct triple *constraint;
7733                 constraint = out_param[i].constraint;
7734                 info->tmpl.lhs[i] = arch_reg_constraint(state,
7735                         out_param[i].expr->type, constraint->u.blob);
7736
7737                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7738                 piece->u.cval = i;
7739                 LHS(def, i) = piece;
7740                 flatten(state, first,
7741                         write_expr(state, out_param[i].expr, piece));
7742                 free_triple(state, constraint);
7743         }
7744         for(; i - out < clobbers; i++) {
7745                 struct triple *piece;
7746                 struct triple *constraint;
7747                 constraint = clob_param[i - out].constraint;
7748                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7749
7750                 piece = triple(state, OP_PIECE, &void_type, def, 0);
7751                 piece->u.cval = i;
7752                 LHS(def, i) = piece;
7753                 flatten(state, first, piece);
7754                 free_triple(state, constraint);
7755         }
7756 }
7757
7758
7759 static int isdecl(int tok)
7760 {
7761         switch(tok) {
7762         case TOK_AUTO:
7763         case TOK_REGISTER:
7764         case TOK_STATIC:
7765         case TOK_EXTERN:
7766         case TOK_TYPEDEF:
7767         case TOK_CONST:
7768         case TOK_RESTRICT:
7769         case TOK_VOLATILE:
7770         case TOK_VOID:
7771         case TOK_CHAR:
7772         case TOK_SHORT:
7773         case TOK_INT:
7774         case TOK_LONG:
7775         case TOK_FLOAT:
7776         case TOK_DOUBLE:
7777         case TOK_SIGNED:
7778         case TOK_UNSIGNED:
7779         case TOK_STRUCT:
7780         case TOK_UNION:
7781         case TOK_ENUM:
7782         case TOK_TYPE_NAME: /* typedef name */
7783                 return 1;
7784         default:
7785                 return 0;
7786         }
7787 }
7788
7789 static void compound_statement(struct compile_state *state, struct triple *first)
7790 {
7791         eat(state, TOK_LBRACE);
7792         start_scope(state);
7793
7794         /* statement-list opt */
7795         while (peek(state) != TOK_RBRACE) {
7796                 statement(state, first);
7797         }
7798         end_scope(state);
7799         eat(state, TOK_RBRACE);
7800 }
7801
7802 static void statement(struct compile_state *state, struct triple *first)
7803 {
7804         int tok;
7805         tok = peek(state);
7806         if (tok == TOK_LBRACE) {
7807                 compound_statement(state, first);
7808         }
7809         else if (tok == TOK_IF) {
7810                 if_statement(state, first); 
7811         }
7812         else if (tok == TOK_FOR) {
7813                 for_statement(state, first);
7814         }
7815         else if (tok == TOK_WHILE) {
7816                 while_statement(state, first);
7817         }
7818         else if (tok == TOK_DO) {
7819                 do_statement(state, first);
7820         }
7821         else if (tok == TOK_RETURN) {
7822                 return_statement(state, first);
7823         }
7824         else if (tok == TOK_BREAK) {
7825                 break_statement(state, first);
7826         }
7827         else if (tok == TOK_CONTINUE) {
7828                 continue_statement(state, first);
7829         }
7830         else if (tok == TOK_GOTO) {
7831                 goto_statement(state, first);
7832         }
7833         else if (tok == TOK_SWITCH) {
7834                 switch_statement(state, first);
7835         }
7836         else if (tok == TOK_ASM) {
7837                 asm_statement(state, first);
7838         }
7839         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7840                 labeled_statement(state, first); 
7841         }
7842         else if (tok == TOK_CASE) {
7843                 case_statement(state, first);
7844         }
7845         else if (tok == TOK_DEFAULT) {
7846                 default_statement(state, first);
7847         }
7848         else if (isdecl(tok)) {
7849                 /* This handles C99 intermixing of statements and decls */
7850                 decl(state, first);
7851         }
7852         else {
7853                 expr_statement(state, first);
7854         }
7855 }
7856
7857 static struct type *param_decl(struct compile_state *state)
7858 {
7859         struct type *type;
7860         struct hash_entry *ident;
7861         /* Cheat so the declarator will know we are not global */
7862         start_scope(state); 
7863         ident = 0;
7864         type = decl_specifiers(state);
7865         type = declarator(state, type, &ident, 0);
7866         type->field_ident = ident;
7867         end_scope(state);
7868         return type;
7869 }
7870
7871 static struct type *param_type_list(struct compile_state *state, struct type *type)
7872 {
7873         struct type *ftype, **next;
7874         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7875         next = &ftype->right;
7876         while(peek(state) == TOK_COMMA) {
7877                 eat(state, TOK_COMMA);
7878                 if (peek(state) == TOK_DOTS) {
7879                         eat(state, TOK_DOTS);
7880                         error(state, 0, "variadic functions not supported");
7881                 }
7882                 else {
7883                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7884                         next = &((*next)->right);
7885                 }
7886         }
7887         return ftype;
7888 }
7889
7890
7891 static struct type *type_name(struct compile_state *state)
7892 {
7893         struct type *type;
7894         type = specifier_qualifier_list(state);
7895         /* abstract-declarator (may consume no tokens) */
7896         type = declarator(state, type, 0, 0);
7897         return type;
7898 }
7899
7900 static struct type *direct_declarator(
7901         struct compile_state *state, struct type *type, 
7902         struct hash_entry **ident, int need_ident)
7903 {
7904         struct type *outer;
7905         int op;
7906         outer = 0;
7907         arrays_complete(state, type);
7908         switch(peek(state)) {
7909         case TOK_IDENT:
7910                 eat(state, TOK_IDENT);
7911                 if (!ident) {
7912                         error(state, 0, "Unexpected identifier found");
7913                 }
7914                 /* The name of what we are declaring */
7915                 *ident = state->token[0].ident;
7916                 break;
7917         case TOK_LPAREN:
7918                 eat(state, TOK_LPAREN);
7919                 outer = declarator(state, type, ident, need_ident);
7920                 eat(state, TOK_RPAREN);
7921                 break;
7922         default:
7923                 if (need_ident) {
7924                         error(state, 0, "Identifier expected");
7925                 }
7926                 break;
7927         }
7928         do {
7929                 op = 1;
7930                 arrays_complete(state, type);
7931                 switch(peek(state)) {
7932                 case TOK_LPAREN:
7933                         eat(state, TOK_LPAREN);
7934                         type = param_type_list(state, type);
7935                         eat(state, TOK_RPAREN);
7936                         break;
7937                 case TOK_LBRACKET:
7938                 {
7939                         unsigned int qualifiers;
7940                         struct triple *value;
7941                         value = 0;
7942                         eat(state, TOK_LBRACKET);
7943                         if (peek(state) != TOK_RBRACKET) {
7944                                 value = constant_expr(state);
7945                                 integral(state, value);
7946                         }
7947                         eat(state, TOK_RBRACKET);
7948
7949                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7950                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7951                         if (value) {
7952                                 type->elements = value->u.cval;
7953                                 free_triple(state, value);
7954                         } else {
7955                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7956                                 op = 0;
7957                         }
7958                 }
7959                         break;
7960                 default:
7961                         op = 0;
7962                         break;
7963                 }
7964         } while(op);
7965         if (outer) {
7966                 struct type *inner;
7967                 arrays_complete(state, type);
7968                 FINISHME();
7969                 for(inner = outer; inner->left; inner = inner->left)
7970                         ;
7971                 inner->left = type;
7972                 type = outer;
7973         }
7974         return type;
7975 }
7976
7977 static struct type *declarator(
7978         struct compile_state *state, struct type *type, 
7979         struct hash_entry **ident, int need_ident)
7980 {
7981         while(peek(state) == TOK_STAR) {
7982                 eat(state, TOK_STAR);
7983                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7984         }
7985         type = direct_declarator(state, type, ident, need_ident);
7986         return type;
7987 }
7988
7989
7990 static struct type *typedef_name(
7991         struct compile_state *state, unsigned int specifiers)
7992 {
7993         struct hash_entry *ident;
7994         struct type *type;
7995         eat(state, TOK_TYPE_NAME);
7996         ident = state->token[0].ident;
7997         type = ident->sym_ident->type;
7998         specifiers |= type->type & QUAL_MASK;
7999         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8000                 (type->type & (STOR_MASK | QUAL_MASK))) {
8001                 type = clone_type(specifiers, type);
8002         }
8003         return type;
8004 }
8005
8006 static struct type *enum_specifier(
8007         struct compile_state *state, unsigned int specifiers)
8008 {
8009         int tok;
8010         struct type *type;
8011         type = 0;
8012         FINISHME();
8013         eat(state, TOK_ENUM);
8014         tok = peek(state);
8015         if (tok == TOK_IDENT) {
8016                 eat(state, TOK_IDENT);
8017         }
8018         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8019                 eat(state, TOK_LBRACE);
8020                 do {
8021                         eat(state, TOK_IDENT);
8022                         if (peek(state) == TOK_EQ) {
8023                                 eat(state, TOK_EQ);
8024                                 constant_expr(state);
8025                         }
8026                         if (peek(state) == TOK_COMMA) {
8027                                 eat(state, TOK_COMMA);
8028                         }
8029                 } while(peek(state) != TOK_RBRACE);
8030                 eat(state, TOK_RBRACE);
8031         }
8032         FINISHME();
8033         return type;
8034 }
8035
8036 #if 0
8037 static struct type *struct_declarator(
8038         struct compile_state *state, struct type *type, struct hash_entry **ident)
8039 {
8040         int tok;
8041 #warning "struct_declarator is complicated because of bitfields, kill them?"
8042         tok = peek(state);
8043         if (tok != TOK_COLON) {
8044                 type = declarator(state, type, ident, 1);
8045         }
8046         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8047                 eat(state, TOK_COLON);
8048                 constant_expr(state);
8049         }
8050         FINISHME();
8051         return type;
8052 }
8053 #endif
8054
8055 static struct type *struct_or_union_specifier(
8056         struct compile_state *state, unsigned int specifiers)
8057 {
8058         struct type *struct_type;
8059         struct hash_entry *ident;
8060         unsigned int type_join;
8061         int tok;
8062         struct_type = 0;
8063         ident = 0;
8064         switch(peek(state)) {
8065         case TOK_STRUCT:
8066                 eat(state, TOK_STRUCT);
8067                 type_join = TYPE_PRODUCT;
8068                 break;
8069         case TOK_UNION:
8070                 eat(state, TOK_UNION);
8071                 type_join = TYPE_OVERLAP;
8072                 error(state, 0, "unions not yet supported\n");
8073                 break;
8074         default:
8075                 eat(state, TOK_STRUCT);
8076                 type_join = TYPE_PRODUCT;
8077                 break;
8078         }
8079         tok = peek(state);
8080         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8081                 eat(state, tok);
8082                 ident = state->token[0].ident;
8083         }
8084         if (!ident || (peek(state) == TOK_LBRACE)) {
8085                 ulong_t elements;
8086                 elements = 0;
8087                 eat(state, TOK_LBRACE);
8088                 do {
8089                         struct type *base_type;
8090                         struct type **next;
8091                         int done;
8092                         base_type = specifier_qualifier_list(state);
8093                         next = &struct_type;
8094                         do {
8095                                 struct type *type;
8096                                 struct hash_entry *fident;
8097                                 done = 1;
8098                                 type = declarator(state, base_type, &fident, 1);
8099                                 elements++;
8100                                 if (peek(state) == TOK_COMMA) {
8101                                         done = 0;
8102                                         eat(state, TOK_COMMA);
8103                                 }
8104                                 type = clone_type(0, type);
8105                                 type->field_ident = fident;
8106                                 if (*next) {
8107                                         *next = new_type(type_join, *next, type);
8108                                         next = &((*next)->right);
8109                                 } else {
8110                                         *next = type;
8111                                 }
8112                         } while(!done);
8113                         eat(state, TOK_SEMI);
8114                 } while(peek(state) != TOK_RBRACE);
8115                 eat(state, TOK_RBRACE);
8116                 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8117                 struct_type->type_ident = ident;
8118                 struct_type->elements = elements;
8119                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8120         }
8121         if (ident && ident->sym_struct) {
8122                 struct_type = ident->sym_struct->type;
8123         }
8124         else if (ident && !ident->sym_struct) {
8125                 error(state, 0, "struct %s undeclared", ident->name);
8126         }
8127         return struct_type;
8128 }
8129
8130 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8131 {
8132         unsigned int specifiers;
8133         switch(peek(state)) {
8134         case TOK_AUTO:
8135                 eat(state, TOK_AUTO);
8136                 specifiers = STOR_AUTO;
8137                 break;
8138         case TOK_REGISTER:
8139                 eat(state, TOK_REGISTER);
8140                 specifiers = STOR_REGISTER;
8141                 break;
8142         case TOK_STATIC:
8143                 eat(state, TOK_STATIC);
8144                 specifiers = STOR_STATIC;
8145                 break;
8146         case TOK_EXTERN:
8147                 eat(state, TOK_EXTERN);
8148                 specifiers = STOR_EXTERN;
8149                 break;
8150         case TOK_TYPEDEF:
8151                 eat(state, TOK_TYPEDEF);
8152                 specifiers = STOR_TYPEDEF;
8153                 break;
8154         default:
8155                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8156                         specifiers = STOR_STATIC;
8157                 }
8158                 else {
8159                         specifiers = STOR_AUTO;
8160                 }
8161         }
8162         return specifiers;
8163 }
8164
8165 static unsigned int function_specifier_opt(struct compile_state *state)
8166 {
8167         /* Ignore the inline keyword */
8168         unsigned int specifiers;
8169         specifiers = 0;
8170         switch(peek(state)) {
8171         case TOK_INLINE:
8172                 eat(state, TOK_INLINE);
8173                 specifiers = STOR_INLINE;
8174         }
8175         return specifiers;
8176 }
8177
8178 static unsigned int type_qualifiers(struct compile_state *state)
8179 {
8180         unsigned int specifiers;
8181         int done;
8182         done = 0;
8183         specifiers = QUAL_NONE;
8184         do {
8185                 switch(peek(state)) {
8186                 case TOK_CONST:
8187                         eat(state, TOK_CONST);
8188                         specifiers = QUAL_CONST;
8189                         break;
8190                 case TOK_VOLATILE:
8191                         eat(state, TOK_VOLATILE);
8192                         specifiers = QUAL_VOLATILE;
8193                         break;
8194                 case TOK_RESTRICT:
8195                         eat(state, TOK_RESTRICT);
8196                         specifiers = QUAL_RESTRICT;
8197                         break;
8198                 default:
8199                         done = 1;
8200                         break;
8201                 }
8202         } while(!done);
8203         return specifiers;
8204 }
8205
8206 static struct type *type_specifier(
8207         struct compile_state *state, unsigned int spec)
8208 {
8209         struct type *type;
8210         type = 0;
8211         switch(peek(state)) {
8212         case TOK_VOID:
8213                 eat(state, TOK_VOID);
8214                 type = new_type(TYPE_VOID | spec, 0, 0);
8215                 break;
8216         case TOK_CHAR:
8217                 eat(state, TOK_CHAR);
8218                 type = new_type(TYPE_CHAR | spec, 0, 0);
8219                 break;
8220         case TOK_SHORT:
8221                 eat(state, TOK_SHORT);
8222                 if (peek(state) == TOK_INT) {
8223                         eat(state, TOK_INT);
8224                 }
8225                 type = new_type(TYPE_SHORT | spec, 0, 0);
8226                 break;
8227         case TOK_INT:
8228                 eat(state, TOK_INT);
8229                 type = new_type(TYPE_INT | spec, 0, 0);
8230                 break;
8231         case TOK_LONG:
8232                 eat(state, TOK_LONG);
8233                 switch(peek(state)) {
8234                 case TOK_LONG:
8235                         eat(state, TOK_LONG);
8236                         error(state, 0, "long long not supported");
8237                         break;
8238                 case TOK_DOUBLE:
8239                         eat(state, TOK_DOUBLE);
8240                         error(state, 0, "long double not supported");
8241                         break;
8242                 case TOK_INT:
8243                         eat(state, TOK_INT);
8244                         type = new_type(TYPE_LONG | spec, 0, 0);
8245                         break;
8246                 default:
8247                         type = new_type(TYPE_LONG | spec, 0, 0);
8248                         break;
8249                 }
8250                 break;
8251         case TOK_FLOAT:
8252                 eat(state, TOK_FLOAT);
8253                 error(state, 0, "type float not supported");
8254                 break;
8255         case TOK_DOUBLE:
8256                 eat(state, TOK_DOUBLE);
8257                 error(state, 0, "type double not supported");
8258                 break;
8259         case TOK_SIGNED:
8260                 eat(state, TOK_SIGNED);
8261                 switch(peek(state)) {
8262                 case TOK_LONG:
8263                         eat(state, TOK_LONG);
8264                         switch(peek(state)) {
8265                         case TOK_LONG:
8266                                 eat(state, TOK_LONG);
8267                                 error(state, 0, "type long long not supported");
8268                                 break;
8269                         case TOK_INT:
8270                                 eat(state, TOK_INT);
8271                                 type = new_type(TYPE_LONG | spec, 0, 0);
8272                                 break;
8273                         default:
8274                                 type = new_type(TYPE_LONG | spec, 0, 0);
8275                                 break;
8276                         }
8277                         break;
8278                 case TOK_INT:
8279                         eat(state, TOK_INT);
8280                         type = new_type(TYPE_INT | spec, 0, 0);
8281                         break;
8282                 case TOK_SHORT:
8283                         eat(state, TOK_SHORT);
8284                         type = new_type(TYPE_SHORT | spec, 0, 0);
8285                         break;
8286                 case TOK_CHAR:
8287                         eat(state, TOK_CHAR);
8288                         type = new_type(TYPE_CHAR | spec, 0, 0);
8289                         break;
8290                 default:
8291                         type = new_type(TYPE_INT | spec, 0, 0);
8292                         break;
8293                 }
8294                 break;
8295         case TOK_UNSIGNED:
8296                 eat(state, TOK_UNSIGNED);
8297                 switch(peek(state)) {
8298                 case TOK_LONG:
8299                         eat(state, TOK_LONG);
8300                         switch(peek(state)) {
8301                         case TOK_LONG:
8302                                 eat(state, TOK_LONG);
8303                                 error(state, 0, "unsigned long long not supported");
8304                                 break;
8305                         case TOK_INT:
8306                                 eat(state, TOK_INT);
8307                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8308                                 break;
8309                         default:
8310                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8311                                 break;
8312                         }
8313                         break;
8314                 case TOK_INT:
8315                         eat(state, TOK_INT);
8316                         type = new_type(TYPE_UINT | spec, 0, 0);
8317                         break;
8318                 case TOK_SHORT:
8319                         eat(state, TOK_SHORT);
8320                         type = new_type(TYPE_USHORT | spec, 0, 0);
8321                         break;
8322                 case TOK_CHAR:
8323                         eat(state, TOK_CHAR);
8324                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8325                         break;
8326                 default:
8327                         type = new_type(TYPE_UINT | spec, 0, 0);
8328                         break;
8329                 }
8330                 break;
8331                 /* struct or union specifier */
8332         case TOK_STRUCT:
8333         case TOK_UNION:
8334                 type = struct_or_union_specifier(state, spec);
8335                 break;
8336                 /* enum-spefifier */
8337         case TOK_ENUM:
8338                 type = enum_specifier(state, spec);
8339                 break;
8340                 /* typedef name */
8341         case TOK_TYPE_NAME:
8342                 type = typedef_name(state, spec);
8343                 break;
8344         default:
8345                 error(state, 0, "bad type specifier %s", 
8346                         tokens[peek(state)]);
8347                 break;
8348         }
8349         return type;
8350 }
8351
8352 static int istype(int tok)
8353 {
8354         switch(tok) {
8355         case TOK_CONST:
8356         case TOK_RESTRICT:
8357         case TOK_VOLATILE:
8358         case TOK_VOID:
8359         case TOK_CHAR:
8360         case TOK_SHORT:
8361         case TOK_INT:
8362         case TOK_LONG:
8363         case TOK_FLOAT:
8364         case TOK_DOUBLE:
8365         case TOK_SIGNED:
8366         case TOK_UNSIGNED:
8367         case TOK_STRUCT:
8368         case TOK_UNION:
8369         case TOK_ENUM:
8370         case TOK_TYPE_NAME:
8371                 return 1;
8372         default:
8373                 return 0;
8374         }
8375 }
8376
8377
8378 static struct type *specifier_qualifier_list(struct compile_state *state)
8379 {
8380         struct type *type;
8381         unsigned int specifiers = 0;
8382
8383         /* type qualifiers */
8384         specifiers |= type_qualifiers(state);
8385
8386         /* type specifier */
8387         type = type_specifier(state, specifiers);
8388
8389         return type;
8390 }
8391
8392 static int isdecl_specifier(int tok)
8393 {
8394         switch(tok) {
8395                 /* storage class specifier */
8396         case TOK_AUTO:
8397         case TOK_REGISTER:
8398         case TOK_STATIC:
8399         case TOK_EXTERN:
8400         case TOK_TYPEDEF:
8401                 /* type qualifier */
8402         case TOK_CONST:
8403         case TOK_RESTRICT:
8404         case TOK_VOLATILE:
8405                 /* type specifiers */
8406         case TOK_VOID:
8407         case TOK_CHAR:
8408         case TOK_SHORT:
8409         case TOK_INT:
8410         case TOK_LONG:
8411         case TOK_FLOAT:
8412         case TOK_DOUBLE:
8413         case TOK_SIGNED:
8414         case TOK_UNSIGNED:
8415                 /* struct or union specifier */
8416         case TOK_STRUCT:
8417         case TOK_UNION:
8418                 /* enum-spefifier */
8419         case TOK_ENUM:
8420                 /* typedef name */
8421         case TOK_TYPE_NAME:
8422                 /* function specifiers */
8423         case TOK_INLINE:
8424                 return 1;
8425         default:
8426                 return 0;
8427         }
8428 }
8429
8430 static struct type *decl_specifiers(struct compile_state *state)
8431 {
8432         struct type *type;
8433         unsigned int specifiers;
8434         /* I am overly restrictive in the arragement of specifiers supported.
8435          * C is overly flexible in this department it makes interpreting
8436          * the parse tree difficult.
8437          */
8438         specifiers = 0;
8439
8440         /* storage class specifier */
8441         specifiers |= storage_class_specifier_opt(state);
8442
8443         /* function-specifier */
8444         specifiers |= function_specifier_opt(state);
8445
8446         /* type qualifier */
8447         specifiers |= type_qualifiers(state);
8448
8449         /* type specifier */
8450         type = type_specifier(state, specifiers);
8451         return type;
8452 }
8453
8454 static unsigned designator(struct compile_state *state)
8455 {
8456         int tok;
8457         unsigned index;
8458         index = -1U;
8459         do {
8460                 switch(peek(state)) {
8461                 case TOK_LBRACKET:
8462                 {
8463                         struct triple *value;
8464                         eat(state, TOK_LBRACKET);
8465                         value = constant_expr(state);
8466                         eat(state, TOK_RBRACKET);
8467                         index = value->u.cval;
8468                         break;
8469                 }
8470                 case TOK_DOT:
8471                         eat(state, TOK_DOT);
8472                         eat(state, TOK_IDENT);
8473                         error(state, 0, "Struct Designators not currently supported");
8474                         break;
8475                 default:
8476                         error(state, 0, "Invalid designator");
8477                 }
8478                 tok = peek(state);
8479         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8480         eat(state, TOK_EQ);
8481         return index;
8482 }
8483
8484 static struct triple *initializer(
8485         struct compile_state *state, struct type *type)
8486 {
8487         struct triple *result;
8488         if (peek(state) != TOK_LBRACE) {
8489                 result = assignment_expr(state);
8490         }
8491         else {
8492                 int comma;
8493                 unsigned index, max_index;
8494                 void *buf;
8495                 max_index = index = 0;
8496                 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8497                         max_index = type->elements;
8498                         if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8499                                 type->elements = 0;
8500                         }
8501                 } else {
8502                         error(state, 0, "Struct initializers not currently supported");
8503                 }
8504                 buf = xcmalloc(size_of(state, type), "initializer");
8505                 eat(state, TOK_LBRACE);
8506                 do {
8507                         struct triple *value;
8508                         struct type *value_type;
8509                         size_t value_size;
8510                         int tok;
8511                         comma = 0;
8512                         tok = peek(state);
8513                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8514                                 index = designator(state);
8515                         }
8516                         if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8517                                 (index > max_index)) {
8518                                 error(state, 0, "element beyond bounds");
8519                         }
8520                         value_type = 0;
8521                         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8522                                 value_type = type->left;
8523                         }
8524                         value = eval_const_expr(state, initializer(state, value_type));
8525                         value_size = size_of(state, value_type);
8526                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8527                                 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8528                                 (type->elements <= index)) {
8529                                 void *old_buf;
8530                                 size_t old_size;
8531                                 old_buf = buf;
8532                                 old_size = size_of(state, type);
8533                                 type->elements = index + 1;
8534                                 buf = xmalloc(size_of(state, type), "initializer");
8535                                 memcpy(buf, old_buf, old_size);
8536                                 xfree(old_buf);
8537                         }
8538                         if (value->op == OP_BLOBCONST) {
8539                                 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8540                         }
8541                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8542                                 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8543                         }
8544                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8545                                 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8546                         }
8547                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8548                                 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8549                         }
8550                         else {
8551                                 fprintf(stderr, "%d %d\n",
8552                                         value->op, value_size);
8553                                 internal_error(state, 0, "unhandled constant initializer");
8554                         }
8555                         if (peek(state) == TOK_COMMA) {
8556                                 eat(state, TOK_COMMA);
8557                                 comma = 1;
8558                         }
8559                         index += 1;
8560                 } while(comma && (peek(state) != TOK_RBRACE));
8561                 eat(state, TOK_RBRACE);
8562                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8563                 result->u.blob = buf;
8564         }
8565         return result;
8566 }
8567
8568 static struct triple *function_definition(
8569         struct compile_state *state, struct type *type)
8570 {
8571         struct triple *def, *tmp, *first, *end;
8572         struct hash_entry *ident;
8573         struct type *param;
8574         int i;
8575         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8576                 error(state, 0, "Invalid function header");
8577         }
8578
8579         /* Verify the function type */
8580         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8581                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8582                 (type->right->field_ident == 0)) {
8583                 error(state, 0, "Invalid function parameters");
8584         }
8585         param = type->right;
8586         i = 0;
8587         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8588                 i++;
8589                 if (!param->left->field_ident) {
8590                         error(state, 0, "No identifier for parameter %d\n", i);
8591                 }
8592                 param = param->right;
8593         }
8594         i++;
8595         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8596                 error(state, 0, "No identifier for paramter %d\n", i);
8597         }
8598         
8599         /* Get a list of statements for this function. */
8600         def = triple(state, OP_LIST, type, 0, 0);
8601
8602         /* Start a new scope for the passed parameters */
8603         start_scope(state);
8604
8605         /* Put a label at the very start of a function */
8606         first = label(state);
8607         RHS(def, 0) = first;
8608
8609         /* Put a label at the very end of a function */
8610         end = label(state);
8611         flatten(state, first, end);
8612
8613         /* Walk through the parameters and create symbol table entries
8614          * for them.
8615          */
8616         param = type->right;
8617         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8618                 ident = param->left->field_ident;
8619                 tmp = variable(state, param->left);
8620                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8621                 flatten(state, end, tmp);
8622                 param = param->right;
8623         }
8624         if ((param->type & TYPE_MASK) != TYPE_VOID) {
8625                 /* And don't forget the last parameter */
8626                 ident = param->field_ident;
8627                 tmp = variable(state, param);
8628                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8629                 flatten(state, end, tmp);
8630         }
8631         /* Add a variable for the return value */
8632         MISC(def, 0) = 0;
8633         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8634                 /* Remove all type qualifiers from the return type */
8635                 tmp = variable(state, clone_type(0, type->left));
8636                 flatten(state, end, tmp);
8637                 /* Remember where the return value is */
8638                 MISC(def, 0) = tmp;
8639         }
8640
8641         /* Remember which function I am compiling.
8642          * Also assume the last defined function is the main function.
8643          */
8644         state->main_function = def;
8645
8646         /* Now get the actual function definition */
8647         compound_statement(state, end);
8648
8649         /* Remove the parameter scope */
8650         end_scope(state);
8651 #if 0
8652         fprintf(stdout, "\n");
8653         loc(stdout, state, 0);
8654         fprintf(stdout, "\n__________ function_definition _________\n");
8655         print_triple(state, def);
8656         fprintf(stdout, "__________ function_definition _________ done\n\n");
8657 #endif
8658
8659         return def;
8660 }
8661
8662 static struct triple *do_decl(struct compile_state *state, 
8663         struct type *type, struct hash_entry *ident)
8664 {
8665         struct triple *def;
8666         def = 0;
8667         /* Clean up the storage types used */
8668         switch (type->type & STOR_MASK) {
8669         case STOR_AUTO:
8670         case STOR_STATIC:
8671                 /* These are the good types I am aiming for */
8672                 break;
8673         case STOR_REGISTER:
8674                 type->type &= ~STOR_MASK;
8675                 type->type |= STOR_AUTO;
8676                 break;
8677         case STOR_EXTERN:
8678                 type->type &= ~STOR_MASK;
8679                 type->type |= STOR_STATIC;
8680                 break;
8681         case STOR_TYPEDEF:
8682                 if (!ident) {
8683                         error(state, 0, "typedef without name");
8684                 }
8685                 symbol(state, ident, &ident->sym_ident, 0, type);
8686                 ident->tok = TOK_TYPE_NAME;
8687                 return 0;
8688                 break;
8689         default:
8690                 internal_error(state, 0, "Undefined storage class");
8691         }
8692         if (((type->type & STOR_MASK) == STOR_STATIC) &&
8693                 ((type->type & QUAL_CONST) == 0)) {
8694                 error(state, 0, "non const static variables not supported");
8695         }
8696         if (ident) {
8697                 def = variable(state, type);
8698                 symbol(state, ident, &ident->sym_ident, def, type);
8699         }
8700         return def;
8701 }
8702
8703 static void decl(struct compile_state *state, struct triple *first)
8704 {
8705         struct type *base_type, *type;
8706         struct hash_entry *ident;
8707         struct triple *def;
8708         int global;
8709         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8710         base_type = decl_specifiers(state);
8711         ident = 0;
8712         type = declarator(state, base_type, &ident, 0);
8713         if (global && ident && (peek(state) == TOK_LBRACE)) {
8714                 /* function */
8715                 def = function_definition(state, type);
8716                 symbol(state, ident, &ident->sym_ident, def, type);
8717         }
8718         else {
8719                 int done;
8720                 flatten(state, first, do_decl(state, type, ident));
8721                 /* type or variable definition */
8722                 do {
8723                         done = 1;
8724                         if (peek(state) == TOK_EQ) {
8725                                 if (!ident) {
8726                                         error(state, 0, "cannot assign to a type");
8727                                 }
8728                                 eat(state, TOK_EQ);
8729                                 flatten(state, first,
8730                                         init_expr(state, 
8731                                                 ident->sym_ident->def, 
8732                                                 initializer(state, type)));
8733                         }
8734                         arrays_complete(state, type);
8735                         if (peek(state) == TOK_COMMA) {
8736                                 eat(state, TOK_COMMA);
8737                                 ident = 0;
8738                                 type = declarator(state, base_type, &ident, 0);
8739                                 flatten(state, first, do_decl(state, type, ident));
8740                                 done = 0;
8741                         }
8742                 } while(!done);
8743                 eat(state, TOK_SEMI);
8744         }
8745 }
8746
8747 static void decls(struct compile_state *state)
8748 {
8749         struct triple *list;
8750         int tok;
8751         list = label(state);
8752         while(1) {
8753                 tok = peek(state);
8754                 if (tok == TOK_EOF) {
8755                         return;
8756                 }
8757                 if (tok == TOK_SPACE) {
8758                         eat(state, TOK_SPACE);
8759                 }
8760                 decl(state, list);
8761                 if (list->next != list) {
8762                         error(state, 0, "global variables not supported");
8763                 }
8764         }
8765 }
8766
8767 /*
8768  * Data structurs for optimation.
8769  */
8770
8771 static void do_use_block(
8772         struct block *used, struct block_set **head, struct block *user, 
8773         int front)
8774 {
8775         struct block_set **ptr, *new;
8776         if (!used)
8777                 return;
8778         if (!user)
8779                 return;
8780         ptr = head;
8781         while(*ptr) {
8782                 if ((*ptr)->member == user) {
8783                         return;
8784                 }
8785                 ptr = &(*ptr)->next;
8786         }
8787         new = xcmalloc(sizeof(*new), "block_set");
8788         new->member = user;
8789         if (front) {
8790                 new->next = *head;
8791                 *head = new;
8792         }
8793         else {
8794                 new->next = 0;
8795                 *ptr = new;
8796         }
8797 }
8798 static void do_unuse_block(
8799         struct block *used, struct block_set **head, struct block *unuser)
8800 {
8801         struct block_set *use, **ptr;
8802         ptr = head;
8803         while(*ptr) {
8804                 use = *ptr;
8805                 if (use->member == unuser) {
8806                         *ptr = use->next;
8807                         memset(use, -1, sizeof(*use));
8808                         xfree(use);
8809                 }
8810                 else {
8811                         ptr = &use->next;
8812                 }
8813         }
8814 }
8815
8816 static void use_block(struct block *used, struct block *user)
8817 {
8818         /* Append new to the head of the list, print_block
8819          * depends on this.
8820          */
8821         do_use_block(used, &used->use, user, 1); 
8822         used->users++;
8823 }
8824 static void unuse_block(struct block *used, struct block *unuser)
8825 {
8826         do_unuse_block(used, &used->use, unuser); 
8827         used->users--;
8828 }
8829
8830 static void idom_block(struct block *idom, struct block *user)
8831 {
8832         do_use_block(idom, &idom->idominates, user, 0);
8833 }
8834
8835 static void unidom_block(struct block *idom, struct block *unuser)
8836 {
8837         do_unuse_block(idom, &idom->idominates, unuser);
8838 }
8839
8840 static void domf_block(struct block *block, struct block *domf)
8841 {
8842         do_use_block(block, &block->domfrontier, domf, 0);
8843 }
8844
8845 static void undomf_block(struct block *block, struct block *undomf)
8846 {
8847         do_unuse_block(block, &block->domfrontier, undomf);
8848 }
8849
8850 static void ipdom_block(struct block *ipdom, struct block *user)
8851 {
8852         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8853 }
8854
8855 static void unipdom_block(struct block *ipdom, struct block *unuser)
8856 {
8857         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8858 }
8859
8860 static void ipdomf_block(struct block *block, struct block *ipdomf)
8861 {
8862         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8863 }
8864
8865 static void unipdomf_block(struct block *block, struct block *unipdomf)
8866 {
8867         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8868 }
8869
8870
8871
8872 static int do_walk_triple(struct compile_state *state,
8873         struct triple *ptr, int depth,
8874         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
8875 {
8876         int result;
8877         result = cb(state, ptr, depth);
8878         if ((result == 0) && (ptr->op == OP_LIST)) {
8879                 struct triple *list;
8880                 list = ptr;
8881                 ptr = RHS(list, 0);
8882                 do {
8883                         result = do_walk_triple(state, ptr, depth + 1, cb);
8884                         if (ptr->next->prev != ptr) {
8885                                 internal_error(state, ptr->next, "bad prev");
8886                         }
8887                         ptr = ptr->next;
8888                         
8889                 } while((result == 0) && (ptr != RHS(list, 0)));
8890         }
8891         return result;
8892 }
8893
8894 static int walk_triple(
8895         struct compile_state *state, 
8896         struct triple *ptr, 
8897         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8898 {
8899         return do_walk_triple(state, ptr, 0, cb);
8900 }
8901
8902 static void do_print_prefix(int depth)
8903 {
8904         int i;
8905         for(i = 0; i < depth; i++) {
8906                 printf("  ");
8907         }
8908 }
8909
8910 #define PRINT_LIST 1
8911 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8912 {
8913         int op;
8914         op = ins->op;
8915         if (op == OP_LIST) {
8916 #if !PRINT_LIST
8917                 return 0;
8918 #endif
8919         }
8920         if ((op == OP_LABEL) && (ins->use)) {
8921                 printf("\n%p:\n", ins);
8922         }
8923         do_print_prefix(depth);
8924         display_triple(stdout, ins);
8925
8926         if ((ins->op == OP_BRANCH) && ins->use) {
8927                 internal_error(state, ins, "branch used?");
8928         }
8929 #if 0
8930         {
8931                 struct triple_set *user;
8932                 for(user = ins->use; user; user = user->next) {
8933                         printf("use: %p\n", user->member);
8934                 }
8935         }
8936 #endif
8937         if (triple_is_branch(state, ins)) {
8938                 printf("\n");
8939         }
8940         return 0;
8941 }
8942
8943 static void print_triple(struct compile_state *state, struct triple *ins)
8944 {
8945         walk_triple(state, ins, do_print_triple);
8946 }
8947
8948 static void print_triples(struct compile_state *state)
8949 {
8950         print_triple(state, state->main_function);
8951 }
8952
8953 struct cf_block {
8954         struct block *block;
8955 };
8956 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8957 {
8958         if (!block || (cf[block->vertex].block == block)) {
8959                 return;
8960         }
8961         cf[block->vertex].block = block;
8962         find_cf_blocks(cf, block->left);
8963         find_cf_blocks(cf, block->right);
8964 }
8965
8966 static void print_control_flow(struct compile_state *state)
8967 {
8968         struct cf_block *cf;
8969         int i;
8970         printf("\ncontrol flow\n");
8971         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8972         find_cf_blocks(cf, state->first_block);
8973
8974         for(i = 1; i <= state->last_vertex; i++) {
8975                 struct block *block;
8976                 block = cf[i].block;
8977                 if (!block)
8978                         continue;
8979                 printf("(%p) %d:", block, block->vertex);
8980                 if (block->left) {
8981                         printf(" %d", block->left->vertex);
8982                 }
8983                 if (block->right && (block->right != block->left)) {
8984                         printf(" %d", block->right->vertex);
8985                 }
8986                 printf("\n");
8987         }
8988
8989         xfree(cf);
8990 }
8991
8992
8993 static struct block *basic_block(struct compile_state *state,
8994         struct triple *first)
8995 {
8996         struct block *block;
8997         struct triple *ptr;
8998         int op;
8999         if (first->op != OP_LABEL) {
9000                 internal_error(state, 0, "block does not start with a label");
9001         }
9002         /* See if this basic block has already been setup */
9003         if (first->u.block != 0) {
9004                 return first->u.block;
9005         }
9006         /* Allocate another basic block structure */
9007         state->last_vertex += 1;
9008         block = xcmalloc(sizeof(*block), "block");
9009         block->first = block->last = first;
9010         block->vertex = state->last_vertex;
9011         ptr = first;
9012         do {
9013                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9014                         break;
9015                 }
9016                 block->last = ptr;
9017                 /* If ptr->u is not used remember where the baic block is */
9018                 if (triple_stores_block(state, ptr)) {
9019                         ptr->u.block = block;
9020                 }
9021                 if (ptr->op == OP_BRANCH) {
9022                         break;
9023                 }
9024                 ptr = ptr->next;
9025         } while (ptr != RHS(state->main_function, 0));
9026         if (ptr == RHS(state->main_function, 0))
9027                 return block;
9028         op = ptr->op;
9029         if (op == OP_LABEL) {
9030                 block->left = basic_block(state, ptr);
9031                 block->right = 0;
9032                 use_block(block->left, block);
9033         }
9034         else if (op == OP_BRANCH) {
9035                 block->left = 0;
9036                 /* Trace the branch target */
9037                 block->right = basic_block(state, TARG(ptr, 0));
9038                 use_block(block->right, block);
9039                 /* If there is a test trace the branch as well */
9040                 if (TRIPLE_RHS(ptr->sizes)) {
9041                         block->left = basic_block(state, ptr->next);
9042                         use_block(block->left, block);
9043                 }
9044         }
9045         else {
9046                 internal_error(state, 0, "Bad basic block split");
9047         }
9048         return block;
9049 }
9050
9051
9052 static void walk_blocks(struct compile_state *state,
9053         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9054         void *arg)
9055 {
9056         struct triple *ptr, *first;
9057         struct block *last_block;
9058         last_block = 0;
9059         first = RHS(state->main_function, 0);
9060         ptr = first;
9061         do {
9062                 struct block *block;
9063                 if (ptr->op == OP_LABEL) {
9064                         block = ptr->u.block;
9065                         if (block && (block != last_block)) {
9066                                 cb(state, block, arg);
9067                         }
9068                         last_block = block;
9069                 }
9070                 ptr = ptr->next;
9071         } while(ptr != first);
9072 }
9073
9074 static void print_block(
9075         struct compile_state *state, struct block *block, void *arg)
9076 {
9077         struct triple *ptr;
9078         FILE *fp = arg;
9079
9080         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9081                 block, 
9082                 block->vertex,
9083                 block->left, 
9084                 block->left && block->left->use?block->left->use->member : 0,
9085                 block->right, 
9086                 block->right && block->right->use?block->right->use->member : 0);
9087         if (block->first->op == OP_LABEL) {
9088                 fprintf(fp, "%p:\n", block->first);
9089         }
9090         for(ptr = block->first; ; ptr = ptr->next) {
9091                 struct triple_set *user;
9092                 int op = ptr->op;
9093                 
9094                 if (triple_stores_block(state, ptr)) {
9095                         if (ptr->u.block != block) {
9096                                 internal_error(state, ptr, 
9097                                         "Wrong block pointer: %p\n",
9098                                         ptr->u.block);
9099                         }
9100                 }
9101                 if (op == OP_ADECL) {
9102                         for(user = ptr->use; user; user = user->next) {
9103                                 if (!user->member->u.block) {
9104                                         internal_error(state, user->member, 
9105                                                 "Use %p not in a block?\n",
9106                                                 user->member);
9107                                 }
9108                         }
9109                 }
9110                 display_triple(fp, ptr);
9111
9112 #if 0
9113                 for(user = ptr->use; user; user = user->next) {
9114                         fprintf(fp, "use: %p\n", user->member);
9115                 }
9116 #endif
9117
9118                 /* Sanity checks... */
9119                 valid_ins(state, ptr);
9120                 for(user = ptr->use; user; user = user->next) {
9121                         struct triple *use;
9122                         use = user->member;
9123                         valid_ins(state, use);
9124                         if (triple_stores_block(state, user->member) &&
9125                                 !user->member->u.block) {
9126                                 internal_error(state, user->member,
9127                                         "Use %p not in a block?",
9128                                         user->member);
9129                         }
9130                 }
9131
9132                 if (ptr == block->last)
9133                         break;
9134         }
9135         fprintf(fp,"\n");
9136 }
9137
9138
9139 static void print_blocks(struct compile_state *state, FILE *fp)
9140 {
9141         fprintf(fp, "--------------- blocks ---------------\n");
9142         walk_blocks(state, print_block, fp);
9143 }
9144
9145 static void prune_nonblock_triples(struct compile_state *state)
9146 {
9147         struct block *block;
9148         struct triple *first, *ins, *next;
9149         /* Delete the triples not in a basic block */
9150         first = RHS(state->main_function, 0);
9151         block = 0;
9152         ins = first;
9153         do {
9154                 next = ins->next;
9155                 if (ins->op == OP_LABEL) {
9156                         block = ins->u.block;
9157                 }
9158                 if (!block) {
9159                         release_triple(state, ins);
9160                 }
9161                 ins = next;
9162         } while(ins != first);
9163 }
9164
9165 static void setup_basic_blocks(struct compile_state *state)
9166 {
9167         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9168                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9169                 internal_error(state, 0, "ins will not store block?");
9170         }
9171         /* Find the basic blocks */
9172         state->last_vertex = 0;
9173         state->first_block = basic_block(state, RHS(state->main_function,0));
9174         /* Delete the triples not in a basic block */
9175         prune_nonblock_triples(state);
9176         /* Find the last basic block */
9177         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9178         if (!state->last_block) {
9179                 internal_error(state, 0, "end not used?");
9180         }
9181         /* Insert an extra unused edge from start to the end 
9182          * This helps with reverse control flow calculations.
9183          */
9184         use_block(state->first_block, state->last_block);
9185         /* If we are debugging print what I have just done */
9186         if (state->debug & DEBUG_BASIC_BLOCKS) {
9187                 print_blocks(state, stdout);
9188                 print_control_flow(state);
9189         }
9190 }
9191
9192 static void free_basic_block(struct compile_state *state, struct block *block)
9193 {
9194         struct block_set *entry, *next;
9195         struct block *child;
9196         if (!block) {
9197                 return;
9198         }
9199         if (block->vertex == -1) {
9200                 return;
9201         }
9202         block->vertex = -1;
9203         if (block->left) {
9204                 unuse_block(block->left, block);
9205         }
9206         if (block->right) {
9207                 unuse_block(block->right, block);
9208         }
9209         if (block->idom) {
9210                 unidom_block(block->idom, block);
9211         }
9212         block->idom = 0;
9213         if (block->ipdom) {
9214                 unipdom_block(block->ipdom, block);
9215         }
9216         block->ipdom = 0;
9217         for(entry = block->use; entry; entry = next) {
9218                 next = entry->next;
9219                 child = entry->member;
9220                 unuse_block(block, child);
9221                 if (child->left == block) {
9222                         child->left = 0;
9223                 }
9224                 if (child->right == block) {
9225                         child->right = 0;
9226                 }
9227         }
9228         for(entry = block->idominates; entry; entry = next) {
9229                 next = entry->next;
9230                 child = entry->member;
9231                 unidom_block(block, child);
9232                 child->idom = 0;
9233         }
9234         for(entry = block->domfrontier; entry; entry = next) {
9235                 next = entry->next;
9236                 child = entry->member;
9237                 undomf_block(block, child);
9238         }
9239         for(entry = block->ipdominates; entry; entry = next) {
9240                 next = entry->next;
9241                 child = entry->member;
9242                 unipdom_block(block, child);
9243                 child->ipdom = 0;
9244         }
9245         for(entry = block->ipdomfrontier; entry; entry = next) {
9246                 next = entry->next;
9247                 child = entry->member;
9248                 unipdomf_block(block, child);
9249         }
9250         if (block->users != 0) {
9251                 internal_error(state, 0, "block still has users");
9252         }
9253         free_basic_block(state, block->left);
9254         block->left = 0;
9255         free_basic_block(state, block->right);
9256         block->right = 0;
9257         memset(block, -1, sizeof(*block));
9258         xfree(block);
9259 }
9260
9261 static void free_basic_blocks(struct compile_state *state)
9262 {
9263         struct triple *first, *ins;
9264         free_basic_block(state, state->first_block);
9265         state->last_vertex = 0;
9266         state->first_block = state->last_block = 0;
9267         first = RHS(state->main_function, 0);
9268         ins = first;
9269         do {
9270                 if (triple_stores_block(state, ins)) {
9271                         ins->u.block = 0;
9272                 }
9273                 ins = ins->next;
9274         } while(ins != first);
9275         
9276 }
9277
9278 struct sdom_block {
9279         struct block *block;
9280         struct sdom_block *sdominates;
9281         struct sdom_block *sdom_next;
9282         struct sdom_block *sdom;
9283         struct sdom_block *label;
9284         struct sdom_block *parent;
9285         struct sdom_block *ancestor;
9286         int vertex;
9287 };
9288
9289
9290 static void unsdom_block(struct sdom_block *block)
9291 {
9292         struct sdom_block **ptr;
9293         if (!block->sdom_next) {
9294                 return;
9295         }
9296         ptr = &block->sdom->sdominates;
9297         while(*ptr) {
9298                 if ((*ptr) == block) {
9299                         *ptr = block->sdom_next;
9300                         return;
9301                 }
9302                 ptr = &(*ptr)->sdom_next;
9303         }
9304 }
9305
9306 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9307 {
9308         unsdom_block(block);
9309         block->sdom = sdom;
9310         block->sdom_next = sdom->sdominates;
9311         sdom->sdominates = block;
9312 }
9313
9314
9315
9316 static int initialize_sdblock(struct sdom_block *sd,
9317         struct block *parent, struct block *block, int vertex)
9318 {
9319         if (!block || (sd[block->vertex].block == block)) {
9320                 return vertex;
9321         }
9322         vertex += 1;
9323         /* Renumber the blocks in a convinient fashion */
9324         block->vertex = vertex;
9325         sd[vertex].block    = block;
9326         sd[vertex].sdom     = &sd[vertex];
9327         sd[vertex].label    = &sd[vertex];
9328         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9329         sd[vertex].ancestor = 0;
9330         sd[vertex].vertex   = vertex;
9331         vertex = initialize_sdblock(sd, block, block->left, vertex);
9332         vertex = initialize_sdblock(sd, block, block->right, vertex);
9333         return vertex;
9334 }
9335
9336 static int initialize_sdpblock(struct sdom_block *sd,
9337         struct block *parent, struct block *block, int vertex)
9338 {
9339         struct block_set *user;
9340         if (!block || (sd[block->vertex].block == block)) {
9341                 return vertex;
9342         }
9343         vertex += 1;
9344         /* Renumber the blocks in a convinient fashion */
9345         block->vertex = vertex;
9346         sd[vertex].block    = block;
9347         sd[vertex].sdom     = &sd[vertex];
9348         sd[vertex].label    = &sd[vertex];
9349         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9350         sd[vertex].ancestor = 0;
9351         sd[vertex].vertex   = vertex;
9352         for(user = block->use; user; user = user->next) {
9353                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9354         }
9355         return vertex;
9356 }
9357
9358 static void compress_ancestors(struct sdom_block *v)
9359 {
9360         /* This procedure assumes ancestor(v) != 0 */
9361         /* if (ancestor(ancestor(v)) != 0) {
9362          *      compress(ancestor(ancestor(v)));
9363          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9364          *              label(v) = label(ancestor(v));
9365          *      }
9366          *      ancestor(v) = ancestor(ancestor(v));
9367          * }
9368          */
9369         if (!v->ancestor) {
9370                 return;
9371         }
9372         if (v->ancestor->ancestor) {
9373                 compress_ancestors(v->ancestor->ancestor);
9374                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9375                         v->label = v->ancestor->label;
9376                 }
9377                 v->ancestor = v->ancestor->ancestor;
9378         }
9379 }
9380
9381 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9382 {
9383         int i;
9384         /* // step 2 
9385          *  for each v <= pred(w) {
9386          *      u = EVAL(v);
9387          *      if (semi[u] < semi[w] { 
9388          *              semi[w] = semi[u]; 
9389          *      } 
9390          * }
9391          * add w to bucket(vertex(semi[w]));
9392          * LINK(parent(w), w);
9393          *
9394          * // step 3
9395          * for each v <= bucket(parent(w)) {
9396          *      delete v from bucket(parent(w));
9397          *      u = EVAL(v);
9398          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9399          * }
9400          */
9401         for(i = state->last_vertex; i >= 2; i--) {
9402                 struct sdom_block *v, *parent, *next;
9403                 struct block_set *user;
9404                 struct block *block;
9405                 block = sd[i].block;
9406                 parent = sd[i].parent;
9407                 /* Step 2 */
9408                 for(user = block->use; user; user = user->next) {
9409                         struct sdom_block *v, *u;
9410                         v = &sd[user->member->vertex];
9411                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9412                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9413                                 sd[i].sdom = u->sdom;
9414                         }
9415                 }
9416                 sdom_block(sd[i].sdom, &sd[i]);
9417                 sd[i].ancestor = parent;
9418                 /* Step 3 */
9419                 for(v = parent->sdominates; v; v = next) {
9420                         struct sdom_block *u;
9421                         next = v->sdom_next;
9422                         unsdom_block(v);
9423                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9424                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9425                                 u->block : parent->block;
9426                 }
9427         }
9428 }
9429
9430 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9431 {
9432         int i;
9433         /* // step 2 
9434          *  for each v <= pred(w) {
9435          *      u = EVAL(v);
9436          *      if (semi[u] < semi[w] { 
9437          *              semi[w] = semi[u]; 
9438          *      } 
9439          * }
9440          * add w to bucket(vertex(semi[w]));
9441          * LINK(parent(w), w);
9442          *
9443          * // step 3
9444          * for each v <= bucket(parent(w)) {
9445          *      delete v from bucket(parent(w));
9446          *      u = EVAL(v);
9447          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9448          * }
9449          */
9450         for(i = state->last_vertex; i >= 2; i--) {
9451                 struct sdom_block *u, *v, *parent, *next;
9452                 struct block *block;
9453                 block = sd[i].block;
9454                 parent = sd[i].parent;
9455                 /* Step 2 */
9456                 if (block->left) {
9457                         v = &sd[block->left->vertex];
9458                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9459                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9460                                 sd[i].sdom = u->sdom;
9461                         }
9462                 }
9463                 if (block->right && (block->right != block->left)) {
9464                         v = &sd[block->right->vertex];
9465                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9466                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9467                                 sd[i].sdom = u->sdom;
9468                         }
9469                 }
9470                 sdom_block(sd[i].sdom, &sd[i]);
9471                 sd[i].ancestor = parent;
9472                 /* Step 3 */
9473                 for(v = parent->sdominates; v; v = next) {
9474                         struct sdom_block *u;
9475                         next = v->sdom_next;
9476                         unsdom_block(v);
9477                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9478                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9479                                 u->block : parent->block;
9480                 }
9481         }
9482 }
9483
9484 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9485 {
9486         int i;
9487         for(i = 2; i <= state->last_vertex; i++) {
9488                 struct block *block;
9489                 block = sd[i].block;
9490                 if (block->idom->vertex != sd[i].sdom->vertex) {
9491                         block->idom = block->idom->idom;
9492                 }
9493                 idom_block(block->idom, block);
9494         }
9495         sd[1].block->idom = 0;
9496 }
9497
9498 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9499 {
9500         int i;
9501         for(i = 2; i <= state->last_vertex; i++) {
9502                 struct block *block;
9503                 block = sd[i].block;
9504                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9505                         block->ipdom = block->ipdom->ipdom;
9506                 }
9507                 ipdom_block(block->ipdom, block);
9508         }
9509         sd[1].block->ipdom = 0;
9510 }
9511
9512         /* Theorem 1:
9513          *   Every vertex of a flowgraph G = (V, E, r) except r has
9514          *   a unique immediate dominator.  
9515          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9516          *   rooted at r, called the dominator tree of G, such that 
9517          *   v dominates w if and only if v is a proper ancestor of w in
9518          *   the dominator tree.
9519          */
9520         /* Lemma 1:  
9521          *   If v and w are vertices of G such that v <= w,
9522          *   than any path from v to w must contain a common ancestor
9523          *   of v and w in T.
9524          */
9525         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9526         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9527         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9528         /* Theorem 2:
9529          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9530          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9531          */
9532         /* Theorem 3:
9533          *   Let w != r and let u be a vertex for which sdom(u) is 
9534          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9535          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9536          */
9537         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9538          *           Then v -> idom(w) or idom(w) -> idom(v)
9539          */
9540
9541 static void find_immediate_dominators(struct compile_state *state)
9542 {
9543         struct sdom_block *sd;
9544         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9545          *           vi > w for (1 <= i <= k - 1}
9546          */
9547         /* Theorem 4:
9548          *   For any vertex w != r.
9549          *   sdom(w) = min(
9550          *                 {v|(v,w) <= E  and v < w } U 
9551          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9552          */
9553         /* Corollary 1:
9554          *   Let w != r and let u be a vertex for which sdom(u) is 
9555          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9556          *   Then:
9557          *                   { sdom(w) if sdom(w) = sdom(u),
9558          *        idom(w) = {
9559          *                   { idom(u) otherwise
9560          */
9561         /* The algorithm consists of the following 4 steps.
9562          * Step 1.  Carry out a depth-first search of the problem graph.  
9563          *    Number the vertices from 1 to N as they are reached during
9564          *    the search.  Initialize the variables used in succeeding steps.
9565          * Step 2.  Compute the semidominators of all vertices by applying
9566          *    theorem 4.   Carry out the computation vertex by vertex in
9567          *    decreasing order by number.
9568          * Step 3.  Implicitly define the immediate dominator of each vertex
9569          *    by applying Corollary 1.
9570          * Step 4.  Explicitly define the immediate dominator of each vertex,
9571          *    carrying out the computation vertex by vertex in increasing order
9572          *    by number.
9573          */
9574         /* Step 1 initialize the basic block information */
9575         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9576         initialize_sdblock(sd, 0, state->first_block, 0);
9577 #if 0
9578         sd[1].size  = 0;
9579         sd[1].label = 0;
9580         sd[1].sdom  = 0;
9581 #endif
9582         /* Step 2 compute the semidominators */
9583         /* Step 3 implicitly define the immediate dominator of each vertex */
9584         compute_sdom(state, sd);
9585         /* Step 4 explicitly define the immediate dominator of each vertex */
9586         compute_idom(state, sd);
9587         xfree(sd);
9588 }
9589
9590 static void find_post_dominators(struct compile_state *state)
9591 {
9592         struct sdom_block *sd;
9593         /* Step 1 initialize the basic block information */
9594         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9595
9596         initialize_sdpblock(sd, 0, state->last_block, 0);
9597
9598         /* Step 2 compute the semidominators */
9599         /* Step 3 implicitly define the immediate dominator of each vertex */
9600         compute_spdom(state, sd);
9601         /* Step 4 explicitly define the immediate dominator of each vertex */
9602         compute_ipdom(state, sd);
9603         xfree(sd);
9604 }
9605
9606
9607
9608 static void find_block_domf(struct compile_state *state, struct block *block)
9609 {
9610         struct block *child;
9611         struct block_set *user;
9612         if (block->domfrontier != 0) {
9613                 internal_error(state, block->first, "domfrontier present?");
9614         }
9615         for(user = block->idominates; user; user = user->next) {
9616                 child = user->member;
9617                 if (child->idom != block) {
9618                         internal_error(state, block->first, "bad idom");
9619                 }
9620                 find_block_domf(state, child);
9621         }
9622         if (block->left && block->left->idom != block) {
9623                 domf_block(block, block->left);
9624         }
9625         if (block->right && block->right->idom != block) {
9626                 domf_block(block, block->right);
9627         }
9628         for(user = block->idominates; user; user = user->next) {
9629                 struct block_set *frontier;
9630                 child = user->member;
9631                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9632                         if (frontier->member->idom != block) {
9633                                 domf_block(block, frontier->member);
9634                         }
9635                 }
9636         }
9637 }
9638
9639 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9640 {
9641         struct block *child;
9642         struct block_set *user;
9643         if (block->ipdomfrontier != 0) {
9644                 internal_error(state, block->first, "ipdomfrontier present?");
9645         }
9646         for(user = block->ipdominates; user; user = user->next) {
9647                 child = user->member;
9648                 if (child->ipdom != block) {
9649                         internal_error(state, block->first, "bad ipdom");
9650                 }
9651                 find_block_ipdomf(state, child);
9652         }
9653         if (block->left && block->left->ipdom != block) {
9654                 ipdomf_block(block, block->left);
9655         }
9656         if (block->right && block->right->ipdom != block) {
9657                 ipdomf_block(block, block->right);
9658         }
9659         for(user = block->idominates; user; user = user->next) {
9660                 struct block_set *frontier;
9661                 child = user->member;
9662                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9663                         if (frontier->member->ipdom != block) {
9664                                 ipdomf_block(block, frontier->member);
9665                         }
9666                 }
9667         }
9668 }
9669
9670 static void print_dominated(
9671         struct compile_state *state, struct block *block, void *arg)
9672 {
9673         struct block_set *user;
9674         FILE *fp = arg;
9675
9676         fprintf(fp, "%d:", block->vertex);
9677         for(user = block->idominates; user; user = user->next) {
9678                 fprintf(fp, " %d", user->member->vertex);
9679                 if (user->member->idom != block) {
9680                         internal_error(state, user->member->first, "bad idom");
9681                 }
9682         }
9683         fprintf(fp,"\n");
9684 }
9685
9686 static void print_dominators(struct compile_state *state, FILE *fp)
9687 {
9688         fprintf(fp, "\ndominates\n");
9689         walk_blocks(state, print_dominated, fp);
9690 }
9691
9692
9693 static int print_frontiers(
9694         struct compile_state *state, struct block *block, int vertex)
9695 {
9696         struct block_set *user;
9697
9698         if (!block || (block->vertex != vertex + 1)) {
9699                 return vertex;
9700         }
9701         vertex += 1;
9702
9703         printf("%d:", block->vertex);
9704         for(user = block->domfrontier; user; user = user->next) {
9705                 printf(" %d", user->member->vertex);
9706         }
9707         printf("\n");
9708
9709         vertex = print_frontiers(state, block->left, vertex);
9710         vertex = print_frontiers(state, block->right, vertex);
9711         return vertex;
9712 }
9713 static void print_dominance_frontiers(struct compile_state *state)
9714 {
9715         printf("\ndominance frontiers\n");
9716         print_frontiers(state, state->first_block, 0);
9717         
9718 }
9719
9720 static void analyze_idominators(struct compile_state *state)
9721 {
9722         /* Find the immediate dominators */
9723         find_immediate_dominators(state);
9724         /* Find the dominance frontiers */
9725         find_block_domf(state, state->first_block);
9726         /* If debuging print the print what I have just found */
9727         if (state->debug & DEBUG_FDOMINATORS) {
9728                 print_dominators(state, stdout);
9729                 print_dominance_frontiers(state);
9730                 print_control_flow(state);
9731         }
9732 }
9733
9734
9735
9736 static void print_ipdominated(
9737         struct compile_state *state, struct block *block, void *arg)
9738 {
9739         struct block_set *user;
9740         FILE *fp = arg;
9741
9742         fprintf(fp, "%d:", block->vertex);
9743         for(user = block->ipdominates; user; user = user->next) {
9744                 fprintf(fp, " %d", user->member->vertex);
9745                 if (user->member->ipdom != block) {
9746                         internal_error(state, user->member->first, "bad ipdom");
9747                 }
9748         }
9749         fprintf(fp, "\n");
9750 }
9751
9752 static void print_ipdominators(struct compile_state *state, FILE *fp)
9753 {
9754         fprintf(fp, "\nipdominates\n");
9755         walk_blocks(state, print_ipdominated, fp);
9756 }
9757
9758 static int print_pfrontiers(
9759         struct compile_state *state, struct block *block, int vertex)
9760 {
9761         struct block_set *user;
9762
9763         if (!block || (block->vertex != vertex + 1)) {
9764                 return vertex;
9765         }
9766         vertex += 1;
9767
9768         printf("%d:", block->vertex);
9769         for(user = block->ipdomfrontier; user; user = user->next) {
9770                 printf(" %d", user->member->vertex);
9771         }
9772         printf("\n");
9773         for(user = block->use; user; user = user->next) {
9774                 vertex = print_pfrontiers(state, user->member, vertex);
9775         }
9776         return vertex;
9777 }
9778 static void print_ipdominance_frontiers(struct compile_state *state)
9779 {
9780         printf("\nipdominance frontiers\n");
9781         print_pfrontiers(state, state->last_block, 0);
9782         
9783 }
9784
9785 static void analyze_ipdominators(struct compile_state *state)
9786 {
9787         /* Find the post dominators */
9788         find_post_dominators(state);
9789         /* Find the control dependencies (post dominance frontiers) */
9790         find_block_ipdomf(state, state->last_block);
9791         /* If debuging print the print what I have just found */
9792         if (state->debug & DEBUG_RDOMINATORS) {
9793                 print_ipdominators(state, stdout);
9794                 print_ipdominance_frontiers(state);
9795                 print_control_flow(state);
9796         }
9797 }
9798
9799 static int bdominates(struct compile_state *state,
9800         struct block *dom, struct block *sub)
9801 {
9802         while(sub && (sub != dom)) {
9803                 sub = sub->idom;
9804         }
9805         return sub == dom;
9806 }
9807
9808 static int tdominates(struct compile_state *state,
9809         struct triple *dom, struct triple *sub)
9810 {
9811         struct block *bdom, *bsub;
9812         int result;
9813         bdom = block_of_triple(state, dom);
9814         bsub = block_of_triple(state, sub);
9815         if (bdom != bsub) {
9816                 result = bdominates(state, bdom, bsub);
9817         } 
9818         else {
9819                 struct triple *ins;
9820                 ins = sub;
9821                 while((ins != bsub->first) && (ins != dom)) {
9822                         ins = ins->prev;
9823                 }
9824                 result = (ins == dom);
9825         }
9826         return result;
9827 }
9828
9829 static void insert_phi_operations(struct compile_state *state)
9830 {
9831         size_t size;
9832         struct triple *first;
9833         int *has_already, *work;
9834         struct block *work_list, **work_list_tail;
9835         int iter;
9836         struct triple *var;
9837
9838         size = sizeof(int) * (state->last_vertex + 1);
9839         has_already = xcmalloc(size, "has_already");
9840         work =        xcmalloc(size, "work");
9841         iter = 0;
9842
9843         first = RHS(state->main_function, 0);
9844         for(var = first->next; var != first ; var = var->next) {
9845                 struct block *block;
9846                 struct triple_set *user;
9847                 if ((var->op != OP_ADECL) || !var->use) {
9848                         continue;
9849                 }
9850                 iter += 1;
9851                 work_list = 0;
9852                 work_list_tail = &work_list;
9853                 for(user = var->use; user; user = user->next) {
9854                         if (user->member->op == OP_READ) {
9855                                 continue;
9856                         }
9857                         if (user->member->op != OP_WRITE) {
9858                                 internal_error(state, user->member, 
9859                                         "bad variable access");
9860                         }
9861                         block = user->member->u.block;
9862                         if (!block) {
9863                                 warning(state, user->member, "dead code");
9864                         }
9865                         if (work[block->vertex] >= iter) {
9866                                 continue;
9867                         }
9868                         work[block->vertex] = iter;
9869                         *work_list_tail = block;
9870                         block->work_next = 0;
9871                         work_list_tail = &block->work_next;
9872                 }
9873                 for(block = work_list; block; block = block->work_next) {
9874                         struct block_set *df;
9875                         for(df = block->domfrontier; df; df = df->next) {
9876                                 struct triple *phi;
9877                                 struct block *front;
9878                                 int in_edges;
9879                                 front = df->member;
9880
9881                                 if (has_already[front->vertex] >= iter) {
9882                                         continue;
9883                                 }
9884                                 /* Count how many edges flow into this block */
9885                                 in_edges = front->users;
9886                                 /* Insert a phi function for this variable */
9887                                 phi = alloc_triple(
9888                                         state, OP_PHI, var->type, -1, in_edges, 
9889                                         front->first->filename, 
9890                                         front->first->line,
9891                                         front->first->col);
9892                                 phi->u.block = front;
9893                                 MISC(phi, 0) = var;
9894                                 use_triple(var, phi);
9895                                 /* Insert the phi functions immediately after the label */
9896                                 insert_triple(state, front->first->next, phi);
9897                                 if (front->first == front->last) {
9898                                         front->last = front->first->next;
9899                                 }
9900                                 has_already[front->vertex] = iter;
9901
9902                                 /* If necessary plan to visit the basic block */
9903                                 if (work[front->vertex] >= iter) {
9904                                         continue;
9905                                 }
9906                                 work[front->vertex] = iter;
9907                                 *work_list_tail = front;
9908                                 front->work_next = 0;
9909                                 work_list_tail = &front->work_next;
9910                         }
9911                 }
9912         }
9913         xfree(has_already);
9914         xfree(work);
9915 }
9916
9917 /*
9918  * C(V)
9919  * S(V)
9920  */
9921 static void fixup_block_phi_variables(
9922         struct compile_state *state, struct block *parent, struct block *block)
9923 {
9924         struct block_set *set;
9925         struct triple *ptr;
9926         int edge;
9927         if (!parent || !block)
9928                 return;
9929         /* Find the edge I am coming in on */
9930         edge = 0;
9931         for(set = block->use; set; set = set->next, edge++) {
9932                 if (set->member == parent) {
9933                         break;
9934                 }
9935         }
9936         if (!set) {
9937                 internal_error(state, 0, "phi input is not on a control predecessor");
9938         }
9939         for(ptr = block->first; ; ptr = ptr->next) {
9940                 if (ptr->op == OP_PHI) {
9941                         struct triple *var, *val, **slot;
9942                         var = MISC(ptr, 0);
9943                         if (!var) {
9944                                 internal_error(state, ptr, "no var???");
9945                         }
9946                         /* Find the current value of the variable */
9947                         val = var->use->member;
9948                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9949                                 internal_error(state, val, "bad value in phi");
9950                         }
9951                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
9952                                 internal_error(state, ptr, "edges > phi rhs");
9953                         }
9954                         slot = &RHS(ptr, edge);
9955                         if ((*slot != 0) && (*slot != val)) {
9956                                 internal_error(state, ptr, "phi already bound on this edge");
9957                         }
9958                         *slot = val;
9959                         use_triple(val, ptr);
9960                 }
9961                 if (ptr == block->last) {
9962                         break;
9963                 }
9964         }
9965 }
9966
9967
9968 static void rename_block_variables(
9969         struct compile_state *state, struct block *block)
9970 {
9971         struct block_set *user;
9972         struct triple *ptr, *next, *last;
9973         int done;
9974         if (!block)
9975                 return;
9976         last = block->first;
9977         done = 0;
9978         for(ptr = block->first; !done; ptr = next) {
9979                 next = ptr->next;
9980                 if (ptr == block->last) {
9981                         done = 1;
9982                 }
9983                 /* RHS(A) */
9984                 if (ptr->op == OP_READ) {
9985                         struct triple *var, *val;
9986                         var = RHS(ptr, 0);
9987                         unuse_triple(var, ptr);
9988                         if (!var->use) {
9989                                 error(state, ptr, "variable used without being set");
9990                         }
9991                         /* Find the current value of the variable */
9992                         val = var->use->member;
9993                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9994                                 internal_error(state, val, "bad value in read");
9995                         }
9996                         propogate_use(state, ptr, val);
9997                         release_triple(state, ptr);
9998                         continue;
9999                 }
10000                 /* LHS(A) */
10001                 if (ptr->op == OP_WRITE) {
10002                         struct triple *var, *val;
10003                         var = LHS(ptr, 0);
10004                         val = RHS(ptr, 0);
10005                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10006                                 internal_error(state, val, "bad value in write");
10007                         }
10008                         propogate_use(state, ptr, val);
10009                         unuse_triple(var, ptr);
10010                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10011                         push_triple(var, val);
10012                 }
10013                 if (ptr->op == OP_PHI) {
10014                         struct triple *var;
10015                         var = MISC(ptr, 0);
10016                         /* Push OP_PHI onto a stack of variable uses */
10017                         push_triple(var, ptr);
10018                 }
10019                 last = ptr;
10020         }
10021         block->last = last;
10022
10023         /* Fixup PHI functions in the cf successors */
10024         fixup_block_phi_variables(state, block, block->left);
10025         fixup_block_phi_variables(state, block, block->right);
10026         /* rename variables in the dominated nodes */
10027         for(user = block->idominates; user; user = user->next) {
10028                 rename_block_variables(state, user->member);
10029         }
10030         /* pop the renamed variable stack */
10031         last = block->first;
10032         done = 0;
10033         for(ptr = block->first; !done ; ptr = next) {
10034                 next = ptr->next;
10035                 if (ptr == block->last) {
10036                         done = 1;
10037                 }
10038                 if (ptr->op == OP_WRITE) {
10039                         struct triple *var;
10040                         var = LHS(ptr, 0);
10041                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10042                         pop_triple(var, RHS(ptr, 0));
10043                         release_triple(state, ptr);
10044                         continue;
10045                 }
10046                 if (ptr->op == OP_PHI) {
10047                         struct triple *var;
10048                         var = MISC(ptr, 0);
10049                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10050                         pop_triple(var, ptr);
10051                 }
10052                 last = ptr;
10053         }
10054         block->last = last;
10055 }
10056
10057 static void prune_block_variables(struct compile_state *state,
10058         struct block *block)
10059 {
10060         struct block_set *user;
10061         struct triple *next, *last, *ptr;
10062         int done;
10063         last = block->first;
10064         done = 0;
10065         for(ptr = block->first; !done; ptr = next) {
10066                 next = ptr->next;
10067                 if (ptr == block->last) {
10068                         done = 1;
10069                 }
10070                 if (ptr->op == OP_ADECL) {
10071                         struct triple_set *user, *next;
10072                         for(user = ptr->use; user; user = next) {
10073                                 struct triple *use;
10074                                 next = user->next;
10075                                 use = user->member;
10076                                 if (use->op != OP_PHI) {
10077                                         internal_error(state, use, "decl still used");
10078                                 }
10079                                 if (MISC(use, 0) != ptr) {
10080                                         internal_error(state, use, "bad phi use of decl");
10081                                 }
10082                                 unuse_triple(ptr, use);
10083                                 MISC(use, 0) = 0;
10084                         }
10085                         release_triple(state, ptr);
10086                         continue;
10087                 }
10088                 last = ptr;
10089         }
10090         block->last = last;
10091         for(user = block->idominates; user; user = user->next) {
10092                 prune_block_variables(state, user->member);
10093         }
10094 }
10095
10096 static void transform_to_ssa_form(struct compile_state *state)
10097 {
10098         insert_phi_operations(state);
10099 #if 0
10100         printf("@%s:%d\n", __FILE__, __LINE__);
10101         print_blocks(state, stdout);
10102 #endif
10103         rename_block_variables(state, state->first_block);
10104         prune_block_variables(state, state->first_block);
10105 }
10106
10107
10108 static void clear_vertex(
10109         struct compile_state *state, struct block *block, void *arg)
10110 {
10111         block->vertex = 0;
10112 }
10113
10114 static void mark_live_block(
10115         struct compile_state *state, struct block *block, int *next_vertex)
10116 {
10117         /* See if this is a block that has not been marked */
10118         if (block->vertex != 0) {
10119                 return;
10120         }
10121         block->vertex = *next_vertex;
10122         *next_vertex += 1;
10123         if (triple_is_branch(state, block->last)) {
10124                 struct triple **targ;
10125                 targ = triple_targ(state, block->last, 0);
10126                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10127                         if (!*targ) {
10128                                 continue;
10129                         }
10130                         if (!triple_stores_block(state, *targ)) {
10131                                 internal_error(state, 0, "bad targ");
10132                         }
10133                         mark_live_block(state, (*targ)->u.block, next_vertex);
10134                 }
10135         }
10136         else if (block->last->next != RHS(state->main_function, 0)) {
10137                 struct triple *ins;
10138                 ins = block->last->next;
10139                 if (!triple_stores_block(state, ins)) {
10140                         internal_error(state, 0, "bad block start");
10141                 }
10142                 mark_live_block(state, ins->u.block, next_vertex);
10143         }
10144 }
10145
10146 static void transform_from_ssa_form(struct compile_state *state)
10147 {
10148         /* To get out of ssa form we insert moves on the incoming
10149          * edges to blocks containting phi functions.
10150          */
10151         struct triple *first;
10152         struct triple *phi, *next;
10153         int next_vertex;
10154
10155         /* Walk the control flow to see which blocks remain alive */
10156         walk_blocks(state, clear_vertex, 0);
10157         next_vertex = 1;
10158         mark_live_block(state, state->first_block, &next_vertex);
10159
10160         /* Walk all of the operations to find the phi functions */
10161         first = RHS(state->main_function, 0);
10162         for(phi = first->next; phi != first ; phi = next) {
10163                 struct block_set *set;
10164                 struct block *block;
10165                 struct triple **slot;
10166                 struct triple *var, *read;
10167                 struct triple_set *use, *use_next;
10168                 int edge, used;
10169                 next = phi->next;
10170                 if (phi->op != OP_PHI) {
10171                         continue;
10172                 }
10173                 block = phi->u.block;
10174                 slot  = &RHS(phi, 0);
10175
10176                 /* Forget uses from code in dead blocks */
10177                 for(use = phi->use; use; use = use_next) {
10178                         struct block *ublock;
10179                         struct triple **expr;
10180                         use_next = use->next;
10181                         ublock = block_of_triple(state, use->member);
10182                         if ((use->member == phi) || (ublock->vertex != 0)) {
10183                                 continue;
10184                         }
10185                         expr = triple_rhs(state, use->member, 0);
10186                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10187                                 if (*expr == phi) {
10188                                         *expr = 0;
10189                                 }
10190                         }
10191                         unuse_triple(phi, use->member);
10192                 }
10193
10194                 /* A variable to replace the phi function */
10195                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10196                 /* A read of the single value that is set into the variable */
10197                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10198                 use_triple(var, read);
10199
10200                 /* Replaces uses of the phi with variable reads */
10201                 propogate_use(state, phi, read);
10202
10203                 /* Walk all of the incoming edges/blocks and insert moves.
10204                  */
10205                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10206                         struct block *eblock;
10207                         struct triple *move;
10208                         struct triple *val;
10209                         eblock = set->member;
10210                         val = slot[edge];
10211                         slot[edge] = 0;
10212                         unuse_triple(val, phi);
10213
10214                         if (!val || (val == &zero_triple) ||
10215                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10216                                 (val == phi) || (val == read)) {
10217                                 continue;
10218                         }
10219                         
10220                         move = post_triple(state, 
10221                                 val, OP_WRITE, phi->type, var, val);
10222                         use_triple(val, move);
10223                         use_triple(var, move);
10224                 }               
10225                 /* See if there are any writers of var */
10226                 used = 0;
10227                 for(use = var->use; use; use = use->next) {
10228                         struct triple **expr;
10229                         expr = triple_lhs(state, use->member, 0);
10230                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10231                                 if (*expr == var) {
10232                                         used = 1;
10233                                 }
10234                         }
10235                 }
10236                 /* If var is not used free it */
10237                 if (!used) {
10238                         unuse_triple(var, read);
10239                         free_triple(state, read);
10240                         free_triple(state, var);
10241                 }
10242
10243                 /* Release the phi function */
10244                 release_triple(state, phi);
10245         }
10246         
10247 }
10248
10249
10250 /* 
10251  * Register conflict resolution
10252  * =========================================================
10253  */
10254
10255 static struct reg_info find_def_color(
10256         struct compile_state *state, struct triple *def)
10257 {
10258         struct triple_set *set;
10259         struct reg_info info;
10260         info.reg = REG_UNSET;
10261         info.regcm = 0;
10262         if (!triple_is_def(state, def)) {
10263                 return info;
10264         }
10265         info = arch_reg_lhs(state, def, 0);
10266         if (info.reg >= MAX_REGISTERS) {
10267                 info.reg = REG_UNSET;
10268         }
10269         for(set = def->use; set; set = set->next) {
10270                 struct reg_info tinfo;
10271                 int i;
10272                 i = find_rhs_use(state, set->member, def);
10273                 if (i < 0) {
10274                         continue;
10275                 }
10276                 tinfo = arch_reg_rhs(state, set->member, i);
10277                 if (tinfo.reg >= MAX_REGISTERS) {
10278                         tinfo.reg = REG_UNSET;
10279                 }
10280                 if ((tinfo.reg != REG_UNSET) && 
10281                         (info.reg != REG_UNSET) &&
10282                         (tinfo.reg != info.reg)) {
10283                         internal_error(state, def, "register conflict");
10284                 }
10285                 if ((info.regcm & tinfo.regcm) == 0) {
10286                         internal_error(state, def, "regcm conflict %x & %x == 0",
10287                                 info.regcm, tinfo.regcm);
10288                 }
10289                 if (info.reg == REG_UNSET) {
10290                         info.reg = tinfo.reg;
10291                 }
10292                 info.regcm &= tinfo.regcm;
10293         }
10294         if (info.reg >= MAX_REGISTERS) {
10295                 internal_error(state, def, "register out of range");
10296         }
10297         return info;
10298 }
10299
10300 static struct reg_info find_lhs_pre_color(
10301         struct compile_state *state, struct triple *ins, int index)
10302 {
10303         struct reg_info info;
10304         int zlhs, zrhs, i;
10305         zrhs = TRIPLE_RHS(ins->sizes);
10306         zlhs = TRIPLE_LHS(ins->sizes);
10307         if (!zlhs && triple_is_def(state, ins)) {
10308                 zlhs = 1;
10309         }
10310         if (index >= zlhs) {
10311                 internal_error(state, ins, "Bad lhs %d", index);
10312         }
10313         info = arch_reg_lhs(state, ins, index);
10314         for(i = 0; i < zrhs; i++) {
10315                 struct reg_info rinfo;
10316                 rinfo = arch_reg_rhs(state, ins, i);
10317                 if ((info.reg == rinfo.reg) &&
10318                         (rinfo.reg >= MAX_REGISTERS)) {
10319                         struct reg_info tinfo;
10320                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10321                         info.reg = tinfo.reg;
10322                         info.regcm &= tinfo.regcm;
10323                         break;
10324                 }
10325         }
10326         if (info.reg >= MAX_REGISTERS) {
10327                 info.reg = REG_UNSET;
10328         }
10329         return info;
10330 }
10331
10332 static struct reg_info find_rhs_post_color(
10333         struct compile_state *state, struct triple *ins, int index);
10334
10335 static struct reg_info find_lhs_post_color(
10336         struct compile_state *state, struct triple *ins, int index)
10337 {
10338         struct triple_set *set;
10339         struct reg_info info;
10340         struct triple *lhs;
10341 #if 0
10342         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10343                 ins, index);
10344 #endif
10345         if ((index == 0) && triple_is_def(state, ins)) {
10346                 lhs = ins;
10347         }
10348         else if (index < TRIPLE_LHS(ins->sizes)) {
10349                 lhs = LHS(ins, index);
10350         }
10351         else {
10352                 internal_error(state, ins, "Bad lhs %d", index);
10353                 lhs = 0;
10354         }
10355         info = arch_reg_lhs(state, ins, index);
10356         if (info.reg >= MAX_REGISTERS) {
10357                 info.reg = REG_UNSET;
10358         }
10359         for(set = lhs->use; set; set = set->next) {
10360                 struct reg_info rinfo;
10361                 struct triple *user;
10362                 int zrhs, i;
10363                 user = set->member;
10364                 zrhs = TRIPLE_RHS(user->sizes);
10365                 for(i = 0; i < zrhs; i++) {
10366                         if (RHS(user, i) != lhs) {
10367                                 continue;
10368                         }
10369                         rinfo = find_rhs_post_color(state, user, i);
10370                         if ((info.reg != REG_UNSET) &&
10371                                 (rinfo.reg != REG_UNSET) &&
10372                                 (info.reg != rinfo.reg)) {
10373                                 internal_error(state, ins, "register conflict");
10374                         }
10375                         if ((info.regcm & rinfo.regcm) == 0) {
10376                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10377                                         info.regcm, rinfo.regcm);
10378                         }
10379                         if (info.reg == REG_UNSET) {
10380                                 info.reg = rinfo.reg;
10381                         }
10382                         info.regcm &= rinfo.regcm;
10383                 }
10384         }
10385 #if 0
10386         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10387                 ins, index, info.reg, info.regcm);
10388 #endif
10389         return info;
10390 }
10391
10392 static struct reg_info find_rhs_post_color(
10393         struct compile_state *state, struct triple *ins, int index)
10394 {
10395         struct reg_info info, rinfo;
10396         int zlhs, i;
10397 #if 0
10398         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10399                 ins, index);
10400 #endif
10401         rinfo = arch_reg_rhs(state, ins, index);
10402         zlhs = TRIPLE_LHS(ins->sizes);
10403         if (!zlhs && triple_is_def(state, ins)) {
10404                 zlhs = 1;
10405         }
10406         info = rinfo;
10407         if (info.reg >= MAX_REGISTERS) {
10408                 info.reg = REG_UNSET;
10409         }
10410         for(i = 0; i < zlhs; i++) {
10411                 struct reg_info linfo;
10412                 linfo = arch_reg_lhs(state, ins, i);
10413                 if ((linfo.reg == rinfo.reg) &&
10414                         (linfo.reg >= MAX_REGISTERS)) {
10415                         struct reg_info tinfo;
10416                         tinfo = find_lhs_post_color(state, ins, i);
10417                         if (tinfo.reg >= MAX_REGISTERS) {
10418                                 tinfo.reg = REG_UNSET;
10419                         }
10420                         info.regcm &= linfo.reg;
10421                         info.regcm &= tinfo.regcm;
10422                         if (info.reg != REG_UNSET) {
10423                                 internal_error(state, ins, "register conflict");
10424                         }
10425                         if (info.regcm == 0) {
10426                                 internal_error(state, ins, "regcm conflict");
10427                         }
10428                         info.reg = tinfo.reg;
10429                 }
10430         }
10431 #if 0
10432         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10433                 ins, index, info.reg, info.regcm);
10434 #endif
10435         return info;
10436 }
10437
10438 static struct reg_info find_lhs_color(
10439         struct compile_state *state, struct triple *ins, int index)
10440 {
10441         struct reg_info pre, post, info;
10442 #if 0
10443         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10444                 ins, index);
10445 #endif
10446         pre = find_lhs_pre_color(state, ins, index);
10447         post = find_lhs_post_color(state, ins, index);
10448         if ((pre.reg != post.reg) &&
10449                 (pre.reg != REG_UNSET) &&
10450                 (post.reg != REG_UNSET)) {
10451                 internal_error(state, ins, "register conflict");
10452         }
10453         info.regcm = pre.regcm & post.regcm;
10454         info.reg = pre.reg;
10455         if (info.reg == REG_UNSET) {
10456                 info.reg = post.reg;
10457         }
10458 #if 0
10459         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10460                 ins, index, info.reg, info.regcm);
10461 #endif
10462         return info;
10463 }
10464
10465 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10466 {
10467         struct triple_set *entry, *next;
10468         struct triple *out;
10469         struct reg_info info, rinfo;
10470
10471         info = arch_reg_lhs(state, ins, 0);
10472         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10473         use_triple(RHS(out, 0), out);
10474         /* Get the users of ins to use out instead */
10475         for(entry = ins->use; entry; entry = next) {
10476                 int i;
10477                 next = entry->next;
10478                 if (entry->member == out) {
10479                         continue;
10480                 }
10481                 i = find_rhs_use(state, entry->member, ins);
10482                 if (i < 0) {
10483                         continue;
10484                 }
10485                 rinfo = arch_reg_rhs(state, entry->member, i);
10486                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10487                         continue;
10488                 }
10489                 replace_rhs_use(state, ins, out, entry->member);
10490         }
10491         transform_to_arch_instruction(state, out);
10492         return out;
10493 }
10494
10495 static struct triple *pre_copy(
10496         struct compile_state *state, struct triple *ins, int index)
10497 {
10498         /* Carefully insert enough operations so that I can
10499          * enter any operation with a GPR32.
10500          */
10501         struct triple *in;
10502         struct triple **expr;
10503         expr = &RHS(ins, index);
10504         in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10505         unuse_triple(*expr, ins);
10506         *expr = in;
10507         use_triple(RHS(in, 0), in);
10508         use_triple(in, ins);
10509         transform_to_arch_instruction(state, in);
10510         return in;
10511 }
10512
10513
10514 static void insert_copies_to_phi(struct compile_state *state)
10515 {
10516         /* To get out of ssa form we insert moves on the incoming
10517          * edges to blocks containting phi functions.
10518          */
10519         struct triple *first;
10520         struct triple *phi;
10521
10522         /* Walk all of the operations to find the phi functions */
10523         first = RHS(state->main_function, 0);
10524         for(phi = first->next; phi != first ; phi = phi->next) {
10525                 struct block_set *set;
10526                 struct block *block;
10527                 struct triple **slot;
10528                 int edge;
10529                 if (phi->op != OP_PHI) {
10530                         continue;
10531                 }
10532                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10533                 block = phi->u.block;
10534                 slot  = &RHS(phi, 0);
10535                 /* Walk all of the incoming edges/blocks and insert moves.
10536                  */
10537                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10538                         struct block *eblock;
10539                         struct triple *move;
10540                         struct triple *val;
10541                         struct triple *ptr;
10542                         eblock = set->member;
10543                         val = slot[edge];
10544
10545                         if (val == phi) {
10546                                 continue;
10547                         }
10548
10549                         move = build_triple(state, OP_COPY, phi->type, val, 0,
10550                                 val->filename, val->line, val->col);
10551                         move->u.block = eblock;
10552                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
10553                         use_triple(val, move);
10554                         
10555                         slot[edge] = move;
10556                         unuse_triple(val, phi);
10557                         use_triple(move, phi);
10558
10559                         /* Walk through the block backwards to find
10560                          * an appropriate location for the OP_COPY.
10561                          */
10562                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10563                                 struct triple **expr;
10564                                 if ((ptr == phi) || (ptr == val)) {
10565                                         goto out;
10566                                 }
10567                                 expr = triple_rhs(state, ptr, 0);
10568                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10569                                         if ((*expr) == phi) {
10570                                                 goto out;
10571                                         }
10572                                 }
10573                         }
10574                 out:
10575                         if (triple_is_branch(state, ptr)) {
10576                                 internal_error(state, ptr,
10577                                         "Could not insert write to phi");
10578                         }
10579                         insert_triple(state, ptr->next, move);
10580                         if (eblock->last == ptr) {
10581                                 eblock->last = move;
10582                         }
10583                         transform_to_arch_instruction(state, move);
10584                 }
10585         }
10586 }
10587
10588 struct triple_reg_set {
10589         struct triple_reg_set *next;
10590         struct triple *member;
10591         struct triple *new;
10592 };
10593
10594 struct reg_block {
10595         struct block *block;
10596         struct triple_reg_set *in;
10597         struct triple_reg_set *out;
10598         int vertex;
10599 };
10600
10601 static int do_triple_set(struct triple_reg_set **head, 
10602         struct triple *member, struct triple *new_member)
10603 {
10604         struct triple_reg_set **ptr, *new;
10605         if (!member)
10606                 return 0;
10607         ptr = head;
10608         while(*ptr) {
10609                 if ((*ptr)->member == member) {
10610                         return 0;
10611                 }
10612                 ptr = &(*ptr)->next;
10613         }
10614         new = xcmalloc(sizeof(*new), "triple_set");
10615         new->member = member;
10616         new->new    = new_member;
10617         new->next   = *head;
10618         *head       = new;
10619         return 1;
10620 }
10621
10622 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10623 {
10624         struct triple_reg_set *entry, **ptr;
10625         ptr = head;
10626         while(*ptr) {
10627                 entry = *ptr;
10628                 if (entry->member == member) {
10629                         *ptr = entry->next;
10630                         xfree(entry);
10631                         return;
10632                 }
10633                 else {
10634                         ptr = &entry->next;
10635                 }
10636         }
10637 }
10638
10639 static int in_triple(struct reg_block *rb, struct triple *in)
10640 {
10641         return do_triple_set(&rb->in, in, 0);
10642 }
10643 static void unin_triple(struct reg_block *rb, struct triple *unin)
10644 {
10645         do_triple_unset(&rb->in, unin);
10646 }
10647
10648 static int out_triple(struct reg_block *rb, struct triple *out)
10649 {
10650         return do_triple_set(&rb->out, out, 0);
10651 }
10652 static void unout_triple(struct reg_block *rb, struct triple *unout)
10653 {
10654         do_triple_unset(&rb->out, unout);
10655 }
10656
10657 static int initialize_regblock(struct reg_block *blocks,
10658         struct block *block, int vertex)
10659 {
10660         struct block_set *user;
10661         if (!block || (blocks[block->vertex].block == block)) {
10662                 return vertex;
10663         }
10664         vertex += 1;
10665         /* Renumber the blocks in a convinient fashion */
10666         block->vertex = vertex;
10667         blocks[vertex].block    = block;
10668         blocks[vertex].vertex   = vertex;
10669         for(user = block->use; user; user = user->next) {
10670                 vertex = initialize_regblock(blocks, user->member, vertex);
10671         }
10672         return vertex;
10673 }
10674
10675 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10676         struct reg_block *rb, struct block *suc)
10677 {
10678         /* Read the conditional input set of a successor block
10679          * (i.e. the input to the phi nodes) and place it in the
10680          * current blocks output set.
10681          */
10682         struct block_set *set;
10683         struct triple *ptr;
10684         int edge;
10685         int done, change;
10686         change = 0;
10687         /* Find the edge I am coming in on */
10688         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10689                 if (set->member == rb->block) {
10690                         break;
10691                 }
10692         }
10693         if (!set) {
10694                 internal_error(state, 0, "Not coming on a control edge?");
10695         }
10696         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10697                 struct triple **slot, *expr, *ptr2;
10698                 int out_change, done2;
10699                 done = (ptr == suc->last);
10700                 if (ptr->op != OP_PHI) {
10701                         continue;
10702                 }
10703                 slot = &RHS(ptr, 0);
10704                 expr = slot[edge];
10705                 out_change = out_triple(rb, expr);
10706                 if (!out_change) {
10707                         continue;
10708                 }
10709                 /* If we don't define the variable also plast it
10710                  * in the current blocks input set.
10711                  */
10712                 ptr2 = rb->block->first;
10713                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10714                         if (ptr2 == expr) {
10715                                 break;
10716                         }
10717                         done2 = (ptr2 == rb->block->last);
10718                 }
10719                 if (!done2) {
10720                         continue;
10721                 }
10722                 change |= in_triple(rb, expr);
10723         }
10724         return change;
10725 }
10726
10727 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10728         struct reg_block *rb, struct block *suc)
10729 {
10730         struct triple_reg_set *in_set;
10731         int change;
10732         change = 0;
10733         /* Read the input set of a successor block
10734          * and place it in the current blocks output set.
10735          */
10736         in_set = blocks[suc->vertex].in;
10737         for(; in_set; in_set = in_set->next) {
10738                 int out_change, done;
10739                 struct triple *first, *last, *ptr;
10740                 out_change = out_triple(rb, in_set->member);
10741                 if (!out_change) {
10742                         continue;
10743                 }
10744                 /* If we don't define the variable also place it
10745                  * in the current blocks input set.
10746                  */
10747                 first = rb->block->first;
10748                 last = rb->block->last;
10749                 done = 0;
10750                 for(ptr = first; !done; ptr = ptr->next) {
10751                         if (ptr == in_set->member) {
10752                                 break;
10753                         }
10754                         done = (ptr == last);
10755                 }
10756                 if (!done) {
10757                         continue;
10758                 }
10759                 change |= in_triple(rb, in_set->member);
10760         }
10761         change |= phi_in(state, blocks, rb, suc);
10762         return change;
10763 }
10764
10765
10766 static int use_in(struct compile_state *state, struct reg_block *rb)
10767 {
10768         /* Find the variables we use but don't define and add
10769          * it to the current blocks input set.
10770          */
10771 #warning "FIXME is this O(N^2) algorithm bad?"
10772         struct block *block;
10773         struct triple *ptr;
10774         int done;
10775         int change;
10776         block = rb->block;
10777         change = 0;
10778         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10779                 struct triple **expr;
10780                 done = (ptr == block->first);
10781                 /* The variable a phi function uses depends on the
10782                  * control flow, and is handled in phi_in, not
10783                  * here.
10784                  */
10785                 if (ptr->op == OP_PHI) {
10786                         continue;
10787                 }
10788                 expr = triple_rhs(state, ptr, 0);
10789                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10790                         struct triple *rhs, *test;
10791                         int tdone;
10792                         rhs = *expr;
10793                         if (!rhs) {
10794                                 continue;
10795                         }
10796                         /* See if rhs is defined in this block */
10797                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10798                                 tdone = (test == block->first);
10799                                 if (test == rhs) {
10800                                         rhs = 0;
10801                                         break;
10802                                 }
10803                         }
10804                         /* If I still have a valid rhs add it to in */
10805                         change |= in_triple(rb, rhs);
10806                 }
10807         }
10808         return change;
10809 }
10810
10811 static struct reg_block *compute_variable_lifetimes(
10812         struct compile_state *state)
10813 {
10814         struct reg_block *blocks;
10815         int change;
10816         blocks = xcmalloc(
10817                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10818         initialize_regblock(blocks, state->last_block, 0);
10819         do {
10820                 int i;
10821                 change = 0;
10822                 for(i = 1; i <= state->last_vertex; i++) {
10823                         struct reg_block *rb;
10824                         rb = &blocks[i];
10825                         /* Add the left successor's input set to in */
10826                         if (rb->block->left) {
10827                                 change |= reg_in(state, blocks, rb, rb->block->left);
10828                         }
10829                         /* Add the right successor's input set to in */
10830                         if ((rb->block->right) && 
10831                                 (rb->block->right != rb->block->left)) {
10832                                 change |= reg_in(state, blocks, rb, rb->block->right);
10833                         }
10834                         /* Add use to in... */
10835                         change |= use_in(state, rb);
10836                 }
10837         } while(change);
10838         return blocks;
10839 }
10840
10841 static void free_variable_lifetimes(
10842         struct compile_state *state, struct reg_block *blocks)
10843 {
10844         int i;
10845         /* free in_set && out_set on each block */
10846         for(i = 1; i <= state->last_vertex; i++) {
10847                 struct triple_reg_set *entry, *next;
10848                 struct reg_block *rb;
10849                 rb = &blocks[i];
10850                 for(entry = rb->in; entry ; entry = next) {
10851                         next = entry->next;
10852                         do_triple_unset(&rb->in, entry->member);
10853                 }
10854                 for(entry = rb->out; entry; entry = next) {
10855                         next = entry->next;
10856                         do_triple_unset(&rb->out, entry->member);
10857                 }
10858         }
10859         xfree(blocks);
10860
10861 }
10862
10863 typedef void (*wvl_cb_t)(
10864         struct compile_state *state, 
10865         struct reg_block *blocks, struct triple_reg_set *live, 
10866         struct reg_block *rb, struct triple *ins, void *arg);
10867
10868 static void walk_variable_lifetimes(struct compile_state *state,
10869         struct reg_block *blocks, wvl_cb_t cb, void *arg)
10870 {
10871         int i;
10872         
10873         for(i = 1; i <= state->last_vertex; i++) {
10874                 struct triple_reg_set *live;
10875                 struct triple_reg_set *entry, *next;
10876                 struct triple *ptr, *prev;
10877                 struct reg_block *rb;
10878                 struct block *block;
10879                 int done;
10880
10881                 /* Get the blocks */
10882                 rb = &blocks[i];
10883                 block = rb->block;
10884
10885                 /* Copy out into live */
10886                 live = 0;
10887                 for(entry = rb->out; entry; entry = next) {
10888                         next = entry->next;
10889                         do_triple_set(&live, entry->member, entry->new);
10890                 }
10891                 /* Walk through the basic block calculating live */
10892                 for(done = 0, ptr = block->last; !done; ptr = prev) {
10893                         struct triple **expr;
10894
10895                         prev = ptr->prev;
10896                         done = (ptr == block->first);
10897
10898                         /* Ensure the current definition is in live */
10899                         if (triple_is_def(state, ptr)) {
10900                                 do_triple_set(&live, ptr, 0);
10901                         }
10902
10903                         /* Inform the callback function of what is
10904                          * going on.
10905                          */
10906                          cb(state, blocks, live, rb, ptr, arg);
10907                         
10908                         /* Remove the current definition from live */
10909                         do_triple_unset(&live, ptr);
10910
10911                         /* Add the current uses to live.
10912                          *
10913                          * It is safe to skip phi functions because they do
10914                          * not have any block local uses, and the block
10915                          * output sets already properly account for what
10916                          * control flow depedent uses phi functions do have.
10917                          */
10918                         if (ptr->op == OP_PHI) {
10919                                 continue;
10920                         }
10921                         expr = triple_rhs(state, ptr, 0);
10922                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
10923                                 /* If the triple is not a definition skip it. */
10924                                 if (!*expr || !triple_is_def(state, *expr)) {
10925                                         continue;
10926                                 }
10927                                 do_triple_set(&live, *expr, 0);
10928                         }
10929                 }
10930                 /* Free live */
10931                 for(entry = live; entry; entry = next) {
10932                         next = entry->next;
10933                         do_triple_unset(&live, entry->member);
10934                 }
10935         }
10936 }
10937
10938 static int count_triples(struct compile_state *state)
10939 {
10940         struct triple *first, *ins;
10941         int triples = 0;
10942         first = RHS(state->main_function, 0);
10943         ins = first;
10944         do {
10945                 triples++;
10946                 ins = ins->next;
10947         } while (ins != first);
10948         return triples;
10949 }
10950 struct dead_triple {
10951         struct triple *triple;
10952         struct dead_triple *work_next;
10953         struct block *block;
10954         int color;
10955         int flags;
10956 #define TRIPLE_FLAG_ALIVE 1
10957 };
10958
10959
10960 static void awaken(
10961         struct compile_state *state,
10962         struct dead_triple *dtriple, struct triple **expr,
10963         struct dead_triple ***work_list_tail)
10964 {
10965         struct triple *triple;
10966         struct dead_triple *dt;
10967         if (!expr) {
10968                 return;
10969         }
10970         triple = *expr;
10971         if (!triple) {
10972                 return;
10973         }
10974         if (triple->id <= 0)  {
10975                 internal_error(state, triple, "bad triple id: %d",
10976                         triple->id);
10977         }
10978         if (triple->op == OP_NOOP) {
10979                 internal_warning(state, triple, "awakening noop?");
10980                 return;
10981         }
10982         dt = &dtriple[triple->id];
10983         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10984                 dt->flags |= TRIPLE_FLAG_ALIVE;
10985                 if (!dt->work_next) {
10986                         **work_list_tail = dt;
10987                         *work_list_tail = &dt->work_next;
10988                 }
10989         }
10990 }
10991
10992 static void eliminate_inefectual_code(struct compile_state *state)
10993 {
10994         struct block *block;
10995         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10996         int triples, i;
10997         struct triple *first, *ins;
10998
10999         /* Setup the work list */
11000         work_list = 0;
11001         work_list_tail = &work_list;
11002
11003         first = RHS(state->main_function, 0);
11004
11005         /* Count how many triples I have */
11006         triples = count_triples(state);
11007
11008         /* Now put then in an array and mark all of the triples dead */
11009         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11010         
11011         ins = first;
11012         i = 1;
11013         block = 0;
11014         do {
11015                 if (ins->op == OP_LABEL) {
11016                         block = ins->u.block;
11017                 }
11018                 dtriple[i].triple = ins;
11019                 dtriple[i].block  = block;
11020                 dtriple[i].flags  = 0;
11021                 dtriple[i].color  = ins->id;
11022                 ins->id = i;
11023                 /* See if it is an operation we always keep */
11024 #warning "FIXME handle the case of killing a branch instruction"
11025                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11026                         awaken(state, dtriple, &ins, &work_list_tail);
11027                 }
11028                 i++;
11029                 ins = ins->next;
11030         } while(ins != first);
11031         while(work_list) {
11032                 struct dead_triple *dt;
11033                 struct block_set *user;
11034                 struct triple **expr;
11035                 dt = work_list;
11036                 work_list = dt->work_next;
11037                 if (!work_list) {
11038                         work_list_tail = &work_list;
11039                 }
11040                 /* Wake up the data depencencies of this triple */
11041                 expr = 0;
11042                 do {
11043                         expr = triple_rhs(state, dt->triple, expr);
11044                         awaken(state, dtriple, expr, &work_list_tail);
11045                 } while(expr);
11046                 do {
11047                         expr = triple_lhs(state, dt->triple, expr);
11048                         awaken(state, dtriple, expr, &work_list_tail);
11049                 } while(expr);
11050                 do {
11051                         expr = triple_misc(state, dt->triple, expr);
11052                         awaken(state, dtriple, expr, &work_list_tail);
11053                 } while(expr);
11054                 /* Wake up the forward control dependencies */
11055                 do {
11056                         expr = triple_targ(state, dt->triple, expr);
11057                         awaken(state, dtriple, expr, &work_list_tail);
11058                 } while(expr);
11059                 /* Wake up the reverse control dependencies of this triple */
11060                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11061                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11062                 }
11063         }
11064         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11065                 if ((dt->triple->op == OP_NOOP) && 
11066                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11067                         internal_error(state, dt->triple, "noop effective?");
11068                 }
11069                 dt->triple->id = dt->color;     /* Restore the color */
11070                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11071 #warning "FIXME handle the case of killing a basic block"
11072                         if (dt->block->first == dt->triple) {
11073                                 continue;
11074                         }
11075                         if (dt->block->last == dt->triple) {
11076                                 dt->block->last = dt->triple->prev;
11077                         }
11078                         release_triple(state, dt->triple);
11079                 }
11080         }
11081         xfree(dtriple);
11082 }
11083
11084
11085 static void insert_mandatory_copies(struct compile_state *state)
11086 {
11087         struct triple *ins, *first;
11088
11089         /* The object is with a minimum of inserted copies,
11090          * to resolve in fundamental register conflicts between
11091          * register value producers and consumers.
11092          * Theoretically we may be greater than minimal when we
11093          * are inserting copies before instructions but that
11094          * case should be rare.
11095          */
11096         first = RHS(state->main_function, 0);
11097         ins = first;
11098         do {
11099                 struct triple_set *entry, *next;
11100                 struct triple *tmp;
11101                 struct reg_info info;
11102                 unsigned reg, regcm;
11103                 int do_post_copy, do_pre_copy;
11104                 tmp = 0;
11105                 if (!triple_is_def(state, ins)) {
11106                         goto next;
11107                 }
11108                 /* Find the architecture specific color information */
11109                 info = arch_reg_lhs(state, ins, 0);
11110                 if (info.reg >= MAX_REGISTERS) {
11111                         info.reg = REG_UNSET;
11112                 }
11113                 
11114                 reg = REG_UNSET;
11115                 regcm = arch_type_to_regcm(state, ins->type);
11116                 do_post_copy = do_pre_copy = 0;
11117
11118                 /* Walk through the uses of ins and check for conflicts */
11119                 for(entry = ins->use; entry; entry = next) {
11120                         struct reg_info rinfo;
11121                         int i;
11122                         next = entry->next;
11123                         i = find_rhs_use(state, entry->member, ins);
11124                         if (i < 0) {
11125                                 continue;
11126                         }
11127                         
11128                         /* Find the users color requirements */
11129                         rinfo = arch_reg_rhs(state, entry->member, i);
11130                         if (rinfo.reg >= MAX_REGISTERS) {
11131                                 rinfo.reg = REG_UNSET;
11132                         }
11133                         
11134                         /* See if I need a pre_copy */
11135                         if (rinfo.reg != REG_UNSET) {
11136                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11137                                         do_pre_copy = 1;
11138                                 }
11139                                 reg = rinfo.reg;
11140                         }
11141                         regcm &= rinfo.regcm;
11142                         regcm = arch_regcm_normalize(state, regcm);
11143                         if (regcm == 0) {
11144                                 do_pre_copy = 1;
11145                         }
11146                 }
11147                 do_post_copy =
11148                         !do_pre_copy &&
11149                         (((info.reg != REG_UNSET) && 
11150                                 (reg != REG_UNSET) &&
11151                                 (info.reg != reg)) ||
11152                         ((info.regcm & regcm) == 0));
11153
11154                 reg = info.reg;
11155                 regcm = info.regcm;
11156                 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11157                 for(entry = ins->use; entry; entry = next) {
11158                         struct reg_info rinfo;
11159                         int i;
11160                         next = entry->next;
11161                         i = find_rhs_use(state, entry->member, ins);
11162                         if (i < 0) {
11163                                 continue;
11164                         }
11165                         
11166                         /* Find the users color requirements */
11167                         rinfo = arch_reg_rhs(state, entry->member, i);
11168                         if (rinfo.reg >= MAX_REGISTERS) {
11169                                 rinfo.reg = REG_UNSET;
11170                         }
11171
11172                         /* Now see if it is time to do the pre_copy */
11173                         if (rinfo.reg != REG_UNSET) {
11174                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11175                                         ((regcm & rinfo.regcm) == 0) ||
11176                                         /* Don't let a mandatory coalesce sneak
11177                                          * into a operation that is marked to prevent
11178                                          * coalescing.
11179                                          */
11180                                         ((reg != REG_UNNEEDED) &&
11181                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11182                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11183                                         ) {
11184                                         if (do_pre_copy) {
11185                                                 struct triple *user;
11186                                                 user = entry->member;
11187                                                 if (RHS(user, i) != ins) {
11188                                                         internal_error(state, user, "bad rhs");
11189                                                 }
11190                                                 tmp = pre_copy(state, user, i);
11191                                                 continue;
11192                                         } else {
11193                                                 do_post_copy = 1;
11194                                         }
11195                                 }
11196                                 reg = rinfo.reg;
11197                         }
11198                         if ((regcm & rinfo.regcm) == 0) {
11199                                 if (do_pre_copy) {
11200                                         struct triple *user;
11201                                         user = entry->member;
11202                                         if (RHS(user, i) != ins) {
11203                                                 internal_error(state, user, "bad rhs");
11204                                         }
11205                                         tmp = pre_copy(state, user, i);
11206                                         continue;
11207                                 } else {
11208                                         do_post_copy = 1;
11209                                 }
11210                         }
11211                         regcm &= rinfo.regcm;
11212                         
11213                 }
11214                 if (do_post_copy) {
11215                         struct reg_info pre, post;
11216                         tmp = post_copy(state, ins);
11217                         pre = arch_reg_lhs(state, ins, 0);
11218                         post = arch_reg_lhs(state, tmp, 0);
11219                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11220                                 internal_error(state, tmp, "useless copy");
11221                         }
11222                 }
11223         next:
11224                 ins = ins->next;
11225         } while(ins != first);
11226 }
11227
11228
11229 struct live_range_edge;
11230 struct live_range_def;
11231 struct live_range {
11232         struct live_range_edge *edges;
11233         struct live_range_def *defs;
11234 /* Note. The list pointed to by defs is kept in order.
11235  * That is baring splits in the flow control
11236  * defs dominates defs->next wich dominates defs->next->next
11237  * etc.
11238  */
11239         unsigned color;
11240         unsigned classes;
11241         unsigned degree;
11242         unsigned length;
11243         struct live_range *group_next, **group_prev;
11244 };
11245
11246 struct live_range_edge {
11247         struct live_range_edge *next;
11248         struct live_range *node;
11249 };
11250
11251 struct live_range_def {
11252         struct live_range_def *next;
11253         struct live_range_def *prev;
11254         struct live_range *lr;
11255         struct triple *def;
11256         unsigned orig_id;
11257 };
11258
11259 #define LRE_HASH_SIZE 2048
11260 struct lre_hash {
11261         struct lre_hash *next;
11262         struct live_range *left;
11263         struct live_range *right;
11264 };
11265
11266
11267 struct reg_state {
11268         struct lre_hash *hash[LRE_HASH_SIZE];
11269         struct reg_block *blocks;
11270         struct live_range_def *lrd;
11271         struct live_range *lr;
11272         struct live_range *low, **low_tail;
11273         struct live_range *high, **high_tail;
11274         unsigned defs;
11275         unsigned ranges;
11276         int passes, max_passes;
11277 #define MAX_ALLOCATION_PASSES 100
11278 };
11279
11280
11281 static unsigned regc_max_size(struct compile_state *state, int classes)
11282 {
11283         unsigned max_size;
11284         int i;
11285         max_size = 0;
11286         for(i = 0; i < MAX_REGC; i++) {
11287                 if (classes & (1 << i)) {
11288                         unsigned size;
11289                         size = arch_regc_size(state, i);
11290                         if (size > max_size) {
11291                                 max_size = size;
11292                         }
11293                 }
11294         }
11295         return max_size;
11296 }
11297
11298 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11299 {
11300         unsigned equivs[MAX_REG_EQUIVS];
11301         int i;
11302         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11303                 internal_error(state, 0, "invalid register");
11304         }
11305         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11306                 internal_error(state, 0, "invalid register");
11307         }
11308         arch_reg_equivs(state, equivs, reg1);
11309         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11310                 if (equivs[i] == reg2) {
11311                         return 1;
11312                 }
11313         }
11314         return 0;
11315 }
11316
11317 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11318 {
11319         unsigned equivs[MAX_REG_EQUIVS];
11320         int i;
11321         if (reg == REG_UNNEEDED) {
11322                 return;
11323         }
11324         arch_reg_equivs(state, equivs, reg);
11325         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11326                 used[equivs[i]] = 1;
11327         }
11328         return;
11329 }
11330
11331 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11332 {
11333         unsigned equivs[MAX_REG_EQUIVS];
11334         int i;
11335         if (reg == REG_UNNEEDED) {
11336                 return;
11337         }
11338         arch_reg_equivs(state, equivs, reg);
11339         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11340                 used[equivs[i]] += 1;
11341         }
11342         return;
11343 }
11344
11345 static unsigned int hash_live_edge(
11346         struct live_range *left, struct live_range *right)
11347 {
11348         unsigned int hash, val;
11349         unsigned long lval, rval;
11350         lval = ((unsigned long)left)/sizeof(struct live_range);
11351         rval = ((unsigned long)right)/sizeof(struct live_range);
11352         hash = 0;
11353         while(lval) {
11354                 val = lval & 0xff;
11355                 lval >>= 8;
11356                 hash = (hash *263) + val;
11357         }
11358         while(rval) {
11359                 val = rval & 0xff;
11360                 rval >>= 8;
11361                 hash = (hash *263) + val;
11362         }
11363         hash = hash & (LRE_HASH_SIZE - 1);
11364         return hash;
11365 }
11366
11367 static struct lre_hash **lre_probe(struct reg_state *rstate,
11368         struct live_range *left, struct live_range *right)
11369 {
11370         struct lre_hash **ptr;
11371         unsigned int index;
11372         /* Ensure left <= right */
11373         if (left > right) {
11374                 struct live_range *tmp;
11375                 tmp = left;
11376                 left = right;
11377                 right = tmp;
11378         }
11379         index = hash_live_edge(left, right);
11380         
11381         ptr = &rstate->hash[index];
11382         while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11383                 ptr = &(*ptr)->next;
11384         }
11385         return ptr;
11386 }
11387
11388 static int interfere(struct reg_state *rstate,
11389         struct live_range *left, struct live_range *right)
11390 {
11391         struct lre_hash **ptr;
11392         ptr = lre_probe(rstate, left, right);
11393         return ptr && *ptr;
11394 }
11395
11396 static void add_live_edge(struct reg_state *rstate, 
11397         struct live_range *left, struct live_range *right)
11398 {
11399         /* FIXME the memory allocation overhead is noticeable here... */
11400         struct lre_hash **ptr, *new_hash;
11401         struct live_range_edge *edge;
11402
11403         if (left == right) {
11404                 return;
11405         }
11406         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11407                 return;
11408         }
11409         /* Ensure left <= right */
11410         if (left > right) {
11411                 struct live_range *tmp;
11412                 tmp = left;
11413                 left = right;
11414                 right = tmp;
11415         }
11416         ptr = lre_probe(rstate, left, right);
11417         if (*ptr) {
11418                 return;
11419         }
11420         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11421         new_hash->next  = *ptr;
11422         new_hash->left  = left;
11423         new_hash->right = right;
11424         *ptr = new_hash;
11425
11426         edge = xmalloc(sizeof(*edge), "live_range_edge");
11427         edge->next   = left->edges;
11428         edge->node   = right;
11429         left->edges  = edge;
11430         left->degree += 1;
11431         
11432         edge = xmalloc(sizeof(*edge), "live_range_edge");
11433         edge->next    = right->edges;
11434         edge->node    = left;
11435         right->edges  = edge;
11436         right->degree += 1;
11437 }
11438
11439 static void remove_live_edge(struct reg_state *rstate,
11440         struct live_range *left, struct live_range *right)
11441 {
11442         struct live_range_edge *edge, **ptr;
11443         struct lre_hash **hptr, *entry;
11444         hptr = lre_probe(rstate, left, right);
11445         if (!hptr || !*hptr) {
11446                 return;
11447         }
11448         entry = *hptr;
11449         *hptr = entry->next;
11450         xfree(entry);
11451
11452         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11453                 edge = *ptr;
11454                 if (edge->node == right) {
11455                         *ptr = edge->next;
11456                         memset(edge, 0, sizeof(*edge));
11457                         xfree(edge);
11458                         break;
11459                 }
11460         }
11461         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11462                 edge = *ptr;
11463                 if (edge->node == left) {
11464                         *ptr = edge->next;
11465                         memset(edge, 0, sizeof(*edge));
11466                         xfree(edge);
11467                         break;
11468                 }
11469         }
11470 }
11471
11472 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11473 {
11474         struct live_range_edge *edge, *next;
11475         for(edge = range->edges; edge; edge = next) {
11476                 next = edge->next;
11477                 remove_live_edge(rstate, range, edge->node);
11478         }
11479 }
11480
11481
11482 /* Interference graph...
11483  * 
11484  * new(n) --- Return a graph with n nodes but no edges.
11485  * add(g,x,y) --- Return a graph including g with an between x and y
11486  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11487  *                x and y in the graph g
11488  * degree(g, x) --- Return the degree of the node x in the graph g
11489  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11490  *
11491  * Implement with a hash table && a set of adjcency vectors.
11492  * The hash table supports constant time implementations of add and interfere.
11493  * The adjacency vectors support an efficient implementation of neighbors.
11494  */
11495
11496 /* 
11497  *     +---------------------------------------------------+
11498  *     |         +--------------+                          |
11499  *     v         v              |                          |
11500  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
11501  *
11502  * -- In simplify implment optimistic coloring... (No backtracking)
11503  * -- Implement Rematerialization it is the only form of spilling we can perform
11504  *    Essentially this means dropping a constant from a register because
11505  *    we can regenerate it later.
11506  *
11507  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11508  *     coalesce at phi points...
11509  * --- Bias coloring if at all possible do the coalesing a compile time.
11510  *
11511  *
11512  */
11513
11514 static void different_colored(
11515         struct compile_state *state, struct reg_state *rstate, 
11516         struct triple *parent, struct triple *ins)
11517 {
11518         struct live_range *lr;
11519         struct triple **expr;
11520         lr = rstate->lrd[ins->id].lr;
11521         expr = triple_rhs(state, ins, 0);
11522         for(;expr; expr = triple_rhs(state, ins, expr)) {
11523                 struct live_range *lr2;
11524                 if (!*expr || (*expr == parent) || (*expr == ins)) {
11525                         continue;
11526                 }
11527                 lr2 = rstate->lrd[(*expr)->id].lr;
11528                 if (lr->color == lr2->color) {
11529                         internal_error(state, ins, "live range too big");
11530                 }
11531         }
11532 }
11533
11534
11535 static struct live_range *coalesce_ranges(
11536         struct compile_state *state, struct reg_state *rstate,
11537         struct live_range *lr1, struct live_range *lr2)
11538 {
11539         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11540         unsigned color;
11541         unsigned classes;
11542         if (lr1 == lr2) {
11543                 return lr1;
11544         }
11545         if (!lr1->defs || !lr2->defs) {
11546                 internal_error(state, 0,
11547                         "cannot coalese dead live ranges");
11548         }
11549         if ((lr1->color == REG_UNNEEDED) ||
11550                 (lr2->color == REG_UNNEEDED)) {
11551                 internal_error(state, 0, 
11552                         "cannot coalesce live ranges without a possible color");
11553         }
11554         if ((lr1->color != lr2->color) &&
11555                 (lr1->color != REG_UNSET) &&
11556                 (lr2->color != REG_UNSET)) {
11557                 internal_error(state, lr1->defs->def, 
11558                         "cannot coalesce live ranges of different colors");
11559         }
11560         color = lr1->color;
11561         if (color == REG_UNSET) {
11562                 color = lr2->color;
11563         }
11564         classes = lr1->classes & lr2->classes;
11565         if (!classes) {
11566                 internal_error(state, lr1->defs->def,
11567                         "cannot coalesce live ranges with dissimilar register classes");
11568         }
11569         /* If there is a clear dominate live range put it in lr1,
11570          * For purposes of this test phi functions are
11571          * considered dominated by the definitions that feed into
11572          * them. 
11573          */
11574         if ((lr1->defs->prev->def->op == OP_PHI) ||
11575                 ((lr2->defs->prev->def->op != OP_PHI) &&
11576                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11577                 struct live_range *tmp;
11578                 tmp = lr1;
11579                 lr1 = lr2;
11580                 lr2 = tmp;
11581         }
11582 #if 0
11583         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11584                 fprintf(stderr, "lr1 post\n");
11585         }
11586         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11587                 fprintf(stderr, "lr1 pre\n");
11588         }
11589         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11590                 fprintf(stderr, "lr2 post\n");
11591         }
11592         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11593                 fprintf(stderr, "lr2 pre\n");
11594         }
11595 #endif
11596 #if 0
11597         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11598                 lr1->defs->def,
11599                 lr1->color,
11600                 lr2->defs->def,
11601                 lr2->color);
11602 #endif
11603         
11604         lr1->classes = classes;
11605         /* Append lr2 onto lr1 */
11606 #warning "FIXME should this be a merge instead of a splice?"
11607         head = lr1->defs;
11608         mid1 = lr1->defs->prev;
11609         mid2 = lr2->defs;
11610         end  = lr2->defs->prev;
11611         
11612         head->prev = end;
11613         end->next  = head;
11614
11615         mid1->next = mid2;
11616         mid2->prev = mid1;
11617
11618         /* Fixup the live range in the added live range defs */
11619         lrd = head;
11620         do {
11621                 lrd->lr = lr1;
11622                 lrd = lrd->next;
11623         } while(lrd != head);
11624
11625         /* Mark lr2 as free. */
11626         lr2->defs = 0;
11627         lr2->color = REG_UNNEEDED;
11628         lr2->classes = 0;
11629
11630         if (!lr1->defs) {
11631                 internal_error(state, 0, "lr1->defs == 0 ?");
11632         }
11633
11634         lr1->color   = color;
11635         lr1->classes = classes;
11636
11637         return lr1;
11638 }
11639
11640 static struct live_range_def *live_range_head(
11641         struct compile_state *state, struct live_range *lr,
11642         struct live_range_def *last)
11643 {
11644         struct live_range_def *result;
11645         result = 0;
11646         if (last == 0) {
11647                 result = lr->defs;
11648         }
11649         else if (!tdominates(state, lr->defs->def, last->next->def)) {
11650                 result = last->next;
11651         }
11652         return result;
11653 }
11654
11655 static struct live_range_def *live_range_end(
11656         struct compile_state *state, struct live_range *lr,
11657         struct live_range_def *last)
11658 {
11659         struct live_range_def *result;
11660         result = 0;
11661         if (last == 0) {
11662                 result = lr->defs->prev;
11663         }
11664         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11665                 result = last->prev;
11666         }
11667         return result;
11668 }
11669
11670
11671 static void initialize_live_ranges(
11672         struct compile_state *state, struct reg_state *rstate)
11673 {
11674         struct triple *ins, *first;
11675         size_t count, size;
11676         int i, j;
11677
11678         first = RHS(state->main_function, 0);
11679         /* First count how many instructions I have.
11680          */
11681         count = count_triples(state);
11682         /* Potentially I need one live range definitions for each
11683          * instruction, plus an extra for the split routines.
11684          */
11685         rstate->defs = count + 1;
11686         /* Potentially I need one live range for each instruction
11687          * plus an extra for the dummy live range.
11688          */
11689         rstate->ranges = count + 1;
11690         size = sizeof(rstate->lrd[0]) * rstate->defs;
11691         rstate->lrd = xcmalloc(size, "live_range_def");
11692         size = sizeof(rstate->lr[0]) * rstate->ranges;
11693         rstate->lr  = xcmalloc(size, "live_range");
11694
11695         /* Setup the dummy live range */
11696         rstate->lr[0].classes = 0;
11697         rstate->lr[0].color = REG_UNSET;
11698         rstate->lr[0].defs = 0;
11699         i = j = 0;
11700         ins = first;
11701         do {
11702                 /* If the triple is a variable give it a live range */
11703                 if (triple_is_def(state, ins)) {
11704                         struct reg_info info;
11705                         /* Find the architecture specific color information */
11706                         info = find_def_color(state, ins);
11707
11708                         i++;
11709                         rstate->lr[i].defs    = &rstate->lrd[j];
11710                         rstate->lr[i].color   = info.reg;
11711                         rstate->lr[i].classes = info.regcm;
11712                         rstate->lr[i].degree  = 0;
11713                         rstate->lrd[j].lr = &rstate->lr[i];
11714                 } 
11715                 /* Otherwise give the triple the dummy live range. */
11716                 else {
11717                         rstate->lrd[j].lr = &rstate->lr[0];
11718                 }
11719
11720                 /* Initalize the live_range_def */
11721                 rstate->lrd[j].next    = &rstate->lrd[j];
11722                 rstate->lrd[j].prev    = &rstate->lrd[j];
11723                 rstate->lrd[j].def     = ins;
11724                 rstate->lrd[j].orig_id = ins->id;
11725                 ins->id = j;
11726
11727                 j++;
11728                 ins = ins->next;
11729         } while(ins != first);
11730         rstate->ranges = i;
11731         rstate->defs -= 1;
11732
11733         /* Make a second pass to handle achitecture specific register
11734          * constraints.
11735          */
11736         ins = first;
11737         do {
11738                 int zlhs, zrhs, i, j;
11739                 if (ins->id > rstate->defs) {
11740                         internal_error(state, ins, "bad id");
11741                 }
11742                 
11743                 /* Walk through the template of ins and coalesce live ranges */
11744                 zlhs = TRIPLE_LHS(ins->sizes);
11745                 if ((zlhs == 0) && triple_is_def(state, ins)) {
11746                         zlhs = 1;
11747                 }
11748                 zrhs = TRIPLE_RHS(ins->sizes);
11749                 
11750                 for(i = 0; i < zlhs; i++) {
11751                         struct reg_info linfo;
11752                         struct live_range_def *lhs;
11753                         linfo = arch_reg_lhs(state, ins, i);
11754                         if (linfo.reg < MAX_REGISTERS) {
11755                                 continue;
11756                         }
11757                         if (triple_is_def(state, ins)) {
11758                                 lhs = &rstate->lrd[ins->id];
11759                         } else {
11760                                 lhs = &rstate->lrd[LHS(ins, i)->id];
11761                         }
11762                         for(j = 0; j < zrhs; j++) {
11763                                 struct reg_info rinfo;
11764                                 struct live_range_def *rhs;
11765                                 rinfo = arch_reg_rhs(state, ins, j);
11766                                 if (rinfo.reg < MAX_REGISTERS) {
11767                                         continue;
11768                                 }
11769                                 rhs = &rstate->lrd[RHS(ins, i)->id];
11770                                 if (rinfo.reg == linfo.reg) {
11771                                         coalesce_ranges(state, rstate, 
11772                                                 lhs->lr, rhs->lr);
11773                                 }
11774                         }
11775                 }
11776                 ins = ins->next;
11777         } while(ins != first);
11778 }
11779
11780 static void graph_ins(
11781         struct compile_state *state, 
11782         struct reg_block *blocks, struct triple_reg_set *live, 
11783         struct reg_block *rb, struct triple *ins, void *arg)
11784 {
11785         struct reg_state *rstate = arg;
11786         struct live_range *def;
11787         struct triple_reg_set *entry;
11788
11789         /* If the triple is not a definition
11790          * we do not have a definition to add to
11791          * the interference graph.
11792          */
11793         if (!triple_is_def(state, ins)) {
11794                 return;
11795         }
11796         def = rstate->lrd[ins->id].lr;
11797         
11798         /* Create an edge between ins and everything that is
11799          * alive, unless the live_range cannot share
11800          * a physical register with ins.
11801          */
11802         for(entry = live; entry; entry = entry->next) {
11803                 struct live_range *lr;
11804                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11805                         internal_error(state, 0, "bad entry?");
11806                 }
11807                 lr = rstate->lrd[entry->member->id].lr;
11808                 if (def == lr) {
11809                         continue;
11810                 }
11811                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11812                         continue;
11813                 }
11814                 add_live_edge(rstate, def, lr);
11815         }
11816         return;
11817 }
11818
11819
11820 static void print_interference_ins(
11821         struct compile_state *state, 
11822         struct reg_block *blocks, struct triple_reg_set *live, 
11823         struct reg_block *rb, struct triple *ins, void *arg)
11824 {
11825         struct reg_state *rstate = arg;
11826         struct live_range *lr;
11827
11828         lr = rstate->lrd[ins->id].lr;
11829         display_triple(stdout, ins);
11830
11831         if (lr->defs) {
11832                 struct live_range_def *lrd;
11833                 printf("       range:");
11834                 lrd = lr->defs;
11835                 do {
11836                         printf(" %-10p", lrd->def);
11837                         lrd = lrd->next;
11838                 } while(lrd != lr->defs);
11839                 printf("\n");
11840         }
11841         if (live) {
11842                 struct triple_reg_set *entry;
11843                 printf("        live:");
11844                 for(entry = live; entry; entry = entry->next) {
11845                         printf(" %-10p", entry->member);
11846                 }
11847                 printf("\n");
11848         }
11849         if (lr->edges) {
11850                 struct live_range_edge *entry;
11851                 printf("       edges:");
11852                 for(entry = lr->edges; entry; entry = entry->next) {
11853                         struct live_range_def *lrd;
11854                         lrd = entry->node->defs;
11855                         do {
11856                                 printf(" %-10p", lrd->def);
11857                                 lrd = lrd->next;
11858                         } while(lrd != entry->node->defs);
11859                         printf("|");
11860                 }
11861                 printf("\n");
11862         }
11863         if (triple_is_branch(state, ins)) {
11864                 printf("\n");
11865         }
11866         return;
11867 }
11868
11869 static int coalesce_live_ranges(
11870         struct compile_state *state, struct reg_state *rstate)
11871 {
11872         /* At the point where a value is moved from one
11873          * register to another that value requires two
11874          * registers, thus increasing register pressure.
11875          * Live range coaleescing reduces the register
11876          * pressure by keeping a value in one register
11877          * longer.
11878          *
11879          * In the case of a phi function all paths leading
11880          * into it must be allocated to the same register
11881          * otherwise the phi function may not be removed.
11882          *
11883          * Forcing a value to stay in a single register
11884          * for an extended period of time does have
11885          * limitations when applied to non homogenous
11886          * register pool.  
11887          *
11888          * The two cases I have identified are:
11889          * 1) Two forced register assignments may
11890          *    collide.
11891          * 2) Registers may go unused because they
11892          *    are only good for storing the value
11893          *    and not manipulating it.
11894          *
11895          * Because of this I need to split live ranges,
11896          * even outside of the context of coalesced live
11897          * ranges.  The need to split live ranges does
11898          * impose some constraints on live range coalescing.
11899          *
11900          * - Live ranges may not be coalesced across phi
11901          *   functions.  This creates a 2 headed live
11902          *   range that cannot be sanely split.
11903          *
11904          * - phi functions (coalesced in initialize_live_ranges) 
11905          *   are handled as pre split live ranges so we will
11906          *   never attempt to split them.
11907          */
11908         int coalesced;
11909         int i;
11910
11911         coalesced = 0;
11912         for(i = 0; i <= rstate->ranges; i++) {
11913                 struct live_range *lr1;
11914                 struct live_range_def *lrd1;
11915                 lr1 = &rstate->lr[i];
11916                 if (!lr1->defs) {
11917                         continue;
11918                 }
11919                 lrd1 = live_range_end(state, lr1, 0);
11920                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11921                         struct triple_set *set;
11922                         if (lrd1->def->op != OP_COPY) {
11923                                 continue;
11924                         }
11925                         /* Skip copies that are the result of a live range split. */
11926                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11927                                 continue;
11928                         }
11929                         for(set = lrd1->def->use; set; set = set->next) {
11930                                 struct live_range_def *lrd2;
11931                                 struct live_range *lr2, *res;
11932
11933                                 lrd2 = &rstate->lrd[set->member->id];
11934
11935                                 /* Don't coalesce with instructions
11936                                  * that are the result of a live range
11937                                  * split.
11938                                  */
11939                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11940                                         continue;
11941                                 }
11942                                 lr2 = rstate->lrd[set->member->id].lr;
11943                                 if (lr1 == lr2) {
11944                                         continue;
11945                                 }
11946                                 if ((lr1->color != lr2->color) &&
11947                                         (lr1->color != REG_UNSET) &&
11948                                         (lr2->color != REG_UNSET)) {
11949                                         continue;
11950                                 }
11951                                 if ((lr1->classes & lr2->classes) == 0) {
11952                                         continue;
11953                                 }
11954                                 
11955                                 if (interfere(rstate, lr1, lr2)) {
11956                                         continue;
11957                                 }
11958                                 
11959                                 res = coalesce_ranges(state, rstate, lr1, lr2);
11960                                 coalesced += 1;
11961                                 if (res != lr1) {
11962                                         goto next;
11963                                 }
11964                         }
11965                 }
11966         next:
11967                 ;
11968         }
11969         return coalesced;
11970 }
11971
11972
11973 static void fix_coalesce_conflicts(struct compile_state *state,
11974         struct reg_block *blocks, struct triple_reg_set *live,
11975         struct reg_block *rb, struct triple *ins, void *arg)
11976 {
11977         int zlhs, zrhs, i, j;
11978
11979         /* See if we have a mandatory coalesce operation between
11980          * a lhs and a rhs value.  If so and the rhs value is also
11981          * alive then this triple needs to be pre copied.  Otherwise
11982          * we would have two definitions in the same live range simultaneously
11983          * alive.
11984          */
11985         zlhs = TRIPLE_LHS(ins->sizes);
11986         if ((zlhs == 0) && triple_is_def(state, ins)) {
11987                 zlhs = 1;
11988         }
11989         zrhs = TRIPLE_RHS(ins->sizes);
11990         for(i = 0; i < zlhs; i++) {
11991                 struct reg_info linfo;
11992                 linfo = arch_reg_lhs(state, ins, i);
11993                 if (linfo.reg < MAX_REGISTERS) {
11994                         continue;
11995                 }
11996                 for(j = 0; j < zrhs; j++) {
11997                         struct reg_info rinfo;
11998                         struct triple *rhs;
11999                         struct triple_reg_set *set;
12000                         int found;
12001                         found = 0;
12002                         rinfo = arch_reg_rhs(state, ins, j);
12003                         if (rinfo.reg != linfo.reg) {
12004                                 continue;
12005                         }
12006                         rhs = RHS(ins, j);
12007                         for(set = live; set && !found; set = set->next) {
12008                                 if (set->member == rhs) {
12009                                         found = 1;
12010                                 }
12011                         }
12012                         if (found) {
12013                                 struct triple *copy;
12014                                 copy = pre_copy(state, ins, j);
12015                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12016                         }
12017                 }
12018         }
12019         return;
12020 }
12021
12022 static void replace_set_use(struct compile_state *state,
12023         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12024 {
12025         struct triple_reg_set *set;
12026         for(set = head; set; set = set->next) {
12027                 if (set->member == orig) {
12028                         set->member = new;
12029                 }
12030         }
12031 }
12032
12033 static void replace_block_use(struct compile_state *state, 
12034         struct reg_block *blocks, struct triple *orig, struct triple *new)
12035 {
12036         int i;
12037 #warning "WISHLIST visit just those blocks that need it *"
12038         for(i = 1; i <= state->last_vertex; i++) {
12039                 struct reg_block *rb;
12040                 rb = &blocks[i];
12041                 replace_set_use(state, rb->in, orig, new);
12042                 replace_set_use(state, rb->out, orig, new);
12043         }
12044 }
12045
12046 static void color_instructions(struct compile_state *state)
12047 {
12048         struct triple *ins, *first;
12049         first = RHS(state->main_function, 0);
12050         ins = first;
12051         do {
12052                 if (triple_is_def(state, ins)) {
12053                         struct reg_info info;
12054                         info = find_lhs_color(state, ins, 0);
12055                         if (info.reg >= MAX_REGISTERS) {
12056                                 info.reg = REG_UNSET;
12057                         }
12058                         SET_INFO(ins->id, info);
12059                 }
12060                 ins = ins->next;
12061         } while(ins != first);
12062 }
12063
12064 static struct reg_info read_lhs_color(
12065         struct compile_state *state, struct triple *ins, int index)
12066 {
12067         struct reg_info info;
12068         if ((index == 0) && triple_is_def(state, ins)) {
12069                 info.reg   = ID_REG(ins->id);
12070                 info.regcm = ID_REGCM(ins->id);
12071         }
12072         else if (index < TRIPLE_LHS(ins->sizes)) {
12073                 info = read_lhs_color(state, LHS(ins, index), 0);
12074         }
12075         else {
12076                 internal_error(state, ins, "Bad lhs %d", index);
12077                 info.reg = REG_UNSET;
12078                 info.regcm = 0;
12079         }
12080         return info;
12081 }
12082
12083 static struct triple *resolve_tangle(
12084         struct compile_state *state, struct triple *tangle)
12085 {
12086         struct reg_info info, uinfo;
12087         struct triple_set *set, *next;
12088         struct triple *copy;
12089
12090 #warning "WISHLIST recalculate all affected instructions colors"
12091         info = find_lhs_color(state, tangle, 0);
12092         for(set = tangle->use; set; set = next) {
12093                 struct triple *user;
12094                 int i, zrhs;
12095                 next = set->next;
12096                 user = set->member;
12097                 zrhs = TRIPLE_RHS(user->sizes);
12098                 for(i = 0; i < zrhs; i++) {
12099                         if (RHS(user, i) != tangle) {
12100                                 continue;
12101                         }
12102                         uinfo = find_rhs_post_color(state, user, i);
12103                         if (uinfo.reg == info.reg) {
12104                                 copy = pre_copy(state, user, i);
12105                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12106                                 SET_INFO(copy->id, uinfo);
12107                         }
12108                 }
12109         }
12110         copy = 0;
12111         uinfo = find_lhs_pre_color(state, tangle, 0);
12112         if (uinfo.reg == info.reg) {
12113                 struct reg_info linfo;
12114                 copy = post_copy(state, tangle);
12115                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12116                 linfo = find_lhs_color(state, copy, 0);
12117                 SET_INFO(copy->id, linfo);
12118         }
12119         info = find_lhs_color(state, tangle, 0);
12120         SET_INFO(tangle->id, info);
12121         
12122         return copy;
12123 }
12124
12125
12126 static void fix_tangles(struct compile_state *state,
12127         struct reg_block *blocks, struct triple_reg_set *live,
12128         struct reg_block *rb, struct triple *ins, void *arg)
12129 {
12130         struct triple *tangle;
12131         do {
12132                 char used[MAX_REGISTERS];
12133                 struct triple_reg_set *set;
12134                 tangle = 0;
12135
12136                 /* Find out which registers have multiple uses at this point */
12137                 memset(used, 0, sizeof(used));
12138                 for(set = live; set; set = set->next) {
12139                         struct reg_info info;
12140                         info = read_lhs_color(state, set->member, 0);
12141                         if (info.reg == REG_UNSET) {
12142                                 continue;
12143                         }
12144                         reg_inc_used(state, used, info.reg);
12145                 }
12146                 
12147                 /* Now find the least dominated definition of a register in
12148                  * conflict I have seen so far.
12149                  */
12150                 for(set = live; set; set = set->next) {
12151                         struct reg_info info;
12152                         info = read_lhs_color(state, set->member, 0);
12153                         if (used[info.reg] < 2) {
12154                                 continue;
12155                         }
12156                         if (!tangle || tdominates(state, set->member, tangle)) {
12157                                 tangle = set->member;
12158                         }
12159                 }
12160                 /* If I have found a tangle resolve it */
12161                 if (tangle) {
12162                         struct triple *post_copy;
12163                         post_copy = resolve_tangle(state, tangle);
12164                         if (post_copy) {
12165                                 replace_block_use(state, blocks, tangle, post_copy);
12166                         }
12167                         if (post_copy && (tangle != ins)) {
12168                                 replace_set_use(state, live, tangle, post_copy);
12169                         }
12170                 }
12171         } while(tangle);
12172         return;
12173 }
12174
12175 static void correct_tangles(
12176         struct compile_state *state, struct reg_block *blocks)
12177 {
12178         color_instructions(state);
12179         walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12180 }
12181
12182 struct least_conflict {
12183         struct reg_state *rstate;
12184         struct live_range *ref_range;
12185         struct triple *ins;
12186         struct triple_reg_set *live;
12187         size_t count;
12188 };
12189 static void least_conflict(struct compile_state *state,
12190         struct reg_block *blocks, struct triple_reg_set *live,
12191         struct reg_block *rb, struct triple *ins, void *arg)
12192 {
12193         struct least_conflict *conflict = arg;
12194         struct live_range_edge *edge;
12195         struct triple_reg_set *set;
12196         size_t count;
12197
12198 #warning "FIXME handle instructions with left hand sides..."
12199         /* Only instructions that introduce a new definition
12200          * can be the conflict instruction.
12201          */
12202         if (!triple_is_def(state, ins)) {
12203                 return;
12204         }
12205
12206         /* See if live ranges at this instruction are a
12207          * strict subset of the live ranges that are in conflict.
12208          */
12209         count = 0;
12210         for(set = live; set; set = set->next) {
12211                 struct live_range *lr;
12212                 lr = conflict->rstate->lrd[set->member->id].lr;
12213                 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12214                         if (edge->node == lr) {
12215                                 break;
12216                         }
12217                 }
12218                 if (!edge && (lr != conflict->ref_range)) {
12219                         return;
12220                 }
12221                 count++;
12222         }
12223         if (count <= 1) {
12224                 return;
12225         }
12226
12227         /* See if there is an uncolored member in this subset. 
12228          */
12229          for(set = live; set; set = set->next) {
12230                 struct live_range *lr;
12231                 lr = conflict->rstate->lrd[set->member->id].lr;
12232                 if (lr->color == REG_UNSET) {
12233                         break;
12234                 }
12235         }
12236         if (!set && (conflict->ref_range != REG_UNSET)) {
12237                 return;
12238         }
12239
12240
12241         /* Find the instruction with the largest possible subset of
12242          * conflict ranges and that dominates any other instruction
12243          * with an equal sized set of conflicting ranges.
12244          */
12245         if ((count > conflict->count) ||
12246                 ((count == conflict->count) &&
12247                         tdominates(state, ins, conflict->ins))) {
12248                 struct triple_reg_set *next;
12249                 /* Remember the canidate instruction */
12250                 conflict->ins = ins;
12251                 conflict->count = count;
12252                 /* Free the old collection of live registers */
12253                 for(set = conflict->live; set; set = next) {
12254                         next = set->next;
12255                         do_triple_unset(&conflict->live, set->member);
12256                 }
12257                 conflict->live = 0;
12258                 /* Rember the registers that are alive but do not feed
12259                  * into or out of conflict->ins.
12260                  */
12261                 for(set = live; set; set = set->next) {
12262                         struct triple **expr;
12263                         if (set->member == ins) {
12264                                 goto next;
12265                         }
12266                         expr = triple_rhs(state, ins, 0);
12267                         for(;expr; expr = triple_rhs(state, ins, expr)) {
12268                                 if (*expr == set->member) {
12269                                         goto next;
12270                                 }
12271                         }
12272                         expr = triple_lhs(state, ins, 0);
12273                         for(; expr; expr = triple_lhs(state, ins, expr)) {
12274                                 if (*expr == set->member) {
12275                                         goto next;
12276                                 }
12277                         }
12278                         do_triple_set(&conflict->live, set->member, set->new);
12279                 next:
12280                         ;
12281                 }
12282         }
12283         return;
12284 }
12285
12286 static void find_range_conflict(struct compile_state *state,
12287         struct reg_state *rstate, char *used, struct live_range *ref_range,
12288         struct least_conflict *conflict)
12289 {
12290         /* there are 3 kinds ways conflicts can occure.
12291          * 1) the life time of 2 values simply overlap.
12292          * 2) the 2 values feed into the same instruction.
12293          * 3) the 2 values feed into a phi function.
12294          */
12295
12296         /* find the instruction where the problematic conflict comes
12297          * into existance.  that the instruction where all of
12298          * the values are alive, and among such instructions it is
12299          * the least dominated one.
12300          *
12301          * a value is alive an an instruction if either;
12302          * 1) the value defintion dominates the instruction and there
12303          *    is a use at or after that instrction
12304          * 2) the value definition feeds into a phi function in the
12305          *    same block as the instruction.  and the phi function
12306          *    is at or after the instruction.
12307          */
12308         memset(conflict, 0, sizeof(*conflict));
12309         conflict->rstate    = rstate;
12310         conflict->ref_range = ref_range;
12311         conflict->ins       = 0;
12312         conflict->count     = 0;
12313         conflict->live      = 0;
12314         walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12315
12316         if (!conflict->ins) {
12317                 internal_error(state, 0, "No conflict ins?");
12318         }
12319         if (!conflict->live) {
12320                 internal_error(state, 0, "No conflict live?");
12321         }
12322         return;
12323 }
12324
12325 static struct triple *split_constrained_range(struct compile_state *state, 
12326         struct reg_state *rstate, char *used, struct least_conflict *conflict)
12327 {
12328         unsigned constrained_size;
12329         struct triple *new, *constrained;
12330         struct triple_reg_set *cset;
12331         /* Find a range that is having problems because it is
12332          * artificially constrained.
12333          */
12334         constrained_size = ~0;
12335         constrained = 0;
12336         new = 0;
12337         for(cset = conflict->live; cset; cset = cset->next) {
12338                 struct triple_set *set;
12339                 struct reg_info info;
12340                 unsigned classes;
12341                 unsigned cur_size, size;
12342                 /* Skip the live range that starts with conflict->ins */
12343                 if (cset->member == conflict->ins) {
12344                         continue;
12345                 }
12346                 /* Find how many registers this value can potentially
12347                  * be assigned to.
12348                  */
12349                 classes = arch_type_to_regcm(state, cset->member->type);
12350                 size = regc_max_size(state, classes);
12351
12352                 /* Find how many registers we allow this value to
12353                  * be assigned to.
12354                  */
12355                 info = arch_reg_lhs(state, cset->member, 0);
12356 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12357                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12358                         cur_size = regc_max_size(state, info.regcm);
12359                 } else {
12360                         cur_size = 1;
12361                 }
12362                 /* If this live_range feeds into conflict->ins
12363                  * splitting it is unlikely to help.
12364                  */
12365                 for(set = cset->member->use; set; set = set->next) {
12366                         if (set->member == conflict->ins) {
12367                                 goto next;
12368                         }
12369                 }
12370
12371                 /* If there is no difference between potential and
12372                  * actual register count there is nothing to do.
12373                  */
12374                 if (cur_size >= size) {
12375                         continue;
12376                 }
12377                 /* Of the constrained registers deal with the
12378                  * most constrained one first.
12379                  */
12380                 if (!constrained ||
12381                         (size < constrained_size)) {
12382                         constrained = cset->member;
12383                         constrained_size = size;
12384                 }
12385         next:
12386                 ;
12387         }
12388         if (constrained) {
12389                 new = post_copy(state, constrained);
12390                 new->id |= TRIPLE_FLAG_POST_SPLIT;
12391         }
12392         return new;
12393 }
12394
12395 static int split_ranges(
12396         struct compile_state *state, struct reg_state *rstate, 
12397         char *used, struct live_range *range)
12398 {
12399         struct triple *new;
12400
12401         if ((range->color == REG_UNNEEDED) ||
12402                 (rstate->passes >= rstate->max_passes)) {
12403                 return 0;
12404         }
12405         new = 0;
12406         /* If I can't allocate a register something needs to be split */
12407         if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12408                 struct least_conflict conflict;
12409
12410                 /* Find where in the set of registers the conflict
12411                  * actually occurs.
12412                  */
12413                 find_range_conflict(state, rstate, used, range, &conflict);
12414
12415                 /* If a range has been artifically constrained split it */
12416                 new = split_constrained_range(state, rstate, used, &conflict);
12417                 
12418                 if (!new) {
12419                 /* Ideally I would split the live range that will not be used
12420                  * for the longest period of time in hopes that this will 
12421                  * (a) allow me to spill a register or
12422                  * (b) allow me to place a value in another register.
12423                  *
12424                  * So far I don't have a test case for this, the resolving
12425                  * of mandatory constraints has solved all of my
12426                  * know issues.  So I have choosen not to write any
12427                  * code until I cat get a better feel for cases where
12428                  * it would be useful to have.
12429                  *
12430                  */
12431 #warning "WISHLIST implement live range splitting..."
12432                         return 0;
12433                 }
12434         }
12435         if (new) {
12436                 rstate->lrd[rstate->defs].orig_id = new->id;
12437                 new->id = rstate->defs;
12438                 rstate->defs++;
12439 #if 0
12440                 fprintf(stderr, "new: %p\n", new);
12441 #endif
12442                 return 1;
12443         }
12444         return 0;
12445 }
12446
12447 #if DEBUG_COLOR_GRAPH > 1
12448 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12449 #define cgdebug_flush() fflush(stdout)
12450 #elif DEBUG_COLOR_GRAPH == 1
12451 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12452 #define cgdebug_flush() fflush(stderr)
12453 #else
12454 #define cgdebug_printf(...)
12455 #define cgdebug_flush()
12456 #endif
12457
12458         
12459 static int select_free_color(struct compile_state *state, 
12460         struct reg_state *rstate, struct live_range *range)
12461 {
12462         struct triple_set *entry;
12463         struct live_range_def *lrd;
12464         struct live_range_def *phi;
12465         struct live_range_edge *edge;
12466         char used[MAX_REGISTERS];
12467         struct triple **expr;
12468
12469         /* Instead of doing just the trivial color select here I try
12470          * a few extra things because a good color selection will help reduce
12471          * copies.
12472          */
12473
12474         /* Find the registers currently in use */
12475         memset(used, 0, sizeof(used));
12476         for(edge = range->edges; edge; edge = edge->next) {
12477                 if (edge->node->color == REG_UNSET) {
12478                         continue;
12479                 }
12480                 reg_fill_used(state, used, edge->node->color);
12481         }
12482 #if DEBUG_COLOR_GRAPH > 1
12483         {
12484                 int i;
12485                 i = 0;
12486                 for(edge = range->edges; edge; edge = edge->next) {
12487                         i++;
12488                 }
12489                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
12490                         tops(range->def->op), i, 
12491                         range->def->filename, range->def->line, range->def->col);
12492                 for(i = 0; i < MAX_REGISTERS; i++) {
12493                         if (used[i]) {
12494                                 cgdebug_printf("used: %s\n",
12495                                         arch_reg_str(i));
12496                         }
12497                 }
12498         }       
12499 #endif
12500
12501 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12502
12503         /* If a color is already assigned see if it will work */
12504         if (range->color != REG_UNSET) {
12505                 struct live_range_def *lrd;
12506                 if (!used[range->color]) {
12507                         return 1;
12508                 }
12509                 for(edge = range->edges; edge; edge = edge->next) {
12510                         if (edge->node->color != range->color) {
12511                                 continue;
12512                         }
12513                         warning(state, edge->node->defs->def, "edge: ");
12514                         lrd = edge->node->defs;
12515                         do {
12516                                 warning(state, lrd->def, " %p %s",
12517                                         lrd->def, tops(lrd->def->op));
12518                                 lrd = lrd->next;
12519                         } while(lrd != edge->node->defs);
12520                 }
12521                 lrd = range->defs;
12522                 warning(state, range->defs->def, "def: ");
12523                 do {
12524                         warning(state, lrd->def, " %p %s",
12525                                 lrd->def, tops(lrd->def->op));
12526                         lrd = lrd->next;
12527                 } while(lrd != range->defs);
12528                 internal_error(state, range->defs->def,
12529                         "live range with already used color %s",
12530                         arch_reg_str(range->color));
12531         }
12532
12533         /* If I feed into an expression reuse it's color.
12534          * This should help remove copies in the case of 2 register instructions
12535          * and phi functions.
12536          */
12537         phi = 0;
12538         lrd = live_range_end(state, range, 0);
12539         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12540                 entry = lrd->def->use;
12541                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12542                         struct live_range_def *insd;
12543                         insd = &rstate->lrd[entry->member->id];
12544                         if (insd->lr->defs == 0) {
12545                                 continue;
12546                         }
12547                         if (!phi && (insd->def->op == OP_PHI) &&
12548                                 !interfere(rstate, range, insd->lr)) {
12549                                 phi = insd;
12550                         }
12551                         if ((insd->lr->color == REG_UNSET) ||
12552                                 ((insd->lr->classes & range->classes) == 0) ||
12553                                 (used[insd->lr->color])) {
12554                                 continue;
12555                         }
12556                         if (interfere(rstate, range, insd->lr)) {
12557                                 continue;
12558                         }
12559                         range->color = insd->lr->color;
12560                 }
12561         }
12562         /* If I feed into a phi function reuse it's color or the color
12563          * of something else that feeds into the phi function.
12564          */
12565         if (phi) {
12566                 if (phi->lr->color != REG_UNSET) {
12567                         if (used[phi->lr->color]) {
12568                                 range->color = phi->lr->color;
12569                         }
12570                 }
12571                 else {
12572                         expr = triple_rhs(state, phi->def, 0);
12573                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12574                                 struct live_range *lr;
12575                                 if (!*expr) {
12576                                         continue;
12577                                 }
12578                                 lr = rstate->lrd[(*expr)->id].lr;
12579                                 if ((lr->color == REG_UNSET) || 
12580                                         ((lr->classes & range->classes) == 0) ||
12581                                         (used[lr->color])) {
12582                                         continue;
12583                                 }
12584                                 if (interfere(rstate, range, lr)) {
12585                                         continue;
12586                                 }
12587                                 range->color = lr->color;
12588                         }
12589                 }
12590         }
12591         /* If I don't interfere with a rhs node reuse it's color */
12592         lrd = live_range_head(state, range, 0);
12593         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12594                 expr = triple_rhs(state, lrd->def, 0);
12595                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12596                         struct live_range *lr;
12597                         if (!*expr) {
12598                                 continue;
12599                         }
12600                         lr = rstate->lrd[(*expr)->id].lr;
12601                         if ((lr->color == -1) || 
12602                                 ((lr->classes & range->classes) == 0) ||
12603                                 (used[lr->color])) {
12604                                 continue;
12605                         }
12606                         if (interfere(rstate, range, lr)) {
12607                                 continue;
12608                         }
12609                         range->color = lr->color;
12610                         break;
12611                 }
12612         }
12613         /* If I have not opportunitically picked a useful color
12614          * pick the first color that is free.
12615          */
12616         if (range->color == REG_UNSET) {
12617                 range->color = 
12618                         arch_select_free_register(state, used, range->classes);
12619         }
12620         if (range->color == REG_UNSET) {
12621                 int i;
12622                 if (split_ranges(state, rstate, used, range)) {
12623                         return 0;
12624                 }
12625                 for(edge = range->edges; edge; edge = edge->next) {
12626                         if (edge->node->color == REG_UNSET) {
12627                                 continue;
12628                         }
12629                         warning(state, edge->node->defs->def, "reg %s", 
12630                                 arch_reg_str(edge->node->color));
12631                 }
12632                 warning(state, range->defs->def, "classes: %x",
12633                         range->classes);
12634                 for(i = 0; i < MAX_REGISTERS; i++) {
12635                         if (used[i]) {
12636                                 warning(state, range->defs->def, "used: %s",
12637                                         arch_reg_str(i));
12638                         }
12639                 }
12640 #if DEBUG_COLOR_GRAPH < 2
12641                 error(state, range->defs->def, "too few registers");
12642 #else
12643                 internal_error(state, range->defs->def, "too few registers");
12644 #endif
12645         }
12646         range->classes = arch_reg_regcm(state, range->color);
12647         if (range->color == -1) {
12648                 internal_error(state, range->defs->def, "select_free_color did not?");
12649         }
12650         return 1;
12651 }
12652
12653 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12654 {
12655         int colored;
12656         struct live_range_edge *edge;
12657         struct live_range *range;
12658         if (rstate->low) {
12659                 cgdebug_printf("Lo: ");
12660                 range = rstate->low;
12661                 if (*range->group_prev != range) {
12662                         internal_error(state, 0, "lo: *prev != range?");
12663                 }
12664                 *range->group_prev = range->group_next;
12665                 if (range->group_next) {
12666                         range->group_next->group_prev = range->group_prev;
12667                 }
12668                 if (&range->group_next == rstate->low_tail) {
12669                         rstate->low_tail = range->group_prev;
12670                 }
12671                 if (rstate->low == range) {
12672                         internal_error(state, 0, "low: next != prev?");
12673                 }
12674         }
12675         else if (rstate->high) {
12676                 cgdebug_printf("Hi: ");
12677                 range = rstate->high;
12678                 if (*range->group_prev != range) {
12679                         internal_error(state, 0, "hi: *prev != range?");
12680                 }
12681                 *range->group_prev = range->group_next;
12682                 if (range->group_next) {
12683                         range->group_next->group_prev = range->group_prev;
12684                 }
12685                 if (&range->group_next == rstate->high_tail) {
12686                         rstate->high_tail = range->group_prev;
12687                 }
12688                 if (rstate->high == range) {
12689                         internal_error(state, 0, "high: next != prev?");
12690                 }
12691         }
12692         else {
12693                 return 1;
12694         }
12695         cgdebug_printf(" %d\n", range - rstate->lr);
12696         range->group_prev = 0;
12697         for(edge = range->edges; edge; edge = edge->next) {
12698                 struct live_range *node;
12699                 node = edge->node;
12700                 /* Move nodes from the high to the low list */
12701                 if (node->group_prev && (node->color == REG_UNSET) &&
12702                         (node->degree == regc_max_size(state, node->classes))) {
12703                         if (*node->group_prev != node) {
12704                                 internal_error(state, 0, "move: *prev != node?");
12705                         }
12706                         *node->group_prev = node->group_next;
12707                         if (node->group_next) {
12708                                 node->group_next->group_prev = node->group_prev;
12709                         }
12710                         if (&node->group_next == rstate->high_tail) {
12711                                 rstate->high_tail = node->group_prev;
12712                         }
12713                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12714                         node->group_prev  = rstate->low_tail;
12715                         node->group_next  = 0;
12716                         *rstate->low_tail = node;
12717                         rstate->low_tail  = &node->group_next;
12718                         if (*node->group_prev != node) {
12719                                 internal_error(state, 0, "move2: *prev != node?");
12720                         }
12721                 }
12722                 node->degree -= 1;
12723         }
12724         colored = color_graph(state, rstate);
12725         if (colored) {
12726                 cgdebug_printf("Coloring %d @%s:%d.%d:", 
12727                         range - rstate->lr,
12728                         range->def->filename, range->def->line, range->def->col);
12729                 cgdebug_flush();
12730                 colored = select_free_color(state, rstate, range);
12731                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12732         }
12733         return colored;
12734 }
12735
12736 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12737 {
12738         struct live_range *lr;
12739         struct live_range_edge *edge;
12740         struct triple *ins, *first;
12741         char used[MAX_REGISTERS];
12742         first = RHS(state->main_function, 0);
12743         ins = first;
12744         do {
12745                 if (triple_is_def(state, ins)) {
12746                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12747                                 internal_error(state, ins, 
12748                                         "triple without a live range def");
12749                         }
12750                         lr = rstate->lrd[ins->id].lr;
12751                         if (lr->color == REG_UNSET) {
12752                                 internal_error(state, ins,
12753                                         "triple without a color");
12754                         }
12755                         /* Find the registers used by the edges */
12756                         memset(used, 0, sizeof(used));
12757                         for(edge = lr->edges; edge; edge = edge->next) {
12758                                 if (edge->node->color == REG_UNSET) {
12759                                         internal_error(state, 0,
12760                                                 "live range without a color");
12761                         }
12762                                 reg_fill_used(state, used, edge->node->color);
12763                         }
12764                         if (used[lr->color]) {
12765                                 internal_error(state, ins,
12766                                         "triple with already used color");
12767                         }
12768                 }
12769                 ins = ins->next;
12770         } while(ins != first);
12771 }
12772
12773 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12774 {
12775         struct live_range *lr;
12776         struct triple *first, *ins;
12777         first = RHS(state->main_function, 0);
12778         ins = first;
12779         do {
12780                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12781                         internal_error(state, ins, 
12782                                 "triple without a live range");
12783                 }
12784                 lr = rstate->lrd[ins->id].lr;
12785                 SET_REG(ins->id, lr->color);
12786                 ins = ins->next;
12787         } while (ins != first);
12788 }
12789
12790 static void print_interference_block(
12791         struct compile_state *state, struct block *block, void *arg)
12792
12793 {
12794         struct reg_state *rstate = arg;
12795         struct reg_block *rb;
12796         struct triple *ptr;
12797         int phi_present;
12798         int done;
12799         rb = &rstate->blocks[block->vertex];
12800
12801         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
12802                 block, 
12803                 block->vertex,
12804                 block->left, 
12805                 block->left && block->left->use?block->left->use->member : 0,
12806                 block->right, 
12807                 block->right && block->right->use?block->right->use->member : 0);
12808         if (rb->in) {
12809                 struct triple_reg_set *in_set;
12810                 printf("        in:");
12811                 for(in_set = rb->in; in_set; in_set = in_set->next) {
12812                         printf(" %-10p", in_set->member);
12813                 }
12814                 printf("\n");
12815         }
12816         phi_present = 0;
12817         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12818                 done = (ptr == block->last);
12819                 if (ptr->op == OP_PHI) {
12820                         phi_present = 1;
12821                         break;
12822                 }
12823         }
12824         if (phi_present) {
12825                 int edge;
12826                 for(edge = 0; edge < block->users; edge++) {
12827                         printf("     in(%d):", edge);
12828                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12829                                 struct triple **slot;
12830                                 done = (ptr == block->last);
12831                                 if (ptr->op != OP_PHI) {
12832                                         continue;
12833                                 }
12834                                 slot = &RHS(ptr, 0);
12835                                 printf(" %-10p", slot[edge]);
12836                         }
12837                         printf("\n");
12838                 }
12839         }
12840         if (block->first->op == OP_LABEL) {
12841                 printf("%p:\n", block->first);
12842         }
12843         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12844                 struct triple_set *user;
12845                 struct live_range *lr;
12846                 unsigned id;
12847                 int op;
12848                 op = ptr->op;
12849                 done = (ptr == block->last);
12850                 lr = rstate->lrd[ptr->id].lr;
12851                 
12852                 if (triple_stores_block(state, ptr)) {
12853                         if (ptr->u.block != block) {
12854                                 internal_error(state, ptr, 
12855                                         "Wrong block pointer: %p",
12856                                         ptr->u.block);
12857                         }
12858                 }
12859                 if (op == OP_ADECL) {
12860                         for(user = ptr->use; user; user = user->next) {
12861                                 if (!user->member->u.block) {
12862                                         internal_error(state, user->member, 
12863                                                 "Use %p not in a block?",
12864                                                 user->member);
12865                                 }
12866                                 
12867                         }
12868                 }
12869                 id = ptr->id;
12870                 SET_REG(ptr->id, lr->color);
12871                 display_triple(stdout, ptr);
12872                 ptr->id = id;
12873
12874                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12875                         internal_error(state, ptr, "lr has no defs!");
12876                 }
12877
12878                 if (lr->defs) {
12879                         struct live_range_def *lrd;
12880                         printf("       range:");
12881                         lrd = lr->defs;
12882                         do {
12883                                 printf(" %-10p", lrd->def);
12884                                 lrd = lrd->next;
12885                         } while(lrd != lr->defs);
12886                         printf("\n");
12887                 }
12888                 if (lr->edges > 0) {
12889                         struct live_range_edge *edge;
12890                         printf("       edges:");
12891                         for(edge = lr->edges; edge; edge = edge->next) {
12892                                 struct live_range_def *lrd;
12893                                 lrd = edge->node->defs;
12894                                 do {
12895                                         printf(" %-10p", lrd->def);
12896                                         lrd = lrd->next;
12897                                 } while(lrd != edge->node->defs);
12898                                 printf("|");
12899                         }
12900                         printf("\n");
12901                 }
12902                 /* Do a bunch of sanity checks */
12903                 valid_ins(state, ptr);
12904                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12905                         internal_error(state, ptr, "Invalid triple id: %d",
12906                                 ptr->id);
12907                 }
12908                 for(user = ptr->use; user; user = user->next) {
12909                         struct triple *use;
12910                         struct live_range *ulr;
12911                         use = user->member;
12912                         valid_ins(state, use);
12913                         if ((use->id < 0) || (use->id > rstate->defs)) {
12914                                 internal_error(state, use, "Invalid triple id: %d",
12915                                         use->id);
12916                         }
12917                         ulr = rstate->lrd[user->member->id].lr;
12918                         if (triple_stores_block(state, user->member) &&
12919                                 !user->member->u.block) {
12920                                 internal_error(state, user->member,
12921                                         "Use %p not in a block?",
12922                                         user->member);
12923                         }
12924                 }
12925         }
12926         if (rb->out) {
12927                 struct triple_reg_set *out_set;
12928                 printf("       out:");
12929                 for(out_set = rb->out; out_set; out_set = out_set->next) {
12930                         printf(" %-10p", out_set->member);
12931                 }
12932                 printf("\n");
12933         }
12934         printf("\n");
12935 }
12936
12937 static struct live_range *merge_sort_lr(
12938         struct live_range *first, struct live_range *last)
12939 {
12940         struct live_range *mid, *join, **join_tail, *pick;
12941         size_t size;
12942         size = (last - first) + 1;
12943         if (size >= 2) {
12944                 mid = first + size/2;
12945                 first = merge_sort_lr(first, mid -1);
12946                 mid   = merge_sort_lr(mid, last);
12947                 
12948                 join = 0;
12949                 join_tail = &join;
12950                 /* merge the two lists */
12951                 while(first && mid) {
12952                         if ((first->degree < mid->degree) ||
12953                                 ((first->degree == mid->degree) &&
12954                                         (first->length < mid->length))) {
12955                                 pick = first;
12956                                 first = first->group_next;
12957                                 if (first) {
12958                                         first->group_prev = 0;
12959                                 }
12960                         }
12961                         else {
12962                                 pick = mid;
12963                                 mid = mid->group_next;
12964                                 if (mid) {
12965                                         mid->group_prev = 0;
12966                                 }
12967                         }
12968                         pick->group_next = 0;
12969                         pick->group_prev = join_tail;
12970                         *join_tail = pick;
12971                         join_tail = &pick->group_next;
12972                 }
12973                 /* Splice the remaining list */
12974                 pick = (first)? first : mid;
12975                 *join_tail = pick;
12976                 if (pick) { 
12977                         pick->group_prev = join_tail;
12978                 }
12979         }
12980         else {
12981                 if (!first->defs) {
12982                         first = 0;
12983                 }
12984                 join = first;
12985         }
12986         return join;
12987 }
12988
12989 static void ids_from_rstate(struct compile_state *state, 
12990         struct reg_state *rstate)
12991 {
12992         struct triple *ins, *first;
12993         if (!rstate->defs) {
12994                 return;
12995         }
12996         /* Display the graph if desired */
12997         if (state->debug & DEBUG_INTERFERENCE) {
12998                 print_blocks(state, stdout);
12999                 print_control_flow(state);
13000         }
13001         first = RHS(state->main_function, 0);
13002         ins = first;
13003         do {
13004                 if (ins->id) {
13005                         struct live_range_def *lrd;
13006                         lrd = &rstate->lrd[ins->id];
13007                         ins->id = lrd->orig_id;
13008                 }
13009                 ins = ins->next;
13010         } while(ins != first);
13011 }
13012
13013 static void cleanup_live_edges(struct reg_state *rstate)
13014 {
13015         int i;
13016         /* Free the edges on each node */
13017         for(i = 1; i <= rstate->ranges; i++) {
13018                 remove_live_edges(rstate, &rstate->lr[i]);
13019         }
13020 }
13021
13022 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13023 {
13024         cleanup_live_edges(rstate);
13025         xfree(rstate->lrd);
13026         xfree(rstate->lr);
13027
13028         /* Free the variable lifetime information */
13029         if (rstate->blocks) {
13030                 free_variable_lifetimes(state, rstate->blocks);
13031         }
13032         rstate->defs = 0;
13033         rstate->ranges = 0;
13034         rstate->lrd = 0;
13035         rstate->lr = 0;
13036         rstate->blocks = 0;
13037 }
13038
13039 static void allocate_registers(struct compile_state *state)
13040 {
13041         struct reg_state rstate;
13042         int colored;
13043
13044         /* Clear out the reg_state */
13045         memset(&rstate, 0, sizeof(rstate));
13046         rstate.max_passes = MAX_ALLOCATION_PASSES;
13047
13048         do {
13049                 struct live_range **point, **next;
13050                 int coalesced;
13051
13052                 /* Restore ids */
13053                 ids_from_rstate(state, &rstate);
13054
13055                 /* Cleanup the temporary data structures */
13056                 cleanup_rstate(state, &rstate);
13057
13058                 /* Compute the variable lifetimes */
13059                 rstate.blocks = compute_variable_lifetimes(state);
13060
13061                 /* Fix invalid mandatory live range coalesce conflicts */
13062                 walk_variable_lifetimes(
13063                         state, rstate.blocks, fix_coalesce_conflicts, 0);
13064
13065                 /* Fix two simultaneous uses of the same register */
13066                 correct_tangles(state, rstate.blocks);
13067
13068                 if (state->debug & DEBUG_INSERTED_COPIES) {
13069                         printf("After resolve_tangles\n");
13070                         print_blocks(state, stdout);
13071                         print_control_flow(state);
13072                 }
13073
13074                 
13075                 /* Allocate and initialize the live ranges */
13076                 initialize_live_ranges(state, &rstate);
13077                 
13078                 do {
13079                         /* Forget previous live range edge calculations */
13080                         cleanup_live_edges(&rstate);
13081
13082                         /* Compute the interference graph */
13083                         walk_variable_lifetimes(
13084                                 state, rstate.blocks, graph_ins, &rstate);
13085                 
13086                         /* Display the interference graph if desired */
13087                         if (state->debug & DEBUG_INTERFERENCE) {
13088                                 printf("\nlive variables by block\n");
13089                                 walk_blocks(state, print_interference_block, &rstate);
13090                                 printf("\nlive variables by instruction\n");
13091                                 walk_variable_lifetimes(
13092                                         state, rstate.blocks, 
13093                                         print_interference_ins, &rstate);
13094                         }
13095                         
13096                         coalesced = coalesce_live_ranges(state, &rstate);
13097                 } while(coalesced);
13098                         
13099                 /* Build the groups low and high.  But with the nodes
13100                  * first sorted by degree order.
13101                  */
13102                 rstate.low_tail  = &rstate.low;
13103                 rstate.high_tail = &rstate.high;
13104                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13105                 if (rstate.high) {
13106                         rstate.high->group_prev = &rstate.high;
13107                 }
13108                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13109                         ;
13110                 rstate.high_tail = point;
13111                 /* Walk through the high list and move everything that needs
13112                  * to be onto low.
13113                  */
13114                 for(point = &rstate.high; *point; point = next) {
13115                         struct live_range *range;
13116                         next = &(*point)->group_next;
13117                         range = *point;
13118                         
13119                         /* If it has a low degree or it already has a color
13120                          * place the node in low.
13121                          */
13122                         if ((range->degree < regc_max_size(state, range->classes)) ||
13123                                 (range->color != REG_UNSET)) {
13124                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13125                                         range - rstate.lr, range->degree,
13126                                         (range->color != REG_UNSET) ? " (colored)": "");
13127                                 *range->group_prev = range->group_next;
13128                                 if (range->group_next) {
13129                                         range->group_next->group_prev = range->group_prev;
13130                                 }
13131                                 if (&range->group_next == rstate.high_tail) {
13132                                         rstate.high_tail = range->group_prev;
13133                                 }
13134                                 range->group_prev  = rstate.low_tail;
13135                                 range->group_next  = 0;
13136                                 *rstate.low_tail   = range;
13137                                 rstate.low_tail    = &range->group_next;
13138                                 next = point;
13139                         }
13140                         else {
13141                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13142                                         range - rstate.lr, range->degree,
13143                                         (range->color != REG_UNSET) ? " (colored)": "");
13144                         }
13145                 }
13146                 /* Color the live_ranges */
13147                 colored = color_graph(state, &rstate);
13148                 rstate.passes++;
13149         } while (!colored);
13150
13151         /* Verify the graph was properly colored */
13152         verify_colors(state, &rstate);
13153
13154         /* Move the colors from the graph to the triples */
13155         color_triples(state, &rstate);
13156
13157         /* Cleanup the temporary data structures */
13158         cleanup_rstate(state, &rstate);
13159 }
13160
13161 /* Sparce Conditional Constant Propogation
13162  * =========================================
13163  */
13164 struct ssa_edge;
13165 struct flow_block;
13166 struct lattice_node {
13167         unsigned old_id;
13168         struct triple *def;
13169         struct ssa_edge *out;
13170         struct flow_block *fblock;
13171         struct triple *val;
13172         /* lattice high   val && !is_const(val) 
13173          * lattice const  is_const(val)
13174          * lattice low    val == 0
13175          */
13176 };
13177 struct ssa_edge {
13178         struct lattice_node *src;
13179         struct lattice_node *dst;
13180         struct ssa_edge *work_next;
13181         struct ssa_edge *work_prev;
13182         struct ssa_edge *out_next;
13183 };
13184 struct flow_edge {
13185         struct flow_block *src;
13186         struct flow_block *dst;
13187         struct flow_edge *work_next;
13188         struct flow_edge *work_prev;
13189         struct flow_edge *in_next;
13190         struct flow_edge *out_next;
13191         int executable;
13192 };
13193 struct flow_block {
13194         struct block *block;
13195         struct flow_edge *in;
13196         struct flow_edge *out;
13197         struct flow_edge left, right;
13198 };
13199
13200 struct scc_state {
13201         int ins_count;
13202         struct lattice_node *lattice;
13203         struct ssa_edge     *ssa_edges;
13204         struct flow_block   *flow_blocks;
13205         struct flow_edge    *flow_work_list;
13206         struct ssa_edge     *ssa_work_list;
13207 };
13208
13209
13210 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13211         struct flow_edge *fedge)
13212 {
13213         if (!scc->flow_work_list) {
13214                 scc->flow_work_list = fedge;
13215                 fedge->work_next = fedge->work_prev = fedge;
13216         }
13217         else {
13218                 struct flow_edge *ftail;
13219                 ftail = scc->flow_work_list->work_prev;
13220                 fedge->work_next = ftail->work_next;
13221                 fedge->work_prev = ftail;
13222                 fedge->work_next->work_prev = fedge;
13223                 fedge->work_prev->work_next = fedge;
13224         }
13225 }
13226
13227 static struct flow_edge *scc_next_fedge(
13228         struct compile_state *state, struct scc_state *scc)
13229 {
13230         struct flow_edge *fedge;
13231         fedge = scc->flow_work_list;
13232         if (fedge) {
13233                 fedge->work_next->work_prev = fedge->work_prev;
13234                 fedge->work_prev->work_next = fedge->work_next;
13235                 if (fedge->work_next != fedge) {
13236                         scc->flow_work_list = fedge->work_next;
13237                 } else {
13238                         scc->flow_work_list = 0;
13239                 }
13240         }
13241         return fedge;
13242 }
13243
13244 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13245         struct ssa_edge *sedge)
13246 {
13247         if (!scc->ssa_work_list) {
13248                 scc->ssa_work_list = sedge;
13249                 sedge->work_next = sedge->work_prev = sedge;
13250         }
13251         else {
13252                 struct ssa_edge *stail;
13253                 stail = scc->ssa_work_list->work_prev;
13254                 sedge->work_next = stail->work_next;
13255                 sedge->work_prev = stail;
13256                 sedge->work_next->work_prev = sedge;
13257                 sedge->work_prev->work_next = sedge;
13258         }
13259 }
13260
13261 static struct ssa_edge *scc_next_sedge(
13262         struct compile_state *state, struct scc_state *scc)
13263 {
13264         struct ssa_edge *sedge;
13265         sedge = scc->ssa_work_list;
13266         if (sedge) {
13267                 sedge->work_next->work_prev = sedge->work_prev;
13268                 sedge->work_prev->work_next = sedge->work_next;
13269                 if (sedge->work_next != sedge) {
13270                         scc->ssa_work_list = sedge->work_next;
13271                 } else {
13272                         scc->ssa_work_list = 0;
13273                 }
13274         }
13275         return sedge;
13276 }
13277
13278 static void initialize_scc_state(
13279         struct compile_state *state, struct scc_state *scc)
13280 {
13281         int ins_count, ssa_edge_count;
13282         int ins_index, ssa_edge_index, fblock_index;
13283         struct triple *first, *ins;
13284         struct block *block;
13285         struct flow_block *fblock;
13286
13287         memset(scc, 0, sizeof(*scc));
13288
13289         /* Inialize pass zero find out how much memory we need */
13290         first = RHS(state->main_function, 0);
13291         ins = first;
13292         ins_count = ssa_edge_count = 0;
13293         do {
13294                 struct triple_set *edge;
13295                 ins_count += 1;
13296                 for(edge = ins->use; edge; edge = edge->next) {
13297                         ssa_edge_count++;
13298                 }
13299                 ins = ins->next;
13300         } while(ins != first);
13301 #if DEBUG_SCC
13302         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13303                 ins_count, ssa_edge_count, state->last_vertex);
13304 #endif
13305         scc->ins_count   = ins_count;
13306         scc->lattice     = 
13307                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13308         scc->ssa_edges   = 
13309                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13310         scc->flow_blocks = 
13311                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
13312                         "flow_blocks");
13313
13314         /* Initialize pass one collect up the nodes */
13315         fblock = 0;
13316         block = 0;
13317         ins_index = ssa_edge_index = fblock_index = 0;
13318         ins = first;
13319         do {
13320                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13321                         block = ins->u.block;
13322                         if (!block) {
13323                                 internal_error(state, ins, "label without block");
13324                         }
13325                         fblock_index += 1;
13326                         block->vertex = fblock_index;
13327                         fblock = &scc->flow_blocks[fblock_index];
13328                         fblock->block = block;
13329                 }
13330                 {
13331                         struct lattice_node *lnode;
13332                         ins_index += 1;
13333                         lnode = &scc->lattice[ins_index];
13334                         lnode->def = ins;
13335                         lnode->out = 0;
13336                         lnode->fblock = fblock;
13337                         lnode->val = ins; /* LATTICE HIGH */
13338                         lnode->old_id = ins->id;
13339                         ins->id = ins_index;
13340                 }
13341                 ins = ins->next;
13342         } while(ins != first);
13343         /* Initialize pass two collect up the edges */
13344         block = 0;
13345         fblock = 0;
13346         ins = first;
13347         do {
13348                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13349                         struct flow_edge *fedge, **ftail;
13350                         struct block_set *bedge;
13351                         block = ins->u.block;
13352                         fblock = &scc->flow_blocks[block->vertex];
13353                         fblock->in = 0;
13354                         fblock->out = 0;
13355                         ftail = &fblock->out;
13356                         if (block->left) {
13357                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13358                                 if (fblock->left.dst->block != block->left) {
13359                                         internal_error(state, 0, "block mismatch");
13360                                 }
13361                                 fblock->left.out_next = 0;
13362                                 *ftail = &fblock->left;
13363                                 ftail = &fblock->left.out_next;
13364                         }
13365                         if (block->right) {
13366                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13367                                 if (fblock->right.dst->block != block->right) {
13368                                         internal_error(state, 0, "block mismatch");
13369                                 }
13370                                 fblock->right.out_next = 0;
13371                                 *ftail = &fblock->right;
13372                                 ftail = &fblock->right.out_next;
13373                         }
13374                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13375                                 fedge->src = fblock;
13376                                 fedge->work_next = fedge->work_prev = fedge;
13377                                 fedge->executable = 0;
13378                         }
13379                         ftail = &fblock->in;
13380                         for(bedge = block->use; bedge; bedge = bedge->next) {
13381                                 struct block *src_block;
13382                                 struct flow_block *sfblock;
13383                                 struct flow_edge *sfedge;
13384                                 src_block = bedge->member;
13385                                 sfblock = &scc->flow_blocks[src_block->vertex];
13386                                 sfedge = 0;
13387                                 if (src_block->left == block) {
13388                                         sfedge = &sfblock->left;
13389                                 } else {
13390                                         sfedge = &sfblock->right;
13391                                 }
13392                                 *ftail = sfedge;
13393                                 ftail = &sfedge->in_next;
13394                                 sfedge->in_next = 0;
13395                         }
13396                 }
13397                 {
13398                         struct triple_set *edge;
13399                         struct ssa_edge **stail;
13400                         struct lattice_node *lnode;
13401                         lnode = &scc->lattice[ins->id];
13402                         lnode->out = 0;
13403                         stail = &lnode->out;
13404                         for(edge = ins->use; edge; edge = edge->next) {
13405                                 struct ssa_edge *sedge;
13406                                 ssa_edge_index += 1;
13407                                 sedge = &scc->ssa_edges[ssa_edge_index];
13408                                 *stail = sedge;
13409                                 stail = &sedge->out_next;
13410                                 sedge->src = lnode;
13411                                 sedge->dst = &scc->lattice[edge->member->id];
13412                                 sedge->work_next = sedge->work_prev = sedge;
13413                                 sedge->out_next = 0;
13414                         }
13415                 }
13416                 ins = ins->next;
13417         } while(ins != first);
13418         /* Setup a dummy block 0 as a node above the start node */
13419         {
13420                 struct flow_block *fblock, *dst;
13421                 struct flow_edge *fedge;
13422                 fblock = &scc->flow_blocks[0];
13423                 fblock->block = 0;
13424                 fblock->in = 0;
13425                 fblock->out = &fblock->left;
13426                 dst = &scc->flow_blocks[state->first_block->vertex];
13427                 fedge = &fblock->left;
13428                 fedge->src        = fblock;
13429                 fedge->dst        = dst;
13430                 fedge->work_next  = fedge;
13431                 fedge->work_prev  = fedge;
13432                 fedge->in_next    = fedge->dst->in;
13433                 fedge->out_next   = 0;
13434                 fedge->executable = 0;
13435                 fedge->dst->in = fedge;
13436                 
13437                 /* Initialize the work lists */
13438                 scc->flow_work_list = 0;
13439                 scc->ssa_work_list  = 0;
13440                 scc_add_fedge(state, scc, fedge);
13441         }
13442 #if DEBUG_SCC
13443         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13444                 ins_index, ssa_edge_index, fblock_index);
13445 #endif
13446 }
13447
13448         
13449 static void free_scc_state(
13450         struct compile_state *state, struct scc_state *scc)
13451 {
13452         xfree(scc->flow_blocks);
13453         xfree(scc->ssa_edges);
13454         xfree(scc->lattice);
13455         
13456 }
13457
13458 static struct lattice_node *triple_to_lattice(
13459         struct compile_state *state, struct scc_state *scc, struct triple *ins)
13460 {
13461         if (ins->id <= 0) {
13462                 internal_error(state, ins, "bad id");
13463         }
13464         return &scc->lattice[ins->id];
13465 }
13466
13467 static struct triple *preserve_lval(
13468         struct compile_state *state, struct lattice_node *lnode)
13469 {
13470         struct triple *old;
13471         /* Preserve the original value */
13472         if (lnode->val) {
13473                 old = dup_triple(state, lnode->val);
13474                 if (lnode->val != lnode->def) {
13475                         xfree(lnode->val);
13476                 }
13477                 lnode->val = 0;
13478         } else {
13479                 old = 0;
13480         }
13481         return old;
13482 }
13483
13484 static int lval_changed(struct compile_state *state, 
13485         struct triple *old, struct lattice_node *lnode)
13486 {
13487         int changed;
13488         /* See if the lattice value has changed */
13489         changed = 1;
13490         if (!old && !lnode->val) {
13491                 changed = 0;
13492         }
13493         if (changed && lnode->val && !is_const(lnode->val)) {
13494                 changed = 0;
13495         }
13496         if (changed &&
13497                 lnode->val && old &&
13498                 (memcmp(lnode->val->param, old->param,
13499                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13500                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13501                 changed = 0;
13502         }
13503         if (old) {
13504                 xfree(old);
13505         }
13506         return changed;
13507
13508 }
13509
13510 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
13511         struct lattice_node *lnode)
13512 {
13513         struct lattice_node *tmp;
13514         struct triple **slot, *old;
13515         struct flow_edge *fedge;
13516         int index;
13517         if (lnode->def->op != OP_PHI) {
13518                 internal_error(state, lnode->def, "not phi");
13519         }
13520         /* Store the original value */
13521         old = preserve_lval(state, lnode);
13522
13523         /* default to lattice high */
13524         lnode->val = lnode->def;
13525         slot = &RHS(lnode->def, 0);
13526         index = 0;
13527         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13528                 if (!fedge->executable) {
13529                         continue;
13530                 }
13531                 if (!slot[index]) {
13532                         internal_error(state, lnode->def, "no phi value");
13533                 }
13534                 tmp = triple_to_lattice(state, scc, slot[index]);
13535                 /* meet(X, lattice low) = lattice low */
13536                 if (!tmp->val) {
13537                         lnode->val = 0;
13538                 }
13539                 /* meet(X, lattice high) = X */
13540                 else if (!tmp->val) {
13541                         lnode->val = lnode->val;
13542                 }
13543                 /* meet(lattice high, X) = X */
13544                 else if (!is_const(lnode->val)) {
13545                         lnode->val = dup_triple(state, tmp->val);
13546                         lnode->val->type = lnode->def->type;
13547                 }
13548                 /* meet(const, const) = const or lattice low */
13549                 else if (!constants_equal(state, lnode->val, tmp->val)) {
13550                         lnode->val = 0;
13551                 }
13552                 if (!lnode->val) {
13553                         break;
13554                 }
13555         }
13556 #if DEBUG_SCC
13557         fprintf(stderr, "phi: %d -> %s\n",
13558                 lnode->def->id,
13559                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13560 #endif
13561         /* If the lattice value has changed update the work lists. */
13562         if (lval_changed(state, old, lnode)) {
13563                 struct ssa_edge *sedge;
13564                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13565                         scc_add_sedge(state, scc, sedge);
13566                 }
13567         }
13568 }
13569
13570 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13571         struct lattice_node *lnode)
13572 {
13573         int changed;
13574         struct triple *old, *scratch;
13575         struct triple **dexpr, **vexpr;
13576         int count, i;
13577         
13578         /* Store the original value */
13579         old = preserve_lval(state, lnode);
13580
13581         /* Reinitialize the value */
13582         lnode->val = scratch = dup_triple(state, lnode->def);
13583         scratch->id = lnode->old_id;
13584         scratch->next     = scratch;
13585         scratch->prev     = scratch;
13586         scratch->use      = 0;
13587
13588         count = TRIPLE_SIZE(scratch->sizes);
13589         for(i = 0; i < count; i++) {
13590                 dexpr = &lnode->def->param[i];
13591                 vexpr = &scratch->param[i];
13592                 *vexpr = *dexpr;
13593                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13594                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13595                         *dexpr) {
13596                         struct lattice_node *tmp;
13597                         tmp = triple_to_lattice(state, scc, *dexpr);
13598                         *vexpr = (tmp->val)? tmp->val : tmp->def;
13599                 }
13600         }
13601         if (scratch->op == OP_BRANCH) {
13602                 scratch->next = lnode->def->next;
13603         }
13604         /* Recompute the value */
13605 #warning "FIXME see if simplify does anything bad"
13606         /* So far it looks like only the strength reduction
13607          * optimization are things I need to worry about.
13608          */
13609         simplify(state, scratch);
13610         /* Cleanup my value */
13611         if (scratch->use) {
13612                 internal_error(state, lnode->def, "scratch used?");
13613         }
13614         if ((scratch->prev != scratch) ||
13615                 ((scratch->next != scratch) &&
13616                         ((lnode->def->op != OP_BRANCH) ||
13617                                 (scratch->next != lnode->def->next)))) {
13618                 internal_error(state, lnode->def, "scratch in list?");
13619         }
13620         /* undo any uses... */
13621         count = TRIPLE_SIZE(scratch->sizes);
13622         for(i = 0; i < count; i++) {
13623                 vexpr = &scratch->param[i];
13624                 if (*vexpr) {
13625                         unuse_triple(*vexpr, scratch);
13626                 }
13627         }
13628         if (!is_const(scratch)) {
13629                 for(i = 0; i < count; i++) {
13630                         dexpr = &lnode->def->param[i];
13631                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13632                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13633                                 *dexpr) {
13634                                 struct lattice_node *tmp;
13635                                 tmp = triple_to_lattice(state, scc, *dexpr);
13636                                 if (!tmp->val) {
13637                                         lnode->val = 0;
13638                                 }
13639                         }
13640                 }
13641         }
13642         if (lnode->val && 
13643                 (lnode->val->op == lnode->def->op) &&
13644                 (memcmp(lnode->val->param, lnode->def->param, 
13645                         count * sizeof(lnode->val->param[0])) == 0) &&
13646                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13647                 lnode->val = lnode->def;
13648         }
13649         /* Find the cases that are always lattice lo */
13650         if (lnode->val && 
13651                 triple_is_def(state, lnode->val) &&
13652                 !triple_is_pure(state, lnode->val)) {
13653                 lnode->val = 0;
13654         }
13655         if (lnode->val && 
13656                 (lnode->val->op == OP_SDECL) && 
13657                 (lnode->val != lnode->def)) {
13658                 internal_error(state, lnode->def, "bad sdecl");
13659         }
13660         /* See if the lattice value has changed */
13661         changed = lval_changed(state, old, lnode);
13662         if (lnode->val != scratch) {
13663                 xfree(scratch);
13664         }
13665         return changed;
13666 }
13667
13668 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13669         struct lattice_node *lnode)
13670 {
13671         struct lattice_node *cond;
13672 #if DEBUG_SCC
13673         {
13674                 struct flow_edge *fedge;
13675                 fprintf(stderr, "branch: %d (",
13676                         lnode->def->id);
13677                 
13678                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13679                         fprintf(stderr, " %d", fedge->dst->block->vertex);
13680                 }
13681                 fprintf(stderr, " )");
13682                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13683                         fprintf(stderr, " <- %d",
13684                                 RHS(lnode->def, 0)->id);
13685                 }
13686                 fprintf(stderr, "\n");
13687         }
13688 #endif
13689         if (lnode->def->op != OP_BRANCH) {
13690                 internal_error(state, lnode->def, "not branch");
13691         }
13692         /* This only applies to conditional branches */
13693         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13694                 return;
13695         }
13696         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13697         if (cond->val && !is_const(cond->val)) {
13698 #warning "FIXME do I need to do something here?"
13699                 warning(state, cond->def, "condition not constant?");
13700                 return;
13701         }
13702         if (cond->val == 0) {
13703                 scc_add_fedge(state, scc, cond->fblock->out);
13704                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13705         }
13706         else if (cond->val->u.cval) {
13707                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13708                 
13709         } else {
13710                 scc_add_fedge(state, scc, cond->fblock->out);
13711         }
13712
13713 }
13714
13715 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13716         struct lattice_node *lnode)
13717 {
13718         int changed;
13719
13720         changed = compute_lnode_val(state, scc, lnode);
13721 #if DEBUG_SCC
13722         {
13723                 struct triple **expr;
13724                 fprintf(stderr, "expr: %3d %10s (",
13725                         lnode->def->id, tops(lnode->def->op));
13726                 expr = triple_rhs(state, lnode->def, 0);
13727                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13728                         if (*expr) {
13729                                 fprintf(stderr, " %d", (*expr)->id);
13730                         }
13731                 }
13732                 fprintf(stderr, " ) -> %s\n",
13733                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13734         }
13735 #endif
13736         if (lnode->def->op == OP_BRANCH) {
13737                 scc_visit_branch(state, scc, lnode);
13738
13739         }
13740         else if (changed) {
13741                 struct ssa_edge *sedge;
13742                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13743                         scc_add_sedge(state, scc, sedge);
13744                 }
13745         }
13746 }
13747
13748 static void scc_writeback_values(
13749         struct compile_state *state, struct scc_state *scc)
13750 {
13751         struct triple *first, *ins;
13752         first = RHS(state->main_function, 0);
13753         ins = first;
13754         do {
13755                 struct lattice_node *lnode;
13756                 lnode = triple_to_lattice(state, scc, ins);
13757                 /* Restore id */
13758                 ins->id = lnode->old_id;
13759 #if DEBUG_SCC
13760                 if (lnode->val && !is_const(lnode->val)) {
13761                         warning(state, lnode->def, 
13762                                 "lattice node still high?");
13763                 }
13764 #endif
13765                 if (lnode->val && (lnode->val != ins)) {
13766                         /* See if it something I know how to write back */
13767                         switch(lnode->val->op) {
13768                         case OP_INTCONST:
13769                                 mkconst(state, ins, lnode->val->u.cval);
13770                                 break;
13771                         case OP_ADDRCONST:
13772                                 mkaddr_const(state, ins, 
13773                                         MISC(lnode->val, 0), lnode->val->u.cval);
13774                                 break;
13775                         default:
13776                                 /* By default don't copy the changes,
13777                                  * recompute them in place instead.
13778                                  */
13779                                 simplify(state, ins);
13780                                 break;
13781                         }
13782                         if (is_const(lnode->val) &&
13783                                 !constants_equal(state, lnode->val, ins)) {
13784                                 internal_error(state, 0, "constants not equal");
13785                         }
13786                         /* Free the lattice nodes */
13787                         xfree(lnode->val);
13788                         lnode->val = 0;
13789                 }
13790                 ins = ins->next;
13791         } while(ins != first);
13792 }
13793
13794 static void scc_transform(struct compile_state *state)
13795 {
13796         struct scc_state scc;
13797
13798         initialize_scc_state(state, &scc);
13799
13800         while(scc.flow_work_list || scc.ssa_work_list) {
13801                 struct flow_edge *fedge;
13802                 struct ssa_edge *sedge;
13803                 struct flow_edge *fptr;
13804                 while((fedge = scc_next_fedge(state, &scc))) {
13805                         struct block *block;
13806                         struct triple *ptr;
13807                         struct flow_block *fblock;
13808                         int time;
13809                         int done;
13810                         if (fedge->executable) {
13811                                 continue;
13812                         }
13813                         if (!fedge->dst) {
13814                                 internal_error(state, 0, "fedge without dst");
13815                         }
13816                         if (!fedge->src) {
13817                                 internal_error(state, 0, "fedge without src");
13818                         }
13819                         fedge->executable = 1;
13820                         fblock = fedge->dst;
13821                         block = fblock->block;
13822                         time = 0;
13823                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13824                                 if (fptr->executable) {
13825                                         time++;
13826                                 }
13827                         }
13828 #if DEBUG_SCC
13829                         fprintf(stderr, "vertex: %d time: %d\n", 
13830                                 block->vertex, time);
13831                         
13832 #endif
13833                         done = 0;
13834                         for(ptr = block->first; !done; ptr = ptr->next) {
13835                                 struct lattice_node *lnode;
13836                                 done = (ptr == block->last);
13837                                 lnode = &scc.lattice[ptr->id];
13838                                 if (ptr->op == OP_PHI) {
13839                                         scc_visit_phi(state, &scc, lnode);
13840                                 }
13841                                 else if (time == 1) {
13842                                         scc_visit_expr(state, &scc, lnode);
13843                                 }
13844                         }
13845                         if (fblock->out && !fblock->out->out_next) {
13846                                 scc_add_fedge(state, &scc, fblock->out);
13847                         }
13848                 }
13849                 while((sedge = scc_next_sedge(state, &scc))) {
13850                         struct lattice_node *lnode;
13851                         struct flow_block *fblock;
13852                         lnode = sedge->dst;
13853                         fblock = lnode->fblock;
13854 #if DEBUG_SCC
13855                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
13856                                 sedge - scc.ssa_edges,
13857                                 sedge->src->def->id,
13858                                 sedge->dst->def->id);
13859 #endif
13860                         if (lnode->def->op == OP_PHI) {
13861                                 scc_visit_phi(state, &scc, lnode);
13862                         }
13863                         else {
13864                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13865                                         if (fptr->executable) {
13866                                                 break;
13867                                         }
13868                                 }
13869                                 if (fptr) {
13870                                         scc_visit_expr(state, &scc, lnode);
13871                                 }
13872                         }
13873                 }
13874         }
13875         
13876         scc_writeback_values(state, &scc);
13877         free_scc_state(state, &scc);
13878 }
13879
13880
13881 static void transform_to_arch_instructions(struct compile_state *state)
13882 {
13883         struct triple *ins, *first;
13884         first = RHS(state->main_function, 0);
13885         ins = first;
13886         do {
13887                 ins = transform_to_arch_instruction(state, ins);
13888         } while(ins != first);
13889 }
13890
13891 #if DEBUG_CONSISTENCY
13892 static void verify_uses(struct compile_state *state)
13893 {
13894         struct triple *first, *ins;
13895         struct triple_set *set;
13896         first = RHS(state->main_function, 0);
13897         ins = first;
13898         do {
13899                 struct triple **expr;
13900                 expr = triple_rhs(state, ins, 0);
13901                 for(; expr; expr = triple_rhs(state, ins, expr)) {
13902                         for(set = *expr?(*expr)->use:0; set; set = set->next) {
13903                                 if (set->member == ins) {
13904                                         break;
13905                                 }
13906                         }
13907                         if (!set) {
13908                                 internal_error(state, ins, "rhs not used");
13909                         }
13910                 }
13911                 expr = triple_lhs(state, ins, 0);
13912                 for(; expr; expr = triple_lhs(state, ins, expr)) {
13913                         for(set =  *expr?(*expr)->use:0; set; set = set->next) {
13914                                 if (set->member == ins) {
13915                                         break;
13916                                 }
13917                         }
13918                         if (!set) {
13919                                 internal_error(state, ins, "lhs not used");
13920                         }
13921                 }
13922                 ins = ins->next;
13923         } while(ins != first);
13924         
13925 }
13926 static void verify_blocks(struct compile_state *state)
13927 {
13928         struct triple *ins;
13929         struct block *block;
13930         block = state->first_block;
13931         if (!block) {
13932                 return;
13933         }
13934         do {
13935                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
13936                         if (!triple_stores_block(state, ins)) {
13937                                 continue;
13938                         }
13939                         if (ins->u.block != block) {
13940                                 internal_error(state, ins, "inconsitent block specified");
13941                         }
13942                 }
13943                 if (!triple_stores_block(state, block->last->next)) {
13944                         internal_error(state, block->last->next, 
13945                                 "cannot find next block");
13946                 }
13947                 block = block->last->next->u.block;
13948                 if (!block) {
13949                         internal_error(state, block->last->next,
13950                                 "bad next block");
13951                 }
13952         } while(block != state->first_block);
13953 }
13954
13955 static void verify_domination(struct compile_state *state)
13956 {
13957         struct triple *first, *ins;
13958         struct triple_set *set;
13959         if (!state->first_block) {
13960                 return;
13961         }
13962         
13963         first = RHS(state->main_function, 0);
13964         ins = first;
13965         do {
13966                 for(set = ins->use; set; set = set->next) {
13967                         struct triple **expr;
13968                         if (set->member->op == OP_PHI) {
13969                                 continue;
13970                         }
13971                         /* See if the use is on the righ hand side */
13972                         expr = triple_rhs(state, set->member, 0);
13973                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
13974                                 if (*expr == ins) {
13975                                         break;
13976                                 }
13977                         }
13978                         if (expr &&
13979                                 !tdominates(state, ins, set->member)) {
13980                                 internal_error(state, set->member, 
13981                                         "non dominated rhs use?");
13982                         }
13983                 }
13984                 ins = ins->next;
13985         } while(ins != first);
13986 }
13987
13988 static void verify_piece(struct compile_state *state)
13989 {
13990         struct triple *first, *ins;
13991         first = RHS(state->main_function, 0);
13992         ins = first;
13993         do {
13994                 struct triple *ptr;
13995                 int lhs, i;
13996                 lhs = TRIPLE_LHS(ins->sizes);
13997                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
13998                         lhs = 0;
13999                 }
14000                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14001                         if (ptr != LHS(ins, i)) {
14002                                 internal_error(state, ins, "malformed lhs on %s",
14003                                         tops(ins->op));
14004                         }
14005                         if (ptr->op != OP_PIECE) {
14006                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14007                                         tops(ptr->op), i, tops(ins->op));
14008                         }
14009                         if (ptr->u.cval != i) {
14010                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14011                                         ptr->u.cval, i);
14012                         }
14013                 }
14014                 ins = ins->next;
14015         } while(ins != first);
14016 }
14017 static void verify_ins_colors(struct compile_state *state)
14018 {
14019         struct triple *first, *ins;
14020         
14021         first = RHS(state->main_function, 0);
14022         ins = first;
14023         do {
14024                 ins = ins->next;
14025         } while(ins != first);
14026 }
14027 static void verify_consistency(struct compile_state *state)
14028 {
14029         verify_uses(state);
14030         verify_blocks(state);
14031         verify_domination(state);
14032         verify_piece(state);
14033         verify_ins_colors(state);
14034 }
14035 #else 
14036 #define verify_consistency(state) do {} while(0)
14037 #endif /* DEBUG_USES */
14038
14039 static void optimize(struct compile_state *state)
14040 {
14041         if (state->debug & DEBUG_TRIPLES) {
14042                 print_triples(state);
14043         }
14044         /* Replace structures with simpler data types */
14045         flatten_structures(state);
14046         if (state->debug & DEBUG_TRIPLES) {
14047                 print_triples(state);
14048         }
14049         verify_consistency(state);
14050         /* Analize the intermediate code */
14051         setup_basic_blocks(state);
14052         analyze_idominators(state);
14053         analyze_ipdominators(state);
14054         /* Transform the code to ssa form */
14055         transform_to_ssa_form(state);
14056         verify_consistency(state);
14057         if (state->debug & DEBUG_CODE_ELIMINATION) {
14058                 fprintf(stdout, "After transform_to_ssa_form\n");
14059                 print_blocks(state, stdout);
14060         }
14061         /* Do strength reduction and simple constant optimizations */
14062         if (state->optimize >= 1) {
14063                 simplify_all(state);
14064         }
14065         verify_consistency(state);
14066         /* Propogate constants throughout the code */
14067         if (state->optimize >= 2) {
14068 #warning "FIXME fix scc_transform"
14069                 scc_transform(state);
14070                 transform_from_ssa_form(state);
14071                 free_basic_blocks(state);
14072                 setup_basic_blocks(state);
14073                 analyze_idominators(state);
14074                 analyze_ipdominators(state);
14075                 transform_to_ssa_form(state);
14076         }
14077         verify_consistency(state);
14078 #warning "WISHLIST implement single use constants (least possible register pressure)"
14079 #warning "WISHLIST implement induction variable elimination"
14080         /* Select architecture instructions and an initial partial
14081          * coloring based on architecture constraints.
14082          */
14083         transform_to_arch_instructions(state);
14084         verify_consistency(state);
14085         if (state->debug & DEBUG_ARCH_CODE) {
14086                 printf("After transform_to_arch_instructions\n");
14087                 print_blocks(state, stdout);
14088                 print_control_flow(state);
14089         }
14090         eliminate_inefectual_code(state);
14091         verify_consistency(state);
14092         if (state->debug & DEBUG_CODE_ELIMINATION) {
14093                 printf("After eliminate_inefectual_code\n");
14094                 print_blocks(state, stdout);
14095                 print_control_flow(state);
14096         }
14097         verify_consistency(state);
14098         /* Color all of the variables to see if they will fit in registers */
14099         insert_copies_to_phi(state);
14100         if (state->debug & DEBUG_INSERTED_COPIES) {
14101                 printf("After insert_copies_to_phi\n");
14102                 print_blocks(state, stdout);
14103                 print_control_flow(state);
14104         }
14105         verify_consistency(state);
14106         insert_mandatory_copies(state);
14107         if (state->debug & DEBUG_INSERTED_COPIES) {
14108                 printf("After insert_mandatory_copies\n");
14109                 print_blocks(state, stdout);
14110                 print_control_flow(state);
14111         }
14112         verify_consistency(state);
14113         allocate_registers(state);
14114         verify_consistency(state);
14115         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14116                 print_blocks(state, stdout);
14117         }
14118         if (state->debug & DEBUG_CONTROL_FLOW) {
14119                 print_control_flow(state);
14120         }
14121         /* Remove the optimization information.
14122          * This is more to check for memory consistency than to free memory.
14123          */
14124         free_basic_blocks(state);
14125 }
14126
14127 static void print_op_asm(struct compile_state *state,
14128         struct triple *ins, FILE *fp)
14129 {
14130         struct asm_info *info;
14131         const char *ptr;
14132         unsigned lhs, rhs, i;
14133         info = ins->u.ainfo;
14134         lhs = TRIPLE_LHS(ins->sizes);
14135         rhs = TRIPLE_RHS(ins->sizes);
14136         /* Don't count the clobbers in lhs */
14137         for(i = 0; i < lhs; i++) {
14138                 if (LHS(ins, i)->type == &void_type) {
14139                         break;
14140                 }
14141         }
14142         lhs = i;
14143         fputc('\t', fp);
14144         for(ptr = info->str; *ptr; ptr++) {
14145                 char *next;
14146                 unsigned long param;
14147                 struct triple *piece;
14148                 if (*ptr != '%') {
14149                         fputc(*ptr, fp);
14150                         continue;
14151                 }
14152                 ptr++;
14153                 if (*ptr == '%') {
14154                         fputc('%', fp);
14155                         continue;
14156                 }
14157                 param = strtoul(ptr, &next, 10);
14158                 if (ptr == next) {
14159                         error(state, ins, "Invalid asm template");
14160                 }
14161                 if (param >= (lhs + rhs)) {
14162                         error(state, ins, "Invalid param %%%u in asm template",
14163                                 param);
14164                 }
14165                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14166                 fprintf(fp, "%s", 
14167                         arch_reg_str(ID_REG(piece->id)));
14168                 ptr = next;
14169         }
14170         fputc('\n', fp);
14171 }
14172
14173
14174 /* Only use the low x86 byte registers.  This allows me
14175  * allocate the entire register when a byte register is used.
14176  */
14177 #define X86_4_8BIT_GPRS 1
14178
14179 /* Recognized x86 cpu variants */
14180 #define BAD_CPU      0
14181 #define CPU_I386     1
14182 #define CPU_P3       2
14183 #define CPU_P4       3
14184 #define CPU_K7       4
14185 #define CPU_K8       5
14186
14187 #define CPU_DEFAULT  CPU_I386
14188
14189 /* The x86 register classes */
14190 #define REGC_FLAGS    0
14191 #define REGC_GPR8     1
14192 #define REGC_GPR16    2
14193 #define REGC_GPR32    3
14194 #define REGC_GPR64    4
14195 #define REGC_MMX      5
14196 #define REGC_XMM      6
14197 #define REGC_GPR32_8  7
14198 #define REGC_GPR16_8  8
14199 #define REGC_IMM32    9
14200 #define REGC_IMM16   10
14201 #define REGC_IMM8    11
14202 #define LAST_REGC  REGC_IMM8
14203 #if LAST_REGC >= MAX_REGC
14204 #error "MAX_REGC is to low"
14205 #endif
14206
14207 /* Register class masks */
14208 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14209 #define REGCM_GPR8    (1 << REGC_GPR8)
14210 #define REGCM_GPR16   (1 << REGC_GPR16)
14211 #define REGCM_GPR32   (1 << REGC_GPR32)
14212 #define REGCM_GPR64   (1 << REGC_GPR64)
14213 #define REGCM_MMX     (1 << REGC_MMX)
14214 #define REGCM_XMM     (1 << REGC_XMM)
14215 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14216 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14217 #define REGCM_IMM32   (1 << REGC_IMM32)
14218 #define REGCM_IMM16   (1 << REGC_IMM16)
14219 #define REGCM_IMM8    (1 << REGC_IMM8)
14220 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14221
14222 /* The x86 registers */
14223 #define REG_EFLAGS  2
14224 #define REGC_FLAGS_FIRST REG_EFLAGS
14225 #define REGC_FLAGS_LAST  REG_EFLAGS
14226 #define REG_AL      3
14227 #define REG_BL      4
14228 #define REG_CL      5
14229 #define REG_DL      6
14230 #define REG_AH      7
14231 #define REG_BH      8
14232 #define REG_CH      9
14233 #define REG_DH      10
14234 #define REGC_GPR8_FIRST  REG_AL
14235 #if X86_4_8BIT_GPRS
14236 #define REGC_GPR8_LAST   REG_DL
14237 #else 
14238 #define REGC_GPR8_LAST   REG_DH
14239 #endif
14240 #define REG_AX     11
14241 #define REG_BX     12
14242 #define REG_CX     13
14243 #define REG_DX     14
14244 #define REG_SI     15
14245 #define REG_DI     16
14246 #define REG_BP     17
14247 #define REG_SP     18
14248 #define REGC_GPR16_FIRST REG_AX
14249 #define REGC_GPR16_LAST  REG_SP
14250 #define REG_EAX    19
14251 #define REG_EBX    20
14252 #define REG_ECX    21
14253 #define REG_EDX    22
14254 #define REG_ESI    23
14255 #define REG_EDI    24
14256 #define REG_EBP    25
14257 #define REG_ESP    26
14258 #define REGC_GPR32_FIRST REG_EAX
14259 #define REGC_GPR32_LAST  REG_ESP
14260 #define REG_EDXEAX 27
14261 #define REGC_GPR64_FIRST REG_EDXEAX
14262 #define REGC_GPR64_LAST  REG_EDXEAX
14263 #define REG_MMX0   28
14264 #define REG_MMX1   29
14265 #define REG_MMX2   30
14266 #define REG_MMX3   31
14267 #define REG_MMX4   32
14268 #define REG_MMX5   33
14269 #define REG_MMX6   34
14270 #define REG_MMX7   35
14271 #define REGC_MMX_FIRST REG_MMX0
14272 #define REGC_MMX_LAST  REG_MMX7
14273 #define REG_XMM0   36
14274 #define REG_XMM1   37
14275 #define REG_XMM2   38
14276 #define REG_XMM3   39
14277 #define REG_XMM4   40
14278 #define REG_XMM5   41
14279 #define REG_XMM6   42
14280 #define REG_XMM7   43
14281 #define REGC_XMM_FIRST REG_XMM0
14282 #define REGC_XMM_LAST  REG_XMM7
14283 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14284 #define LAST_REG   REG_XMM7
14285
14286 #define REGC_GPR32_8_FIRST REG_EAX
14287 #define REGC_GPR32_8_LAST  REG_EDX
14288 #define REGC_GPR16_8_FIRST REG_AX
14289 #define REGC_GPR16_8_LAST  REG_DX
14290
14291 #define REGC_IMM8_FIRST    -1
14292 #define REGC_IMM8_LAST     -1
14293 #define REGC_IMM16_FIRST   -2
14294 #define REGC_IMM16_LAST    -1
14295 #define REGC_IMM32_FIRST   -4
14296 #define REGC_IMM32_LAST    -1
14297
14298 #if LAST_REG >= MAX_REGISTERS
14299 #error "MAX_REGISTERS to low"
14300 #endif
14301
14302
14303 static unsigned regc_size[LAST_REGC +1] = {
14304         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
14305         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
14306         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
14307         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
14308         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
14309         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
14310         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
14311         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14312         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14313         [REGC_IMM32]   = 0,
14314         [REGC_IMM16]   = 0,
14315         [REGC_IMM8]    = 0,
14316 };
14317
14318 static const struct {
14319         int first, last;
14320 } regcm_bound[LAST_REGC + 1] = {
14321         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
14322         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
14323         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
14324         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
14325         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
14326         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
14327         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
14328         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14329         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14330         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
14331         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
14332         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
14333 };
14334
14335 static int arch_encode_cpu(const char *cpu)
14336 {
14337         struct cpu {
14338                 const char *name;
14339                 int cpu;
14340         } cpus[] = {
14341                 { "i386", CPU_I386 },
14342                 { "p3",   CPU_P3 },
14343                 { "p4",   CPU_P4 },
14344                 { "k7",   CPU_K7 },
14345                 { "k8",   CPU_K8 },
14346                 {  0,     BAD_CPU }
14347         };
14348         struct cpu *ptr;
14349         for(ptr = cpus; ptr->name; ptr++) {
14350                 if (strcmp(ptr->name, cpu) == 0) {
14351                         break;
14352                 }
14353         }
14354         return ptr->cpu;
14355 }
14356
14357 static unsigned arch_regc_size(struct compile_state *state, int class)
14358 {
14359         if ((class < 0) || (class > LAST_REGC)) {
14360                 return 0;
14361         }
14362         return regc_size[class];
14363 }
14364 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14365 {
14366         /* See if two register classes may have overlapping registers */
14367         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14368                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14369
14370         /* Special case for the immediates */
14371         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14372                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14373                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14374                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
14375                 return 0;
14376         }
14377         return (regcm1 & regcm2) ||
14378                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14379 }
14380
14381 static void arch_reg_equivs(
14382         struct compile_state *state, unsigned *equiv, int reg)
14383 {
14384         if ((reg < 0) || (reg > LAST_REG)) {
14385                 internal_error(state, 0, "invalid register");
14386         }
14387         *equiv++ = reg;
14388         switch(reg) {
14389         case REG_AL:
14390 #if X86_4_8BIT_GPRS
14391                 *equiv++ = REG_AH;
14392 #endif
14393                 *equiv++ = REG_AX;
14394                 *equiv++ = REG_EAX;
14395                 *equiv++ = REG_EDXEAX;
14396                 break;
14397         case REG_AH:
14398 #if X86_4_8BIT_GPRS
14399                 *equiv++ = REG_AL;
14400 #endif
14401                 *equiv++ = REG_AX;
14402                 *equiv++ = REG_EAX;
14403                 *equiv++ = REG_EDXEAX;
14404                 break;
14405         case REG_BL:  
14406 #if X86_4_8BIT_GPRS
14407                 *equiv++ = REG_BH;
14408 #endif
14409                 *equiv++ = REG_BX;
14410                 *equiv++ = REG_EBX;
14411                 break;
14412
14413         case REG_BH:
14414 #if X86_4_8BIT_GPRS
14415                 *equiv++ = REG_BL;
14416 #endif
14417                 *equiv++ = REG_BX;
14418                 *equiv++ = REG_EBX;
14419                 break;
14420         case REG_CL:
14421 #if X86_4_8BIT_GPRS
14422                 *equiv++ = REG_CH;
14423 #endif
14424                 *equiv++ = REG_CX;
14425                 *equiv++ = REG_ECX;
14426                 break;
14427
14428         case REG_CH:
14429 #if X86_4_8BIT_GPRS
14430                 *equiv++ = REG_CL;
14431 #endif
14432                 *equiv++ = REG_CX;
14433                 *equiv++ = REG_ECX;
14434                 break;
14435         case REG_DL:
14436 #if X86_4_8BIT_GPRS
14437                 *equiv++ = REG_DH;
14438 #endif
14439                 *equiv++ = REG_DX;
14440                 *equiv++ = REG_EDX;
14441                 *equiv++ = REG_EDXEAX;
14442                 break;
14443         case REG_DH:
14444 #if X86_4_8BIT_GPRS
14445                 *equiv++ = REG_DL;
14446 #endif
14447                 *equiv++ = REG_DX;
14448                 *equiv++ = REG_EDX;
14449                 *equiv++ = REG_EDXEAX;
14450                 break;
14451         case REG_AX:
14452                 *equiv++ = REG_AL;
14453                 *equiv++ = REG_AH;
14454                 *equiv++ = REG_EAX;
14455                 *equiv++ = REG_EDXEAX;
14456                 break;
14457         case REG_BX:
14458                 *equiv++ = REG_BL;
14459                 *equiv++ = REG_BH;
14460                 *equiv++ = REG_EBX;
14461                 break;
14462         case REG_CX:  
14463                 *equiv++ = REG_CL;
14464                 *equiv++ = REG_CH;
14465                 *equiv++ = REG_ECX;
14466                 break;
14467         case REG_DX:  
14468                 *equiv++ = REG_DL;
14469                 *equiv++ = REG_DH;
14470                 *equiv++ = REG_EDX;
14471                 *equiv++ = REG_EDXEAX;
14472                 break;
14473         case REG_SI:  
14474                 *equiv++ = REG_ESI;
14475                 break;
14476         case REG_DI:
14477                 *equiv++ = REG_EDI;
14478                 break;
14479         case REG_BP:
14480                 *equiv++ = REG_EBP;
14481                 break;
14482         case REG_SP:
14483                 *equiv++ = REG_ESP;
14484                 break;
14485         case REG_EAX:
14486                 *equiv++ = REG_AL;
14487                 *equiv++ = REG_AH;
14488                 *equiv++ = REG_AX;
14489                 *equiv++ = REG_EDXEAX;
14490                 break;
14491         case REG_EBX:
14492                 *equiv++ = REG_BL;
14493                 *equiv++ = REG_BH;
14494                 *equiv++ = REG_BX;
14495                 break;
14496         case REG_ECX:
14497                 *equiv++ = REG_CL;
14498                 *equiv++ = REG_CH;
14499                 *equiv++ = REG_CX;
14500                 break;
14501         case REG_EDX:
14502                 *equiv++ = REG_DL;
14503                 *equiv++ = REG_DH;
14504                 *equiv++ = REG_DX;
14505                 *equiv++ = REG_EDXEAX;
14506                 break;
14507         case REG_ESI: 
14508                 *equiv++ = REG_SI;
14509                 break;
14510         case REG_EDI: 
14511                 *equiv++ = REG_DI;
14512                 break;
14513         case REG_EBP: 
14514                 *equiv++ = REG_BP;
14515                 break;
14516         case REG_ESP: 
14517                 *equiv++ = REG_SP;
14518                 break;
14519         case REG_EDXEAX: 
14520                 *equiv++ = REG_AL;
14521                 *equiv++ = REG_AH;
14522                 *equiv++ = REG_DL;
14523                 *equiv++ = REG_DH;
14524                 *equiv++ = REG_AX;
14525                 *equiv++ = REG_DX;
14526                 *equiv++ = REG_EAX;
14527                 *equiv++ = REG_EDX;
14528                 break;
14529         }
14530         *equiv++ = REG_UNSET; 
14531 }
14532
14533 static unsigned arch_avail_mask(struct compile_state *state)
14534 {
14535         unsigned avail_mask;
14536         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
14537                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14538                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14539         switch(state->cpu) {
14540         case CPU_P3:
14541         case CPU_K7:
14542                 avail_mask |= REGCM_MMX;
14543                 break;
14544         case CPU_P4:
14545         case CPU_K8:
14546                 avail_mask |= REGCM_MMX | REGCM_XMM;
14547                 break;
14548         }
14549 #if 0
14550         /* Don't enable 8 bit values until I can force both operands
14551          * to be 8bits simultaneously.
14552          */
14553         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14554 #endif
14555         return avail_mask;
14556 }
14557
14558 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14559 {
14560         unsigned mask, result;
14561         int class, class2;
14562         result = regcm;
14563         result &= arch_avail_mask(state);
14564
14565         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14566                 if ((result & mask) == 0) {
14567                         continue;
14568                 }
14569                 if (class > LAST_REGC) {
14570                         result &= ~mask;
14571                 }
14572                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14573                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14574                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14575                                 result |= (1 << class2);
14576                         }
14577                 }
14578         }
14579         return result;
14580 }
14581
14582 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14583 {
14584         unsigned mask;
14585         int class;
14586         mask = 0;
14587         for(class = 0; class <= LAST_REGC; class++) {
14588                 if ((reg >= regcm_bound[class].first) &&
14589                         (reg <= regcm_bound[class].last)) {
14590                         mask |= (1 << class);
14591                 }
14592         }
14593         if (!mask) {
14594                 internal_error(state, 0, "reg %d not in any class", reg);
14595         }
14596         return mask;
14597 }
14598
14599 static struct reg_info arch_reg_constraint(
14600         struct compile_state *state, struct type *type, const char *constraint)
14601 {
14602         static const struct {
14603                 char class;
14604                 unsigned int mask;
14605                 unsigned int reg;
14606         } constraints[] = {
14607                 { 'r', REGCM_GPR32, REG_UNSET },
14608                 { 'g', REGCM_GPR32, REG_UNSET },
14609                 { 'p', REGCM_GPR32, REG_UNSET },
14610                 { 'q', REGCM_GPR8,  REG_UNSET },
14611                 { 'Q', REGCM_GPR32_8, REG_UNSET },
14612                 { 'x', REGCM_XMM,   REG_UNSET },
14613                 { 'y', REGCM_MMX,   REG_UNSET },
14614                 { 'a', REGCM_GPR32, REG_EAX },
14615                 { 'b', REGCM_GPR32, REG_EBX },
14616                 { 'c', REGCM_GPR32, REG_ECX },
14617                 { 'd', REGCM_GPR32, REG_EDX },
14618                 { 'D', REGCM_GPR32, REG_EDI },
14619                 { 'S', REGCM_GPR32, REG_ESI },
14620                 { '\0', 0, REG_UNSET },
14621         };
14622         unsigned int regcm;
14623         unsigned int mask, reg;
14624         struct reg_info result;
14625         const char *ptr;
14626         regcm = arch_type_to_regcm(state, type);
14627         reg = REG_UNSET;
14628         mask = 0;
14629         for(ptr = constraint; *ptr; ptr++) {
14630                 int i;
14631                 if (*ptr ==  ' ') {
14632                         continue;
14633                 }
14634                 for(i = 0; constraints[i].class != '\0'; i++) {
14635                         if (constraints[i].class == *ptr) {
14636                                 break;
14637                         }
14638                 }
14639                 if (constraints[i].class == '\0') {
14640                         error(state, 0, "invalid register constraint ``%c''", *ptr);
14641                         break;
14642                 }
14643                 if ((constraints[i].mask & regcm) == 0) {
14644                         error(state, 0, "invalid register class %c specified",
14645                                 *ptr);
14646                 }
14647                 mask |= constraints[i].mask;
14648                 if (constraints[i].reg != REG_UNSET) {
14649                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14650                                 error(state, 0, "Only one register may be specified");
14651                         }
14652                         reg = constraints[i].reg;
14653                 }
14654         }
14655         result.reg = reg;
14656         result.regcm = mask;
14657         return result;
14658 }
14659
14660 static struct reg_info arch_reg_clobber(
14661         struct compile_state *state, const char *clobber)
14662 {
14663         struct reg_info result;
14664         if (strcmp(clobber, "memory") == 0) {
14665                 result.reg = REG_UNSET;
14666                 result.regcm = 0;
14667         }
14668         else if (strcmp(clobber, "%eax") == 0) {
14669                 result.reg = REG_EAX;
14670                 result.regcm = REGCM_GPR32;
14671         }
14672         else if (strcmp(clobber, "%ebx") == 0) {
14673                 result.reg = REG_EBX;
14674                 result.regcm = REGCM_GPR32;
14675         }
14676         else if (strcmp(clobber, "%ecx") == 0) {
14677                 result.reg = REG_ECX;
14678                 result.regcm = REGCM_GPR32;
14679         }
14680         else if (strcmp(clobber, "%edx") == 0) {
14681                 result.reg = REG_EDX;
14682                 result.regcm = REGCM_GPR32;
14683         }
14684         else if (strcmp(clobber, "%esi") == 0) {
14685                 result.reg = REG_ESI;
14686                 result.regcm = REGCM_GPR32;
14687         }
14688         else if (strcmp(clobber, "%edi") == 0) {
14689                 result.reg = REG_EDI;
14690                 result.regcm = REGCM_GPR32;
14691         }
14692         else if (strcmp(clobber, "%ebp") == 0) {
14693                 result.reg = REG_EBP;
14694                 result.regcm = REGCM_GPR32;
14695         }
14696         else if (strcmp(clobber, "%esp") == 0) {
14697                 result.reg = REG_ESP;
14698                 result.regcm = REGCM_GPR32;
14699         }
14700         else if (strcmp(clobber, "cc") == 0) {
14701                 result.reg = REG_EFLAGS;
14702                 result.regcm = REGCM_FLAGS;
14703         }
14704         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
14705                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14706                 result.reg = REG_XMM0 + octdigval(clobber[3]);
14707                 result.regcm = REGCM_XMM;
14708         }
14709         else if ((strncmp(clobber, "mmx", 3) == 0) &&
14710                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14711                 result.reg = REG_MMX0 + octdigval(clobber[3]);
14712                 result.regcm = REGCM_MMX;
14713         }
14714         else {
14715                 error(state, 0, "Invalid register clobber");
14716                 result.reg = REG_UNSET;
14717                 result.regcm = 0;
14718         }
14719         return result;
14720 }
14721
14722 static int do_select_reg(struct compile_state *state, 
14723         char *used, int reg, unsigned classes)
14724 {
14725         unsigned mask;
14726         if (used[reg]) {
14727                 return REG_UNSET;
14728         }
14729         mask = arch_reg_regcm(state, reg);
14730         return (classes & mask) ? reg : REG_UNSET;
14731 }
14732
14733 static int arch_select_free_register(
14734         struct compile_state *state, char *used, int classes)
14735 {
14736         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14737          * other types of registers.
14738          */
14739         int i, reg;
14740         reg = REG_UNSET;
14741         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14742                 reg = do_select_reg(state, used, i, classes);
14743         }
14744         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14745                 reg = do_select_reg(state, used, i, classes);
14746         }
14747         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14748                 reg = do_select_reg(state, used, i, classes);
14749         }
14750         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14751                 reg = do_select_reg(state, used, i, classes);
14752         }
14753         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14754                 reg = do_select_reg(state, used, i, classes);
14755         }
14756         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14757                 reg = do_select_reg(state, used, i, classes);
14758         }
14759         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14760                 reg = do_select_reg(state, used, i, classes);
14761         }
14762         return reg;
14763 }
14764
14765
14766 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
14767 {
14768 #warning "FIXME force types smaller (if legal) before I get here"
14769         unsigned avail_mask;
14770         unsigned mask;
14771         mask = 0;
14772         avail_mask = arch_avail_mask(state);
14773         switch(type->type & TYPE_MASK) {
14774         case TYPE_ARRAY:
14775         case TYPE_VOID: 
14776                 mask = 0; 
14777                 break;
14778         case TYPE_CHAR:
14779         case TYPE_UCHAR:
14780                 mask = REGCM_GPR8 | 
14781                         REGCM_GPR16 | REGCM_GPR16_8 | 
14782                         REGCM_GPR32 | REGCM_GPR32_8 |
14783                         REGCM_GPR64 |
14784                         REGCM_MMX | REGCM_XMM |
14785                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14786                 break;
14787         case TYPE_SHORT:
14788         case TYPE_USHORT:
14789                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
14790                         REGCM_GPR32 | REGCM_GPR32_8 |
14791                         REGCM_GPR64 |
14792                         REGCM_MMX | REGCM_XMM |
14793                         REGCM_IMM32 | REGCM_IMM16;
14794                 break;
14795         case TYPE_INT:
14796         case TYPE_UINT:
14797         case TYPE_LONG:
14798         case TYPE_ULONG:
14799         case TYPE_POINTER:
14800                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
14801                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
14802                         REGCM_IMM32;
14803                 break;
14804         default:
14805                 internal_error(state, 0, "no register class for type");
14806                 break;
14807         }
14808         mask &= avail_mask;
14809         return mask;
14810 }
14811
14812 static int is_imm32(struct triple *imm)
14813 {
14814         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
14815                 (imm->op == OP_ADDRCONST);
14816         
14817 }
14818 static int is_imm16(struct triple *imm)
14819 {
14820         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
14821 }
14822 static int is_imm8(struct triple *imm)
14823 {
14824         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
14825 }
14826
14827 static int get_imm32(struct triple *ins, struct triple **expr)
14828 {
14829         struct triple *imm;
14830         imm = *expr;
14831         while(imm->op == OP_COPY) {
14832                 imm = RHS(imm, 0);
14833         }
14834         if (!is_imm32(imm)) {
14835                 return 0;
14836         }
14837         unuse_triple(*expr, ins);
14838         use_triple(imm, ins);
14839         *expr = imm;
14840         return 1;
14841 }
14842
14843 static int get_imm8(struct triple *ins, struct triple **expr)
14844 {
14845         struct triple *imm;
14846         imm = *expr;
14847         while(imm->op == OP_COPY) {
14848                 imm = RHS(imm, 0);
14849         }
14850         if (!is_imm8(imm)) {
14851                 return 0;
14852         }
14853         unuse_triple(*expr, ins);
14854         use_triple(imm, ins);
14855         *expr = imm;
14856         return 1;
14857 }
14858
14859 #define TEMPLATE_NOP         0
14860 #define TEMPLATE_INTCONST8   1
14861 #define TEMPLATE_INTCONST32  2
14862 #define TEMPLATE_COPY_REG    3
14863 #define TEMPLATE_COPY_IMM32  4
14864 #define TEMPLATE_COPY_IMM16  5
14865 #define TEMPLATE_COPY_IMM8   6
14866 #define TEMPLATE_PHI         7
14867 #define TEMPLATE_STORE8      8
14868 #define TEMPLATE_STORE16     9
14869 #define TEMPLATE_STORE32    10
14870 #define TEMPLATE_LOAD8      11
14871 #define TEMPLATE_LOAD16     12
14872 #define TEMPLATE_LOAD32     13
14873 #define TEMPLATE_BINARY_REG 14
14874 #define TEMPLATE_BINARY_IMM 15
14875 #define TEMPLATE_SL_CL      16
14876 #define TEMPLATE_SL_IMM     17
14877 #define TEMPLATE_UNARY      18
14878 #define TEMPLATE_CMP_REG    19
14879 #define TEMPLATE_CMP_IMM    20
14880 #define TEMPLATE_TEST       21
14881 #define TEMPLATE_SET        22
14882 #define TEMPLATE_JMP        23
14883 #define TEMPLATE_INB_DX     24
14884 #define TEMPLATE_INB_IMM    25
14885 #define TEMPLATE_INW_DX     26
14886 #define TEMPLATE_INW_IMM    27
14887 #define TEMPLATE_INL_DX     28
14888 #define TEMPLATE_INL_IMM    29
14889 #define TEMPLATE_OUTB_DX    30
14890 #define TEMPLATE_OUTB_IMM   31
14891 #define TEMPLATE_OUTW_DX    32
14892 #define TEMPLATE_OUTW_IMM   33
14893 #define TEMPLATE_OUTL_DX    34
14894 #define TEMPLATE_OUTL_IMM   35
14895 #define TEMPLATE_BSF        36
14896 #define TEMPLATE_RDMSR      37
14897 #define TEMPLATE_WRMSR      38
14898 #define LAST_TEMPLATE       TEMPLATE_WRMSR
14899 #if LAST_TEMPLATE >= MAX_TEMPLATES
14900 #error "MAX_TEMPLATES to low"
14901 #endif
14902
14903 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
14904 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
14905
14906 static struct ins_template templates[] = {
14907         [TEMPLATE_NOP]      = {},
14908         [TEMPLATE_INTCONST8] = { 
14909                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14910         },
14911         [TEMPLATE_INTCONST32] = { 
14912                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14913         },
14914         [TEMPLATE_COPY_REG] = {
14915                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14916                 .rhs = { [0] = { REG_UNSET, COPY_REGCM }  },
14917         },
14918         [TEMPLATE_COPY_IMM32] = {
14919                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
14920                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14921         },
14922         [TEMPLATE_COPY_IMM16] = {
14923                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
14924                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
14925         },
14926         [TEMPLATE_COPY_IMM8] = {
14927                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14928                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14929         },
14930         [TEMPLATE_PHI] = { 
14931                 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
14932                 .rhs = { 
14933                         [ 0] = { REG_VIRT0, COPY_REGCM },
14934                         [ 1] = { REG_VIRT0, COPY_REGCM },
14935                         [ 2] = { REG_VIRT0, COPY_REGCM },
14936                         [ 3] = { REG_VIRT0, COPY_REGCM },
14937                         [ 4] = { REG_VIRT0, COPY_REGCM },
14938                         [ 5] = { REG_VIRT0, COPY_REGCM },
14939                         [ 6] = { REG_VIRT0, COPY_REGCM },
14940                         [ 7] = { REG_VIRT0, COPY_REGCM },
14941                         [ 8] = { REG_VIRT0, COPY_REGCM },
14942                         [ 9] = { REG_VIRT0, COPY_REGCM },
14943                         [10] = { REG_VIRT0, COPY_REGCM },
14944                         [11] = { REG_VIRT0, COPY_REGCM },
14945                         [12] = { REG_VIRT0, COPY_REGCM },
14946                         [13] = { REG_VIRT0, COPY_REGCM },
14947                         [14] = { REG_VIRT0, COPY_REGCM },
14948                         [15] = { REG_VIRT0, COPY_REGCM },
14949                 }, },
14950         [TEMPLATE_STORE8] = {
14951                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14952                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14953         },
14954         [TEMPLATE_STORE16] = {
14955                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14956                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14957         },
14958         [TEMPLATE_STORE32] = {
14959                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14960                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14961         },
14962         [TEMPLATE_LOAD8] = {
14963                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14964                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14965         },
14966         [TEMPLATE_LOAD16] = {
14967                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14968                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14969         },
14970         [TEMPLATE_LOAD32] = {
14971                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14972                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14973         },
14974         [TEMPLATE_BINARY_REG] = {
14975                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14976                 .rhs = { 
14977                         [0] = { REG_VIRT0, REGCM_GPR32 },
14978                         [1] = { REG_UNSET, REGCM_GPR32 },
14979                 },
14980         },
14981         [TEMPLATE_BINARY_IMM] = {
14982                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14983                 .rhs = { 
14984                         [0] = { REG_VIRT0,    REGCM_GPR32 },
14985                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
14986                 },
14987         },
14988         [TEMPLATE_SL_CL] = {
14989                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14990                 .rhs = { 
14991                         [0] = { REG_VIRT0, REGCM_GPR32 },
14992                         [1] = { REG_CL, REGCM_GPR8 },
14993                 },
14994         },
14995         [TEMPLATE_SL_IMM] = {
14996                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14997                 .rhs = { 
14998                         [0] = { REG_VIRT0,    REGCM_GPR32 },
14999                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15000                 },
15001         },
15002         [TEMPLATE_UNARY] = {
15003                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15004                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15005         },
15006         [TEMPLATE_CMP_REG] = {
15007                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15008                 .rhs = {
15009                         [0] = { REG_UNSET, REGCM_GPR32 },
15010                         [1] = { REG_UNSET, REGCM_GPR32 },
15011                 },
15012         },
15013         [TEMPLATE_CMP_IMM] = {
15014                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15015                 .rhs = {
15016                         [0] = { REG_UNSET, REGCM_GPR32 },
15017                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15018                 },
15019         },
15020         [TEMPLATE_TEST] = {
15021                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15022                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15023         },
15024         [TEMPLATE_SET] = {
15025                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15026                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15027         },
15028         [TEMPLATE_JMP] = {
15029                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15030         },
15031         [TEMPLATE_INB_DX] = {
15032                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15033                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15034         },
15035         [TEMPLATE_INB_IMM] = {
15036                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15037                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15038         },
15039         [TEMPLATE_INW_DX]  = { 
15040                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15041                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15042         },
15043         [TEMPLATE_INW_IMM] = { 
15044                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15045                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15046         },
15047         [TEMPLATE_INL_DX]  = {
15048                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15049                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15050         },
15051         [TEMPLATE_INL_IMM] = {
15052                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15053                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15054         },
15055         [TEMPLATE_OUTB_DX] = { 
15056                 .rhs = {
15057                         [0] = { REG_AL,  REGCM_GPR8 },
15058                         [1] = { REG_DX, REGCM_GPR16 },
15059                 },
15060         },
15061         [TEMPLATE_OUTB_IMM] = { 
15062                 .rhs = {
15063                         [0] = { REG_AL,  REGCM_GPR8 },  
15064                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15065                 },
15066         },
15067         [TEMPLATE_OUTW_DX] = { 
15068                 .rhs = {
15069                         [0] = { REG_AX,  REGCM_GPR16 },
15070                         [1] = { REG_DX, REGCM_GPR16 },
15071                 },
15072         },
15073         [TEMPLATE_OUTW_IMM] = {
15074                 .rhs = {
15075                         [0] = { REG_AX,  REGCM_GPR16 }, 
15076                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15077                 },
15078         },
15079         [TEMPLATE_OUTL_DX] = { 
15080                 .rhs = {
15081                         [0] = { REG_EAX, REGCM_GPR32 },
15082                         [1] = { REG_DX, REGCM_GPR16 },
15083                 },
15084         },
15085         [TEMPLATE_OUTL_IMM] = { 
15086                 .rhs = {
15087                         [0] = { REG_EAX, REGCM_GPR32 }, 
15088                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15089                 },
15090         },
15091         [TEMPLATE_BSF] = {
15092                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15093                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15094         },
15095         [TEMPLATE_RDMSR] = {
15096                 .lhs = { 
15097                         [0] = { REG_EAX, REGCM_GPR32 },
15098                         [1] = { REG_EDX, REGCM_GPR32 },
15099                 },
15100                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15101         },
15102         [TEMPLATE_WRMSR] = {
15103                 .rhs = {
15104                         [0] = { REG_ECX, REGCM_GPR32 },
15105                         [1] = { REG_EAX, REGCM_GPR32 },
15106                         [2] = { REG_EDX, REGCM_GPR32 },
15107                 },
15108         },
15109 };
15110
15111 static void fixup_branches(struct compile_state *state,
15112         struct triple *cmp, struct triple *use, int jmp_op)
15113 {
15114         struct triple_set *entry, *next;
15115         for(entry = use->use; entry; entry = next) {
15116                 next = entry->next;
15117                 if (entry->member->op == OP_COPY) {
15118                         fixup_branches(state, cmp, entry->member, jmp_op);
15119                 }
15120                 else if (entry->member->op == OP_BRANCH) {
15121                         struct triple *branch, *test;
15122                         struct triple *left, *right;
15123                         left = right = 0;
15124                         left = RHS(cmp, 0);
15125                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15126                                 right = RHS(cmp, 1);
15127                         }
15128                         branch = entry->member;
15129                         test = pre_triple(state, branch,
15130                                 cmp->op, cmp->type, left, right);
15131                         test->template_id = TEMPLATE_TEST; 
15132                         if (cmp->op == OP_CMP) {
15133                                 test->template_id = TEMPLATE_CMP_REG;
15134                                 if (get_imm32(test, &RHS(test, 1))) {
15135                                         test->template_id = TEMPLATE_CMP_IMM;
15136                                 }
15137                         }
15138                         use_triple(RHS(test, 0), test);
15139                         use_triple(RHS(test, 1), test);
15140                         unuse_triple(RHS(branch, 0), branch);
15141                         RHS(branch, 0) = test;
15142                         branch->op = jmp_op;
15143                         branch->template_id = TEMPLATE_JMP;
15144                         use_triple(RHS(branch, 0), branch);
15145                 }
15146         }
15147 }
15148
15149 static void bool_cmp(struct compile_state *state, 
15150         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15151 {
15152         struct triple_set *entry, *next;
15153         struct triple *set;
15154
15155         /* Put a barrier up before the cmp which preceeds the
15156          * copy instruction.  If a set actually occurs this gives
15157          * us a chance to move variables in registers out of the way.
15158          */
15159
15160         /* Modify the comparison operator */
15161         ins->op = cmp_op;
15162         ins->template_id = TEMPLATE_TEST;
15163         if (cmp_op == OP_CMP) {
15164                 ins->template_id = TEMPLATE_CMP_REG;
15165                 if (get_imm32(ins, &RHS(ins, 1))) {
15166                         ins->template_id =  TEMPLATE_CMP_IMM;
15167                 }
15168         }
15169         /* Generate the instruction sequence that will transform the
15170          * result of the comparison into a logical value.
15171          */
15172         set = post_triple(state, ins, set_op, ins->type, ins, 0);
15173         use_triple(ins, set);
15174         set->template_id = TEMPLATE_SET;
15175
15176         for(entry = ins->use; entry; entry = next) {
15177                 next = entry->next;
15178                 if (entry->member == set) {
15179                         continue;
15180                 }
15181                 replace_rhs_use(state, ins, set, entry->member);
15182         }
15183         fixup_branches(state, ins, set, jmp_op);
15184 }
15185
15186 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15187 {
15188         struct triple *next;
15189         int lhs, i;
15190         lhs = TRIPLE_LHS(ins->sizes);
15191         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15192                 if (next != LHS(ins, i)) {
15193                         internal_error(state, ins, "malformed lhs on %s",
15194                                 tops(ins->op));
15195                 }
15196                 if (next->op != OP_PIECE) {
15197                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15198                                 tops(next->op), i, tops(ins->op));
15199                 }
15200                 if (next->u.cval != i) {
15201                         internal_error(state, ins, "bad u.cval of %d %d expected",
15202                                 next->u.cval, i);
15203                 }
15204         }
15205         return next;
15206 }
15207
15208 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15209 {
15210         struct ins_template *template;
15211         struct reg_info result;
15212         int zlhs;
15213         if (ins->op == OP_PIECE) {
15214                 index = ins->u.cval;
15215                 ins = MISC(ins, 0);
15216         }
15217         zlhs = TRIPLE_LHS(ins->sizes);
15218         if (triple_is_def(state, ins)) {
15219                 zlhs = 1;
15220         }
15221         if (index >= zlhs) {
15222                 internal_error(state, ins, "index %d out of range for %s\n",
15223                         index, tops(ins->op));
15224         }
15225         switch(ins->op) {
15226         case OP_ASM:
15227                 template = &ins->u.ainfo->tmpl;
15228                 break;
15229         default:
15230                 if (ins->template_id > LAST_TEMPLATE) {
15231                         internal_error(state, ins, "bad template number %d", 
15232                                 ins->template_id);
15233                 }
15234                 template = &templates[ins->template_id];
15235                 break;
15236         }
15237         result = template->lhs[index];
15238         result.regcm = arch_regcm_normalize(state, result.regcm);
15239         if (result.reg != REG_UNNEEDED) {
15240                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15241         }
15242         if (result.regcm == 0) {
15243                 internal_error(state, ins, "lhs %d regcm == 0", index);
15244         }
15245         return result;
15246 }
15247
15248 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15249 {
15250         struct reg_info result;
15251         struct ins_template *template;
15252         if ((index > TRIPLE_RHS(ins->sizes)) ||
15253                 (ins->op == OP_PIECE)) {
15254                 internal_error(state, ins, "index %d out of range for %s\n",
15255                         index, tops(ins->op));
15256         }
15257         switch(ins->op) {
15258         case OP_ASM:
15259                 template = &ins->u.ainfo->tmpl;
15260                 break;
15261         default:
15262                 if (ins->template_id > LAST_TEMPLATE) {
15263                         internal_error(state, ins, "bad template number %d", 
15264                                 ins->template_id);
15265                 }
15266                 template = &templates[ins->template_id];
15267                 break;
15268         }
15269         result = template->rhs[index];
15270         result.regcm = arch_regcm_normalize(state, result.regcm);
15271         if (result.regcm == 0) {
15272                 internal_error(state, ins, "rhs %d regcm == 0", index);
15273         }
15274         return result;
15275 }
15276
15277 static struct triple *transform_to_arch_instruction(
15278         struct compile_state *state, struct triple *ins)
15279 {
15280         /* Transform from generic 3 address instructions
15281          * to archtecture specific instructions.
15282          * And apply architecture specific constrains to instructions.
15283          * Copies are inserted to preserve the register flexibility
15284          * of 3 address instructions.
15285          */
15286         struct triple *next;
15287         next = ins->next;
15288         switch(ins->op) {
15289         case OP_INTCONST:
15290                 ins->template_id = TEMPLATE_INTCONST32;
15291                 if (ins->u.cval < 256) {
15292                         ins->template_id = TEMPLATE_INTCONST8;
15293                 }
15294                 break;
15295         case OP_ADDRCONST:
15296                 ins->template_id = TEMPLATE_INTCONST32;
15297                 break;
15298         case OP_NOOP:
15299         case OP_SDECL:
15300         case OP_BLOBCONST:
15301         case OP_LABEL:
15302                 ins->template_id = TEMPLATE_NOP;
15303                 break;
15304         case OP_COPY:
15305                 ins->template_id = TEMPLATE_COPY_REG;
15306                 if (is_imm8(RHS(ins, 0))) {
15307                         ins->template_id = TEMPLATE_COPY_IMM8;
15308                 }
15309                 else if (is_imm16(RHS(ins, 0))) {
15310                         ins->template_id = TEMPLATE_COPY_IMM16;
15311                 }
15312                 else if (is_imm32(RHS(ins, 0))) {
15313                         ins->template_id = TEMPLATE_COPY_IMM32;
15314                 }
15315                 else if (is_const(RHS(ins, 0))) {
15316                         internal_error(state, ins, "bad constant passed to copy");
15317                 }
15318                 break;
15319         case OP_PHI:
15320                 ins->template_id = TEMPLATE_PHI;
15321                 break;
15322         case OP_STORE:
15323                 switch(ins->type->type & TYPE_MASK) {
15324                 case TYPE_CHAR:    case TYPE_UCHAR:
15325                         ins->template_id = TEMPLATE_STORE8;
15326                         break;
15327                 case TYPE_SHORT:   case TYPE_USHORT:
15328                         ins->template_id = TEMPLATE_STORE16;
15329                         break;
15330                 case TYPE_INT:     case TYPE_UINT:
15331                 case TYPE_LONG:    case TYPE_ULONG:
15332                 case TYPE_POINTER:
15333                         ins->template_id = TEMPLATE_STORE32;
15334                         break;
15335                 default:
15336                         internal_error(state, ins, "unknown type in store");
15337                         break;
15338                 }
15339                 break;
15340         case OP_LOAD:
15341                 switch(ins->type->type & TYPE_MASK) {
15342                 case TYPE_CHAR:   case TYPE_UCHAR:
15343                         ins->template_id = TEMPLATE_LOAD8;
15344                         break;
15345                 case TYPE_SHORT:
15346                 case TYPE_USHORT:
15347                         ins->template_id = TEMPLATE_LOAD16;
15348                         break;
15349                 case TYPE_INT:
15350                 case TYPE_UINT:
15351                 case TYPE_LONG:
15352                 case TYPE_ULONG:
15353                 case TYPE_POINTER:
15354                         ins->template_id = TEMPLATE_LOAD32;
15355                         break;
15356                 default:
15357                         internal_error(state, ins, "unknown type in load");
15358                         break;
15359                 }
15360                 break;
15361         case OP_ADD:
15362         case OP_SUB:
15363         case OP_AND:
15364         case OP_XOR:
15365         case OP_OR:
15366         case OP_SMUL:
15367                 ins->template_id = TEMPLATE_BINARY_REG;
15368                 if (get_imm32(ins, &RHS(ins, 1))) {
15369                         ins->template_id = TEMPLATE_BINARY_IMM;
15370                 }
15371                 break;
15372         case OP_SL:
15373         case OP_SSR:
15374         case OP_USR:
15375                 ins->template_id = TEMPLATE_SL_CL;
15376                 if (get_imm8(ins, &RHS(ins, 1))) {
15377                         ins->template_id = TEMPLATE_SL_IMM;
15378                 }
15379                 break;
15380         case OP_INVERT:
15381         case OP_NEG:
15382                 ins->template_id = TEMPLATE_UNARY;
15383                 break;
15384         case OP_EQ: 
15385                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
15386                 break;
15387         case OP_NOTEQ:
15388                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15389                 break;
15390         case OP_SLESS:
15391                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15392                 break;
15393         case OP_ULESS:
15394                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15395                 break;
15396         case OP_SMORE:
15397                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15398                 break;
15399         case OP_UMORE:
15400                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15401                 break;
15402         case OP_SLESSEQ:
15403                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15404                 break;
15405         case OP_ULESSEQ:
15406                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15407                 break;
15408         case OP_SMOREEQ:
15409                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15410                 break;
15411         case OP_UMOREEQ:
15412                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15413                 break;
15414         case OP_LTRUE:
15415                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15416                 break;
15417         case OP_LFALSE:
15418                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15419                 break;
15420         case OP_BRANCH:
15421                 if (TRIPLE_RHS(ins->sizes) > 0) {
15422                         internal_error(state, ins, "bad branch test");
15423                 }
15424                 ins->op = OP_JMP;
15425                 ins->template_id = TEMPLATE_NOP;
15426                 break;
15427         case OP_INB:
15428         case OP_INW:
15429         case OP_INL:
15430                 switch(ins->op) {
15431                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15432                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15433                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15434                 }
15435                 if (get_imm8(ins, &RHS(ins, 0))) {
15436                         ins->template_id += 1;
15437                 }
15438                 break;
15439         case OP_OUTB:
15440         case OP_OUTW:
15441         case OP_OUTL:
15442                 switch(ins->op) {
15443                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15444                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15445                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15446                 }
15447                 if (get_imm8(ins, &RHS(ins, 1))) {
15448                         ins->template_id += 1;
15449                 }
15450                 break;
15451         case OP_BSF:
15452         case OP_BSR:
15453                 ins->template_id = TEMPLATE_BSF;
15454                 break;
15455         case OP_RDMSR:
15456                 ins->template_id = TEMPLATE_RDMSR;
15457                 next = after_lhs(state, ins);
15458                 break;
15459         case OP_WRMSR:
15460                 ins->template_id = TEMPLATE_WRMSR;
15461                 break;
15462         case OP_HLT:
15463                 ins->template_id = TEMPLATE_NOP;
15464                 break;
15465         case OP_ASM:
15466                 ins->template_id = TEMPLATE_NOP;
15467                 next = after_lhs(state, ins);
15468                 break;
15469                 /* Already transformed instructions */
15470         case OP_TEST:
15471                 ins->template_id = TEMPLATE_TEST;
15472                 break;
15473         case OP_CMP:
15474                 ins->template_id = TEMPLATE_CMP_REG;
15475                 if (get_imm32(ins, &RHS(ins, 1))) {
15476                         ins->template_id = TEMPLATE_CMP_IMM;
15477                 }
15478                 break;
15479         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
15480         case OP_JMP_SLESS:   case OP_JMP_ULESS:
15481         case OP_JMP_SMORE:   case OP_JMP_UMORE:
15482         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15483         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15484                 ins->template_id = TEMPLATE_JMP;
15485                 break;
15486         case OP_SET_EQ:      case OP_SET_NOTEQ:
15487         case OP_SET_SLESS:   case OP_SET_ULESS:
15488         case OP_SET_SMORE:   case OP_SET_UMORE:
15489         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15490         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15491                 ins->template_id = TEMPLATE_SET;
15492                 break;
15493                 /* Unhandled instructions */
15494         case OP_PIECE:
15495         default:
15496                 internal_error(state, ins, "unhandled ins: %d %s\n",
15497                         ins->op, tops(ins->op));
15498                 break;
15499         }
15500         return next;
15501 }
15502
15503 static void generate_local_labels(struct compile_state *state)
15504 {
15505         struct triple *first, *label;
15506         int label_counter;
15507         label_counter = 0;
15508         first = RHS(state->main_function, 0);
15509         label = first;
15510         do {
15511                 if ((label->op == OP_LABEL) || 
15512                         (label->op == OP_SDECL)) {
15513                         if (label->use) {
15514                                 label->u.cval = ++label_counter;
15515                         } else {
15516                                 label->u.cval = 0;
15517                         }
15518                         
15519                 }
15520                 label = label->next;
15521         } while(label != first);
15522 }
15523
15524 static int check_reg(struct compile_state *state, 
15525         struct triple *triple, int classes)
15526 {
15527         unsigned mask;
15528         int reg;
15529         reg = ID_REG(triple->id);
15530         if (reg == REG_UNSET) {
15531                 internal_error(state, triple, "register not set");
15532         }
15533         mask = arch_reg_regcm(state, reg);
15534         if (!(classes & mask)) {
15535                 internal_error(state, triple, "reg %d in wrong class",
15536                         reg);
15537         }
15538         return reg;
15539 }
15540
15541 static const char *arch_reg_str(int reg)
15542 {
15543         static const char *regs[] = {
15544                 "%bad_register",
15545                 "%bad_register2",
15546                 "%eflags",
15547                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15548                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15549                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15550                 "%edx:%eax",
15551                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15552                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
15553                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15554         };
15555         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15556                 reg = 0;
15557         }
15558         return regs[reg];
15559 }
15560
15561
15562 static const char *reg(struct compile_state *state, struct triple *triple,
15563         int classes)
15564 {
15565         int reg;
15566         reg = check_reg(state, triple, classes);
15567         return arch_reg_str(reg);
15568 }
15569
15570 const char *type_suffix(struct compile_state *state, struct type *type)
15571 {
15572         const char *suffix;
15573         switch(size_of(state, type)) {
15574         case 1: suffix = "b"; break;
15575         case 2: suffix = "w"; break;
15576         case 4: suffix = "l"; break;
15577         default:
15578                 internal_error(state, 0, "unknown suffix");
15579                 suffix = 0;
15580                 break;
15581         }
15582         return suffix;
15583 }
15584
15585 static void print_const_val(
15586         struct compile_state *state, struct triple *ins, FILE *fp)
15587 {
15588         switch(ins->op) {
15589         case OP_INTCONST:
15590                 fprintf(fp, " $%ld ", 
15591                         (long_t)(ins->u.cval));
15592                 break;
15593         case OP_ADDRCONST:
15594                 fprintf(fp, " $L%s%lu+%lu ",
15595                         state->label_prefix, 
15596                         MISC(ins, 0)->u.cval,
15597                         ins->u.cval);
15598                 break;
15599         default:
15600                 internal_error(state, ins, "unknown constant type");
15601                 break;
15602         }
15603 }
15604
15605 static void print_binary_op(struct compile_state *state,
15606         const char *op, struct triple *ins, FILE *fp) 
15607 {
15608         unsigned mask;
15609         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15610         if (RHS(ins, 0)->id != ins->id) {
15611                 internal_error(state, ins, "invalid register assignment");
15612         }
15613         if (is_const(RHS(ins, 1))) {
15614                 fprintf(fp, "\t%s ", op);
15615                 print_const_val(state, RHS(ins, 1), fp);
15616                 fprintf(fp, ", %s\n",
15617                         reg(state, RHS(ins, 0), mask));
15618         }
15619         else {
15620                 unsigned lmask, rmask;
15621                 int lreg, rreg;
15622                 lreg = check_reg(state, RHS(ins, 0), mask);
15623                 rreg = check_reg(state, RHS(ins, 1), mask);
15624                 lmask = arch_reg_regcm(state, lreg);
15625                 rmask = arch_reg_regcm(state, rreg);
15626                 mask = lmask & rmask;
15627                 fprintf(fp, "\t%s %s, %s\n",
15628                         op,
15629                         reg(state, RHS(ins, 1), mask),
15630                         reg(state, RHS(ins, 0), mask));
15631         }
15632 }
15633 static void print_unary_op(struct compile_state *state, 
15634         const char *op, struct triple *ins, FILE *fp)
15635 {
15636         unsigned mask;
15637         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15638         fprintf(fp, "\t%s %s\n",
15639                 op,
15640                 reg(state, RHS(ins, 0), mask));
15641 }
15642
15643 static void print_op_shift(struct compile_state *state,
15644         const char *op, struct triple *ins, FILE *fp)
15645 {
15646         unsigned mask;
15647         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15648         if (RHS(ins, 0)->id != ins->id) {
15649                 internal_error(state, ins, "invalid register assignment");
15650         }
15651         if (is_const(RHS(ins, 1))) {
15652                 fprintf(fp, "\t%s ", op);
15653                 print_const_val(state, RHS(ins, 1), fp);
15654                 fprintf(fp, ", %s\n",
15655                         reg(state, RHS(ins, 0), mask));
15656         }
15657         else {
15658                 fprintf(fp, "\t%s %s, %s\n",
15659                         op,
15660                         reg(state, RHS(ins, 1), REGCM_GPR8),
15661                         reg(state, RHS(ins, 0), mask));
15662         }
15663 }
15664
15665 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15666 {
15667         const char *op;
15668         int mask;
15669         int dreg;
15670         mask = 0;
15671         switch(ins->op) {
15672         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15673         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15674         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15675         default:
15676                 internal_error(state, ins, "not an in operation");
15677                 op = 0;
15678                 break;
15679         }
15680         dreg = check_reg(state, ins, mask);
15681         if (!reg_is_reg(state, dreg, REG_EAX)) {
15682                 internal_error(state, ins, "dst != %%eax");
15683         }
15684         if (is_const(RHS(ins, 0))) {
15685                 fprintf(fp, "\t%s ", op);
15686                 print_const_val(state, RHS(ins, 0), fp);
15687                 fprintf(fp, ", %s\n",
15688                         reg(state, ins, mask));
15689         }
15690         else {
15691                 int addr_reg;
15692                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15693                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15694                         internal_error(state, ins, "src != %%dx");
15695                 }
15696                 fprintf(fp, "\t%s %s, %s\n",
15697                         op, 
15698                         reg(state, RHS(ins, 0), REGCM_GPR16),
15699                         reg(state, ins, mask));
15700         }
15701 }
15702
15703 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15704 {
15705         const char *op;
15706         int mask;
15707         int lreg;
15708         mask = 0;
15709         switch(ins->op) {
15710         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15711         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15712         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15713         default:
15714                 internal_error(state, ins, "not an out operation");
15715                 op = 0;
15716                 break;
15717         }
15718         lreg = check_reg(state, RHS(ins, 0), mask);
15719         if (!reg_is_reg(state, lreg, REG_EAX)) {
15720                 internal_error(state, ins, "src != %%eax");
15721         }
15722         if (is_const(RHS(ins, 1))) {
15723                 fprintf(fp, "\t%s %s,", 
15724                         op, reg(state, RHS(ins, 0), mask));
15725                 print_const_val(state, RHS(ins, 1), fp);
15726                 fprintf(fp, "\n");
15727         }
15728         else {
15729                 int addr_reg;
15730                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15731                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15732                         internal_error(state, ins, "dst != %%dx");
15733                 }
15734                 fprintf(fp, "\t%s %s, %s\n",
15735                         op, 
15736                         reg(state, RHS(ins, 0), mask),
15737                         reg(state, RHS(ins, 1), REGCM_GPR16));
15738         }
15739 }
15740
15741 static void print_op_move(struct compile_state *state,
15742         struct triple *ins, FILE *fp)
15743 {
15744         /* op_move is complex because there are many types
15745          * of registers we can move between.
15746          * Because OP_COPY will be introduced in arbitrary locations
15747          * OP_COPY must not affect flags.
15748          */
15749         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15750         struct triple *dst, *src;
15751         if (ins->op == OP_COPY) {
15752                 src = RHS(ins, 0);
15753                 dst = ins;
15754         }
15755         else if (ins->op == OP_WRITE) {
15756                 dst = LHS(ins, 0);
15757                 src = RHS(ins, 0);
15758         }
15759         else {
15760                 internal_error(state, ins, "unknown move operation");
15761                 src = dst = 0;
15762         }
15763         if (!is_const(src)) {
15764                 int src_reg, dst_reg;
15765                 int src_regcm, dst_regcm;
15766                 src_reg = ID_REG(src->id);
15767                 dst_reg   = ID_REG(dst->id);
15768                 src_regcm = arch_reg_regcm(state, src_reg);
15769                 dst_regcm   = arch_reg_regcm(state, dst_reg);
15770                 /* If the class is the same just move the register */
15771                 if (src_regcm & dst_regcm & 
15772                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15773                         if ((src_reg != dst_reg) || !omit_copy) {
15774                                 fprintf(fp, "\tmov %s, %s\n",
15775                                         reg(state, src, src_regcm),
15776                                         reg(state, dst, dst_regcm));
15777                         }
15778                 }
15779                 /* Move 32bit to 16bit */
15780                 else if ((src_regcm & REGCM_GPR32) &&
15781                         (dst_regcm & REGCM_GPR16)) {
15782                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15783                         if ((src_reg != dst_reg) || !omit_copy) {
15784                                 fprintf(fp, "\tmovw %s, %s\n",
15785                                         arch_reg_str(src_reg), 
15786                                         arch_reg_str(dst_reg));
15787                         }
15788                 }
15789                 /* Move 32bit to 8bit */
15790                 else if ((src_regcm & REGCM_GPR32_8) &&
15791                         (dst_regcm & REGCM_GPR8))
15792                 {
15793                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15794                         if ((src_reg != dst_reg) || !omit_copy) {
15795                                 fprintf(fp, "\tmovb %s, %s\n",
15796                                         arch_reg_str(src_reg),
15797                                         arch_reg_str(dst_reg));
15798                         }
15799                 }
15800                 /* Move 16bit to 8bit */
15801                 else if ((src_regcm & REGCM_GPR16_8) &&
15802                         (dst_regcm & REGCM_GPR8))
15803                 {
15804                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
15805                         if ((src_reg != dst_reg) || !omit_copy) {
15806                                 fprintf(fp, "\tmovb %s, %s\n",
15807                                         arch_reg_str(src_reg),
15808                                         arch_reg_str(dst_reg));
15809                         }
15810                 }
15811                 /* Move 8/16bit to 16/32bit */
15812                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
15813                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
15814                         const char *op;
15815                         op = is_signed(src->type)? "movsx": "movzx";
15816                         fprintf(fp, "\t%s %s, %s\n",
15817                                 op,
15818                                 reg(state, src, src_regcm),
15819                                 reg(state, dst, dst_regcm));
15820                 }
15821                 /* Move between sse registers */
15822                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
15823                         if ((src_reg != dst_reg) || !omit_copy) {
15824                                 fprintf(fp, "\tmovdqa %s, %s\n",
15825                                         reg(state, src, src_regcm),
15826                                         reg(state, dst, dst_regcm));
15827                         }
15828                 }
15829                 /* Move between mmx registers or mmx & sse  registers */
15830                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15831                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15832                         if ((src_reg != dst_reg) || !omit_copy) {
15833                                 fprintf(fp, "\tmovq %s, %s\n",
15834                                         reg(state, src, src_regcm),
15835                                         reg(state, dst, dst_regcm));
15836                         }
15837                 }
15838                 /* Move between 32bit gprs & mmx/sse registers */
15839                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
15840                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
15841                         fprintf(fp, "\tmovd %s, %s\n",
15842                                 reg(state, src, src_regcm),
15843                                 reg(state, dst, dst_regcm));
15844                 }
15845 #if X86_4_8BIT_GPRS
15846                 /* Move from 8bit gprs to  mmx/sse registers */
15847                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
15848                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15849                         const char *op;
15850                         int mid_reg;
15851                         op = is_signed(src->type)? "movsx":"movzx";
15852                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15853                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
15854                                 op,
15855                                 reg(state, src, src_regcm),
15856                                 arch_reg_str(mid_reg),
15857                                 arch_reg_str(mid_reg),
15858                                 reg(state, dst, dst_regcm));
15859                 }
15860                 /* Move from mmx/sse registers and 8bit gprs */
15861                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15862                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
15863                         int mid_reg;
15864                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15865                         fprintf(fp, "\tmovd %s, %s\n",
15866                                 reg(state, src, src_regcm),
15867                                 arch_reg_str(mid_reg));
15868                 }
15869                 /* Move from 32bit gprs to 16bit gprs */
15870                 else if ((src_regcm & REGCM_GPR32) &&
15871                         (dst_regcm & REGCM_GPR16)) {
15872                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
15873                         if ((src_reg != dst_reg) || !omit_copy) {
15874                                 fprintf(fp, "\tmov %s, %s\n",
15875                                         arch_reg_str(src_reg),
15876                                         arch_reg_str(dst_reg));
15877                         }
15878                 }
15879                 /* Move from 32bit gprs to 8bit gprs */
15880                 else if ((src_regcm & REGCM_GPR32) &&
15881                         (dst_regcm & REGCM_GPR8)) {
15882                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15883                         if ((src_reg != dst_reg) || !omit_copy) {
15884                                 fprintf(fp, "\tmov %s, %s\n",
15885                                         arch_reg_str(src_reg),
15886                                         arch_reg_str(dst_reg));
15887                         }
15888                 }
15889                 /* Move from 16bit gprs to 8bit gprs */
15890                 else if ((src_regcm & REGCM_GPR16) &&
15891                         (dst_regcm & REGCM_GPR8)) {
15892                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
15893                         if ((src_reg != dst_reg) || !omit_copy) {
15894                                 fprintf(fp, "\tmov %s, %s\n",
15895                                         arch_reg_str(src_reg),
15896                                         arch_reg_str(dst_reg));
15897                         }
15898                 }
15899 #endif /* X86_4_8BIT_GPRS */
15900                 else {
15901                         internal_error(state, ins, "unknown copy type");
15902                 }
15903         }
15904         else {
15905                 fprintf(fp, "\tmov ");
15906                 print_const_val(state, src, fp);
15907                 fprintf(fp, ", %s\n",
15908                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
15909         }
15910 }
15911
15912 static void print_op_load(struct compile_state *state,
15913         struct triple *ins, FILE *fp)
15914 {
15915         struct triple *dst, *src;
15916         dst = ins;
15917         src = RHS(ins, 0);
15918         if (is_const(src) || is_const(dst)) {
15919                 internal_error(state, ins, "unknown load operation");
15920         }
15921         fprintf(fp, "\tmov (%s), %s\n",
15922                 reg(state, src, REGCM_GPR32),
15923                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
15924 }
15925
15926
15927 static void print_op_store(struct compile_state *state,
15928         struct triple *ins, FILE *fp)
15929 {
15930         struct triple *dst, *src;
15931         dst = LHS(ins, 0);
15932         src = RHS(ins, 0);
15933         if (is_const(src) && (src->op == OP_INTCONST)) {
15934                 long_t value;
15935                 value = (long_t)(src->u.cval);
15936                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
15937                         type_suffix(state, src->type),
15938                         value,
15939                         reg(state, dst, REGCM_GPR32));
15940         }
15941         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
15942                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
15943                         type_suffix(state, src->type),
15944                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15945                         dst->u.cval);
15946         }
15947         else {
15948                 if (is_const(src) || is_const(dst)) {
15949                         internal_error(state, ins, "unknown store operation");
15950                 }
15951                 fprintf(fp, "\tmov%s %s, (%s)\n",
15952                         type_suffix(state, src->type),
15953                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15954                         reg(state, dst, REGCM_GPR32));
15955         }
15956         
15957         
15958 }
15959
15960 static void print_op_smul(struct compile_state *state,
15961         struct triple *ins, FILE *fp)
15962 {
15963         if (!is_const(RHS(ins, 1))) {
15964                 fprintf(fp, "\timul %s, %s\n",
15965                         reg(state, RHS(ins, 1), REGCM_GPR32),
15966                         reg(state, RHS(ins, 0), REGCM_GPR32));
15967         }
15968         else {
15969                 fprintf(fp, "\timul ");
15970                 print_const_val(state, RHS(ins, 1), fp);
15971                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
15972         }
15973 }
15974
15975 static void print_op_cmp(struct compile_state *state,
15976         struct triple *ins, FILE *fp)
15977 {
15978         unsigned mask;
15979         int dreg;
15980         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15981         dreg = check_reg(state, ins, REGCM_FLAGS);
15982         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
15983                 internal_error(state, ins, "bad dest register for cmp");
15984         }
15985         if (is_const(RHS(ins, 1))) {
15986                 fprintf(fp, "\tcmp ");
15987                 print_const_val(state, RHS(ins, 1), fp);
15988                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
15989         }
15990         else {
15991                 unsigned lmask, rmask;
15992                 int lreg, rreg;
15993                 lreg = check_reg(state, RHS(ins, 0), mask);
15994                 rreg = check_reg(state, RHS(ins, 1), mask);
15995                 lmask = arch_reg_regcm(state, lreg);
15996                 rmask = arch_reg_regcm(state, rreg);
15997                 mask = lmask & rmask;
15998                 fprintf(fp, "\tcmp %s, %s\n",
15999                         reg(state, RHS(ins, 1), mask),
16000                         reg(state, RHS(ins, 0), mask));
16001         }
16002 }
16003
16004 static void print_op_test(struct compile_state *state,
16005         struct triple *ins, FILE *fp)
16006 {
16007         unsigned mask;
16008         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16009         fprintf(fp, "\ttest %s, %s\n",
16010                 reg(state, RHS(ins, 0), mask),
16011                 reg(state, RHS(ins, 0), mask));
16012 }
16013
16014 static void print_op_branch(struct compile_state *state,
16015         struct triple *branch, FILE *fp)
16016 {
16017         const char *bop = "j";
16018         if (branch->op == OP_JMP) {
16019                 if (TRIPLE_RHS(branch->sizes) != 0) {
16020                         internal_error(state, branch, "jmp with condition?");
16021                 }
16022                 bop = "jmp";
16023         }
16024         else {
16025                 struct triple *ptr;
16026                 if (TRIPLE_RHS(branch->sizes) != 1) {
16027                         internal_error(state, branch, "jmpcc without condition?");
16028                 }
16029                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16030                 if ((RHS(branch, 0)->op != OP_CMP) &&
16031                         (RHS(branch, 0)->op != OP_TEST)) {
16032                         internal_error(state, branch, "bad branch test");
16033                 }
16034 #warning "FIXME I have observed instructions between the test and branch instructions"
16035                 ptr = RHS(branch, 0);
16036                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16037                         if (ptr->op != OP_COPY) {
16038                                 internal_error(state, branch, "branch does not follow test");
16039                         }
16040                 }
16041                 switch(branch->op) {
16042                 case OP_JMP_EQ:       bop = "jz";  break;
16043                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16044                 case OP_JMP_SLESS:    bop = "jl";  break;
16045                 case OP_JMP_ULESS:    bop = "jb";  break;
16046                 case OP_JMP_SMORE:    bop = "jg";  break;
16047                 case OP_JMP_UMORE:    bop = "ja";  break;
16048                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16049                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16050                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16051                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16052                 default:
16053                         internal_error(state, branch, "Invalid branch op");
16054                         break;
16055                 }
16056                 
16057         }
16058         fprintf(fp, "\t%s L%s%lu\n",
16059                 bop, 
16060                 state->label_prefix,
16061                 TARG(branch, 0)->u.cval);
16062 }
16063
16064 static void print_op_set(struct compile_state *state,
16065         struct triple *set, FILE *fp)
16066 {
16067         const char *sop = "set";
16068         if (TRIPLE_RHS(set->sizes) != 1) {
16069                 internal_error(state, set, "setcc without condition?");
16070         }
16071         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16072         if ((RHS(set, 0)->op != OP_CMP) &&
16073                 (RHS(set, 0)->op != OP_TEST)) {
16074                 internal_error(state, set, "bad set test");
16075         }
16076         if (RHS(set, 0)->next != set) {
16077                 internal_error(state, set, "set does not follow test");
16078         }
16079         switch(set->op) {
16080         case OP_SET_EQ:       sop = "setz";  break;
16081         case OP_SET_NOTEQ:    sop = "setnz"; break;
16082         case OP_SET_SLESS:    sop = "setl";  break;
16083         case OP_SET_ULESS:    sop = "setb";  break;
16084         case OP_SET_SMORE:    sop = "setg";  break;
16085         case OP_SET_UMORE:    sop = "seta";  break;
16086         case OP_SET_SLESSEQ:  sop = "setle"; break;
16087         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16088         case OP_SET_SMOREEQ:  sop = "setge"; break;
16089         case OP_SET_UMOREEQ:  sop = "setae"; break;
16090         default:
16091                 internal_error(state, set, "Invalid set op");
16092                 break;
16093         }
16094         fprintf(fp, "\t%s %s\n",
16095                 sop, reg(state, set, REGCM_GPR8));
16096 }
16097
16098 static void print_op_bit_scan(struct compile_state *state, 
16099         struct triple *ins, FILE *fp) 
16100 {
16101         const char *op;
16102         switch(ins->op) {
16103         case OP_BSF: op = "bsf"; break;
16104         case OP_BSR: op = "bsr"; break;
16105         default: 
16106                 internal_error(state, ins, "unknown bit scan");
16107                 op = 0;
16108                 break;
16109         }
16110         fprintf(fp, 
16111                 "\t%s %s, %s\n"
16112                 "\tjnz 1f\n"
16113                 "\tmovl $-1, %s\n"
16114                 "1:\n",
16115                 op,
16116                 reg(state, RHS(ins, 0), REGCM_GPR32),
16117                 reg(state, ins, REGCM_GPR32),
16118                 reg(state, ins, REGCM_GPR32));
16119 }
16120
16121 static void print_const(struct compile_state *state,
16122         struct triple *ins, FILE *fp)
16123 {
16124         switch(ins->op) {
16125         case OP_INTCONST:
16126                 switch(ins->type->type & TYPE_MASK) {
16127                 case TYPE_CHAR:
16128                 case TYPE_UCHAR:
16129                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16130                         break;
16131                 case TYPE_SHORT:
16132                 case TYPE_USHORT:
16133                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16134                         break;
16135                 case TYPE_INT:
16136                 case TYPE_UINT:
16137                 case TYPE_LONG:
16138                 case TYPE_ULONG:
16139                         fprintf(fp, ".int %lu\n", ins->u.cval);
16140                         break;
16141                 default:
16142                         internal_error(state, ins, "Unknown constant type");
16143                 }
16144                 break;
16145         case OP_BLOBCONST:
16146         {
16147                 unsigned char *blob;
16148                 size_t size, i;
16149                 size = size_of(state, ins->type);
16150                 blob = ins->u.blob;
16151                 for(i = 0; i < size; i++) {
16152                         fprintf(fp, ".byte 0x%02x\n",
16153                                 blob[i]);
16154                 }
16155                 break;
16156         }
16157         default:
16158                 internal_error(state, ins, "Unknown constant type");
16159                 break;
16160         }
16161 }
16162
16163 #define TEXT_SECTION ".rom.text"
16164 #define DATA_SECTION ".rom.data"
16165
16166 static void print_sdecl(struct compile_state *state,
16167         struct triple *ins, FILE *fp)
16168 {
16169         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16170         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16171         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16172         print_const(state, MISC(ins, 0), fp);
16173         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16174                 
16175 }
16176
16177 static void print_instruction(struct compile_state *state,
16178         struct triple *ins, FILE *fp)
16179 {
16180         /* Assumption: after I have exted the register allocator
16181          * everything is in a valid register. 
16182          */
16183         switch(ins->op) {
16184         case OP_ASM:
16185                 print_op_asm(state, ins, fp);
16186                 break;
16187         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16188         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16189         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16190         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16191         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16192         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16193         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16194         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16195         case OP_POS:    break;
16196         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16197         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16198         case OP_INTCONST:
16199         case OP_ADDRCONST:
16200         case OP_BLOBCONST:
16201                 /* Don't generate anything here for constants */
16202         case OP_PHI:
16203                 /* Don't generate anything for variable declarations. */
16204                 break;
16205         case OP_SDECL:
16206                 print_sdecl(state, ins, fp);
16207                 break;
16208         case OP_WRITE: 
16209         case OP_COPY:   
16210                 print_op_move(state, ins, fp);
16211                 break;
16212         case OP_LOAD:
16213                 print_op_load(state, ins, fp);
16214                 break;
16215         case OP_STORE:
16216                 print_op_store(state, ins, fp);
16217                 break;
16218         case OP_SMUL:
16219                 print_op_smul(state, ins, fp);
16220                 break;
16221         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16222         case OP_TEST:   print_op_test(state, ins, fp); break;
16223         case OP_JMP:
16224         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16225         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16226         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16227         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16228         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16229                 print_op_branch(state, ins, fp);
16230                 break;
16231         case OP_SET_EQ:      case OP_SET_NOTEQ:
16232         case OP_SET_SLESS:   case OP_SET_ULESS:
16233         case OP_SET_SMORE:   case OP_SET_UMORE:
16234         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16235         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16236                 print_op_set(state, ins, fp);
16237                 break;
16238         case OP_INB:  case OP_INW:  case OP_INL:
16239                 print_op_in(state, ins, fp); 
16240                 break;
16241         case OP_OUTB: case OP_OUTW: case OP_OUTL:
16242                 print_op_out(state, ins, fp); 
16243                 break;
16244         case OP_BSF:
16245         case OP_BSR:
16246                 print_op_bit_scan(state, ins, fp);
16247                 break;
16248         case OP_RDMSR:
16249                 after_lhs(state, ins);
16250                 fprintf(fp, "\trdmsr\n");
16251                 break;
16252         case OP_WRMSR:
16253                 fprintf(fp, "\twrmsr\n");
16254                 break;
16255         case OP_HLT:
16256                 fprintf(fp, "\thlt\n");
16257                 break;
16258         case OP_LABEL:
16259                 if (!ins->use) {
16260                         return;
16261                 }
16262                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16263                 break;
16264                 /* Ignore OP_PIECE */
16265         case OP_PIECE:
16266                 break;
16267                 /* Operations I am not yet certain how to handle */
16268         case OP_UMUL:
16269         case OP_SDIV: case OP_UDIV:
16270         case OP_SMOD: case OP_UMOD:
16271                 /* Operations that should never get here */
16272         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
16273         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
16274         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16275         default:
16276                 internal_error(state, ins, "unknown op: %d %s",
16277                         ins->op, tops(ins->op));
16278                 break;
16279         }
16280 }
16281
16282 static void print_instructions(struct compile_state *state)
16283 {
16284         struct triple *first, *ins;
16285         int print_location;
16286         int last_line;
16287         int last_col;
16288         const char *last_filename;
16289         FILE *fp;
16290         print_location = 1;
16291         last_line = -1;
16292         last_col  = -1;
16293         last_filename = 0;
16294         fp = state->output;
16295         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16296         first = RHS(state->main_function, 0);
16297         ins = first;
16298         do {
16299                 if (print_location &&
16300                         ((last_filename != ins->filename) ||
16301                                 (last_line != ins->line) ||
16302                                 (last_col  != ins->col))) {
16303                         fprintf(fp, "\t/* %s:%d */\n",
16304                                 ins->filename, ins->line);
16305                         last_filename = ins->filename;
16306                         last_line = ins->line;
16307                         last_col  = ins->col;
16308                 }
16309
16310                 print_instruction(state, ins, fp);
16311                 ins = ins->next;
16312         } while(ins != first);
16313         
16314 }
16315 static void generate_code(struct compile_state *state)
16316 {
16317         generate_local_labels(state);
16318         print_instructions(state);
16319         
16320 }
16321
16322 static void print_tokens(struct compile_state *state)
16323 {
16324         struct token *tk;
16325         tk = &state->token[0];
16326         do {
16327 #if 1
16328                 token(state, 0);
16329 #else
16330                 next_token(state, 0);
16331 #endif
16332                 loc(stdout, state, 0);
16333                 printf("%s <- `%s'\n",
16334                         tokens[tk->tok],
16335                         tk->ident ? tk->ident->name :
16336                         tk->str_len ? tk->val.str : "");
16337                 
16338         } while(tk->tok != TOK_EOF);
16339 }
16340
16341 static void compile(const char *filename, const char *ofilename, 
16342         int cpu, int debug, int opt, const char *label_prefix)
16343 {
16344         int i;
16345         struct compile_state state;
16346         memset(&state, 0, sizeof(state));
16347         state.file = 0;
16348         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16349                 memset(&state.token[i], 0, sizeof(state.token[i]));
16350                 state.token[i].tok = -1;
16351         }
16352         /* Remember the debug settings */
16353         state.cpu      = cpu;
16354         state.debug    = debug;
16355         state.optimize = opt;
16356         /* Remember the output filename */
16357         state.ofilename = ofilename;
16358         state.output    = fopen(state.ofilename, "w");
16359         if (!state.output) {
16360                 error(&state, 0, "Cannot open output file %s\n",
16361                         ofilename);
16362         }
16363         /* Remember the label prefix */
16364         state.label_prefix = label_prefix;
16365         /* Prep the preprocessor */
16366         state.if_depth = 0;
16367         state.if_value = 0;
16368         /* register the C keywords */
16369         register_keywords(&state);
16370         /* register the keywords the macro preprocessor knows */
16371         register_macro_keywords(&state);
16372         /* Memorize where some special keywords are. */
16373         state.i_continue = lookup(&state, "continue", 8);
16374         state.i_break    = lookup(&state, "break", 5);
16375         /* Enter the globl definition scope */
16376         start_scope(&state);
16377         register_builtins(&state);
16378         compile_file(&state, filename, 1);
16379 #if 0
16380         print_tokens(&state);
16381 #endif  
16382         decls(&state);
16383         /* Exit the global definition scope */
16384         end_scope(&state);
16385
16386         /* Now that basic compilation has happened 
16387          * optimize the intermediate code 
16388          */
16389         optimize(&state);
16390
16391         generate_code(&state);
16392         if (state.debug) {
16393                 fprintf(stderr, "done\n");
16394         }
16395 }
16396
16397 static void version(void)
16398 {
16399         printf("romcc " VERSION " released " RELEASE_DATE "\n");
16400 }
16401
16402 static void usage(void)
16403 {
16404         version();
16405         printf(
16406                 "Usage: romcc <source>.c\n"
16407                 "Compile a C source file without using ram\n"
16408         );
16409 }
16410
16411 static void arg_error(char *fmt, ...)
16412 {
16413         va_list args;
16414         va_start(args, fmt);
16415         vfprintf(stderr, fmt, args);
16416         va_end(args);
16417         usage();
16418         exit(1);
16419 }
16420
16421 int main(int argc, char **argv)
16422 {
16423         const char *filename;
16424         const char *ofilename;
16425         const char *label_prefix;
16426         int cpu;
16427         int last_argc;
16428         int debug;
16429         int optimize;
16430         cpu = CPU_DEFAULT;
16431         label_prefix = "";
16432         ofilename = "auto.inc";
16433         optimize = 0;
16434         debug = 0;
16435         last_argc = -1;
16436         while((argc > 1) && (argc != last_argc)) {
16437                 last_argc = argc;
16438                 if (strncmp(argv[1], "--debug=", 8) == 0) {
16439                         debug = atoi(argv[1] + 8);
16440                         argv++;
16441                         argc--;
16442                 }
16443                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16444                         label_prefix= argv[1] + 15;
16445                         argv++;
16446                         argc--;
16447                 }
16448                 else if ((strcmp(argv[1],"-O") == 0) ||
16449                         (strcmp(argv[1], "-O1") == 0)) {
16450                         optimize = 1;
16451                         argv++;
16452                         argc--;
16453                 }
16454                 else if (strcmp(argv[1],"-O2") == 0) {
16455                         optimize = 2;
16456                         argv++;
16457                         argc--;
16458                 }
16459                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16460                         ofilename = argv[2];
16461                         argv += 2;
16462                         argc -= 2;
16463                 }
16464                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16465                         cpu = arch_encode_cpu(argv[1] + 6);
16466                         if (cpu == BAD_CPU) {
16467                                 arg_error("Invalid cpu specified: %s\n",
16468                                         argv[1] + 6);
16469                         }
16470                         argv++;
16471                         argc--;
16472                 }
16473         }
16474         if (argc != 2) {
16475                 arg_error("Wrong argument count %d\n", argc);
16476         }
16477         filename = argv[1];
16478         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
16479
16480         return 0;
16481 }