- Fix ? expressions previously they were reversed.
[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 X86_4_8BIT_GPRS 1
19
20 #warning "FIXME static constant variables"
21 #warning "FIXME enable pointers"
22 #warning "FIXME enable string constants"
23
24 /*  Control flow graph of a loop without goto.
25  * 
26  *        AAA
27  *   +---/
28  *  /
29  * / +--->CCC
30  * | |    / \
31  * | |  DDD EEE    break;
32  * | |    \    \
33  * | |    FFF   \
34  *  \|    / \    \
35  *   |\ GGG HHH   |   continue;
36  *   | \  \   |   |
37  *   |  \ III |  /
38  *   |   \ | /  / 
39  *   |    vvv  /  
40  *   +----BBB /   
41  *         | /
42  *         vv
43  *        JJJ
44  *
45  * 
46  *             AAA
47  *     +-----+  |  +----+
48  *     |      \ | /     |
49  *     |       BBB  +-+ |
50  *     |       / \ /  | |
51  *     |     CCC JJJ / /
52  *     |     / \    / / 
53  *     |   DDD EEE / /  
54  *     |    |   +-/ /
55  *     |   FFF     /    
56  *     |   / \    /     
57  *     | GGG HHH /      
58  *     |  |   +-/
59  *     | III
60  *     +--+ 
61  *
62  * 
63  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
65  *
66  *
67  * [] == DFlocal(X) U DF(X)
68  * () == DFup(X)
69  *
70  * Dominator graph of the same nodes.
71  *
72  *           AAA     AAA: [ ] ()
73  *          /   \
74  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
75  *         |
76  *        CCC        CCC: [ ] ( BBB, JJJ )
77  *        / \
78  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
79  *      |
80  *     FFF           FFF: [ ] ( BBB )
81  *     / \         
82  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
83  *   |
84  *  III              III: [ BBB ] ()
85  *
86  *
87  * BBB and JJJ are definitely the dominance frontier.
88  * Where do I place phi functions and how do I make that decision.
89  *   
90  */
91 static void die(char *fmt, ...)
92 {
93         va_list args;
94
95         va_start(args, fmt);
96         vfprintf(stderr, fmt, args);
97         va_end(args);
98         fflush(stdout);
99         fflush(stderr);
100         exit(1);
101 }
102
103 #define MALLOC_STRONG_DEBUG
104 static void *xmalloc(size_t size, const char *name)
105 {
106         void *buf;
107         buf = malloc(size);
108         if (!buf) {
109                 die("Cannot malloc %ld bytes to hold %s: %s\n",
110                         size + 0UL, name, strerror(errno));
111         }
112         return buf;
113 }
114
115 static void *xcmalloc(size_t size, const char *name)
116 {
117         void *buf;
118         buf = xmalloc(size, name);
119         memset(buf, 0, size);
120         return buf;
121 }
122
123 static void xfree(const void *ptr)
124 {
125         free((void *)ptr);
126 }
127
128 static char *xstrdup(const char *str)
129 {
130         char *new;
131         int len;
132         len = strlen(str);
133         new = xmalloc(len + 1, "xstrdup string");
134         memcpy(new, str, len);
135         new[len] = '\0';
136         return new;
137 }
138
139 static void xchdir(const char *path)
140 {
141         if (chdir(path) != 0) {
142                 die("chdir to %s failed: %s\n",
143                         path, strerror(errno));
144         }
145 }
146
147 static int exists(const char *dirname, const char *filename)
148 {
149         int does_exist = 1;
150         xchdir(dirname);
151         if (access(filename, O_RDONLY) < 0) {
152                 if ((errno != EACCES) && (errno != EROFS)) {
153                         does_exist = 0;
154                 }
155         }
156         return does_exist;
157 }
158
159
160 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
161 {
162         int fd;
163         char *buf;
164         off_t size, progress;
165         ssize_t result;
166         struct stat stats;
167         
168         if (!filename) {
169                 *r_size = 0;
170                 return 0;
171         }
172         xchdir(dirname);
173         fd = open(filename, O_RDONLY);
174         if (fd < 0) {
175                 die("Cannot open '%s' : %s\n",
176                         filename, strerror(errno));
177         }
178         result = fstat(fd, &stats);
179         if (result < 0) {
180                 die("Cannot stat: %s: %s\n",
181                         filename, strerror(errno));
182         }
183         size = stats.st_size;
184         *r_size = size +1;
185         buf = xmalloc(size +2, filename);
186         buf[size] = '\n'; /* Make certain the file is newline terminated */
187         buf[size+1] = '\0'; /* Null terminate the file for good measure */
188         progress = 0;
189         while(progress < size) {
190                 result = read(fd, buf + progress, size - progress);
191                 if (result < 0) {
192                         if ((errno == EINTR) || (errno == EAGAIN))
193                                 continue;
194                         die("read on %s of %ld bytes failed: %s\n",
195                                 filename, (size - progress)+ 0UL, strerror(errno));
196                 }
197                 progress += result;
198         }
199         result = close(fd);
200         if (result < 0) {
201                 die("Close of %s failed: %s\n",
202                         filename, strerror(errno));
203         }
204         return buf;
205 }
206
207 /* Long on the destination platform */
208 typedef unsigned long ulong_t;
209 typedef long long_t;
210
211 struct file_state {
212         struct file_state *prev;
213         const char *basename;
214         char *dirname;
215         char *buf;
216         off_t size;
217         char *pos;
218         int line;
219         char *line_start;
220 };
221 struct hash_entry;
222 struct token {
223         int tok;
224         struct hash_entry *ident;
225         int str_len;
226         union {
227                 ulong_t integer;
228                 const char *str;
229         } val;
230 };
231
232 /* I have two classes of types:
233  * Operational types.
234  * Logical types.  (The type the C standard says the operation is of)
235  *
236  * The operational types are:
237  * chars
238  * shorts
239  * ints
240  * longs
241  *
242  * floats
243  * doubles
244  * long doubles
245  *
246  * pointer
247  */
248
249
250 /* Machine model.
251  * No memory is useable by the compiler.
252  * There is no floating point support.
253  * All operations take place in general purpose registers.
254  * There is one type of general purpose register.
255  * Unsigned longs are stored in that general purpose register.
256  */
257
258 /* Operations on general purpose registers.
259  */
260
261 #define OP_SMUL       0
262 #define OP_UMUL       1
263 #define OP_SDIV       2
264 #define OP_UDIV       3
265 #define OP_SMOD       4
266 #define OP_UMOD       5
267 #define OP_ADD        6
268 #define OP_SUB        7
269 #define OP_SL         8
270 #define OP_USR        9
271 #define OP_SSR       10 
272 #define OP_AND       11 
273 #define OP_XOR       12
274 #define OP_OR        13
275 #define OP_POS       14 /* Dummy positive operator don't use it */
276 #define OP_NEG       15
277 #define OP_INVERT    16
278                      
279 #define OP_EQ        20
280 #define OP_NOTEQ     21
281 #define OP_SLESS     22
282 #define OP_ULESS     23
283 #define OP_SMORE     24
284 #define OP_UMORE     25
285 #define OP_SLESSEQ   26
286 #define OP_ULESSEQ   27
287 #define OP_SMOREEQ   28
288 #define OP_UMOREEQ   29
289                      
290 #define OP_LFALSE    30  /* Test if the expression is logically false */
291 #define OP_LTRUE     31  /* Test if the expression is logcially true */
292
293 #define OP_LOAD      32
294 #define OP_STORE     33
295
296 #define OP_NOOP      34
297
298 #define OP_MIN_CONST 50
299 #define OP_MAX_CONST 59
300 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
301 #define OP_INTCONST  50
302 #define OP_BLOBCONST 51
303 /* For OP_BLOBCONST ->type holds the layout and size
304  * information.  u.blob holds a pointer to the raw binary
305  * data for the constant initializer.
306  */
307 #define OP_ADDRCONST 52
308 /* For OP_ADDRCONST ->type holds the type.
309  * RHS(0) holds the reference to the static variable.
310  * ->u.cval holds an offset from that value.
311  */
312
313 #define OP_WRITE     60 
314 /* OP_WRITE moves one pseudo register to another.
315  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
316  * RHS(0) holds the psuedo to move.
317  */
318
319 #define OP_READ      61
320 /* OP_READ reads the value of a variable and makes
321  * it available for the pseudo operation.
322  * Useful for things like def-use chains.
323  * RHS(0) holds points to the triple to read from.
324  */
325 #define OP_COPY      62
326 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
327  */
328 #define OP_PIECE     63
329 /* OP_PIECE returns one piece of a instruction that returns a structure.
330  * RHS(0) is the instruction
331  * u.cval is the LHS piece of the instruction to return.
332  */
333
334 #define OP_DEREF     65
335 /* OP_DEREF generates an lvalue from a pointer.
336  * RHS(0) holds the pointer value.
337  * OP_DEREF serves as a place holder to indicate all necessary
338  * checks have been done to indicate a value is an lvalue.
339  */
340 #define OP_DOT       66
341 /* OP_DOT references a submember of a structure lvalue.
342  * RHS(0) holds the lvalue.
343  * ->u.field holds the name of the field we want.
344  *
345  * Not seen outside of expressions.
346  */
347 #define OP_VAL       67
348 /* OP_VAL returns the value of a subexpression of the current expression.
349  * Useful for operators that have side effects.
350  * RHS(0) holds the expression.
351  * MISC(0) holds the subexpression of RHS(0) that is the
352  * value of the expression.
353  *
354  * Not seen outside of expressions.
355  */
356 #define OP_LAND      68
357 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
358  * Not seen outside of expressions.
359  */
360 #define OP_LOR       69
361 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
362  * Not seen outside of expressions.
363  */
364 #define OP_COND      70
365 /* OP_CODE performas a C ? : operation. 
366  * RHS(0) holds the test.
367  * RHS(1) holds the expression to evaluate if the test returns true.
368  * RHS(2) holds the expression to evaluate if the test returns false.
369  * Not seen outside of expressions.
370  */
371 #define OP_COMMA     71
372 /* OP_COMMA performacs a C comma operation.
373  * That is RHS(0) is evaluated, then RHS(1)
374  * and the value of RHS(1) is returned.
375  * Not seen outside of expressions.
376  */
377
378 #define OP_CALL      72
379 /* OP_CALL performs a procedure call. 
380  * MISC(0) holds a pointer to the OP_LIST of a function
381  * RHS(x) holds argument x of a function
382  * 
383  * Currently not seen outside of expressions.
384  */
385 #define OP_VAL_VEC   74
386 /* OP_VAL_VEC is an array of triples that are either variable
387  * or values for a structure or an array.
388  * RHS(x) holds element x of the vector.
389  * triple->type->elements holds the size of the vector.
390  */
391
392 /* statements */
393 #define OP_LIST      80
394 /* OP_LIST Holds a list of statements, and a result value.
395  * RHS(0) holds the list of statements.
396  * MISC(0) holds the value of the statements.
397  */
398
399 #define OP_BRANCH    81 /* branch */
400 /* For branch instructions
401  * TARG(0) holds the branch target.
402  * RHS(0) if present holds the branch condition.
403  * ->next holds where to branch to if the branch is not taken.
404  * The branch target can only be a decl...
405  */
406
407 #define OP_LABEL     83
408 /* OP_LABEL is a triple that establishes an target for branches.
409  * ->use is the list of all branches that use this label.
410  */
411
412 #define OP_ADECL     84 
413 /* OP_DECL is a triple that establishes an lvalue for assignments.
414  * ->use is a list of statements that use the variable.
415  */
416
417 #define OP_SDECL     85
418 /* OP_VAR is a triple that establishes a variable of static
419  * storage duration.
420  * ->use is a list of statements that use the variable.
421  * MISC(0) holds the initializer expression.
422  */
423
424
425 #define OP_PHI       86
426 /* OP_PHI is a triple used in SSA form code.  
427  * It is used when multiple code paths merge and a variable needs
428  * a single assignment from any of those code paths.
429  * The operation is a cross between OP_DECL and OP_WRITE, which
430  * is what OP_PHI is geneared from.
431  * 
432  * RHS(x) points to the value from code path x
433  * The number of RHS entries is the number of control paths into the block
434  * in which OP_PHI resides.  The elements of the array point to point
435  * to the variables OP_PHI is derived from.
436  *
437  * MISC(0) holds a pointer to the orginal OP_DECL node.
438  */
439
440 /* Architecture specific instructions */
441 #define OP_CMP         100
442 #define OP_TEST        101
443 #define OP_SET_EQ      102
444 #define OP_SET_NOTEQ   103
445 #define OP_SET_SLESS   104
446 #define OP_SET_ULESS   105
447 #define OP_SET_SMORE   106
448 #define OP_SET_UMORE   107
449 #define OP_SET_SLESSEQ 108
450 #define OP_SET_ULESSEQ 109
451 #define OP_SET_SMOREEQ 110
452 #define OP_SET_UMOREEQ 111
453
454 #define OP_JMP         112
455 #define OP_JMP_EQ      113
456 #define OP_JMP_NOTEQ   114
457 #define OP_JMP_SLESS   115
458 #define OP_JMP_ULESS   116
459 #define OP_JMP_SMORE   117
460 #define OP_JMP_UMORE   118
461 #define OP_JMP_SLESSEQ 119
462 #define OP_JMP_ULESSEQ 120
463 #define OP_JMP_SMOREEQ 121
464 #define OP_JMP_UMOREEQ 122
465
466 /* Builtin operators that it is just simpler to use the compiler for */
467 #define OP_INB         130
468 #define OP_INW         131
469 #define OP_INL         132
470 #define OP_OUTB        133
471 #define OP_OUTW        134
472 #define OP_OUTL        135
473 #define OP_BSF         136
474 #define OP_BSR         137
475 #define OP_RDMSR       138
476 #define OP_WRMSR       139
477 #define OP_HLT         140
478
479 struct op_info {
480         const char *name;
481         unsigned flags;
482 #define PURE   1
483 #define IMPURE 2
484 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
485 #define DEF    4
486         unsigned char lhs, rhs, misc, targ;
487 };
488
489 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
490         .name = (NAME), \
491         .flags = (FLAGS), \
492         .lhs = (LHS), \
493         .rhs = (RHS), \
494         .misc = (MISC), \
495         .targ = (TARG), \
496          }
497 static const struct op_info table_ops[] = {
498 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF, "smul"),
499 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF, "umul"),
500 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF, "sdiv"),
501 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF, "udiv"),
502 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF, "smod"),
503 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF, "umod"),
504 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF, "add"),
505 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF, "sub"),
506 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF, "sl"),
507 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF, "usr"),
508 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF, "ssr"),
509 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF, "and"),
510 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF, "xor"),
511 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF, "or"),
512 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF, "pos"),
513 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF, "neg"),
514 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF, "invert"),
515
516 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF, "eq"),
517 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF, "noteq"),
518 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF, "sless"),
519 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF, "uless"),
520 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF, "smore"),
521 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF, "umore"),
522 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "slesseq"),
523 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "ulesseq"),
524 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "smoreeq"),
525 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "umoreeq"),
526 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF, "lfalse"),
527 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF, "ltrue"),
528
529 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF, "load"),
530 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE, "store"),
531
532 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE, "noop"),
533
534 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE, "intconst"),
535 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
536 [OP_ADDRCONST  ] = OP( 0,  1, 0, 0, PURE, "addrconst"),
537
538 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE, "write"),
539 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF, "read"),
540 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF, "copy"),
541 [OP_PIECE      ] = OP( 0,  1, 0, 0, PURE | DEF, "piece"),
542 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF, "deref"), 
543 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF, "dot"),
544
545 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF, "val"),
546 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF, "land"),
547 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF, "lor"),
548 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF, "cond"),
549 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF, "comma"),
550 /* Call is special most it can stand in for anything so it depends on context */
551 [OP_CALL       ] = OP(-1, -1, 1, 0, 0, "call"),
552 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
553 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0, "valvec"),
554
555 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
556 /* The number of targets for OP_BRANCH depends on context */
557 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE, "branch"),
558 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE, "label"),
559 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE, "adecl"),
560 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE, "sdecl"),
561 /* The number of RHS elements of OP_PHI depend upon context */
562 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF, "phi"),
563
564 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF, "cmp"),
565 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF, "test"),
566 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF, "set_eq"),
567 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_noteq"),
568 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_sless"),
569 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_uless"),
570 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_smore"),
571 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_umore"),
572 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_slesseq"),
573 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_ulesseq"),
574 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_smoreq"),
575 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_umoreq"),
576 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE, "jmp"),
577 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE, "jmp_eq"),
578 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE, "jmp_noteq"),
579 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE, "jmp_sless"),
580 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE, "jmp_uless"),
581 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE, "jmp_smore"),
582 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE, "jmp_umore"),
583 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE, "jmp_slesseq"),
584 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE, "jmp_ulesseq"),
585 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE, "jmp_smoreq"),
586 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE, "jmp_umoreq"),
587
588 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inb"),
589 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inw"),
590 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inl"),
591 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE, "__outb"),
592 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE, "__outw"),
593 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE, "__outl"),
594 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF, "__bsf"),
595 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF, "__bsr"),
596 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE, "__rdmsr"),
597 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE, "__wrmsr"),
598 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE, "__hlt"),
599 };
600 #undef OP
601 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
602
603 static const char *tops(int index) 
604 {
605         static const char unknown[] = "unknown op";
606         if (index < 0) {
607                 return unknown;
608         }
609         if (index > OP_MAX) {
610                 return unknown;
611         }
612         return table_ops[index].name;
613 }
614
615 struct triple;
616 struct block;
617 struct triple_set {
618         struct triple_set *next;
619         struct triple *member;
620 };
621
622 #define MAX_LHS  15
623 #define MAX_RHS  15
624 #define MAX_MISC 15
625 #define MAX_TARG 15
626
627 struct triple {
628         struct triple *next, *prev;
629         struct triple_set *use;
630         struct type *type;
631         short op;
632         unsigned short sizes;
633 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
634 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
635 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
636 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
637 #define TRIPLE_SIZE(SIZES) \
638         ((((SIZES) >> 0) & 0x0f) + \
639         (((SIZES) >>  4) & 0x0f) + \
640         (((SIZES) >>  8) & 0x0f) + \
641         (((SIZES) >> 12) & 0x0f))
642 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
643         ((((LHS) & 0x0f) <<  0) | \
644         (((RHS) & 0x0f)  <<  4) | \
645         (((MISC) & 0x0f) <<  8) | \
646         (((TARG) & 0x0f) << 12))
647 #define TRIPLE_LHS_OFF(SIZES)  (0)
648 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
649 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
650 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
651 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
652 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
653 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
654 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
655         unsigned id; /* A scratch value and finally the register */
656 #define TRIPLE_FLAG_FLATTENED 1
657         const char *filename;
658         int line;
659         int col;
660         union {
661                 ulong_t cval;
662                 struct block  *block;
663                 void *blob;
664                 struct hash_entry *field;
665         } u;
666         struct triple *param[2];
667 };
668
669 struct block_set {
670         struct block_set *next;
671         struct block *member;
672 };
673 struct block {
674         struct block *work_next;
675         struct block *left, *right;
676         struct triple *first, *last;
677         int users;
678         struct block_set *use;
679         struct block_set *idominates;
680         struct block_set *domfrontier;
681         struct block *idom;
682         struct block_set *ipdominates;
683         struct block_set *ipdomfrontier;
684         struct block *ipdom;
685         int vertex;
686         
687 };
688
689 struct symbol {
690         struct symbol *next;
691         struct hash_entry *ident;
692         struct triple *def;
693         struct type *type;
694         int scope_depth;
695 };
696
697 struct macro {
698         struct hash_entry *ident;
699         char *buf;
700         int buf_len;
701 };
702
703 struct hash_entry {
704         struct hash_entry *next;
705         const char *name;
706         int name_len;
707         int tok;
708         struct macro *sym_define;
709         struct symbol *sym_label;
710         struct symbol *sym_struct;
711         struct symbol *sym_ident;
712 };
713
714 #define HASH_TABLE_SIZE 2048
715
716 struct compile_state {
717         struct triple *vars;
718         struct file_state *file;
719         struct token token[4];
720         struct hash_entry *hash_table[HASH_TABLE_SIZE];
721         struct hash_entry *i_continue;
722         struct hash_entry *i_break;
723         int scope_depth;
724         int if_depth, if_value;
725         int macro_line;
726         struct file_state *macro_file;
727         struct triple *main_function;
728         struct block *first_block, *last_block;
729         int last_vertex;
730         int debug;
731         int optimize;
732 };
733
734 /* visibility global/local */
735 /* static/auto duration */
736 /* typedef, register, inline */
737 #define STOR_SHIFT         0
738 #define STOR_MASK     0x000f
739 /* Visibility */
740 #define STOR_GLOBAL   0x0001
741 /* Duration */
742 #define STOR_PERM     0x0002
743 /* Storage specifiers */
744 #define STOR_AUTO     0x0000
745 #define STOR_STATIC   0x0002
746 #define STOR_EXTERN   0x0003
747 #define STOR_REGISTER 0x0004
748 #define STOR_TYPEDEF  0x0008
749 #define STOR_INLINE   0x000c
750
751 #define QUAL_SHIFT         4
752 #define QUAL_MASK     0x0070
753 #define QUAL_NONE     0x0000
754 #define QUAL_CONST    0x0010
755 #define QUAL_VOLATILE 0x0020
756 #define QUAL_RESTRICT 0x0040
757
758 #define TYPE_SHIFT         8
759 #define TYPE_MASK     0x1f00
760 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
761 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
762 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
763 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
764 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
765 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
766 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
767 #define TYPE_DEFAULT  0x0000
768 #define TYPE_VOID     0x0100
769 #define TYPE_CHAR     0x0200
770 #define TYPE_UCHAR    0x0300
771 #define TYPE_SHORT    0x0400
772 #define TYPE_USHORT   0x0500
773 #define TYPE_INT      0x0600
774 #define TYPE_UINT     0x0700
775 #define TYPE_LONG     0x0800
776 #define TYPE_ULONG    0x0900
777 #define TYPE_LLONG    0x0a00 /* long long */
778 #define TYPE_ULLONG   0x0b00
779 #define TYPE_FLOAT    0x0c00
780 #define TYPE_DOUBLE   0x0d00
781 #define TYPE_LDOUBLE  0x0e00 /* long double */
782 #define TYPE_STRUCT   0x1000
783 #define TYPE_ENUM     0x1100
784 #define TYPE_POINTER  0x1200 
785 /* For TYPE_POINTER:
786  * type->left holds the type pointed to.
787  */
788 #define TYPE_FUNCTION 0x1300 
789 /* For TYPE_FUNCTION:
790  * type->left holds the return type.
791  * type->right holds the...
792  */
793 #define TYPE_PRODUCT  0x1400
794 /* TYPE_PRODUCT is a basic building block when defining structures
795  * type->left holds the type that appears first in memory.
796  * type->right holds the type that appears next in memory.
797  */
798 #define TYPE_OVERLAP  0x1500
799 /* TYPE_OVERLAP is a basic building block when defining unions
800  * type->left and type->right holds to types that overlap
801  * each other in memory.
802  */
803 #define TYPE_ARRAY    0x1600
804 /* TYPE_ARRAY is a basic building block when definitng arrays.
805  * type->left holds the type we are an array of.
806  * type-> holds the number of elements.
807  */
808
809 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
810
811 struct type {
812         unsigned int type;
813         struct type *left, *right;
814         ulong_t elements;
815         struct hash_entry *field_ident;
816         struct hash_entry *type_ident;
817 };
818
819 #define MAX_REGISTERS      75
820 #define MAX_REG_EQUIVS     16
821 #define MAX_REGC           12
822 #define REG_UNSET          0
823
824 /* Provision for 8 register classes */
825 #define REGC_MASK ((1 << MAX_REGC) - 1)
826 #define ID_REG_CLASSES(ID)      ((ID) & REGC_MASK)
827 #define ID_REG(ID)              ((ID) >> MAX_REGC)
828 #define MK_REG_ID(REG, CLASSES) (((REG) << MAX_REGC) | ((CLASSES) & REGC_MASK))
829
830 static unsigned alloc_virtual_reg(void)
831 {
832         static unsigned virtual_reg = MAX_REGISTERS;
833         virtual_reg += 1;
834         return virtual_reg;
835 }
836
837 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
838 static void arch_reg_equivs(
839         struct compile_state *state, unsigned *equiv, int reg);
840 static int arch_select_free_register(
841         struct compile_state *state, char *used, int classes);
842 static unsigned arch_regc_size(struct compile_state *state, int class);
843 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
844 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
845 static const char *arch_reg_str(int reg);
846
847 #define DEBUG_ABORT_ON_ERROR    0x0001
848 #define DEBUG_INTERMEDIATE_CODE 0x0002
849 #define DEBUG_CONTROL_FLOW      0x0004
850 #define DEBUG_BASIC_BLOCKS      0x0008
851 #define DEBUG_FDOMINATORS       0x0010
852 #define DEBUG_RDOMINATORS       0x0020
853 #define DEBUG_TRIPLES           0x0040
854 #define DEBUG_INTERFERENCE      0x0080
855 #define DEBUG_ARCH_CODE         0x0100
856 #define DEBUG_CODE_ELIMINATION  0x0200
857
858 #define GLOBAL_SCOPE_DEPTH 1
859
860 static void compile_file(struct compile_state *old_state, char *filename, int local);
861
862 static int get_col(struct file_state *file)
863 {
864         int col;
865         char *ptr, *end;
866         ptr = file->line_start;
867         end = file->pos;
868         for(col = 0; ptr < end; ptr++) {
869                 if (*ptr != '\t') {
870                         col++;
871                 } 
872                 else {
873                         col = (col & ~7) + 8;
874                 }
875         }
876         return col;
877 }
878
879 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
880 {
881         int col;
882         if (triple) {
883                 fprintf(fp, "%s:%d.%d: ", 
884                         triple->filename, triple->line, triple->col);
885                 return;
886         }
887         if (!state->file) {
888                 return;
889         }
890         col = get_col(state->file);
891         fprintf(fp, "%s:%d.%d: ", 
892                 state->file->basename, state->file->line, col);
893 }
894
895 static void __internal_error(struct compile_state *state, struct triple *ptr, 
896         char *fmt, ...)
897 {
898         va_list args;
899         va_start(args, fmt);
900         loc(stderr, state, ptr);
901         fprintf(stderr, "Internal compiler error: ");
902         vfprintf(stderr, fmt, args);
903         fprintf(stderr, "\n");
904         va_end(args);
905         abort();
906 }
907
908
909 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
910         char *fmt, ...)
911 {
912         va_list args;
913         va_start(args, fmt);
914         loc(stderr, state, ptr);
915         fprintf(stderr, "Internal compiler warning: ");
916         vfprintf(stderr, fmt, args);
917         fprintf(stderr, "\n");
918         va_end(args);
919 }
920
921
922
923 static void __error(struct compile_state *state, struct triple *ptr, 
924         char *fmt, ...)
925 {
926         va_list args;
927         va_start(args, fmt);
928         loc(stderr, state, ptr);
929         vfprintf(stderr, fmt, args);
930         va_end(args);
931         fprintf(stderr, "\n");
932         if (state->debug & DEBUG_ABORT_ON_ERROR) {
933                 abort();
934         }
935         exit(1);
936 }
937
938 static void __warning(struct compile_state *state, struct triple *ptr, 
939         char *fmt, ...)
940 {
941         va_list args;
942         va_start(args, fmt);
943         loc(stderr, state, ptr);
944         fprintf(stderr, "warning: "); 
945         vfprintf(stderr, fmt, args);
946         fprintf(stderr, "\n");
947         va_end(args);
948 }
949
950 #if DEBUG_ERROR_MESSAGES 
951 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
952 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
953 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
954 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
955 #else
956 #  define internal_error __internal_error
957 #  define internal_warning __internal_warning
958 #  define error __error
959 #  define warning __warning
960 #endif
961 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
962
963
964 static void valid_op(struct compile_state *state, int op)
965 {
966         char *fmt = "invalid op: %d";
967         if (op >= OP_MAX) {
968                 internal_error(state, 0, fmt, op);
969         }
970         if (op < 0) {
971                 internal_error(state, 0, fmt, op);
972         }
973 }
974
975 static void valid_ins(struct compile_state *state, struct triple *ptr)
976 {
977         valid_op(state, ptr->op);
978 }
979
980 static void process_trigraphs(struct compile_state *state)
981 {
982         char *src, *dest, *end;
983         struct file_state *file;
984         file = state->file;
985         src = dest = file->buf;
986         end = file->buf + file->size;
987         while((end - src) >= 3) {
988                 if ((src[0] == '?') && (src[1] == '?')) {
989                         int c = -1;
990                         switch(src[2]) {
991                         case '=': c = '#'; break;
992                         case '/': c = '\\'; break;
993                         case '\'': c = '^'; break;
994                         case '(': c = '['; break;
995                         case ')': c = ']'; break;
996                         case '!': c = '!'; break;
997                         case '<': c = '{'; break;
998                         case '>': c = '}'; break;
999                         case '-': c = '~'; break;
1000                         }
1001                         if (c != -1) {
1002                                 *dest++ = c;
1003                                 src += 3;
1004                         }
1005                         else {
1006                                 *dest++ = *src++;
1007                         }
1008                 }
1009                 else {
1010                         *dest++ = *src++;
1011                 }
1012         }
1013         while(src != end) {
1014                 *dest++ = *src++;
1015         }
1016         file->size = dest - file->buf;
1017 }
1018
1019 static void splice_lines(struct compile_state *state)
1020 {
1021         char *src, *dest, *end;
1022         struct file_state *file;
1023         file = state->file;
1024         src = dest = file->buf;
1025         end = file->buf + file->size;
1026         while((end - src) >= 2) {
1027                 if ((src[0] == '\\') && (src[1] == '\n')) {
1028                         src += 2;
1029                 }
1030                 else {
1031                         *dest++ = *src++;
1032                 }
1033         }
1034         while(src != end) {
1035                 *dest++ = *src++;
1036         }
1037         file->size = dest - file->buf;
1038 }
1039
1040 static struct type void_type;
1041 static void use_triple(struct triple *used, struct triple *user)
1042 {
1043         struct triple_set **ptr, *new;
1044         if (!used)
1045                 return;
1046         if (!user)
1047                 return;
1048         ptr = &used->use;
1049         while(*ptr) {
1050                 if ((*ptr)->member == user) {
1051                         return;
1052                 }
1053                 ptr = &(*ptr)->next;
1054         }
1055         /* Append new to the head of the list, 
1056          * copy_func and rename_block_variables
1057          * depends on this.
1058          */
1059         new = xcmalloc(sizeof(*new), "triple_set");
1060         new->member = user;
1061         new->next   = used->use;
1062         used->use   = new;
1063 }
1064
1065 static void unuse_triple(struct triple *used, struct triple *unuser)
1066 {
1067         struct triple_set *use, **ptr;
1068         ptr = &used->use;
1069         while(*ptr) {
1070                 use = *ptr;
1071                 if (use->member == unuser) {
1072                         *ptr = use->next;
1073                         xfree(use);
1074                 }
1075                 else {
1076                         ptr = &use->next;
1077                 }
1078         }
1079 }
1080
1081 static void push_triple(struct triple *used, struct triple *user)
1082 {
1083         struct triple_set *new;
1084         if (!used)
1085                 return;
1086         if (!user)
1087                 return;
1088         /* Append new to the head of the list,
1089          * it's the only sensible behavoir for a stack.
1090          */
1091         new = xcmalloc(sizeof(*new), "triple_set");
1092         new->member = user;
1093         new->next   = used->use;
1094         used->use   = new;
1095 }
1096
1097 static void pop_triple(struct triple *used, struct triple *unuser)
1098 {
1099         struct triple_set *use, **ptr;
1100         ptr = &used->use;
1101         while(*ptr) {
1102                 use = *ptr;
1103                 if (use->member == unuser) {
1104                         *ptr = use->next;
1105                         xfree(use);
1106                         /* Only free one occurance from the stack */
1107                         return;
1108                 }
1109                 else {
1110                         ptr = &use->next;
1111                 }
1112         }
1113 }
1114
1115
1116 /* The zero triple is used as a place holder when we are removing pointers
1117  * from a triple.  Having allows certain sanity checks to pass even
1118  * when the original triple that was pointed to is gone.
1119  */
1120 static struct triple zero_triple = {
1121         .next     = &zero_triple,
1122         .prev     = &zero_triple,
1123         .use      = 0,
1124         .op       = OP_INTCONST,
1125         .sizes    = TRIPLE_SIZES(0, 0, 0, 0),
1126         .id       = -1, /* An invalid id */
1127         .u = { .cval   = 0, },
1128         .filename = __FILE__,
1129         .line     = __LINE__,
1130         .col      = 0,
1131         .param { [0] = 0, [1] = 0, },
1132 };
1133
1134
1135 static unsigned short triple_sizes(struct compile_state *state,
1136         int op, struct type *type, int rhs_wanted)
1137 {
1138         int lhs, rhs, misc, targ;
1139         valid_op(state, op);
1140         lhs = table_ops[op].lhs;
1141         rhs = table_ops[op].rhs;
1142         misc = table_ops[op].misc;
1143         targ = table_ops[op].targ;
1144         
1145         
1146         if (op == OP_CALL) {
1147                 struct type *param;
1148                 rhs = 0;
1149                 param = type->right;
1150                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1151                         rhs++;
1152                         param = param->right;
1153                 }
1154                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1155                         rhs++;
1156                 }
1157                 lhs = 0;
1158                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1159                         lhs = type->left->elements;
1160                 }
1161         }
1162         else if (op == OP_VAL_VEC) {
1163                 rhs = type->elements;
1164         }
1165         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1166                 rhs = rhs_wanted;
1167         }
1168         if ((rhs < 0) || (rhs > MAX_RHS)) {
1169                 internal_error(state, 0, "bad rhs");
1170         }
1171         if ((lhs < 0) || (lhs > MAX_LHS)) {
1172                 internal_error(state, 0, "bad lhs");
1173         }
1174         if ((misc < 0) || (misc > MAX_MISC)) {
1175                 internal_error(state, 0, "bad misc");
1176         }
1177         if ((targ < 0) || (targ > MAX_TARG)) {
1178                 internal_error(state, 0, "bad targs");
1179         }
1180         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1181 }
1182
1183 static struct triple *alloc_triple(struct compile_state *state, 
1184         int op, struct type *type, int rhs,
1185         const char *filename, int line, int col)
1186 {
1187         size_t size, sizes, extra_count, min_count;
1188         struct triple *ret;
1189         sizes = triple_sizes(state, op, type, rhs);
1190
1191         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1192         extra_count = TRIPLE_SIZE(sizes);
1193         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1194
1195         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1196         ret = xcmalloc(size, "tripple");
1197         ret->op       = op;
1198         ret->sizes    = sizes;
1199         ret->type     = type;
1200         ret->next     = ret;
1201         ret->prev     = ret;
1202         ret->filename = filename;
1203         ret->line     = line;
1204         ret->col      = col;
1205         return ret;
1206 }
1207
1208 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1209 {
1210         struct triple *dup;
1211         int src_rhs;
1212         src_rhs = TRIPLE_RHS(src->sizes);
1213         dup = alloc_triple(state, src->op, src->type, src_rhs,
1214                 src->filename, src->line, src->col);
1215         memcpy(dup, src, sizeof(*src));
1216         memcpy(dup->param, src->param, src_rhs * sizeof(src->param[0]));
1217         return dup;
1218 }
1219
1220 static struct triple *new_triple(struct compile_state *state, 
1221         int op, struct type *type, int rhs)
1222 {
1223         struct triple *ret;
1224         const char *filename;
1225         int line, col;
1226         filename = 0;
1227         line = 0;
1228         col  = 0;
1229         if (state->file) {
1230                 filename = state->file->basename;
1231                 line     = state->file->line;
1232                 col      = get_col(state->file);
1233         }
1234         ret = alloc_triple(state, op, type, rhs,
1235                 filename, line, col);
1236         return ret;
1237 }
1238
1239 static struct triple *build_triple(struct compile_state *state, 
1240         int op, struct type *type, struct triple *left, struct triple *right,
1241         const char *filename, int line, int col)
1242 {
1243         struct triple *ret;
1244         size_t count;
1245         ret = alloc_triple(state, op, type, -1, filename, line, col);
1246         count = TRIPLE_SIZE(ret->sizes);
1247         if (count > 0) {
1248                 ret->param[0] = left;
1249         }
1250         if (count > 1) {
1251                 ret->param[1] = right;
1252         }
1253         return ret;
1254 }
1255
1256 static struct triple *triple(struct compile_state *state, 
1257         int op, struct type *type, struct triple *left, struct triple *right)
1258 {
1259         struct triple *ret;
1260         size_t count;
1261         ret = new_triple(state, op, type, -1);
1262         count = TRIPLE_SIZE(ret->sizes);
1263         if (count >= 1) {
1264                 ret->param[0] = left;
1265         }
1266         if (count >= 2) {
1267                 ret->param[1] = right;
1268         }
1269         return ret;
1270 }
1271
1272 static struct triple *branch(struct compile_state *state, 
1273         struct triple *targ, struct triple *test)
1274 {
1275         struct triple *ret;
1276         ret = new_triple(state, OP_BRANCH, &void_type, test?1:0);
1277         if (test) {
1278                 RHS(ret, 0) = test;
1279         }
1280         TARG(ret, 0) = targ;
1281         /* record the branch target was used */
1282         if (!targ || (targ->op != OP_LABEL)) {
1283                 internal_error(state, 0, "branch not to label");
1284                 use_triple(targ, ret);
1285         }
1286         return ret;
1287 }
1288
1289
1290 static void insert_triple(struct compile_state *state,
1291         struct triple *first, struct triple *ptr)
1292 {
1293         if (ptr) {
1294                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1295                         internal_error(state, ptr, "expression already used");
1296                 }
1297                 ptr->next       = first;
1298                 ptr->prev       = first->prev;
1299                 ptr->prev->next = ptr;
1300                 ptr->next->prev = ptr;
1301                 if ((ptr->prev->op == OP_BRANCH) && 
1302                         TRIPLE_RHS(ptr->prev->sizes)) {
1303                         unuse_triple(first, ptr->prev);
1304                         use_triple(ptr, ptr->prev);
1305                 }
1306         }
1307 }
1308
1309 static struct triple *pre_triple(struct compile_state *state,
1310         struct triple *base,
1311         int op, struct type *type, struct triple *left, struct triple *right)
1312 {
1313         /* Careful this assumes it can do the easy thing to get the block */
1314         struct triple *ret;
1315         ret = build_triple(state, op, type, left, right, 
1316                 base->filename, base->line, base->col);
1317         ret->u.block = base->u.block;
1318         insert_triple(state, base, ret);
1319         return ret;
1320 }
1321
1322 static struct triple *post_triple(struct compile_state *state,
1323         struct triple *base,
1324         int op, struct type *type, struct triple *left, struct triple *right)
1325 {
1326         /* Careful this assumes it can do the easy thing to get the block */
1327         struct triple *ret;
1328         ret = build_triple(state, op, type, left, right, 
1329                 base->filename, base->line, base->col);
1330         ret->u.block = base->u.block;
1331         insert_triple(state, base->next, ret);
1332         return ret;
1333 }
1334
1335 static struct triple *label(struct compile_state *state)
1336 {
1337         /* Labels don't get a type */
1338         struct triple *result;
1339         result = triple(state, OP_LABEL, &void_type, 0, 0);
1340         return result;
1341 }
1342
1343 static void display_triple(FILE *fp, struct triple *ins)
1344 {
1345         if (ins->op == OP_INTCONST) {
1346                 fprintf(fp, "(%p) %3d %-10s 0x%08lx            @ %s:%d.%d\n",
1347                         ins, ID_REG(ins->id), tops(ins->op), ins->u.cval,
1348                         ins->filename, ins->line, ins->col);
1349         }
1350         else if (ins->op == OP_SDECL) {
1351                 fprintf(fp, "(%p) %3d %-10s %-10p            @ %s:%d.%d\n",
1352                         ins, ID_REG(ins->id), tops(ins->op), MISC(ins, 0),
1353                         ins->filename, ins->line, ins->col);
1354 #if 0
1355                 print_ins(state, MISC(ins, 0));
1356 #endif
1357         }
1358         else {
1359                 int i, count;
1360                 fprintf(fp, "(%p) %3d %-10s", 
1361                         ins, ID_REG(ins->id), tops(ins->op));
1362                 count = TRIPLE_SIZE(ins->sizes);
1363                 for(i = 0; i < count; i++) {
1364                         fprintf(fp, " %-10p", ins->param[i]);
1365                 }
1366                 for(; i < 2; i++) {
1367                         printf("           ");
1368                 }
1369                 fprintf(fp, " @ %s:%d.%d\n", 
1370                         ins->filename, ins->line, ins->col);
1371         }
1372         fflush(fp);
1373 }
1374
1375 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1376 {
1377         /* Does the triple have no side effects.
1378          * I.e. Rexecuting the triple with the same arguments 
1379          * gives the same value.
1380          */
1381         unsigned pure;
1382         valid_ins(state, ins);
1383         pure = PURE_BITS(table_ops[ins->op].flags);
1384         if ((pure != PURE) && (pure != IMPURE)) {
1385                 internal_error(state, 0, "Purity of %s not known\n",
1386                         tops(ins->op));
1387         }
1388         return pure == PURE;
1389 }
1390
1391 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1392 {
1393         /* This function is used to determine which triples need
1394          * a register.
1395          */
1396         int is_branch;
1397         valid_ins(state, ins);
1398         is_branch = (table_ops[ins->op].targ != 0);
1399         return is_branch;
1400 }
1401
1402 static int triple_is_def(struct compile_state *state, struct triple *ins)
1403 {
1404         /* This function is used to determine which triples need
1405          * a register.
1406          */
1407         int is_def;
1408         valid_ins(state, ins);
1409         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1410         return is_def;
1411 }
1412
1413 static struct triple **triple_iter(struct compile_state *state,
1414         size_t count, struct triple **vector,
1415         struct triple *ins, struct triple **last)
1416 {
1417         struct triple **ret;
1418         ret = 0;
1419         if (count) {
1420                 if (!last) {
1421                         ret = vector;
1422                 }
1423                 else if ((last >= vector) && (last < (vector + count - 1))) {
1424                         ret = last + 1;
1425                 }
1426         }
1427         return ret;
1428         
1429 }
1430
1431 static struct triple **triple_lhs(struct compile_state *state,
1432         struct triple *ins, struct triple **last)
1433 {
1434         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1435                 ins, last);
1436 }
1437
1438 static struct triple **triple_rhs(struct compile_state *state,
1439         struct triple *ins, struct triple **last)
1440 {
1441         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1442                 ins, last);
1443 }
1444
1445 static struct triple **triple_misc(struct compile_state *state,
1446         struct triple *ins, struct triple **last)
1447 {
1448         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1449                 ins, last);
1450 }
1451 static struct triple **triple_targ(struct compile_state *state,
1452         struct triple *ins, struct triple **last)
1453 {
1454         return triple_iter(state, TRIPLE_TARG(ins->sizes), &TARG(ins,0), 
1455                 ins, last);
1456 }
1457
1458 static void free_triple(struct compile_state *state, struct triple *ptr)
1459 {
1460         size_t size;
1461         size = sizeof(*ptr) - sizeof(ptr->param) +
1462                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1463         ptr->prev->next = ptr->next;
1464         ptr->next->prev = ptr->prev;
1465         if (ptr->use) {
1466                 internal_error(state, ptr, "ptr->use != 0");
1467         }
1468         memset(ptr, -1, size);
1469         xfree(ptr);
1470 }
1471
1472 static void release_triple(struct compile_state *state, struct triple *ptr)
1473 {
1474         struct triple_set *set, *next;
1475         struct triple **expr;
1476         /* Remove ptr from use chains where it is the user */
1477         expr = triple_rhs(state, ptr, 0);
1478         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1479                 if (*expr) {
1480                         unuse_triple(*expr, ptr);
1481                 }
1482         }
1483         expr = triple_lhs(state, ptr, 0);
1484         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1485                 if (*expr) {
1486                         unuse_triple(*expr, ptr);
1487                 }
1488         }
1489         expr = triple_targ(state, ptr, 0);
1490         for(; expr; expr = triple_targ(state, ptr, expr)) {
1491                 if (*expr) {
1492                         unuse_triple(*expr, ptr);
1493                 }
1494         }
1495         /* Reomve ptr from use chains where it is used */
1496         for(set = ptr->use; set; set = next) {
1497                 next = set->next;
1498                 expr = triple_rhs(state, set->member, 0);
1499                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1500                         if (*expr == ptr) {
1501                                 *expr = &zero_triple;
1502                         }
1503                 }
1504                 expr = triple_lhs(state, set->member, 0);
1505                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1506                         if (*expr == ptr) {
1507                                 *expr = &zero_triple;
1508                         }
1509                 }
1510                 expr = triple_targ(state, set->member, 0);
1511                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1512                         if (*expr == ptr) {
1513                                 *expr = &zero_triple;
1514                         }
1515                 }
1516                 unuse_triple(ptr, set->member);
1517         }
1518         free_triple(state, ptr);
1519 }
1520
1521 static void print_triple(struct compile_state *state, struct triple *ptr);
1522
1523 #define TOK_UNKNOWN     0
1524 #define TOK_SPACE       1
1525 #define TOK_SEMI        2
1526 #define TOK_LBRACE      3
1527 #define TOK_RBRACE      4
1528 #define TOK_COMMA       5
1529 #define TOK_EQ          6
1530 #define TOK_COLON       7
1531 #define TOK_LBRACKET    8
1532 #define TOK_RBRACKET    9
1533 #define TOK_LPAREN      10
1534 #define TOK_RPAREN      11
1535 #define TOK_STAR        12
1536 #define TOK_DOTS        13
1537 #define TOK_MORE        14
1538 #define TOK_LESS        15
1539 #define TOK_TIMESEQ     16
1540 #define TOK_DIVEQ       17
1541 #define TOK_MODEQ       18
1542 #define TOK_PLUSEQ      19
1543 #define TOK_MINUSEQ     20
1544 #define TOK_SLEQ        21
1545 #define TOK_SREQ        22
1546 #define TOK_ANDEQ       23
1547 #define TOK_XOREQ       24
1548 #define TOK_OREQ        25
1549 #define TOK_EQEQ        26
1550 #define TOK_NOTEQ       27
1551 #define TOK_QUEST       28
1552 #define TOK_LOGOR       29
1553 #define TOK_LOGAND      30
1554 #define TOK_OR          31
1555 #define TOK_AND         32
1556 #define TOK_XOR         33
1557 #define TOK_LESSEQ      34
1558 #define TOK_MOREEQ      35
1559 #define TOK_SL          36
1560 #define TOK_SR          37
1561 #define TOK_PLUS        38
1562 #define TOK_MINUS       39
1563 #define TOK_DIV         40
1564 #define TOK_MOD         41
1565 #define TOK_PLUSPLUS    42
1566 #define TOK_MINUSMINUS  43
1567 #define TOK_BANG        44
1568 #define TOK_ARROW       45
1569 #define TOK_DOT         46
1570 #define TOK_TILDE       47
1571 #define TOK_LIT_STRING  48
1572 #define TOK_LIT_CHAR    49
1573 #define TOK_LIT_INT     50
1574 #define TOK_LIT_FLOAT   51
1575 #define TOK_MACRO       52
1576 #define TOK_CONCATENATE 53
1577
1578 #define TOK_IDENT       54
1579 #define TOK_STRUCT_NAME 55
1580 #define TOK_ENUM_CONST  56
1581 #define TOK_TYPE_NAME   57
1582
1583 #define TOK_AUTO        58
1584 #define TOK_BREAK       59
1585 #define TOK_CASE        60
1586 #define TOK_CHAR        61
1587 #define TOK_CONST       62
1588 #define TOK_CONTINUE    63
1589 #define TOK_DEFAULT     64
1590 #define TOK_DO          65
1591 #define TOK_DOUBLE      66
1592 #define TOK_ELSE        67
1593 #define TOK_ENUM        68
1594 #define TOK_EXTERN      69
1595 #define TOK_FLOAT       70
1596 #define TOK_FOR         71
1597 #define TOK_GOTO        72
1598 #define TOK_IF          73
1599 #define TOK_INLINE      74
1600 #define TOK_INT         75
1601 #define TOK_LONG        76
1602 #define TOK_REGISTER    77
1603 #define TOK_RESTRICT    78
1604 #define TOK_RETURN      79
1605 #define TOK_SHORT       80
1606 #define TOK_SIGNED      81
1607 #define TOK_SIZEOF      82
1608 #define TOK_STATIC      83
1609 #define TOK_STRUCT      84
1610 #define TOK_SWITCH      85
1611 #define TOK_TYPEDEF     86
1612 #define TOK_UNION       87
1613 #define TOK_UNSIGNED    88
1614 #define TOK_VOID        89
1615 #define TOK_VOLATILE    90
1616 #define TOK_WHILE       91
1617 #define TOK_ASM         92
1618 #define TOK_ATTRIBUTE   93
1619 #define TOK_ALIGNOF     94
1620 #define TOK_FIRST_KEYWORD TOK_AUTO
1621 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1622
1623 #define TOK_DEFINE      100
1624 #define TOK_UNDEF       101
1625 #define TOK_INCLUDE     102
1626 #define TOK_LINE        103
1627 #define TOK_ERROR       104
1628 #define TOK_WARNING     105
1629 #define TOK_PRAGMA      106
1630 #define TOK_IFDEF       107
1631 #define TOK_IFNDEF      108
1632 #define TOK_ELIF        109
1633 #define TOK_ENDIF       110
1634
1635 #define TOK_FIRST_MACRO TOK_DEFINE
1636 #define TOK_LAST_MACRO  TOK_ENDIF
1637          
1638 #define TOK_EOF         111
1639
1640 static const char *tokens[] = {
1641 [TOK_UNKNOWN     ] = "unknown",
1642 [TOK_SPACE       ] = ":space:",
1643 [TOK_SEMI        ] = ";",
1644 [TOK_LBRACE      ] = "{",
1645 [TOK_RBRACE      ] = "}",
1646 [TOK_COMMA       ] = ",",
1647 [TOK_EQ          ] = "=",
1648 [TOK_COLON       ] = ":",
1649 [TOK_LBRACKET    ] = "[",
1650 [TOK_RBRACKET    ] = "]",
1651 [TOK_LPAREN      ] = "(",
1652 [TOK_RPAREN      ] = ")",
1653 [TOK_STAR        ] = "*",
1654 [TOK_DOTS        ] = "...",
1655 [TOK_MORE        ] = ">",
1656 [TOK_LESS        ] = "<",
1657 [TOK_TIMESEQ     ] = "*=",
1658 [TOK_DIVEQ       ] = "/=",
1659 [TOK_MODEQ       ] = "%=",
1660 [TOK_PLUSEQ      ] = "+=",
1661 [TOK_MINUSEQ     ] = "-=",
1662 [TOK_SLEQ        ] = "<<=",
1663 [TOK_SREQ        ] = ">>=",
1664 [TOK_ANDEQ       ] = "&=",
1665 [TOK_XOREQ       ] = "^=",
1666 [TOK_OREQ        ] = "|=",
1667 [TOK_EQEQ        ] = "==",
1668 [TOK_NOTEQ       ] = "!=",
1669 [TOK_QUEST       ] = "?",
1670 [TOK_LOGOR       ] = "||",
1671 [TOK_LOGAND      ] = "&&",
1672 [TOK_OR          ] = "|",
1673 [TOK_AND         ] = "&",
1674 [TOK_XOR         ] = "^",
1675 [TOK_LESSEQ      ] = "<=",
1676 [TOK_MOREEQ      ] = ">=",
1677 [TOK_SL          ] = "<<",
1678 [TOK_SR          ] = ">>",
1679 [TOK_PLUS        ] = "+",
1680 [TOK_MINUS       ] = "-",
1681 [TOK_DIV         ] = "/",
1682 [TOK_MOD         ] = "%",
1683 [TOK_PLUSPLUS    ] = "++",
1684 [TOK_MINUSMINUS  ] = "--",
1685 [TOK_BANG        ] = "!",
1686 [TOK_ARROW       ] = "->",
1687 [TOK_DOT         ] = ".",
1688 [TOK_TILDE       ] = "~",
1689 [TOK_LIT_STRING  ] = ":string:",
1690 [TOK_IDENT       ] = ":ident:",
1691 [TOK_TYPE_NAME   ] = ":typename:",
1692 [TOK_LIT_CHAR    ] = ":char:",
1693 [TOK_LIT_INT     ] = ":integer:",
1694 [TOK_LIT_FLOAT   ] = ":float:",
1695 [TOK_MACRO       ] = "#",
1696 [TOK_CONCATENATE ] = "##",
1697
1698 [TOK_AUTO        ] = "auto",
1699 [TOK_BREAK       ] = "break",
1700 [TOK_CASE        ] = "case",
1701 [TOK_CHAR        ] = "char",
1702 [TOK_CONST       ] = "const",
1703 [TOK_CONTINUE    ] = "continue",
1704 [TOK_DEFAULT     ] = "default",
1705 [TOK_DO          ] = "do",
1706 [TOK_DOUBLE      ] = "double",
1707 [TOK_ELSE        ] = "else",
1708 [TOK_ENUM        ] = "enum",
1709 [TOK_EXTERN      ] = "extern",
1710 [TOK_FLOAT       ] = "float",
1711 [TOK_FOR         ] = "for",
1712 [TOK_GOTO        ] = "goto",
1713 [TOK_IF          ] = "if",
1714 [TOK_INLINE      ] = "inline",
1715 [TOK_INT         ] = "int",
1716 [TOK_LONG        ] = "long",
1717 [TOK_REGISTER    ] = "register",
1718 [TOK_RESTRICT    ] = "restrict",
1719 [TOK_RETURN      ] = "return",
1720 [TOK_SHORT       ] = "short",
1721 [TOK_SIGNED      ] = "signed",
1722 [TOK_SIZEOF      ] = "sizeof",
1723 [TOK_STATIC      ] = "static",
1724 [TOK_STRUCT      ] = "struct",
1725 [TOK_SWITCH      ] = "switch",
1726 [TOK_TYPEDEF     ] = "typedef",
1727 [TOK_UNION       ] = "union",
1728 [TOK_UNSIGNED    ] = "unsigned",
1729 [TOK_VOID        ] = "void",
1730 [TOK_VOLATILE    ] = "volatile",
1731 [TOK_WHILE       ] = "while",
1732 [TOK_ASM         ] = "asm",
1733 [TOK_ATTRIBUTE   ] = "__attribute__",
1734 [TOK_ALIGNOF     ] = "__alignof__",
1735
1736 [TOK_DEFINE      ] = "define",
1737 [TOK_UNDEF       ] = "undef",
1738 [TOK_INCLUDE     ] = "include",
1739 [TOK_LINE        ] = "line",
1740 [TOK_ERROR       ] = "error",
1741 [TOK_WARNING     ] = "warning",
1742 [TOK_PRAGMA      ] = "pragma",
1743 [TOK_IFDEF       ] = "ifdef",
1744 [TOK_IFNDEF      ] = "ifndef",
1745 [TOK_ELIF        ] = "elif",
1746 [TOK_ENDIF       ] = "endif",
1747
1748 [TOK_EOF         ] = "EOF",
1749 };
1750
1751 static unsigned int hash(const char *str, int str_len)
1752 {
1753         unsigned int hash;
1754         const char *end;
1755         end = str + str_len;
1756         hash = 0;
1757         for(; str < end; str++) {
1758                 hash = (hash *263) + *str;
1759         }
1760         hash = hash & (HASH_TABLE_SIZE -1);
1761         return hash;
1762 }
1763
1764 static struct hash_entry *lookup(
1765         struct compile_state *state, const char *name, int name_len)
1766 {
1767         struct hash_entry *entry;
1768         unsigned int index;
1769         index = hash(name, name_len);
1770         entry = state->hash_table[index];
1771         while(entry && 
1772                 ((entry->name_len != name_len) ||
1773                         (memcmp(entry->name, name, name_len) != 0))) {
1774                 entry = entry->next;
1775         }
1776         if (!entry) {
1777                 char *new_name;
1778                 /* Get a private copy of the name */
1779                 new_name = xmalloc(name_len + 1, "hash_name");
1780                 memcpy(new_name, name, name_len);
1781                 new_name[name_len] = '\0';
1782
1783                 /* Create a new hash entry */
1784                 entry = xcmalloc(sizeof(*entry), "hash_entry");
1785                 entry->next = state->hash_table[index];
1786                 entry->name = new_name;
1787                 entry->name_len = name_len;
1788
1789                 /* Place the new entry in the hash table */
1790                 state->hash_table[index] = entry;
1791         }
1792         return entry;
1793 }
1794
1795 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1796 {
1797         struct hash_entry *entry;
1798         entry = tk->ident;
1799         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1800                 (entry->tok == TOK_ENUM_CONST) ||
1801                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
1802                         (entry->tok <= TOK_LAST_KEYWORD)))) {
1803                 tk->tok = entry->tok;
1804         }
1805 }
1806
1807 static void ident_to_macro(struct compile_state *state, struct token *tk)
1808 {
1809         struct hash_entry *entry;
1810         entry = tk->ident;
1811         if (entry && 
1812                 (entry->tok >= TOK_FIRST_MACRO) &&
1813                 (entry->tok <= TOK_LAST_MACRO)) {
1814                 tk->tok = entry->tok;
1815         }
1816 }
1817
1818 static void hash_keyword(
1819         struct compile_state *state, const char *keyword, int tok)
1820 {
1821         struct hash_entry *entry;
1822         entry = lookup(state, keyword, strlen(keyword));
1823         if (entry && entry->tok != TOK_UNKNOWN) {
1824                 die("keyword %s already hashed", keyword);
1825         }
1826         entry->tok  = tok;
1827 }
1828
1829 static void symbol(
1830         struct compile_state *state, struct hash_entry *ident,
1831         struct symbol **chain, struct triple *def, struct type *type)
1832 {
1833         struct symbol *sym;
1834         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
1835                 error(state, 0, "%s already defined", ident->name);
1836         }
1837         sym = xcmalloc(sizeof(*sym), "symbol");
1838         sym->ident = ident;
1839         sym->def   = def;
1840         sym->type  = type;
1841         sym->scope_depth = state->scope_depth;
1842         sym->next = *chain;
1843         *chain    = sym;
1844 }
1845
1846 static void start_scope(struct compile_state *state)
1847 {
1848         state->scope_depth++;
1849 }
1850
1851 static void end_scope_syms(struct symbol **chain, int depth)
1852 {
1853         struct symbol *sym, *next;
1854         sym = *chain;
1855         while(sym && (sym->scope_depth == depth)) {
1856                 next = sym->next;
1857                 xfree(sym);
1858                 sym = next;
1859         }
1860         *chain = sym;
1861 }
1862
1863 static void end_scope(struct compile_state *state)
1864 {
1865         int i;
1866         int depth;
1867         /* Walk through the hash table and remove all symbols
1868          * in the current scope. 
1869          */
1870         depth = state->scope_depth;
1871         for(i = 0; i < HASH_TABLE_SIZE; i++) {
1872                 struct hash_entry *entry;
1873                 entry = state->hash_table[i];
1874                 while(entry) {
1875                         end_scope_syms(&entry->sym_label,  depth);
1876                         end_scope_syms(&entry->sym_struct, depth);
1877                         end_scope_syms(&entry->sym_ident,  depth);
1878                         entry = entry->next;
1879                 }
1880         }
1881         state->scope_depth = depth - 1;
1882 }
1883
1884 static void register_keywords(struct compile_state *state)
1885 {
1886         hash_keyword(state, "auto",          TOK_AUTO);
1887         hash_keyword(state, "break",         TOK_BREAK);
1888         hash_keyword(state, "case",          TOK_CASE);
1889         hash_keyword(state, "char",          TOK_CHAR);
1890         hash_keyword(state, "const",         TOK_CONST);
1891         hash_keyword(state, "continue",      TOK_CONTINUE);
1892         hash_keyword(state, "default",       TOK_DEFAULT);
1893         hash_keyword(state, "do",            TOK_DO);
1894         hash_keyword(state, "double",        TOK_DOUBLE);
1895         hash_keyword(state, "else",          TOK_ELSE);
1896         hash_keyword(state, "enum",          TOK_ENUM);
1897         hash_keyword(state, "extern",        TOK_EXTERN);
1898         hash_keyword(state, "float",         TOK_FLOAT);
1899         hash_keyword(state, "for",           TOK_FOR);
1900         hash_keyword(state, "goto",          TOK_GOTO);
1901         hash_keyword(state, "if",            TOK_IF);
1902         hash_keyword(state, "inline",        TOK_INLINE);
1903         hash_keyword(state, "int",           TOK_INT);
1904         hash_keyword(state, "long",          TOK_LONG);
1905         hash_keyword(state, "register",      TOK_REGISTER);
1906         hash_keyword(state, "restrict",      TOK_RESTRICT);
1907         hash_keyword(state, "return",        TOK_RETURN);
1908         hash_keyword(state, "short",         TOK_SHORT);
1909         hash_keyword(state, "signed",        TOK_SIGNED);
1910         hash_keyword(state, "sizeof",        TOK_SIZEOF);
1911         hash_keyword(state, "static",        TOK_STATIC);
1912         hash_keyword(state, "struct",        TOK_STRUCT);
1913         hash_keyword(state, "switch",        TOK_SWITCH);
1914         hash_keyword(state, "typedef",       TOK_TYPEDEF);
1915         hash_keyword(state, "union",         TOK_UNION);
1916         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
1917         hash_keyword(state, "void",          TOK_VOID);
1918         hash_keyword(state, "volatile",      TOK_VOLATILE);
1919         hash_keyword(state, "while",         TOK_WHILE);
1920         hash_keyword(state, "asm",           TOK_ASM);
1921         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
1922         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
1923 }
1924
1925 static void register_macro_keywords(struct compile_state *state)
1926 {
1927         hash_keyword(state, "define",        TOK_DEFINE);
1928         hash_keyword(state, "undef",         TOK_UNDEF);
1929         hash_keyword(state, "include",       TOK_INCLUDE);
1930         hash_keyword(state, "line",          TOK_LINE);
1931         hash_keyword(state, "error",         TOK_ERROR);
1932         hash_keyword(state, "warning",       TOK_WARNING);
1933         hash_keyword(state, "pragma",        TOK_PRAGMA);
1934         hash_keyword(state, "ifdef",         TOK_IFDEF);
1935         hash_keyword(state, "ifndef",        TOK_IFNDEF);
1936         hash_keyword(state, "elif",          TOK_ELIF);
1937         hash_keyword(state, "endif",         TOK_ENDIF);
1938 }
1939
1940 static int spacep(int c)
1941 {
1942         int ret = 0;
1943         switch(c) {
1944         case ' ':
1945         case '\t':
1946         case '\f':
1947         case '\v':
1948         case '\r':
1949         case '\n':
1950                 ret = 1;
1951                 break;
1952         }
1953         return ret;
1954 }
1955
1956 static int digitp(int c)
1957 {
1958         int ret = 0;
1959         switch(c) {
1960         case '0': case '1': case '2': case '3': case '4': 
1961         case '5': case '6': case '7': case '8': case '9':
1962                 ret = 1;
1963                 break;
1964         }
1965         return ret;
1966 }
1967
1968 static int hexdigitp(int c)
1969 {
1970         int ret = 0;
1971         switch(c) {
1972         case '0': case '1': case '2': case '3': case '4': 
1973         case '5': case '6': case '7': case '8': case '9':
1974         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1975         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1976                 ret = 1;
1977                 break;
1978         }
1979         return ret;
1980 }
1981 static int hexdigval(int c) 
1982 {
1983         int val = -1;
1984         if ((c >= '0') && (c <= '9')) {
1985                 val = c - '0';
1986         }
1987         else if ((c >= 'A') && (c <= 'F')) {
1988                 val = 10 + (c - 'A');
1989         }
1990         else if ((c >= 'a') && (c <= 'f')) {
1991                 val = 10 + (c - 'a');
1992         }
1993         return val;
1994 }
1995
1996 static int octdigitp(int c)
1997 {
1998         int ret = 0;
1999         switch(c) {
2000         case '0': case '1': case '2': case '3': 
2001         case '4': case '5': case '6': case '7':
2002                 ret = 1;
2003                 break;
2004         }
2005         return ret;
2006 }
2007 static int octdigval(int c)
2008 {
2009         int val = -1;
2010         if ((c >= '0') && (c <= '7')) {
2011                 val = c - '0';
2012         }
2013         return val;
2014 }
2015
2016 static int letterp(int c)
2017 {
2018         int ret = 0;
2019         switch(c) {
2020         case 'a': case 'b': case 'c': case 'd': case 'e':
2021         case 'f': case 'g': case 'h': case 'i': case 'j':
2022         case 'k': case 'l': case 'm': case 'n': case 'o':
2023         case 'p': case 'q': case 'r': case 's': case 't':
2024         case 'u': case 'v': case 'w': case 'x': case 'y':
2025         case 'z':
2026         case 'A': case 'B': case 'C': case 'D': case 'E':
2027         case 'F': case 'G': case 'H': case 'I': case 'J':
2028         case 'K': case 'L': case 'M': case 'N': case 'O':
2029         case 'P': case 'Q': case 'R': case 'S': case 'T':
2030         case 'U': case 'V': case 'W': case 'X': case 'Y':
2031         case 'Z':
2032         case '_':
2033                 ret = 1;
2034                 break;
2035         }
2036         return ret;
2037 }
2038
2039 static int char_value(struct compile_state *state,
2040         const signed char **strp, const signed char *end)
2041 {
2042         const signed char *str;
2043         int c;
2044         str = *strp;
2045         c = *str++;
2046         if ((c == '\\') && (str < end)) {
2047                 switch(*str) {
2048                 case 'n':  c = '\n'; str++; break;
2049                 case 't':  c = '\t'; str++; break;
2050                 case 'v':  c = '\v'; str++; break;
2051                 case 'b':  c = '\b'; str++; break;
2052                 case 'r':  c = '\r'; str++; break;
2053                 case 'f':  c = '\f'; str++; break;
2054                 case 'a':  c = '\a'; str++; break;
2055                 case '\\': c = '\\'; str++; break;
2056                 case '?':  c = '?';  str++; break;
2057                 case '\'': c = '\''; str++; break;
2058                 case '"':  c = '"';  break;
2059                 case 'x': 
2060                         c = 0;
2061                         str++;
2062                         while((str < end) && hexdigitp(*str)) {
2063                                 c <<= 4;
2064                                 c += hexdigval(*str);
2065                                 str++;
2066                         }
2067                         break;
2068                 case '0': case '1': case '2': case '3': 
2069                 case '4': case '5': case '6': case '7':
2070                         c = 0;
2071                         while((str < end) && octdigitp(*str)) {
2072                                 c <<= 3;
2073                                 c += octdigval(*str);
2074                                 str++;
2075                         }
2076                         break;
2077                 default:
2078                         error(state, 0, "Invalid character constant");
2079                         break;
2080                 }
2081         }
2082         *strp = str;
2083         return c;
2084 }
2085
2086 static char *after_digits(char *ptr, char *end)
2087 {
2088         while((ptr < end) && digitp(*ptr)) {
2089                 ptr++;
2090         }
2091         return ptr;
2092 }
2093
2094 static char *after_octdigits(char *ptr, char *end)
2095 {
2096         while((ptr < end) && octdigitp(*ptr)) {
2097                 ptr++;
2098         }
2099         return ptr;
2100 }
2101
2102 static char *after_hexdigits(char *ptr, char *end)
2103 {
2104         while((ptr < end) && hexdigitp(*ptr)) {
2105                 ptr++;
2106         }
2107         return ptr;
2108 }
2109
2110 static void save_string(struct compile_state *state, 
2111         struct token *tk, char *start, char *end, const char *id)
2112 {
2113         char *str;
2114         int str_len;
2115         /* Create a private copy of the string */
2116         str_len = end - start + 1;
2117         str = xmalloc(str_len + 1, id);
2118         memcpy(str, start, str_len);
2119         str[str_len] = '\0';
2120
2121         /* Store the copy in the token */
2122         tk->val.str = str;
2123         tk->str_len = str_len;
2124 }
2125 static void next_token(struct compile_state *state, int index)
2126 {
2127         struct file_state *file;
2128         struct token *tk;
2129         char *token;
2130         int c, c1, c2, c3;
2131         char *tokp, *end;
2132         int tok;
2133 next_token:
2134         file = state->file;
2135         tk = &state->token[index];
2136         tk->str_len = 0;
2137         tk->ident = 0;
2138         token = tokp = file->pos;
2139         end = file->buf + file->size;
2140         tok = TOK_UNKNOWN;
2141         c = -1;
2142         if (tokp < end) {
2143                 c = *tokp;
2144         }
2145         c1 = -1;
2146         if ((tokp + 1) < end) {
2147                 c1 = tokp[1];
2148         }
2149         c2 = -1;
2150         if ((tokp + 2) < end) {
2151                 c2 = tokp[2];
2152         }
2153         c3 = -1;
2154         if ((tokp + 3) < end) {
2155                 c3 = tokp[3];
2156         }
2157         if (tokp >= end) {
2158                 tok = TOK_EOF;
2159                 tokp = end;
2160         }
2161         /* Whitespace */
2162         else if (spacep(c)) {
2163                 tok = TOK_SPACE;
2164                 while ((tokp < end) && spacep(c)) {
2165                         if (c == '\n') {
2166                                 file->line++;
2167                                 file->line_start = tokp + 1;
2168                         }
2169                         c = *(++tokp);
2170                 }
2171                 if (!spacep(c)) {
2172                         tokp--;
2173                 }
2174         }
2175         /* EOL Comments */
2176         else if ((c == '/') && (c1 == '/')) {
2177                 tok = TOK_SPACE;
2178                 for(tokp += 2; tokp < end; tokp++) {
2179                         c = *tokp;
2180                         if (c == '\n') {
2181                                 file->line++;
2182                                 file->line_start = tokp +1;
2183                                 break;
2184                         }
2185                 }
2186         }
2187         /* Comments */
2188         else if ((c == '/') && (c1 == '*')) {
2189                 int line;
2190                 char *line_start;
2191                 line = file->line;
2192                 line_start = file->line_start;
2193                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2194                         c = *tokp;
2195                         if (c == '\n') {
2196                                 line++;
2197                                 line_start = tokp +1;
2198                         }
2199                         else if ((c == '*') && (tokp[1] == '/')) {
2200                                 tok = TOK_SPACE;
2201                                 tokp += 1;
2202                                 break;
2203                         }
2204                 }
2205                 if (tok == TOK_UNKNOWN) {
2206                         error(state, 0, "unterminated comment");
2207                 }
2208                 file->line = line;
2209                 file->line_start = line_start;
2210         }
2211         /* string constants */
2212         else if ((c == '"') ||
2213                 ((c == 'L') && (c1 == '"'))) {
2214                 int line;
2215                 char *line_start;
2216                 int wchar;
2217                 line = file->line;
2218                 line_start = file->line_start;
2219                 wchar = 0;
2220                 if (c == 'L') {
2221                         wchar = 1;
2222                         tokp++;
2223                 }
2224                 for(tokp += 1; tokp < end; tokp++) {
2225                         c = *tokp;
2226                         if (c == '\n') {
2227                                 line++;
2228                                 line_start = tokp + 1;
2229                         }
2230                         else if ((c == '\\') && (tokp +1 < end)) {
2231                                 tokp++;
2232                         }
2233                         else if (c == '"') {
2234                                 tok = TOK_LIT_STRING;
2235                                 break;
2236                         }
2237                 }
2238                 if (tok == TOK_UNKNOWN) {
2239                         error(state, 0, "unterminated string constant");
2240                 }
2241                 if (line != file->line) {
2242                         warning(state, 0, "multiline string constant");
2243                 }
2244                 file->line = line;
2245                 file->line_start = line_start;
2246
2247                 /* Save the string value */
2248                 save_string(state, tk, token, tokp, "literal string");
2249         }
2250         /* character constants */
2251         else if ((c == '\'') ||
2252                 ((c == 'L') && (c1 == '\''))) {
2253                 int line;
2254                 char *line_start;
2255                 int wchar;
2256                 line = file->line;
2257                 line_start = file->line_start;
2258                 wchar = 0;
2259                 if (c == 'L') {
2260                         wchar = 1;
2261                         tokp++;
2262                 }
2263                 for(tokp += 1; tokp < end; tokp++) {
2264                         c = *tokp;
2265                         if (c == '\n') {
2266                                 line++;
2267                                 line_start = tokp + 1;
2268                         }
2269                         else if ((c == '\\') && (tokp +1 < end)) {
2270                                 tokp++;
2271                         }
2272                         else if (c == '\'') {
2273                                 tok = TOK_LIT_CHAR;
2274                                 break;
2275                         }
2276                 }
2277                 if (tok == TOK_UNKNOWN) {
2278                         error(state, 0, "unterminated character constant");
2279                 }
2280                 if (line != file->line) {
2281                         warning(state, 0, "multiline character constant");
2282                 }
2283                 file->line = line;
2284                 file->line_start = line_start;
2285
2286                 /* Save the character value */
2287                 save_string(state, tk, token, tokp, "literal character");
2288         }
2289         /* integer and floating constants 
2290          * Integer Constants
2291          * {digits}
2292          * 0[Xx]{hexdigits}
2293          * 0{octdigit}+
2294          * 
2295          * Floating constants
2296          * {digits}.{digits}[Ee][+-]?{digits}
2297          * {digits}.{digits}
2298          * {digits}[Ee][+-]?{digits}
2299          * .{digits}[Ee][+-]?{digits}
2300          * .{digits}
2301          */
2302         
2303         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2304                 char *next, *new;
2305                 int is_float;
2306                 is_float = 0;
2307                 if (c != '.') {
2308                         next = after_digits(tokp, end);
2309                 }
2310                 else {
2311                         next = tokp;
2312                 }
2313                 if (next[0] == '.') {
2314                         new = after_digits(next, end);
2315                         is_float = (new != next);
2316                         next = new;
2317                 }
2318                 if ((next[0] == 'e') || (next[0] == 'E')) {
2319                         if (((next + 1) < end) && 
2320                                 ((next[1] == '+') || (next[1] == '-'))) {
2321                                 next++;
2322                         }
2323                         new = after_digits(next, end);
2324                         is_float = (new != next);
2325                         next = new;
2326                 }
2327                 if (is_float) {
2328                         tok = TOK_LIT_FLOAT;
2329                         if ((next < end) && (
2330                                 (next[0] == 'f') ||
2331                                 (next[0] == 'F') ||
2332                                 (next[0] == 'l') ||
2333                                 (next[0] == 'L'))
2334                                 ) {
2335                                 next++;
2336                         }
2337                 }
2338                 if (!is_float && digitp(c)) {
2339                         tok = TOK_LIT_INT;
2340                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2341                                 next = after_hexdigits(tokp + 2, end);
2342                         }
2343                         else if (c == '0') {
2344                                 next = after_octdigits(tokp, end);
2345                         }
2346                         else {
2347                                 next = after_digits(tokp, end);
2348                         }
2349                         /* crazy integer suffixes */
2350                         if ((next < end) && 
2351                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2352                                 next++;
2353                                 if ((next < end) &&
2354                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2355                                         next++;
2356                                 }
2357                         }
2358                         else if ((next < end) &&
2359                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2360                                 next++;
2361                                 if ((next < end) && 
2362                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2363                                         next++;
2364                                 }
2365                         }
2366                 }
2367                 tokp = next - 1;
2368
2369                 /* Save the integer/floating point value */
2370                 save_string(state, tk, token, tokp, "literal number");
2371         }
2372         /* identifiers */
2373         else if (letterp(c)) {
2374                 tok = TOK_IDENT;
2375                 for(tokp += 1; tokp < end; tokp++) {
2376                         c = *tokp;
2377                         if (!letterp(c) && !digitp(c)) {
2378                                 break;
2379                         }
2380                 }
2381                 tokp -= 1;
2382                 tk->ident = lookup(state, token, tokp +1 - token);
2383         }
2384         /* C99 alternate macro characters */
2385         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2386                 tokp += 3; 
2387                 tok = TOK_CONCATENATE; 
2388         }
2389         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2390         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2391         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2392         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2393         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2394         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2395         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2396         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2397         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2398         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2399         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2400         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2401         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2402         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2403         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2404         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2405         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2406         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2407         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2408         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2409         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2410         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2411         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2412         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2413         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2414         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2415         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2416         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2417         else if (c == ';') { tok = TOK_SEMI; }
2418         else if (c == '{') { tok = TOK_LBRACE; }
2419         else if (c == '}') { tok = TOK_RBRACE; }
2420         else if (c == ',') { tok = TOK_COMMA; }
2421         else if (c == '=') { tok = TOK_EQ; }
2422         else if (c == ':') { tok = TOK_COLON; }
2423         else if (c == '[') { tok = TOK_LBRACKET; }
2424         else if (c == ']') { tok = TOK_RBRACKET; }
2425         else if (c == '(') { tok = TOK_LPAREN; }
2426         else if (c == ')') { tok = TOK_RPAREN; }
2427         else if (c == '*') { tok = TOK_STAR; }
2428         else if (c == '>') { tok = TOK_MORE; }
2429         else if (c == '<') { tok = TOK_LESS; }
2430         else if (c == '?') { tok = TOK_QUEST; }
2431         else if (c == '|') { tok = TOK_OR; }
2432         else if (c == '&') { tok = TOK_AND; }
2433         else if (c == '^') { tok = TOK_XOR; }
2434         else if (c == '+') { tok = TOK_PLUS; }
2435         else if (c == '-') { tok = TOK_MINUS; }
2436         else if (c == '/') { tok = TOK_DIV; }
2437         else if (c == '%') { tok = TOK_MOD; }
2438         else if (c == '!') { tok = TOK_BANG; }
2439         else if (c == '.') { tok = TOK_DOT; }
2440         else if (c == '~') { tok = TOK_TILDE; }
2441         else if (c == '#') { tok = TOK_MACRO; }
2442         if (tok == TOK_MACRO) {
2443                 /* Only match preprocessor directives at the start of a line */
2444                 char *ptr;
2445                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2446                         ;
2447                 if (ptr != tokp) {
2448                         tok = TOK_UNKNOWN;
2449                 }
2450         }
2451         if (tok == TOK_UNKNOWN) {
2452                 error(state, 0, "unknown token");
2453         }
2454
2455         file->pos = tokp + 1;
2456         tk->tok = tok;
2457         if (tok == TOK_IDENT) {
2458                 ident_to_keyword(state, tk);
2459         }
2460         /* Don't return space tokens. */
2461         if (tok == TOK_SPACE) {
2462                 goto next_token;
2463         }
2464 }
2465
2466 static void compile_macro(struct compile_state *state, struct token *tk)
2467 {
2468         struct file_state *file;
2469         struct hash_entry *ident;
2470         ident = tk->ident;
2471         file = xmalloc(sizeof(*file), "file_state");
2472         file->basename = xstrdup(tk->ident->name);
2473         file->dirname = xstrdup("");
2474         file->size = ident->sym_define->buf_len;
2475         file->buf = xmalloc(file->size +2,  file->basename);
2476         memcpy(file->buf, ident->sym_define->buf, file->size);
2477         file->buf[file->size] = '\n';
2478         file->buf[file->size + 1] = '\0';
2479         file->pos = file->buf;
2480         file->line_start = file->pos;
2481         file->line = 1;
2482         file->prev = state->file;
2483         state->file = file;
2484 }
2485
2486
2487 static int mpeek(struct compile_state *state, int index)
2488 {
2489         struct token *tk;
2490         int rescan;
2491         tk = &state->token[index + 1];
2492         if (tk->tok == -1) {
2493                 next_token(state, index + 1);
2494         }
2495         do {
2496                 rescan = 0;
2497                 if ((tk->tok == TOK_EOF) && 
2498                         (state->file != state->macro_file) &&
2499                         (state->file->prev)) {
2500                         struct file_state *file = state->file;
2501                         state->file = file->prev;
2502                         /* file->basename is used keep it */
2503                         xfree(file->dirname);
2504                         xfree(file->buf);
2505                         xfree(file);
2506                         next_token(state, index + 1);
2507                         rescan = 1;
2508                 }
2509                 else if (tk->ident && tk->ident->sym_define) {
2510                         compile_macro(state, tk);
2511                         next_token(state, index + 1);
2512                         rescan = 1;
2513                 }
2514         } while(rescan);
2515         /* Don't show the token on the next line */
2516         if (state->macro_line < state->macro_file->line) {
2517                 return TOK_EOF;
2518         }
2519         return state->token[index +1].tok;
2520 }
2521
2522 static void meat(struct compile_state *state, int index, int tok)
2523 {
2524         int next_tok;
2525         int i;
2526         next_tok = mpeek(state, index);
2527         if (next_tok != tok) {
2528                 const char *name1, *name2;
2529                 name1 = tokens[next_tok];
2530                 name2 = "";
2531                 if (next_tok == TOK_IDENT) {
2532                         name2 = state->token[index + 1].ident->name;
2533                 }
2534                 error(state, 0, "found %s %s expected %s", 
2535                         name1, name2, tokens[tok]);
2536         }
2537         /* Free the old token value */
2538         if (state->token[index].str_len) {
2539                 memset((void *)(state->token[index].val.str), -1, 
2540                         state->token[index].str_len);
2541                 xfree(state->token[index].val.str);
2542         }
2543         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2544                 state->token[i] = state->token[i + 1];
2545         }
2546         memset(&state->token[i], 0, sizeof(state->token[i]));
2547         state->token[i].tok = -1;
2548 }
2549
2550 static long_t mcexpr(struct compile_state *state, int index);
2551
2552 static long_t mprimary_expr(struct compile_state *state, int index)
2553 {
2554         long_t val;
2555         int tok;
2556         tok = mpeek(state, index);
2557         while(state->token[index + 1].ident && 
2558                 state->token[index + 1].ident->sym_define) {
2559                 meat(state, index, tok);
2560                 compile_macro(state, &state->token[index]);
2561                 tok = mpeek(state, index);
2562         }
2563         switch(tok) {
2564         case TOK_LPAREN:
2565                 meat(state, index, TOK_LPAREN);
2566                 val = mcexpr(state, index);
2567                 meat(state, index, TOK_RPAREN);
2568                 break;
2569         case TOK_LIT_INT:
2570         {
2571                 char *end;
2572                 meat(state, index, TOK_LIT_INT);
2573                 errno = 0;
2574                 val = strtol(state->token[index].val.str, &end, 0);
2575                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2576                         (errno == ERANGE)) {
2577                         error(state, 0, "Integer constant to large");
2578                 }
2579                 break;
2580         }
2581         default:
2582                 meat(state, index, TOK_LIT_INT);
2583                 val = 0;
2584         }
2585         return val;
2586 }
2587 static long_t munary_expr(struct compile_state *state, int index)
2588 {
2589         long_t val;
2590         switch(mpeek(state, index)) {
2591         case TOK_PLUS:
2592                 meat(state, index, TOK_PLUS);
2593                 val = munary_expr(state, index);
2594                 val = + val;
2595                 break;
2596         case TOK_MINUS:
2597                 meat(state, index, TOK_MINUS);
2598                 val = munary_expr(state, index);
2599                 val = - val;
2600                 break;
2601         case TOK_TILDE:
2602                 meat(state, index, TOK_BANG);
2603                 val = munary_expr(state, index);
2604                 val = ~ val;
2605                 break;
2606         case TOK_BANG:
2607                 meat(state, index, TOK_BANG);
2608                 val = munary_expr(state, index);
2609                 val = ! val;
2610                 break;
2611         default:
2612                 val = mprimary_expr(state, index);
2613                 break;
2614         }
2615         return val;
2616         
2617 }
2618 static long_t mmul_expr(struct compile_state *state, int index)
2619 {
2620         long_t val;
2621         int done;
2622         val = munary_expr(state, index);
2623         do {
2624                 long_t right;
2625                 done = 0;
2626                 switch(mpeek(state, index)) {
2627                 case TOK_STAR:
2628                         meat(state, index, TOK_STAR);
2629                         right = munary_expr(state, index);
2630                         val = val * right;
2631                         break;
2632                 case TOK_DIV:
2633                         meat(state, index, TOK_DIV);
2634                         right = munary_expr(state, index);
2635                         val = val / right;
2636                         break;
2637                 case TOK_MOD:
2638                         meat(state, index, TOK_MOD);
2639                         right = munary_expr(state, index);
2640                         val = val % right;
2641                         break;
2642                 default:
2643                         done = 1;
2644                         break;
2645                 }
2646         } while(!done);
2647
2648         return val;
2649 }
2650
2651 static long_t madd_expr(struct compile_state *state, int index)
2652 {
2653         long_t val;
2654         int done;
2655         val = mmul_expr(state, index);
2656         do {
2657                 long_t right;
2658                 done = 0;
2659                 switch(mpeek(state, index)) {
2660                 case TOK_PLUS:
2661                         meat(state, index, TOK_PLUS);
2662                         right = mmul_expr(state, index);
2663                         val = val + right;
2664                         break;
2665                 case TOK_MINUS:
2666                         meat(state, index, TOK_MINUS);
2667                         right = mmul_expr(state, index);
2668                         val = val - right;
2669                         break;
2670                 default:
2671                         done = 1;
2672                         break;
2673                 }
2674         } while(!done);
2675
2676         return val;
2677 }
2678
2679 static long_t mshift_expr(struct compile_state *state, int index)
2680 {
2681         long_t val;
2682         int done;
2683         val = madd_expr(state, index);
2684         do {
2685                 long_t right;
2686                 done = 0;
2687                 switch(mpeek(state, index)) {
2688                 case TOK_SL:
2689                         meat(state, index, TOK_SL);
2690                         right = madd_expr(state, index);
2691                         val = val << right;
2692                         break;
2693                 case TOK_SR:
2694                         meat(state, index, TOK_SR);
2695                         right = madd_expr(state, index);
2696                         val = val >> right;
2697                         break;
2698                 default:
2699                         done = 1;
2700                         break;
2701                 }
2702         } while(!done);
2703
2704         return val;
2705 }
2706
2707 static long_t mrel_expr(struct compile_state *state, int index)
2708 {
2709         long_t val;
2710         int done;
2711         val = mshift_expr(state, index);
2712         do {
2713                 long_t right;
2714                 done = 0;
2715                 switch(mpeek(state, index)) {
2716                 case TOK_LESS:
2717                         meat(state, index, TOK_LESS);
2718                         right = mshift_expr(state, index);
2719                         val = val < right;
2720                         break;
2721                 case TOK_MORE:
2722                         meat(state, index, TOK_MORE);
2723                         right = mshift_expr(state, index);
2724                         val = val > right;
2725                         break;
2726                 case TOK_LESSEQ:
2727                         meat(state, index, TOK_LESSEQ);
2728                         right = mshift_expr(state, index);
2729                         val = val <= right;
2730                         break;
2731                 case TOK_MOREEQ:
2732                         meat(state, index, TOK_MOREEQ);
2733                         right = mshift_expr(state, index);
2734                         val = val >= right;
2735                         break;
2736                 default:
2737                         done = 1;
2738                         break;
2739                 }
2740         } while(!done);
2741         return val;
2742 }
2743
2744 static long_t meq_expr(struct compile_state *state, int index)
2745 {
2746         long_t val;
2747         int done;
2748         val = mrel_expr(state, index);
2749         do {
2750                 long_t right;
2751                 done = 0;
2752                 switch(mpeek(state, index)) {
2753                 case TOK_EQEQ:
2754                         meat(state, index, TOK_EQEQ);
2755                         right = mrel_expr(state, index);
2756                         val = val == right;
2757                         break;
2758                 case TOK_NOTEQ:
2759                         meat(state, index, TOK_NOTEQ);
2760                         right = mrel_expr(state, index);
2761                         val = val != right;
2762                         break;
2763                 default:
2764                         done = 1;
2765                         break;
2766                 }
2767         } while(!done);
2768         return val;
2769 }
2770
2771 static long_t mand_expr(struct compile_state *state, int index)
2772 {
2773         long_t val;
2774         val = meq_expr(state, index);
2775         if (mpeek(state, index) == TOK_AND) {
2776                 long_t right;
2777                 meat(state, index, TOK_AND);
2778                 right = meq_expr(state, index);
2779                 val = val & right;
2780         }
2781         return val;
2782 }
2783
2784 static long_t mxor_expr(struct compile_state *state, int index)
2785 {
2786         long_t val;
2787         val = mand_expr(state, index);
2788         if (mpeek(state, index) == TOK_XOR) {
2789                 long_t right;
2790                 meat(state, index, TOK_XOR);
2791                 right = mand_expr(state, index);
2792                 val = val ^ right;
2793         }
2794         return val;
2795 }
2796
2797 static long_t mor_expr(struct compile_state *state, int index)
2798 {
2799         long_t val;
2800         val = mxor_expr(state, index);
2801         if (mpeek(state, index) == TOK_OR) {
2802                 long_t right;
2803                 meat(state, index, TOK_OR);
2804                 right = mxor_expr(state, index);
2805                 val = val | right;
2806         }
2807         return val;
2808 }
2809
2810 static long_t mland_expr(struct compile_state *state, int index)
2811 {
2812         long_t val;
2813         val = mor_expr(state, index);
2814         if (mpeek(state, index) == TOK_LOGAND) {
2815                 long_t right;
2816                 meat(state, index, TOK_LOGAND);
2817                 right = mor_expr(state, index);
2818                 val = val && right;
2819         }
2820         return val;
2821 }
2822 static long_t mlor_expr(struct compile_state *state, int index)
2823 {
2824         long_t val;
2825         val = mland_expr(state, index);
2826         if (mpeek(state, index) == TOK_LOGOR) {
2827                 long_t right;
2828                 meat(state, index, TOK_LOGOR);
2829                 right = mland_expr(state, index);
2830                 val = val || right;
2831         }
2832         return val;
2833 }
2834
2835 static long_t mcexpr(struct compile_state *state, int index)
2836 {
2837         return mlor_expr(state, index);
2838 }
2839 static void preprocess(struct compile_state *state, int index)
2840 {
2841         /* Doing much more with the preprocessor would require
2842          * a parser and a major restructuring.
2843          * Postpone that for later.
2844          */
2845         struct file_state *file;
2846         struct token *tk;
2847         int line;
2848         int tok;
2849         
2850         file = state->file;
2851         tk = &state->token[index];
2852         state->macro_line = line = file->line;
2853         state->macro_file = file;
2854
2855         next_token(state, index);
2856         ident_to_macro(state, tk);
2857         if (tk->tok == TOK_IDENT) {
2858                 error(state, 0, "undefined preprocessing directive `%s'",
2859                         tk->ident->name);
2860         }
2861         switch(tk->tok) {
2862         case TOK_UNDEF:
2863         case TOK_LINE:
2864         case TOK_PRAGMA:
2865                 if (state->if_value < 0) {
2866                         break;
2867                 }
2868                 warning(state, 0, "Ignoring preprocessor directive: %s", 
2869                         tk->ident->name);
2870                 break;
2871         case TOK_ELIF:
2872                 error(state, 0, "#elif not supported");
2873 #warning "FIXME multiple #elif and #else in an #if do not work properly"
2874                 if (state->if_depth == 0) {
2875                         error(state, 0, "#elif without #if");
2876                 }
2877                 /* If the #if was taken the #elif just disables the following code */
2878                 if (state->if_value >= 0) {
2879                         state->if_value = - state->if_value;
2880                 }
2881                 /* If the previous #if was not taken see if the #elif enables the 
2882                  * trailing code.
2883                  */
2884                 else if ((state->if_value < 0) && 
2885                         (state->if_depth == - state->if_value))
2886                 {
2887                         if (mcexpr(state, index) != 0) {
2888                                 state->if_value = state->if_depth;
2889                         }
2890                         else {
2891                                 state->if_value = - state->if_depth;
2892                         }
2893                 }
2894                 break;
2895         case TOK_IF:
2896                 state->if_depth++;
2897                 if (state->if_value < 0) {
2898                         break;
2899                 }
2900                 if (mcexpr(state, index) != 0) {
2901                         state->if_value = state->if_depth;
2902                 }
2903                 else {
2904                         state->if_value = - state->if_depth;
2905                 }
2906                 break;
2907         case TOK_IFNDEF:
2908                 state->if_depth++;
2909                 if (state->if_value < 0) {
2910                         break;
2911                 }
2912                 next_token(state, index);
2913                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2914                         error(state, 0, "Invalid macro name");
2915                 }
2916                 if (tk->ident->sym_define == 0) {
2917                         state->if_value = state->if_depth;
2918                 } 
2919                 else {
2920                         state->if_value = - state->if_depth;
2921                 }
2922                 break;
2923         case TOK_IFDEF:
2924                 state->if_depth++;
2925                 if (state->if_value < 0) {
2926                         break;
2927                 }
2928                 next_token(state, index);
2929                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2930                         error(state, 0, "Invalid macro name");
2931                 }
2932                 if (tk->ident->sym_define != 0) {
2933                         state->if_value = state->if_depth;
2934                 }
2935                 else {
2936                         state->if_value = - state->if_depth;
2937                 }
2938                 break;
2939         case TOK_ELSE:
2940                 if (state->if_depth == 0) {
2941                         error(state, 0, "#else without #if");
2942                 }
2943                 if ((state->if_value >= 0) ||
2944                         ((state->if_value < 0) && 
2945                                 (state->if_depth == -state->if_value)))
2946                 {
2947                         state->if_value = - state->if_value;
2948                 }
2949                 break;
2950         case TOK_ENDIF:
2951                 if (state->if_depth == 0) {
2952                         error(state, 0, "#endif without #if");
2953                 }
2954                 if ((state->if_value >= 0) ||
2955                         ((state->if_value < 0) &&
2956                                 (state->if_depth == -state->if_value))) 
2957                 {
2958                         state->if_value = state->if_depth - 1;
2959                 }
2960                 state->if_depth--;
2961                 break;
2962         case TOK_DEFINE:
2963         {
2964                 struct hash_entry *ident;
2965                 struct macro *macro;
2966                 char *ptr;
2967                 
2968                 if (state->if_value < 0) /* quit early when #if'd out */
2969                         break;
2970
2971                 meat(state, index, TOK_IDENT);
2972                 ident = tk->ident;
2973                 
2974
2975                 if (*file->pos == '(') {
2976 #warning "FIXME macros with arguments not supported"
2977                         error(state, 0, "Macros with arguments not supported");
2978                 }
2979
2980                 /* Find the end of the line to get an estimate of
2981                  * the macro's length.
2982                  */
2983                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
2984                         ;
2985
2986                 if (ident->sym_define != 0) {
2987                         error(state, 0, "macro %s already defined\n", ident->name);
2988                 }
2989                 macro = xmalloc(sizeof(*macro), "macro");
2990                 macro->ident = ident;
2991                 macro->buf_len = ptr - file->pos +1;
2992                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
2993
2994                 memcpy(macro->buf, file->pos, macro->buf_len);
2995                 macro->buf[macro->buf_len] = '\n';
2996                 macro->buf[macro->buf_len +1] = '\0';
2997
2998                 ident->sym_define = macro;
2999                 break;
3000         }
3001         case TOK_ERROR:
3002         {
3003                 char *end;
3004                 int len;
3005                 /* Find the end of the line */
3006                 for(end = file->pos; *end != '\n'; end++)
3007                         ;
3008                 len = (end - file->pos);
3009                 if (state->if_value >= 0) {
3010                         error(state, 0, "%*.*s", len, len, file->pos);
3011                 }
3012                 file->pos = end;
3013                 break;
3014         }
3015         case TOK_WARNING:
3016         {
3017                 char *end;
3018                 int len;
3019                 /* Find the end of the line */
3020                 for(end = file->pos; *end != '\n'; end++)
3021                         ;
3022                 len = (end - file->pos);
3023                 if (state->if_value >= 0) {
3024                         warning(state, 0, "%*.*s", len, len, file->pos);
3025                 }
3026                 file->pos = end;
3027                 break;
3028         }
3029         case TOK_INCLUDE:
3030         {
3031                 char *name;
3032                 char *ptr;
3033                 int local;
3034                 local = 0;
3035                 name = 0;
3036                 next_token(state, index);
3037                 if (tk->tok == TOK_LIT_STRING) {
3038                         const char *token;
3039                         int name_len;
3040                         name = xmalloc(tk->str_len, "include");
3041                         token = tk->val.str +1;
3042                         name_len = tk->str_len -2;
3043                         if (*token == '"') {
3044                                 token++;
3045                                 name_len--;
3046                         }
3047                         memcpy(name, token, name_len);
3048                         name[name_len] = '\0';
3049                         local = 1;
3050                 }
3051                 else if (tk->tok == TOK_LESS) {
3052                         char *start, *end;
3053                         start = file->pos;
3054                         for(end = start; *end != '\n'; end++) {
3055                                 if (*end == '>') {
3056                                         break;
3057                                 }
3058                         }
3059                         if (*end == '\n') {
3060                                 error(state, 0, "Unterminated included directive");
3061                         }
3062                         name = xmalloc(end - start + 1, "include");
3063                         memcpy(name, start, end - start);
3064                         name[end - start] = '\0';
3065                         file->pos = end +1;
3066                         local = 0;
3067                 }
3068                 else {
3069                         error(state, 0, "Invalid include directive");
3070                 }
3071                 /* Error if there are any characters after the include */
3072                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3073                         if (!isspace(*ptr)) {
3074                                 error(state, 0, "garbage after include directive");
3075                         }
3076                 }
3077                 if (state->if_value >= 0) {
3078                         compile_file(state, name, local);
3079                 }
3080                 xfree(name);
3081                 next_token(state, index);
3082                 return;
3083         }
3084         default:
3085                 /* Ignore # without a following ident */
3086                 if (tk->tok == TOK_IDENT) {
3087                         error(state, 0, "Invalid preprocessor directive: %s", 
3088                                 tk->ident->name);
3089                 }
3090                 break;
3091         }
3092         /* Consume the rest of the macro line */
3093         do {
3094                 tok = mpeek(state, index);
3095                 meat(state, index, tok);
3096         } while(tok != TOK_EOF);
3097         return;
3098 }
3099
3100 static void token(struct compile_state *state, int index)
3101 {
3102         struct file_state *file;
3103         struct token *tk;
3104         int rescan;
3105
3106         tk = &state->token[index];
3107         next_token(state, index);
3108         do {
3109                 rescan = 0;
3110                 file = state->file;
3111                 if (tk->tok == TOK_EOF && file->prev) {
3112                         state->file = file->prev;
3113                         /* file->basename is used keep it */
3114                         xfree(file->dirname);
3115                         xfree(file->buf);
3116                         xfree(file);
3117                         next_token(state, index);
3118                         rescan = 1;
3119                 }
3120                 else if (tk->tok == TOK_MACRO) {
3121                         preprocess(state, index);
3122                         rescan = 1;
3123                 }
3124                 else if (tk->ident && tk->ident->sym_define) {
3125                         compile_macro(state, tk);
3126                         next_token(state, index);
3127                         rescan = 1;
3128                 }
3129                 else if (state->if_value < 0) {
3130                         next_token(state, index);
3131                         rescan = 1;
3132                 }
3133         } while(rescan);
3134 }
3135
3136 static int peek(struct compile_state *state)
3137 {
3138         if (state->token[1].tok == -1) {
3139                 token(state, 1);
3140         }
3141         return state->token[1].tok;
3142 }
3143
3144 static int peek2(struct compile_state *state)
3145 {
3146         if (state->token[1].tok == -1) {
3147                 token(state, 1);
3148         }
3149         if (state->token[2].tok == -1) {
3150                 token(state, 2);
3151         }
3152         return state->token[2].tok;
3153 }
3154
3155 static void eat(struct compile_state *state, int tok)
3156 {
3157         int next_tok;
3158         int i;
3159         next_tok = peek(state);
3160         if (next_tok != tok) {
3161                 const char *name1, *name2;
3162                 name1 = tokens[next_tok];
3163                 name2 = "";
3164                 if (next_tok == TOK_IDENT) {
3165                         name2 = state->token[1].ident->name;
3166                 }
3167                 error(state, 0, "\tfound %s %s expected %s",
3168                         name1, name2 ,tokens[tok]);
3169         }
3170         /* Free the old token value */
3171         if (state->token[0].str_len) {
3172                 xfree((void *)(state->token[0].val.str));
3173         }
3174         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3175                 state->token[i] = state->token[i + 1];
3176         }
3177         memset(&state->token[i], 0, sizeof(state->token[i]));
3178         state->token[i].tok = -1;
3179 }
3180
3181 #warning "FIXME do not hardcode the include paths"
3182 static char *include_paths[] = {
3183         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3184         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3185         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3186         0
3187 };
3188
3189 static void compile_file(struct compile_state *state, char *filename, int local)
3190 {
3191         char cwd[4096];
3192         char *subdir, *base;
3193         int subdir_len;
3194         struct file_state *file;
3195         char *basename;
3196         file = xmalloc(sizeof(*file), "file_state");
3197
3198         base = strrchr(filename, '/');
3199         subdir = filename;
3200         if (base != 0) {
3201                 subdir_len = base - filename;
3202                 base++;
3203         }
3204         else {
3205                 base = filename;
3206                 subdir_len = 0;
3207         }
3208         basename = xmalloc(strlen(base) +1, "basename");
3209         strcpy(basename, base);
3210         file->basename = basename;
3211
3212         if (getcwd(cwd, sizeof(cwd)) == 0) {
3213                 die("cwd buffer to small");
3214         }
3215         
3216         if (subdir[0] == '/') {
3217                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3218                 memcpy(file->dirname, subdir, subdir_len);
3219                 file->dirname[subdir_len] = '\0';
3220         }
3221         else {
3222                 char *dir;
3223                 int dirlen;
3224                 char **path;
3225                 /* Find the appropriate directory... */
3226                 dir = 0;
3227                 if (!state->file && exists(cwd, filename)) {
3228                         dir = cwd;
3229                 }
3230                 if (local && state->file && exists(state->file->dirname, filename)) {
3231                         dir = state->file->dirname;
3232                 }
3233                 for(path = include_paths; !dir && *path; path++) {
3234                         if (exists(*path, filename)) {
3235                                 dir = *path;
3236                         }
3237                 }
3238                 if (!dir) {
3239                         error(state, 0, "Cannot find `%s'\n", filename);
3240                 }
3241                 dirlen = strlen(dir);
3242                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3243                 memcpy(file->dirname, dir, dirlen);
3244                 file->dirname[dirlen] = '/';
3245                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3246                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3247         }
3248         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3249         xchdir(cwd);
3250
3251         file->pos = file->buf;
3252         file->line_start = file->pos;
3253         file->line = 1;
3254
3255         file->prev = state->file;
3256         state->file = file;
3257         
3258         process_trigraphs(state);
3259         splice_lines(state);
3260 }
3261
3262 /* Type helper functions */
3263
3264 static struct type *new_type(
3265         unsigned int type, struct type *left, struct type *right)
3266 {
3267         struct type *result;
3268         result = xmalloc(sizeof(*result), "type");
3269         result->type = type;
3270         result->left = left;
3271         result->right = right;
3272         result->field_ident = 0;
3273         result->type_ident = 0;
3274         return result;
3275 }
3276
3277 static struct type *clone_type(unsigned int specifiers, struct type *old)
3278 {
3279         struct type *result;
3280         result = xmalloc(sizeof(*result), "type");
3281         memcpy(result, old, sizeof(*result));
3282         result->type &= TYPE_MASK;
3283         result->type |= specifiers;
3284         return result;
3285 }
3286
3287 #define SIZEOF_SHORT 2
3288 #define SIZEOF_INT   4
3289 #define SIZEOF_LONG  (sizeof(long_t))
3290
3291 #define ALIGNOF_SHORT 2
3292 #define ALIGNOF_INT   4
3293 #define ALIGNOF_LONG  (sizeof(long_t))
3294
3295 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3296 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3297 static inline ulong_t mask_uint(ulong_t x)
3298 {
3299         if (SIZEOF_INT < SIZEOF_LONG) {
3300                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3301                 x &= mask;
3302         }
3303         return x;
3304 }
3305 #define MASK_UINT(X)      (mask_uint(X))
3306 #define MASK_ULONG(X)    (X)
3307
3308 static struct type void_type   = { .type  = TYPE_VOID };
3309 static struct type char_type   = { .type  = TYPE_CHAR };
3310 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3311 static struct type short_type  = { .type  = TYPE_SHORT };
3312 static struct type ushort_type = { .type  = TYPE_USHORT };
3313 static struct type int_type    = { .type  = TYPE_INT };
3314 static struct type uint_type   = { .type  = TYPE_UINT };
3315 static struct type long_type   = { .type  = TYPE_LONG };
3316 static struct type ulong_type  = { .type  = TYPE_ULONG };
3317
3318 static struct triple *variable(struct compile_state *state, struct type *type)
3319 {
3320         struct triple *result;
3321         if ((type->type & STOR_MASK) != STOR_PERM) {
3322                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3323                         result = triple(state, OP_ADECL, type, 0, 0);
3324                 } else {
3325                         struct type *field;
3326                         struct triple **vector;
3327                         ulong_t index;
3328                         result = new_triple(state, OP_VAL_VEC, type, -1);
3329                         vector = &result->param[0];
3330
3331                         field = type->left;
3332                         index = 0;
3333                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3334                                 vector[index] = variable(state, field->left);
3335                                 field = field->right;
3336                                 index++;
3337                         }
3338                         vector[index] = variable(state, field);
3339                 }
3340         }
3341         else {
3342                 result = triple(state, OP_SDECL, type, 0, 0);
3343         }
3344         return result;
3345 }
3346
3347 static void stor_of(FILE *fp, struct type *type)
3348 {
3349         switch(type->type & STOR_MASK) {
3350         case STOR_AUTO:
3351                 fprintf(fp, "auto ");
3352                 break;
3353         case STOR_STATIC:
3354                 fprintf(fp, "static ");
3355                 break;
3356         case STOR_EXTERN:
3357                 fprintf(fp, "extern ");
3358                 break;
3359         case STOR_REGISTER:
3360                 fprintf(fp, "register ");
3361                 break;
3362         case STOR_TYPEDEF:
3363                 fprintf(fp, "typedef ");
3364                 break;
3365         case STOR_INLINE:
3366                 fprintf(fp, "inline ");
3367                 break;
3368         }
3369 }
3370 static void qual_of(FILE *fp, struct type *type)
3371 {
3372         if (type->type & QUAL_CONST) {
3373                 fprintf(fp, " const");
3374         }
3375         if (type->type & QUAL_VOLATILE) {
3376                 fprintf(fp, " volatile");
3377         }
3378         if (type->type & QUAL_RESTRICT) {
3379                 fprintf(fp, " restrict");
3380         }
3381 }
3382
3383 static void name_of(FILE *fp, struct type *type)
3384 {
3385         stor_of(fp, type);
3386         switch(type->type & TYPE_MASK) {
3387         case TYPE_VOID:
3388                 fprintf(fp, "void");
3389                 qual_of(fp, type);
3390                 break;
3391         case TYPE_CHAR:
3392                 fprintf(fp, "signed char");
3393                 qual_of(fp, type);
3394                 break;
3395         case TYPE_UCHAR:
3396                 fprintf(fp, "unsigned char");
3397                 qual_of(fp, type);
3398                 break;
3399         case TYPE_SHORT:
3400                 fprintf(fp, "signed short");
3401                 qual_of(fp, type);
3402                 break;
3403         case TYPE_USHORT:
3404                 fprintf(fp, "unsigned short");
3405                 qual_of(fp, type);
3406                 break;
3407         case TYPE_INT:
3408                 fprintf(fp, "signed int");
3409                 qual_of(fp, type);
3410                 break;
3411         case TYPE_UINT:
3412                 fprintf(fp, "unsigned int");
3413                 qual_of(fp, type);
3414                 break;
3415         case TYPE_LONG:
3416                 fprintf(fp, "signed long");
3417                 qual_of(fp, type);
3418                 break;
3419         case TYPE_ULONG:
3420                 fprintf(fp, "unsigned long");
3421                 qual_of(fp, type);
3422                 break;
3423         case TYPE_POINTER:
3424                 name_of(fp, type->left);
3425                 fprintf(fp, " * ");
3426                 qual_of(fp, type);
3427                 break;
3428         case TYPE_PRODUCT:
3429         case TYPE_OVERLAP:
3430                 name_of(fp, type->left);
3431                 fprintf(fp, ", ");
3432                 name_of(fp, type->right);
3433                 break;
3434         case TYPE_ENUM:
3435                 fprintf(fp, "enum %s", type->type_ident->name);
3436                 qual_of(fp, type);
3437                 break;
3438         case TYPE_STRUCT:
3439                 fprintf(fp, "struct %s", type->type_ident->name);
3440                 qual_of(fp, type);
3441                 break;
3442         case TYPE_FUNCTION:
3443         {
3444                 name_of(fp, type->left);
3445                 fprintf(fp, " (*)(");
3446                 name_of(fp, type->right);
3447                 fprintf(fp, ")");
3448                 break;
3449         }
3450         case TYPE_ARRAY:
3451                 name_of(fp, type->left);
3452                 fprintf(fp, " [%ld]", type->elements);
3453                 break;
3454         default:
3455                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3456                 break;
3457         }
3458 }
3459
3460 static size_t align_of(struct compile_state *state, struct type *type)
3461 {
3462         size_t align;
3463         align = 0;
3464         switch(type->type & TYPE_MASK) {
3465         case TYPE_VOID:
3466                 align = 1;
3467                 break;
3468         case TYPE_CHAR:
3469         case TYPE_UCHAR:
3470                 align = 1;
3471                 break;
3472         case TYPE_SHORT:
3473         case TYPE_USHORT:
3474                 align = ALIGNOF_SHORT;
3475                 break;
3476         case TYPE_INT:
3477         case TYPE_UINT:
3478         case TYPE_ENUM:
3479                 align = ALIGNOF_INT;
3480                 break;
3481         case TYPE_LONG:
3482         case TYPE_ULONG:
3483         case TYPE_POINTER:
3484                 align = ALIGNOF_LONG;
3485                 break;
3486         case TYPE_PRODUCT:
3487         case TYPE_OVERLAP:
3488         {
3489                 size_t left_align, right_align;
3490                 left_align  = align_of(state, type->left);
3491                 right_align = align_of(state, type->right);
3492                 align = (left_align >= right_align) ? left_align : right_align;
3493                 break;
3494         }
3495         case TYPE_ARRAY:
3496                 align = align_of(state, type->left);
3497                 break;
3498         case TYPE_STRUCT:
3499                 align = align_of(state, type->left);
3500                 break;
3501         default:
3502                 error(state, 0, "alignof not yet defined for type\n");
3503                 break;
3504         }
3505         return align;
3506 }
3507
3508 static size_t size_of(struct compile_state *state, struct type *type)
3509 {
3510         size_t size;
3511         size = 0;
3512         switch(type->type & TYPE_MASK) {
3513         case TYPE_VOID:
3514                 size = 0;
3515                 break;
3516         case TYPE_CHAR:
3517         case TYPE_UCHAR:
3518                 size = 1;
3519                 break;
3520         case TYPE_SHORT:
3521         case TYPE_USHORT:
3522                 size = SIZEOF_SHORT;
3523                 break;
3524         case TYPE_INT:
3525         case TYPE_UINT:
3526         case TYPE_ENUM:
3527                 size = SIZEOF_INT;
3528                 break;
3529         case TYPE_LONG:
3530         case TYPE_ULONG:
3531         case TYPE_POINTER:
3532                 size = SIZEOF_LONG;
3533                 break;
3534         case TYPE_PRODUCT:
3535         {
3536                 size_t align, pad;
3537                 size = size_of(state, type->left);
3538                 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3539                         type = type->right;
3540                         align = align_of(state, type->left);
3541                         pad = align - (size % align);
3542                         size = size + pad + size_of(state, type->left);
3543                 }
3544                 align = align_of(state, type->right);
3545                 pad = align - (size % align);
3546                 size = size + pad + sizeof(type->right);
3547                 break;
3548         }
3549         case TYPE_OVERLAP:
3550         {
3551                 size_t size_left, size_right;
3552                 size_left = size_of(state, type->left);
3553                 size_right = size_of(state, type->right);
3554                 size = (size_left >= size_right)? size_left : size_right;
3555                 break;
3556         }
3557         case TYPE_ARRAY:
3558                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3559                         internal_error(state, 0, "Invalid array type");
3560                 } else {
3561                         size = size_of(state, type->left) * type->elements;
3562                 }
3563                 break;
3564         case TYPE_STRUCT:
3565                 size = size_of(state, type->left);
3566                 break;
3567         default:
3568                 error(state, 0, "sizeof not yet defined for type\n");
3569                 break;
3570         }
3571         return size;
3572 }
3573
3574 static size_t field_offset(struct compile_state *state, 
3575         struct type *type, struct hash_entry *field)
3576 {
3577         size_t size, align, pad;
3578         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3579                 internal_error(state, 0, "field_offset only works on structures");
3580         }
3581         size = 0;
3582         type = type->left;
3583         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3584                 if (type->left->field_ident == field) {
3585                         type = type->left;
3586                 }
3587                 size += size_of(state, type->left);
3588                 type = type->right;
3589                 align = align_of(state, type->left);
3590                 pad = align - (size % align);
3591                 size += pad;
3592         }
3593         if (type->field_ident != field) {
3594                 internal_error(state, 0, "field_offset: member %s not present",
3595                         field->name);
3596         }
3597         return size;
3598 }
3599
3600 static struct type *field_type(struct compile_state *state, 
3601         struct type *type, struct hash_entry *field)
3602 {
3603         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3604                 internal_error(state, 0, "field_type only works on structures");
3605         }
3606         type = type->left;
3607         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3608                 if (type->left->field_ident == field) {
3609                         type = type->left;
3610                         break;
3611                 }
3612                 type = type->right;
3613         }
3614         if (type->field_ident != field) {
3615                 internal_error(state, 0, "field_type: member %s not present", 
3616                         field->name);
3617         }
3618         return type;
3619 }
3620
3621 static struct triple *struct_field(struct compile_state *state,
3622         struct triple *decl, struct hash_entry *field)
3623 {
3624         struct triple **vector;
3625         struct type *type;
3626         ulong_t index;
3627         type = decl->type;
3628         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3629                 return decl;
3630         }
3631         if (decl->op != OP_VAL_VEC) {
3632                 internal_error(state, 0, "Invalid struct variable");
3633         }
3634         if (!field) {
3635                 internal_error(state, 0, "Missing structure field");
3636         }
3637         type = type->left;
3638         vector = &RHS(decl, 0);
3639         index = 0;
3640         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3641                 if (type->left->field_ident == field) {
3642                         type = type->left;
3643                         break;
3644                 }
3645                 index += 1;
3646                 type = type->right;
3647         }
3648         if (type->field_ident != field) {
3649                 internal_error(state, 0, "field %s not found?", field->name);
3650         }
3651         return vector[index];
3652 }
3653
3654 static void arrays_complete(struct compile_state *state, struct type *type)
3655 {
3656         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3657                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3658                         error(state, 0, "array size not specified");
3659                 }
3660                 arrays_complete(state, type->left);
3661         }
3662 }
3663
3664 static unsigned int do_integral_promotion(unsigned int type)
3665 {
3666         type &= TYPE_MASK;
3667         if (TYPE_INTEGER(type) && 
3668                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3669                 type = TYPE_INT;
3670         }
3671         return type;
3672 }
3673
3674 static unsigned int do_arithmetic_conversion(
3675         unsigned int left, unsigned int right)
3676 {
3677         left &= TYPE_MASK;
3678         right &= TYPE_MASK;
3679         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3680                 return TYPE_LDOUBLE;
3681         }
3682         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3683                 return TYPE_DOUBLE;
3684         }
3685         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3686                 return TYPE_FLOAT;
3687         }
3688         left = do_integral_promotion(left);
3689         right = do_integral_promotion(right);
3690         /* If both operands have the same size done */
3691         if (left == right) {
3692                 return left;
3693         }
3694         /* If both operands have the same signedness pick the larger */
3695         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3696                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3697         }
3698         /* If the signed type can hold everything use it */
3699         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3700                 return left;
3701         }
3702         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3703                 return right;
3704         }
3705         /* Convert to the unsigned type with the same rank as the signed type */
3706         else if (TYPE_SIGNED(left)) {
3707                 return TYPE_MKUNSIGNED(left);
3708         }
3709         else {
3710                 return TYPE_MKUNSIGNED(right);
3711         }
3712 }
3713
3714 /* see if two types are the same except for qualifiers */
3715 static int equiv_types(struct type *left, struct type *right)
3716 {
3717         unsigned int type;
3718         /* Error if the basic types do not match */
3719         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3720                 return 0;
3721         }
3722         type = left->type & TYPE_MASK;
3723         /* if the basic types match and it is an arithmetic type we are done */
3724         if (TYPE_ARITHMETIC(type)) {
3725                 return 1;
3726         }
3727         /* If it is a pointer type recurse and keep testing */
3728         if (type == TYPE_POINTER) {
3729                 return equiv_types(left->left, right->left);
3730         }
3731         else if (type == TYPE_ARRAY) {
3732                 return (left->elements == right->elements) &&
3733                         equiv_types(left->left, right->left);
3734         }
3735         /* test for struct/union equality */
3736         else if (type == TYPE_STRUCT) {
3737                 return left->type_ident == right->type_ident;
3738         }
3739         /* Test for equivalent functions */
3740         else if (type == TYPE_FUNCTION) {
3741                 return equiv_types(left->left, right->left) &&
3742                         equiv_types(left->right, right->right);
3743         }
3744         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3745         else if (type == TYPE_PRODUCT) {
3746                 return equiv_types(left->left, right->left) &&
3747                         equiv_types(left->right, right->right);
3748         }
3749         /* We should see TYPE_OVERLAP */
3750         else {
3751                 return 0;
3752         }
3753 }
3754
3755 static int equiv_ptrs(struct type *left, struct type *right)
3756 {
3757         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3758                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3759                 return 0;
3760         }
3761         return equiv_types(left->left, right->left);
3762 }
3763
3764 static struct type *compatible_types(struct type *left, struct type *right)
3765 {
3766         struct type *result;
3767         unsigned int type, qual_type;
3768         /* Error if the basic types do not match */
3769         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3770                 return 0;
3771         }
3772         type = left->type & TYPE_MASK;
3773         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3774         result = 0;
3775         /* if the basic types match and it is an arithmetic type we are done */
3776         if (TYPE_ARITHMETIC(type)) {
3777                 result = new_type(qual_type, 0, 0);
3778         }
3779         /* If it is a pointer type recurse and keep testing */
3780         else if (type == TYPE_POINTER) {
3781                 result = compatible_types(left->left, right->left);
3782                 if (result) {
3783                         result = new_type(qual_type, result, 0);
3784                 }
3785         }
3786         /* test for struct/union equality */
3787         else if (type == TYPE_STRUCT) {
3788                 if (left->type_ident == right->type_ident) {
3789                         result = left;
3790                 }
3791         }
3792         /* Test for equivalent functions */
3793         else if (type == TYPE_FUNCTION) {
3794                 struct type *lf, *rf;
3795                 lf = compatible_types(left->left, right->left);
3796                 rf = compatible_types(left->right, right->right);
3797                 if (lf && rf) {
3798                         result = new_type(qual_type, lf, rf);
3799                 }
3800         }
3801         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3802         else if (type == TYPE_PRODUCT) {
3803                 struct type *lf, *rf;
3804                 lf = compatible_types(left->left, right->left);
3805                 rf = compatible_types(left->right, right->right);
3806                 if (lf && rf) {
3807                         result = new_type(qual_type, lf, rf);
3808                 }
3809         }
3810         else {
3811                 /* Nothing else is compatible */
3812         }
3813         return result;
3814 }
3815
3816 static struct type *compatible_ptrs(struct type *left, struct type *right)
3817 {
3818         struct type *result;
3819         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3820                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3821                 return 0;
3822         }
3823         result = compatible_types(left->left, right->left);
3824         if (result) {
3825                 unsigned int qual_type;
3826                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3827                 result = new_type(qual_type, result, 0);
3828         }
3829         return result;
3830         
3831 }
3832 static struct triple *integral_promotion(
3833         struct compile_state *state, struct triple *def)
3834 {
3835         struct type *type;
3836         type = def->type;
3837         /* As all operations are carried out in registers
3838          * the values are converted on load I just convert
3839          * logical type of the operand.
3840          */
3841         if (TYPE_INTEGER(type->type)) {
3842                 unsigned int int_type;
3843                 int_type = type->type & ~TYPE_MASK;
3844                 int_type |= do_integral_promotion(type->type);
3845                 if (int_type != type->type) {
3846                         def->type = new_type(int_type, 0, 0);
3847                 }
3848         }
3849         return def;
3850 }
3851
3852
3853 static void arithmetic(struct compile_state *state, struct triple *def)
3854 {
3855         if (!TYPE_ARITHMETIC(def->type->type)) {
3856                 error(state, def, "arithmetic type expexted");
3857         }
3858 }
3859
3860 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
3861 {
3862         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
3863                 error(state, def, "pointer or arithmetic type expected");
3864         }
3865 }
3866
3867 static int is_integral(struct triple *ins)
3868 {
3869         return TYPE_INTEGER(ins->type->type);
3870 }
3871
3872 static void integral(struct compile_state *state, struct triple *def)
3873 {
3874         if (!is_integral(def)) {
3875                 error(state, 0, "integral type expected");
3876         }
3877 }
3878
3879
3880 static void bool(struct compile_state *state, struct triple *def)
3881 {
3882         if (!TYPE_ARITHMETIC(def->type->type) &&
3883                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
3884                 error(state, 0, "arithmetic or pointer type expected");
3885         }
3886 }
3887
3888 static int is_signed(struct type *type)
3889 {
3890         return !!TYPE_SIGNED(type->type);
3891 }
3892
3893 /* Is this value located in a register otherwise it must be in memory */
3894 static int is_in_reg(struct compile_state *state, struct triple *def)
3895 {
3896         int in_reg;
3897         if (def->op == OP_ADECL) {
3898                 in_reg = 1;
3899         }
3900         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
3901                 in_reg = 0;
3902         }
3903         else if (def->op == OP_VAL_VEC) {
3904                 in_reg = is_in_reg(state, RHS(def, 0));
3905         }
3906         else if (def->op == OP_DOT) {
3907                 in_reg = is_in_reg(state, RHS(def, 0));
3908         }
3909         else {
3910                 internal_error(state, 0, "unknown expr storage location");
3911                 in_reg = -1;
3912         }
3913         return in_reg;
3914 }
3915
3916 /* Is this a stable variable location otherwise it must be a temporary */
3917 static int is_stable(struct compile_state *state, struct triple *def)
3918 {
3919         int ret;
3920         ret = 0;
3921         if (!def) {
3922                 return 0;
3923         }
3924         if ((def->op == OP_ADECL) || 
3925                 (def->op == OP_SDECL) || 
3926                 (def->op == OP_DEREF) ||
3927                 (def->op == OP_BLOBCONST)) {
3928                 ret = 1;
3929         }
3930         else if (def->op == OP_DOT) {
3931                 ret = is_stable(state, RHS(def, 0));
3932         }
3933         else if (def->op == OP_VAL_VEC) {
3934                 struct triple **vector;
3935                 ulong_t i;
3936                 ret = 1;
3937                 vector = &RHS(def, 0);
3938                 for(i = 0; i < def->type->elements; i++) {
3939                         if (!is_stable(state, vector[i])) {
3940                                 ret = 0;
3941                                 break;
3942                         }
3943                 }
3944         }
3945         return ret;
3946 }
3947
3948 static int is_lvalue(struct compile_state *state, struct triple *def)
3949 {
3950         int ret;
3951         ret = 1;
3952         if (!def) {
3953                 return 0;
3954         }
3955         if (!is_stable(state, def)) {
3956                 return 0;
3957         }
3958         if (def->type->type & QUAL_CONST) {
3959                 ret = 0;
3960         }
3961         else if (def->op == OP_DOT) {
3962                 ret = is_lvalue(state, RHS(def, 0));
3963         }
3964         return ret;
3965 }
3966
3967 static void lvalue(struct compile_state *state, struct triple *def)
3968 {
3969         if (!def) {
3970                 internal_error(state, def, "nothing where lvalue expected?");
3971         }
3972         if (!is_lvalue(state, def)) { 
3973                 error(state, def, "lvalue expected");
3974         }
3975 }
3976
3977 static int is_pointer(struct triple *def)
3978 {
3979         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
3980 }
3981
3982 static void pointer(struct compile_state *state, struct triple *def)
3983 {
3984         if (!is_pointer(def)) {
3985                 error(state, def, "pointer expected");
3986         }
3987 }
3988
3989 static struct triple *int_const(
3990         struct compile_state *state, struct type *type, ulong_t value)
3991 {
3992         struct triple *result;
3993         switch(type->type & TYPE_MASK) {
3994         case TYPE_CHAR:
3995         case TYPE_INT:   case TYPE_UINT:
3996         case TYPE_LONG:  case TYPE_ULONG:
3997                 break;
3998         default:
3999                 internal_error(state, 0, "constant for unkown type");
4000         }
4001         result = triple(state, OP_INTCONST, type, 0, 0);
4002         result->u.cval = value;
4003         return result;
4004 }
4005
4006
4007 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4008         struct triple *expr, struct type *type, ulong_t offset)
4009 {
4010         struct triple *result;
4011         lvalue(state, expr);
4012
4013         result = 0;
4014         if (expr->op == OP_ADECL) {
4015                 error(state, expr, "address of auto variables not supported");
4016         }
4017         else if (expr->op == OP_SDECL) {
4018                 result = triple(state, OP_ADDRCONST, type, expr, 0);
4019                 result->u.cval = offset;
4020         }
4021         else if (expr->op == OP_DEREF) {
4022                 result = triple(state, OP_ADD, type,
4023                         RHS(expr, 0),
4024                         int_const(state, &ulong_type, offset));
4025         }
4026         return result;
4027 }
4028
4029 static struct triple *mk_addr_expr(
4030         struct compile_state *state, struct triple *expr, ulong_t offset)
4031 {
4032         struct type *type;
4033         
4034         type = new_type(
4035                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4036                 expr->type, 0);
4037
4038         return do_mk_addr_expr(state, expr, type, offset);
4039 }
4040
4041 static struct triple *mk_deref_expr(
4042         struct compile_state *state, struct triple *expr)
4043 {
4044         struct type *base_type;
4045         pointer(state, expr);
4046         base_type = expr->type->left;
4047         if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4048                 error(state, 0, 
4049                         "Only pointer and arithmetic values can be dereferenced");
4050         }
4051         return triple(state, OP_DEREF, base_type, expr, 0);
4052 }
4053
4054 static struct triple *deref_field(
4055         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4056 {
4057         struct triple *result;
4058         struct type *type, *member;
4059         if (!field) {
4060                 internal_error(state, 0, "No field passed to deref_field");
4061         }
4062         result = 0;
4063         type = expr->type;
4064         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4065                 error(state, 0, "request for member %s in something not a struct or union",
4066                         field->name);
4067         }
4068         member = type->left;
4069         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070                 if (member->left->field_ident == field) {
4071                         member = member->left;
4072                         break;
4073                 }
4074                 member = member->right;
4075         }
4076         if (member->field_ident != field) {
4077                 error(state, 0, "%s is not a member", field->name);
4078         }
4079         if ((type->type & STOR_MASK) == STOR_PERM) {
4080                 /* Do the pointer arithmetic to get a deref the field */
4081                 ulong_t offset;
4082                 offset = field_offset(state, type, field);
4083                 result = do_mk_addr_expr(state, expr, member, offset);
4084                 result = mk_deref_expr(state, result);
4085         }
4086         else {
4087                 /* Find the variable for the field I want. */
4088                 result = triple(state, OP_DOT, 
4089                         field_type(state, type, field), expr, 0);
4090                 result->u.field = field;
4091         }
4092         return result;
4093 }
4094
4095 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4096 {
4097         int op;
4098         if  (!def) {
4099                 return 0;
4100         }
4101         if (!is_stable(state, def)) {
4102                 return def;
4103         }
4104         /* Tranform an array to a pointer to the first element */
4105 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4106         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4107                 struct type *type;
4108                 type = new_type(
4109                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4110                         def->type->left, 0);
4111                 return triple(state, OP_ADDRCONST, type, def, 0);
4112         }
4113         if (is_in_reg(state, def)) {
4114                 op = OP_READ;
4115         } else {
4116                 op = OP_LOAD;
4117         }
4118         return triple(state, op, def->type, def, 0);
4119 }
4120
4121 static void write_compatible(struct compile_state *state,
4122         struct type *dest, struct type *rval)
4123 {
4124         int compatible = 0;
4125         /* Both operands have arithmetic type */
4126         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4127                 compatible = 1;
4128         }
4129         /* One operand is a pointer and the other is a pointer to void */
4130         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4131                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4132                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4133                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4134                 compatible = 1;
4135         }
4136         /* If both types are the same without qualifiers we are good */
4137         else if (equiv_ptrs(dest, rval)) {
4138                 compatible = 1;
4139         }
4140         /* test for struct/union equality  */
4141         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4142                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4143                 (dest->type_ident == rval->type_ident)) {
4144                 compatible = 1;
4145         }
4146         if (!compatible) {
4147                 error(state, 0, "Incompatible types in assignment");
4148         }
4149 }
4150
4151 static struct triple *write_expr(
4152         struct compile_state *state, struct triple *dest, struct triple *rval)
4153 {
4154         struct triple *def;
4155         int op;
4156
4157         def = 0;
4158         if (!rval) {
4159                 internal_error(state, 0, "missing rval");
4160         }
4161
4162         if (rval->op == OP_LIST) {
4163                 internal_error(state, 0, "expression of type OP_LIST?");
4164         }
4165         if (!is_lvalue(state, dest)) {
4166                 internal_error(state, 0, "writing to a non lvalue?");
4167         }
4168
4169         write_compatible(state, dest->type, rval->type);
4170
4171         /* Now figure out which assignment operator to use */
4172         op = -1;
4173         if (is_in_reg(state, dest)) {
4174                 op = OP_WRITE;
4175         } else {
4176                 op = OP_STORE;
4177         }
4178         def = triple(state, op, dest->type, dest, rval);
4179         return def;
4180 }
4181
4182 static struct triple *init_expr(
4183         struct compile_state *state, struct triple *dest, struct triple *rval)
4184 {
4185         struct triple *def;
4186
4187         def = 0;
4188         if (!rval) {
4189                 internal_error(state, 0, "missing rval");
4190         }
4191         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4192                 rval = read_expr(state, rval);
4193                 def = write_expr(state, dest, rval);
4194         }
4195         else {
4196                 /* Fill in the array size if necessary */
4197                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4198                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4199                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4200                                 dest->type->elements = rval->type->elements;
4201                         }
4202                 }
4203                 if (!equiv_types(dest->type, rval->type)) {
4204                         error(state, 0, "Incompatible types in inializer");
4205                 }
4206                 MISC(dest, 0) = rval;
4207         }
4208         return def;
4209 }
4210
4211 struct type *arithmetic_result(
4212         struct compile_state *state, struct triple *left, struct triple *right)
4213 {
4214         struct type *type;
4215         /* Sanity checks to ensure I am working with arithmetic types */
4216         arithmetic(state, left);
4217         arithmetic(state, right);
4218         type = new_type(
4219                 do_arithmetic_conversion(
4220                         left->type->type, 
4221                         right->type->type), 0, 0);
4222         return type;
4223 }
4224
4225 struct type *ptr_arithmetic_result(
4226         struct compile_state *state, struct triple *left, struct triple *right)
4227 {
4228         struct type *type;
4229         /* Sanity checks to ensure I am working with the proper types */
4230         ptr_arithmetic(state, left);
4231         arithmetic(state, right);
4232         if (TYPE_ARITHMETIC(left->type->type) && 
4233                 TYPE_ARITHMETIC(right->type->type)) {
4234                 type = arithmetic_result(state, left, right);
4235         }
4236         else if (TYPE_PTR(left->type->type)) {
4237                 type = left->type;
4238         }
4239         else {
4240                 internal_error(state, 0, "huh?");
4241                 type = 0;
4242         }
4243         return type;
4244 }
4245
4246
4247 /* boolean helper function */
4248
4249 static struct triple *ltrue_expr(struct compile_state *state, 
4250         struct triple *expr)
4251 {
4252         switch(expr->op) {
4253         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4254         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4255         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4256                 /* If the expression is already boolean do nothing */
4257                 break;
4258         default:
4259                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4260                 break;
4261         }
4262         return expr;
4263 }
4264
4265 static struct triple *lfalse_expr(struct compile_state *state, 
4266         struct triple *expr)
4267 {
4268         return triple(state, OP_LFALSE, &int_type, expr, 0);
4269 }
4270
4271 static struct triple *cond_expr(
4272         struct compile_state *state, 
4273         struct triple *test, struct triple *left, struct triple *right)
4274 {
4275         struct triple *def;
4276         struct type *result_type;
4277         unsigned int left_type, right_type;
4278         bool(state, test);
4279         left_type = left->type->type;
4280         right_type = right->type->type;
4281         result_type = 0;
4282         /* Both operands have arithmetic type */
4283         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4284                 result_type = arithmetic_result(state, left, right);
4285         }
4286         /* Both operands have void type */
4287         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4288                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4289                 result_type = &void_type;
4290         }
4291         /* pointers to the same type... */
4292         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4293                 ;
4294         }
4295         /* Both operands are pointers and left is a pointer to void */
4296         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4297                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4298                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4299                 result_type = right->type;
4300         }
4301         /* Both operands are pointers and right is a pointer to void */
4302         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4303                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4304                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4305                 result_type = left->type;
4306         }
4307         if (!result_type) {
4308                 error(state, 0, "Incompatible types in conditional expression");
4309         }
4310         /* Cleanup and invert the test */
4311         test = lfalse_expr(state, read_expr(state, test));
4312         def = new_triple(state, OP_COND, result_type, 3);
4313         def->param[0] = test;
4314         def->param[1] = left;
4315         def->param[2] = right;
4316         return def;
4317 }
4318
4319
4320 static int expr_depth(struct compile_state *state, struct triple *ins)
4321 {
4322         int count;
4323         count = 0;
4324         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4325                 count = 0;
4326         }
4327         else if (ins->op == OP_DEREF) {
4328                 count = expr_depth(state, RHS(ins, 0)) - 1;
4329         }
4330         else if (ins->op == OP_VAL) {
4331                 count = expr_depth(state, RHS(ins, 0)) - 1;
4332         }
4333         else if (ins->op == OP_COMMA) {
4334                 int ldepth, rdepth;
4335                 ldepth = expr_depth(state, RHS(ins, 0));
4336                 rdepth = expr_depth(state, RHS(ins, 1));
4337                 count = (ldepth >= rdepth)? ldepth : rdepth;
4338         }
4339         else if (ins->op == OP_CALL) {
4340                 /* Don't figure the depth of a call just guess it is huge */
4341                 count = 1000;
4342         }
4343         else {
4344                 struct triple **expr;
4345                 expr = triple_rhs(state, ins, 0);
4346                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4347                         if (*expr) {
4348                                 int depth;
4349                                 depth = expr_depth(state, *expr);
4350                                 if (depth > count) {
4351                                         count = depth;
4352                                 }
4353                         }
4354                 }
4355         }
4356         return count + 1;
4357 }
4358
4359 static struct triple *flatten(
4360         struct compile_state *state, struct triple *first, struct triple *ptr);
4361
4362 static struct triple *flatten_generic(
4363         struct compile_state *state, struct triple *first, struct triple *ptr)
4364 {
4365         struct rhs_vector {
4366                 int depth;
4367                 struct triple **ins;
4368         } vector[MAX_RHS];
4369         int i, rhs, lhs;
4370         /* Only operations with just a rhs should come here */
4371         rhs = TRIPLE_RHS(ptr->sizes);
4372         lhs = TRIPLE_LHS(ptr->sizes);
4373         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4374                 internal_error(state, ptr, "unexpected args for: %d %s",
4375                         ptr->op, tops(ptr->op));
4376         }
4377         /* Find the depth of the rhs elements */
4378         for(i = 0; i < rhs; i++) {
4379                 vector[i].ins = &RHS(ptr, i);
4380                 vector[i].depth = expr_depth(state, *vector[i].ins);
4381         }
4382         /* Selection sort the rhs */
4383         for(i = 0; i < rhs; i++) {
4384                 int j, max = i;
4385                 for(j = i + 1; j < rhs; j++ ) {
4386                         if (vector[j].depth > vector[max].depth) {
4387                                 max = j;
4388                         }
4389                 }
4390                 if (max != i) {
4391                         struct rhs_vector tmp;
4392                         tmp = vector[i];
4393                         vector[i] = vector[max];
4394                         vector[max] = tmp;
4395                 }
4396         }
4397         /* Now flatten the rhs elements */
4398         for(i = 0; i < rhs; i++) {
4399                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4400                 use_triple(*vector[i].ins, ptr);
4401         }
4402         
4403         /* Now flatten the lhs elements */
4404         for(i = 0; i < lhs; i++) {
4405                 struct triple **ins = &LHS(ptr, i);
4406                 *ins = flatten(state, first, *ins);
4407                 use_triple(*ins, ptr);
4408         }
4409         return ptr;
4410 }
4411
4412 static struct triple *flatten_land(
4413         struct compile_state *state, struct triple *first, struct triple *ptr)
4414 {
4415         struct triple *left, *right;
4416         struct triple *val, *test, *jmp, *label1, *end;
4417
4418         /* Find the triples */
4419         left = RHS(ptr, 0);
4420         right = RHS(ptr, 1);
4421
4422         /* Generate the needed triples */
4423         end = label(state);
4424
4425         /* Thread the triples together */
4426         val          = flatten(state, first, variable(state, ptr->type));
4427         left         = flatten(state, first, write_expr(state, val, left));
4428         test         = flatten(state, first, 
4429                 lfalse_expr(state, read_expr(state, val)));
4430         jmp          = flatten(state, first, branch(state, end, test));
4431         label1       = flatten(state, first, label(state));
4432         right        = flatten(state, first, write_expr(state, val, right));
4433         TARG(jmp, 0) = flatten(state, first, end); 
4434         
4435         /* Now give the caller something to chew on */
4436         return read_expr(state, val);
4437 }
4438
4439 static struct triple *flatten_lor(
4440         struct compile_state *state, struct triple *first, struct triple *ptr)
4441 {
4442         struct triple *left, *right;
4443         struct triple *val, *jmp, *label1, *end;
4444
4445         /* Find the triples */
4446         left = RHS(ptr, 0);
4447         right = RHS(ptr, 1);
4448
4449         /* Generate the needed triples */
4450         end = label(state);
4451
4452         /* Thread the triples together */
4453         val          = flatten(state, first, variable(state, ptr->type));
4454         left         = flatten(state, first, write_expr(state, val, left));
4455         jmp          = flatten(state, first, branch(state, end, left));
4456         label1       = flatten(state, first, label(state));
4457         right        = flatten(state, first, write_expr(state, val, right));
4458         TARG(jmp, 0) = flatten(state, first, end);
4459        
4460         
4461         /* Now give the caller something to chew on */
4462         return read_expr(state, val);
4463 }
4464
4465 static struct triple *flatten_cond(
4466         struct compile_state *state, struct triple *first, struct triple *ptr)
4467 {
4468         struct triple *test, *left, *right;
4469         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4470
4471         /* Find the triples */
4472         test = RHS(ptr, 0);
4473         left = RHS(ptr, 1);
4474         right = RHS(ptr, 2);
4475
4476         /* Generate the needed triples */
4477         end = label(state);
4478         middle = label(state);
4479
4480         /* Thread the triples together */
4481         val           = flatten(state, first, variable(state, ptr->type));
4482         test          = flatten(state, first, test);
4483         jmp1          = flatten(state, first, branch(state, middle, test));
4484         label1        = flatten(state, first, label(state));
4485         left          = flatten(state, first, left);
4486         mv1           = flatten(state, first, write_expr(state, val, left));
4487         jmp2          = flatten(state, first, branch(state, end, 0));
4488         TARG(jmp1, 0) = flatten(state, first, middle);
4489         right         = flatten(state, first, right);
4490         mv2           = flatten(state, first, write_expr(state, val, right));
4491         TARG(jmp2, 0) = flatten(state, first, end);
4492         
4493         /* Now give the caller something to chew on */
4494         return read_expr(state, val);
4495 }
4496
4497 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4498 {
4499         struct triple *nfunc;
4500         struct triple *nfirst, *ofirst;
4501         struct triple *new, *old;
4502
4503 #if 0
4504         fprintf(stdout, "\n");
4505         loc(stdout, state, 0);
4506         fprintf(stdout, "\n__________ copy_func _________\n");
4507         print_triple(state, ofunc);
4508         fprintf(stdout, "__________ copy_func _________ done\n\n");
4509 #endif
4510
4511         /* Make a new copy of the old function */
4512         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4513         nfirst = 0;
4514         ofirst = old = RHS(ofunc, 0);
4515         do {
4516                 struct triple *new;
4517                 int old_rhs;
4518                 old_rhs = TRIPLE_RHS(old->sizes);
4519                 new = alloc_triple(state, old->op, old->type, old_rhs,
4520                         old->filename, old->line, old->col);
4521                 if (IS_CONST_OP(new->op)) {
4522                         memcpy(&new->u, &old->u, sizeof(new->u));
4523                 }
4524 #warning "WISHLIST find a way to handle SDECL without a special case..."
4525                 /* The problem is that I don't flatten the misc field,
4526                  * so I cannot look the value the misc field should have.
4527                  */
4528                 else if (new->op == OP_SDECL) {
4529                         MISC(new, 0) = MISC(old, 0);
4530                 }
4531                 if (!nfirst) {
4532                         RHS(nfunc, 0) = nfirst = new;
4533                 }
4534                 else {
4535                         insert_triple(state, nfirst, new);
4536                 }
4537                 new->id |= TRIPLE_FLAG_FLATTENED;
4538                 
4539                 /* During the copy remember new as user of old */
4540                 use_triple(old, new);
4541
4542                 /* Populate the return type if present */
4543                 if (old == MISC(ofunc, 0)) {
4544                         MISC(nfunc, 0) = new;
4545                 }
4546                 old = old->next;
4547         } while(old != ofirst);
4548
4549         /* Make a second pass to fix up any unresolved references */
4550         old = ofirst;
4551         new = nfirst;
4552         do {
4553                 struct triple **oexpr, **nexpr;
4554                 int count, i;
4555                 /* Lookup where the copy is, to join pointers */
4556                 count = TRIPLE_SIZE(old->sizes);
4557                 for(i = 0; i < count; i++) {
4558                         oexpr = &old->param[i];
4559                         nexpr = &new->param[i];
4560                         if (!*nexpr && *oexpr && (*oexpr)->use) {
4561                                 *nexpr = (*oexpr)->use->member;
4562                                 if (*nexpr == old) {
4563                                         internal_error(state, 0, "new == old?");
4564                                 }
4565                                 use_triple(*nexpr, new);
4566                         }
4567                         if (!*nexpr && *oexpr) {
4568                                 internal_error(state, 0, "Could not copy %d\n", i);
4569                         }
4570                 }
4571                 old = old->next;
4572                 new = new->next;
4573         } while((old != ofirst) && (new != nfirst));
4574         
4575         /* Make a third pass to cleanup the extra useses */
4576         old = ofirst;
4577         new = nfirst;
4578         do {
4579                 unuse_triple(old, new);
4580                 old = old->next;
4581                 new = new->next;
4582         } while ((old != ofirst) && (new != nfirst));
4583         return nfunc;
4584 }
4585
4586 static struct triple *flatten_call(
4587         struct compile_state *state, struct triple *first, struct triple *ptr)
4588 {
4589         /* Inline the function call */
4590         struct type *ptype;
4591         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4592         struct triple *end, *nend;
4593         int pvals, i;
4594
4595         /* Find the triples */
4596         ofunc = MISC(ptr, 0);
4597         if (ofunc->op != OP_LIST) {
4598                 internal_error(state, 0, "improper function");
4599         }
4600         nfunc = copy_func(state, ofunc);
4601         nfirst = RHS(nfunc, 0)->next;
4602         /* Prepend the parameter reading into the new function list */
4603         ptype = nfunc->type->right;
4604         param = RHS(nfunc, 0)->next;
4605         pvals = TRIPLE_RHS(ptr->sizes);
4606         for(i = 0; i < pvals; i++) {
4607                 struct type *atype;
4608                 struct triple *arg;
4609                 atype = ptype;
4610                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4611                         atype = ptype->left;
4612                 }
4613                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4614                         param = param->next;
4615                 }
4616                 arg = RHS(ptr, i);
4617                 flatten(state, nfirst, write_expr(state, param, arg));
4618                 ptype = ptype->right;
4619                 param = param->next;
4620         }
4621         result = 0;
4622         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4623                 result = read_expr(state, MISC(nfunc,0));
4624         }
4625 #if 0
4626         fprintf(stdout, "\n");
4627         loc(stdout, state, 0);
4628         fprintf(stdout, "\n__________ flatten_call _________\n");
4629         print_triple(state, nfunc);
4630         fprintf(stdout, "__________ flatten_call _________ done\n\n");
4631 #endif
4632
4633         /* Get rid of the extra triples */
4634         nfirst = RHS(nfunc, 0)->next;
4635         free_triple(state, RHS(nfunc, 0));
4636         RHS(nfunc, 0) = 0;
4637         free_triple(state, nfunc);
4638
4639         /* Append the new function list onto the return list */
4640         end = first->prev;
4641         nend = nfirst->prev;
4642         end->next    = nfirst;
4643         nfirst->prev = end;
4644         nend->next   = first;
4645         first->prev  = nend;
4646
4647         return result;
4648 }
4649
4650 static struct triple *flatten(
4651         struct compile_state *state, struct triple *first, struct triple *ptr)
4652 {
4653         struct triple *orig_ptr;
4654         if (!ptr)
4655                 return 0;
4656         do {
4657                 orig_ptr = ptr;
4658                 /* Only flatten triples once */
4659                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4660                         return ptr;
4661                 }
4662                 switch(ptr->op) {
4663                 case OP_WRITE:
4664                 case OP_STORE:
4665                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4666                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4667                         use_triple(LHS(ptr, 0), ptr);
4668                         use_triple(RHS(ptr, 0), ptr);
4669                         break;
4670                 case OP_COMMA:
4671                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4672                         ptr = RHS(ptr, 1);
4673                         break;
4674                 case OP_VAL:
4675                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4676                         return MISC(ptr, 0);
4677                         break;
4678                 case OP_LAND:
4679                         ptr = flatten_land(state, first, ptr);
4680                         break;
4681                 case OP_LOR:
4682                         ptr = flatten_lor(state, first, ptr);
4683                         break;
4684                 case OP_COND:
4685                         ptr = flatten_cond(state, first, ptr);
4686                         break;
4687                 case OP_CALL:
4688                         ptr = flatten_call(state, first, ptr);
4689                         break;
4690                 case OP_READ:
4691                 case OP_LOAD:
4692                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4693                         use_triple(RHS(ptr, 0), ptr);
4694                         break;
4695                 case OP_BRANCH:
4696                         use_triple(TARG(ptr, 0), ptr);
4697                         if (TRIPLE_RHS(ptr->sizes)) {
4698                                 use_triple(RHS(ptr, 0), ptr);
4699                                 if (ptr->next != ptr) {
4700                                         use_triple(ptr->next, ptr);
4701                                 }
4702                         }
4703                         break;
4704                 case OP_BLOBCONST:
4705                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4706                         use_triple(MISC(ptr, 0), ptr);
4707                         break;
4708                 case OP_DEREF:
4709                         /* Since OP_DEREF is just a marker delete it when I flatten it */
4710                         ptr = RHS(ptr, 0);
4711                         RHS(orig_ptr, 0) = 0;
4712                         free_triple(state, orig_ptr);
4713                         break;
4714                 case OP_DOT:
4715                 {
4716                         struct triple *base;
4717                         base = RHS(ptr, 0);
4718                         base = flatten(state, first, base);
4719                         if (base->op == OP_VAL_VEC) {
4720                                 ptr = struct_field(state, base, ptr->u.field);
4721                         }
4722                         break;
4723                 }
4724                 case OP_SDECL:
4725                 case OP_ADECL:
4726                         break;
4727                 default:
4728                         /* Flatten the easy cases we don't override */
4729                         ptr = flatten_generic(state, first, ptr);
4730                         break;
4731                 }
4732         } while(ptr && (ptr != orig_ptr));
4733         if (ptr) {
4734                 insert_triple(state, first, ptr);
4735                 ptr->id |= TRIPLE_FLAG_FLATTENED;
4736         }
4737         return ptr;
4738 }
4739
4740 static void release_expr(struct compile_state *state, struct triple *expr)
4741 {
4742         struct triple *head;
4743         head = label(state);
4744         flatten(state, head, expr);
4745         while(head->next != head) {
4746                 release_triple(state, head->next);
4747         }
4748         free_triple(state, head);
4749 }
4750
4751 static int replace_rhs_use(struct compile_state *state,
4752         struct triple *orig, struct triple *new, struct triple *use)
4753 {
4754         struct triple **expr;
4755         int found;
4756         found = 0;
4757         expr = triple_rhs(state, use, 0);
4758         for(;expr; expr = triple_rhs(state, use, expr)) {
4759                 if (*expr == orig) {
4760                         *expr = new;
4761                         found = 1;
4762                 }
4763         }
4764         if (found) {
4765                 unuse_triple(orig, use);
4766                 use_triple(new, use);
4767         }
4768         return found;
4769 }
4770
4771 static int replace_lhs_use(struct compile_state *state,
4772         struct triple *orig, struct triple *new, struct triple *use)
4773 {
4774         struct triple **expr;
4775         int found;
4776         found = 0;
4777         expr = triple_lhs(state, use, 0);
4778         for(;expr; expr = triple_lhs(state, use, expr)) {
4779                 if (*expr == orig) {
4780                         *expr = new;
4781                         found = 1;
4782                 }
4783         }
4784         if (found) {
4785                 unuse_triple(orig, use);
4786                 use_triple(new, use);
4787         }
4788         return found;
4789 }
4790
4791 static void propogate_use(struct compile_state *state,
4792         struct triple *orig, struct triple *new)
4793 {
4794         struct triple_set *user, *next;
4795         for(user = orig->use; user; user = next) {
4796                 struct triple *use;
4797                 int found;
4798                 next = user->next;
4799                 use = user->member;
4800                 found = 0;
4801                 found |= replace_rhs_use(state, orig, new, use);
4802                 found |= replace_lhs_use(state, orig, new, use);
4803                 if (!found) {
4804                         internal_error(state, use, "use without use");
4805                 }
4806         }
4807         if (orig->use) {
4808                 internal_error(state, orig, "used after propogate_use");
4809         }
4810 }
4811
4812 /*
4813  * Code generators
4814  * ===========================
4815  */
4816
4817 static struct triple *mk_add_expr(
4818         struct compile_state *state, struct triple *left, struct triple *right)
4819 {
4820         struct type *result_type;
4821         /* Put pointer operands on the left */
4822         if (is_pointer(right)) {
4823                 struct triple *tmp;
4824                 tmp = left;
4825                 left = right;
4826                 right = tmp;
4827         }
4828         result_type = ptr_arithmetic_result(state, left, right);
4829         left  = read_expr(state, left);
4830         right = read_expr(state, right);
4831         if (is_pointer(left)) {
4832                 right = triple(state, 
4833                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
4834                         &ulong_type, 
4835                         right, 
4836                         int_const(state, &ulong_type, 
4837                                 size_of(state, left->type->left)));
4838         }
4839         return triple(state, OP_ADD, result_type, left, right);
4840 }
4841
4842 static struct triple *mk_sub_expr(
4843         struct compile_state *state, struct triple *left, struct triple *right)
4844 {
4845         struct type *result_type;
4846         result_type = ptr_arithmetic_result(state, left, right);
4847         left  = read_expr(state, left);
4848         right = read_expr(state, right);
4849         if (is_pointer(left)) {
4850                 right = triple(state, 
4851                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
4852                         &ulong_type, 
4853                         right, 
4854                         int_const(state, &ulong_type, 
4855                                 size_of(state, left->type->left)));
4856         }
4857         return triple(state, OP_SUB, result_type, left, right);
4858 }
4859
4860 static struct triple *mk_pre_inc_expr(
4861         struct compile_state *state, struct triple *def)
4862 {
4863         struct triple *val;
4864         lvalue(state, def);
4865         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
4866         return triple(state, OP_VAL, def->type,
4867                 write_expr(state, def, val),
4868                 val);
4869 }
4870
4871 static struct triple *mk_pre_dec_expr(
4872         struct compile_state *state, struct triple *def)
4873 {
4874         struct triple *val;
4875         lvalue(state, def);
4876         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
4877         return triple(state, OP_VAL, def->type,
4878                 write_expr(state, def, val),
4879                 val);
4880 }
4881
4882 static struct triple *mk_post_inc_expr(
4883         struct compile_state *state, struct triple *def)
4884 {
4885         struct triple *val;
4886         lvalue(state, def);
4887         val = read_expr(state, def);
4888         return triple(state, OP_VAL, def->type,
4889                 write_expr(state, def,
4890                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
4891                 , val);
4892 }
4893
4894 static struct triple *mk_post_dec_expr(
4895         struct compile_state *state, struct triple *def)
4896 {
4897         struct triple *val;
4898         lvalue(state, def);
4899         val = read_expr(state, def);
4900         return triple(state, OP_VAL, def->type, 
4901                 write_expr(state, def,
4902                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
4903                 , val);
4904 }
4905
4906 static struct triple *mk_subscript_expr(
4907         struct compile_state *state, struct triple *left, struct triple *right)
4908 {
4909         left  = read_expr(state, left);
4910         right = read_expr(state, right);
4911         if (!is_pointer(left) && !is_pointer(right)) {
4912                 error(state, left, "subscripted value is not a pointer");
4913         }
4914         return mk_deref_expr(state, mk_add_expr(state, left, right));
4915 }
4916
4917 /*
4918  * Compile time evaluation
4919  * ===========================
4920  */
4921 static int is_const(struct triple *ins)
4922 {
4923         return IS_CONST_OP(ins->op);
4924 }
4925
4926 static int constants_equal(struct compile_state *state, 
4927         struct triple *left, struct triple *right)
4928 {
4929         int equal;
4930         if (!is_const(left) || !is_const(right)) {
4931                 equal = 0;
4932         }
4933         else if (left->op != right->op) {
4934                 equal = 0;
4935         }
4936         else if (!equiv_types(left->type, right->type)) {
4937                 equal = 0;
4938         }
4939         else {
4940                 equal = 0;
4941                 switch(left->op) {
4942                 case OP_INTCONST:
4943                         if (left->u.cval == right->u.cval) {
4944                                 equal = 1;
4945                         }
4946                         break;
4947                 case OP_BLOBCONST:
4948                 {
4949                         size_t lsize, rsize;
4950                         lsize = size_of(state, left->type);
4951                         rsize = size_of(state, right->type);
4952                         if (lsize != rsize) {
4953                                 break;
4954                         }
4955                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
4956                                 equal = 1;
4957                         }
4958                         break;
4959                 }
4960                 case OP_ADDRCONST:
4961                         if ((RHS(left, 0) == RHS(right, 0)) &&
4962                                 (left->u.cval == right->u.cval)) {
4963                                 equal = 1;
4964                         }
4965                         break;
4966                 default:
4967                         internal_error(state, left, "uknown constant type");
4968                         break;
4969                 }
4970         }
4971         return equal;
4972 }
4973
4974 static int is_zero(struct triple *ins)
4975 {
4976         return is_const(ins) && (ins->u.cval == 0);
4977 }
4978
4979 static int is_one(struct triple *ins)
4980 {
4981         return is_const(ins) && (ins->u.cval == 1);
4982 }
4983
4984 static long_t bsr(ulong_t value)
4985 {
4986         int i;
4987         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
4988                 ulong_t mask;
4989                 mask = 1;
4990                 mask <<= i;
4991                 if (value & mask) {
4992                         return i;
4993                 }
4994         }
4995         return -1;
4996 }
4997
4998 static long_t bsf(ulong_t value)
4999 {
5000         int i;
5001         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5002                 ulong_t mask;
5003                 mask = 1;
5004                 mask <<= 1;
5005                 if (value & mask) {
5006                         return i;
5007                 }
5008         }
5009         return -1;
5010 }
5011
5012 static long_t log2(ulong_t value)
5013 {
5014         return bsr(value);
5015 }
5016
5017 static long_t tlog2(struct triple *ins)
5018 {
5019         return log2(ins->u.cval);
5020 }
5021
5022 static int is_pow2(struct triple *ins)
5023 {
5024         ulong_t value, mask;
5025         long_t log;
5026         if (!is_const(ins)) {
5027                 return 0;
5028         }
5029         value = ins->u.cval;
5030         log = log2(value);
5031         if (log == -1) {
5032                 return 0;
5033         }
5034         mask = 1;
5035         mask <<= log;
5036         return  ((value & mask) == value);
5037 }
5038
5039 static ulong_t read_const(struct compile_state *state,
5040         struct triple *ins, struct triple **expr)
5041 {
5042         struct triple *rhs;
5043         rhs = *expr;
5044         switch(rhs->type->type &TYPE_MASK) {
5045         case TYPE_CHAR:   
5046         case TYPE_SHORT:
5047         case TYPE_INT:
5048         case TYPE_LONG:
5049         case TYPE_UCHAR:   
5050         case TYPE_USHORT:  
5051         case TYPE_UINT:
5052         case TYPE_ULONG:
5053         case TYPE_POINTER:
5054                 break;
5055         default:
5056                 internal_error(state, rhs, "bad type to read_const\n");
5057                 break;
5058         }
5059         return rhs->u.cval;
5060 }
5061
5062 static long_t read_sconst(struct triple *ins, struct triple **expr)
5063 {
5064         struct triple *rhs;
5065         rhs = *expr;
5066         return (long_t)(rhs->u.cval);
5067 }
5068
5069 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5070 {
5071         struct triple **expr;
5072         expr = triple_rhs(state, ins, 0);
5073         for(;expr;expr = triple_rhs(state, ins, expr)) {
5074                 if (*expr) {
5075                         unuse_triple(*expr, ins);
5076                         *expr = 0;
5077                 }
5078         }
5079 }
5080
5081 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5082 {
5083         struct triple **expr;
5084         expr = triple_lhs(state, ins, 0);
5085         for(;expr;expr = triple_lhs(state, ins, expr)) {
5086                 unuse_triple(*expr, ins);
5087                 *expr = 0;
5088         }
5089 }
5090
5091 static void check_lhs(struct compile_state *state, struct triple *ins)
5092 {
5093         struct triple **expr;
5094         expr = triple_lhs(state, ins, 0);
5095         for(;expr;expr = triple_lhs(state, ins, expr)) {
5096                 internal_error(state, ins, "unexpected lhs");
5097         }
5098         
5099 }
5100 static void check_targ(struct compile_state *state, struct triple *ins)
5101 {
5102         struct triple **expr;
5103         expr = triple_targ(state, ins, 0);
5104         for(;expr;expr = triple_targ(state, ins, expr)) {
5105                 internal_error(state, ins, "unexpected targ");
5106         }
5107 }
5108
5109 static void wipe_ins(struct compile_state *state, struct triple *ins)
5110 {
5111         /* Becareful which instructions you replace the wiped
5112          * instruction with, as there are not enough slots
5113          * in all instructions to hold all others.
5114          */
5115         check_targ(state, ins);
5116         unuse_rhs(state, ins);
5117         unuse_lhs(state, ins);
5118 }
5119
5120 static void mkcopy(struct compile_state *state, 
5121         struct triple *ins, struct triple *rhs)
5122 {
5123         wipe_ins(state, ins);
5124         ins->op = OP_COPY;
5125         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5126         RHS(ins, 0) = rhs;
5127         use_triple(RHS(ins, 0), ins);
5128 }
5129
5130 static void mkconst(struct compile_state *state, 
5131         struct triple *ins, ulong_t value)
5132 {
5133         if (!is_integral(ins) && !is_pointer(ins)) {
5134                 internal_error(state, ins, "unknown type to make constant\n");
5135         }
5136         wipe_ins(state, ins);
5137         ins->op = OP_INTCONST;
5138         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5139         ins->u.cval = value;
5140 }
5141
5142 static void mkaddr_const(struct compile_state *state,
5143         struct triple *ins, struct triple *sdecl, ulong_t value)
5144 {
5145         wipe_ins(state, ins);
5146         ins->op = OP_ADDRCONST;
5147         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5148         RHS(ins, 0) = sdecl;
5149         ins->u.cval = value;
5150         use_triple(sdecl, ins);
5151 }
5152
5153 /* Transform multicomponent variables into simple register variables */
5154 static void flatten_structures(struct compile_state *state)
5155 {
5156         struct triple *ins, *first;
5157         first = RHS(state->main_function, 0);
5158         ins = first;
5159         /* Pass one expand structure values into valvecs.
5160          */
5161         ins = first;
5162         do {
5163                 struct triple *next;
5164                 next = ins->next;
5165                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5166                         if (ins->op == OP_VAL_VEC) {
5167                                 /* Do nothing */
5168                         }
5169                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5170                                 struct triple *def, **vector;
5171                                 struct type *tptr;
5172                                 int op;
5173                                 ulong_t i;
5174
5175                                 op = ins->op;
5176                                 def = RHS(ins, 0);
5177                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5178                                         ins->filename, ins->line, ins->col);
5179
5180                                 vector = &RHS(next, 0);
5181                                 tptr = next->type->left;
5182                                 for(i = 0; i < next->type->elements; i++) {
5183                                         struct triple *sfield;
5184                                         struct type *mtype;
5185                                         mtype = tptr;
5186                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5187                                                 mtype = mtype->left;
5188                                         }
5189                                         sfield = deref_field(state, def, mtype->field_ident);
5190                                         
5191                                         vector[i] = triple(
5192                                                 state, op, mtype, sfield, 0);
5193                                         vector[i]->filename = next->filename;
5194                                         vector[i]->line = next->line;
5195                                         vector[i]->col = next->col;
5196                                         tptr = tptr->right;
5197                                 }
5198                                 propogate_use(state, ins, next);
5199                                 flatten(state, ins, next);
5200                                 free_triple(state, ins);
5201                         }
5202                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5203                                 struct triple *src, *dst, **vector;
5204                                 struct type *tptr;
5205                                 int op;
5206                                 ulong_t i;
5207
5208                                 op = ins->op;
5209                                 src = RHS(ins, 0);
5210                                 dst = LHS(ins, 0);
5211                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5212                                         ins->filename, ins->line, ins->col);
5213                                 
5214                                 vector = &RHS(next, 0);
5215                                 tptr = next->type->left;
5216                                 for(i = 0; i < ins->type->elements; i++) {
5217                                         struct triple *dfield, *sfield;
5218                                         struct type *mtype;
5219                                         mtype = tptr;
5220                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5221                                                 mtype = mtype->left;
5222                                         }
5223                                         sfield = deref_field(state, src, mtype->field_ident);
5224                                         dfield = deref_field(state, dst, mtype->field_ident);
5225                                         vector[i] = triple(
5226                                                 state, op, mtype, dfield, sfield);
5227                                         vector[i]->filename = next->filename;
5228                                         vector[i]->line = next->line;
5229                                         vector[i]->col = next->col;
5230                                         tptr = tptr->right;
5231                                 }
5232                                 propogate_use(state, ins, next);
5233                                 flatten(state, ins, next);
5234                                 free_triple(state, ins);
5235                         }
5236                 }
5237                 ins = next;
5238         } while(ins != first);
5239         /* Pass two flatten the valvecs.
5240          */
5241         ins = first;
5242         do {
5243                 struct triple *next;
5244                 next = ins->next;
5245                 if (ins->op == OP_VAL_VEC) {
5246                         release_triple(state, ins);
5247                 } 
5248                 ins = next;
5249         } while(ins != first);
5250         /* Pass three verify the state and set ->id to 0.
5251          */
5252         ins = first;
5253         do {
5254                 ins->id = 0;
5255                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5256                         internal_error(state, 0, "STRUCT_TYPE remains?");
5257                 }
5258                 if (ins->op == OP_DOT) {
5259                         internal_error(state, 0, "OP_DOT remains?");
5260                 }
5261                 if (ins->op == OP_VAL_VEC) {
5262                         internal_error(state, 0, "OP_VAL_VEC remains?");
5263                 }
5264                 ins = ins->next;
5265         } while(ins != first);
5266 }
5267
5268 /* For those operations that cannot be simplified */
5269 static void simplify_noop(struct compile_state *state, struct triple *ins)
5270 {
5271         return;
5272 }
5273
5274 static void simplify_smul(struct compile_state *state, struct triple *ins)
5275 {
5276         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5277                 struct triple *tmp;
5278                 tmp = RHS(ins, 0);
5279                 RHS(ins, 0) = RHS(ins, 1);
5280                 RHS(ins, 1) = tmp;
5281         }
5282         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5283                 long_t left, right;
5284                 left  = read_sconst(ins, &RHS(ins, 0));
5285                 right = read_sconst(ins, &RHS(ins, 1));
5286                 mkconst(state, ins, left * right);
5287         }
5288         else if (is_zero(RHS(ins, 1))) {
5289                 mkconst(state, ins, 0);
5290         }
5291         else if (is_one(RHS(ins, 1))) {
5292                 mkcopy(state, ins, RHS(ins, 0));
5293         }
5294         else if (is_pow2(RHS(ins, 1))) {
5295                 struct triple *val;
5296                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5297                 ins->op = OP_SL;
5298                 insert_triple(state, ins, val);
5299                 unuse_triple(RHS(ins, 1), ins);
5300                 use_triple(val, ins);
5301                 RHS(ins, 1) = val;
5302         }
5303 }
5304
5305 static void simplify_umul(struct compile_state *state, struct triple *ins)
5306 {
5307         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5308                 struct triple *tmp;
5309                 tmp = RHS(ins, 0);
5310                 RHS(ins, 0) = RHS(ins, 1);
5311                 RHS(ins, 1) = tmp;
5312         }
5313         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5314                 ulong_t left, right;
5315                 left  = read_const(state, ins, &RHS(ins, 0));
5316                 right = read_const(state, ins, &RHS(ins, 1));
5317                 mkconst(state, ins, left * right);
5318         }
5319         else if (is_zero(RHS(ins, 1))) {
5320                 mkconst(state, ins, 0);
5321         }
5322         else if (is_one(RHS(ins, 1))) {
5323                 mkcopy(state, ins, RHS(ins, 0));
5324         }
5325         else if (is_pow2(RHS(ins, 1))) {
5326                 struct triple *val;
5327                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5328                 ins->op = OP_SL;
5329                 insert_triple(state, ins, val);
5330                 unuse_triple(RHS(ins, 1), ins);
5331                 use_triple(val, ins);
5332                 RHS(ins, 1) = val;
5333         }
5334 }
5335
5336 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5337 {
5338         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5339                 long_t left, right;
5340                 left  = read_sconst(ins, &RHS(ins, 0));
5341                 right = read_sconst(ins, &RHS(ins, 1));
5342                 mkconst(state, ins, left / right);
5343         }
5344         else if (is_zero(RHS(ins, 0))) {
5345                 mkconst(state, ins, 0);
5346         }
5347         else if (is_zero(RHS(ins, 1))) {
5348                 error(state, ins, "division by zero");
5349         }
5350         else if (is_one(RHS(ins, 1))) {
5351                 mkcopy(state, ins, RHS(ins, 0));
5352         }
5353         else if (is_pow2(RHS(ins, 1))) {
5354                 struct triple *val;
5355                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5356                 ins->op = OP_SSR;
5357                 insert_triple(state, ins, val);
5358                 unuse_triple(RHS(ins, 1), ins);
5359                 use_triple(val, ins);
5360                 RHS(ins, 1) = val;
5361         }
5362 }
5363
5364 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5365 {
5366         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5367                 ulong_t left, right;
5368                 left  = read_const(state, ins, &RHS(ins, 0));
5369                 right = read_const(state, ins, &RHS(ins, 1));
5370                 mkconst(state, ins, left / right);
5371         }
5372         else if (is_zero(RHS(ins, 0))) {
5373                 mkconst(state, ins, 0);
5374         }
5375         else if (is_zero(RHS(ins, 1))) {
5376                 error(state, ins, "division by zero");
5377         }
5378         else if (is_one(RHS(ins, 1))) {
5379                 mkcopy(state, ins, RHS(ins, 0));
5380         }
5381         else if (is_pow2(RHS(ins, 1))) {
5382                 struct triple *val;
5383                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5384                 ins->op = OP_USR;
5385                 insert_triple(state, ins, val);
5386                 unuse_triple(RHS(ins, 1), ins);
5387                 use_triple(val, ins);
5388                 RHS(ins, 1) = val;
5389         }
5390 }
5391
5392 static void simplify_smod(struct compile_state *state, struct triple *ins)
5393 {
5394         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5395                 long_t left, right;
5396                 left  = read_const(state, ins, &RHS(ins, 0));
5397                 right = read_const(state, ins, &RHS(ins, 1));
5398                 mkconst(state, ins, left % right);
5399         }
5400         else if (is_zero(RHS(ins, 0))) {
5401                 mkconst(state, ins, 0);
5402         }
5403         else if (is_zero(RHS(ins, 1))) {
5404                 error(state, ins, "division by zero");
5405         }
5406         else if (is_one(RHS(ins, 1))) {
5407                 mkconst(state, ins, 0);
5408         }
5409         else if (is_pow2(RHS(ins, 1))) {
5410                 struct triple *val;
5411                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5412                 ins->op = OP_AND;
5413                 insert_triple(state, ins, val);
5414                 unuse_triple(RHS(ins, 1), ins);
5415                 use_triple(val, ins);
5416                 RHS(ins, 1) = val;
5417         }
5418 }
5419 static void simplify_umod(struct compile_state *state, struct triple *ins)
5420 {
5421         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5422                 ulong_t left, right;
5423                 left  = read_const(state, ins, &RHS(ins, 0));
5424                 right = read_const(state, ins, &RHS(ins, 1));
5425                 mkconst(state, ins, left % right);
5426         }
5427         else if (is_zero(RHS(ins, 0))) {
5428                 mkconst(state, ins, 0);
5429         }
5430         else if (is_zero(RHS(ins, 1))) {
5431                 error(state, ins, "division by zero");
5432         }
5433         else if (is_one(RHS(ins, 1))) {
5434                 mkconst(state, ins, 0);
5435         }
5436         else if (is_pow2(RHS(ins, 1))) {
5437                 struct triple *val;
5438                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5439                 ins->op = OP_AND;
5440                 insert_triple(state, ins, val);
5441                 unuse_triple(RHS(ins, 1), ins);
5442                 use_triple(val, ins);
5443                 RHS(ins, 1) = val;
5444         }
5445 }
5446
5447 static void simplify_add(struct compile_state *state, struct triple *ins)
5448 {
5449         /* start with the pointer on the left */
5450         if (is_pointer(RHS(ins, 1))) {
5451                 struct triple *tmp;
5452                 tmp = RHS(ins, 0);
5453                 RHS(ins, 0) = RHS(ins, 1);
5454                 RHS(ins, 1) = tmp;
5455         }
5456         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5457                 if (!is_pointer(RHS(ins, 0))) {
5458                         ulong_t left, right;
5459                         left  = read_const(state, ins, &RHS(ins, 0));
5460                         right = read_const(state, ins, &RHS(ins, 1));
5461                         mkconst(state, ins, left + right);
5462                 }
5463                 else /* op == OP_ADDRCONST */ {
5464                         struct triple *sdecl;
5465                         ulong_t left, right;
5466                         sdecl = RHS(RHS(ins, 0), 0);
5467                         left  = RHS(ins, 0)->u.cval;
5468                         right = RHS(ins, 1)->u.cval;
5469                         mkaddr_const(state, ins, sdecl, left + right);
5470                 }
5471         }
5472         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5473                 struct triple *tmp;
5474                 tmp = RHS(ins, 1);
5475                 RHS(ins, 1) = RHS(ins, 0);
5476                 RHS(ins, 0) = tmp;
5477         }
5478 }
5479
5480 static void simplify_sub(struct compile_state *state, struct triple *ins)
5481 {
5482         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5483                 if (!is_pointer(RHS(ins, 0))) {
5484                         ulong_t left, right;
5485                         left  = read_const(state, ins, &RHS(ins, 0));
5486                         right = read_const(state, ins, &RHS(ins, 1));
5487                         mkconst(state, ins, left - right);
5488                 }
5489                 else /* op == OP_ADDRCONST */ {
5490                         struct triple *sdecl;
5491                         ulong_t left, right;
5492                         sdecl = RHS(RHS(ins, 0), 0);
5493                         left  = RHS(ins, 0)->u.cval;
5494                         right = RHS(ins, 1)->u.cval;
5495                         mkaddr_const(state, ins, sdecl, left - right);
5496                 }
5497         }
5498 }
5499
5500 static void simplify_sl(struct compile_state *state, struct triple *ins)
5501 {
5502         if (is_const(RHS(ins, 1))) {
5503                 ulong_t right;
5504                 right = read_const(state, ins, &RHS(ins, 1));
5505                 if (right >= (size_of(state, ins->type)*8)) {
5506                         warning(state, ins, "left shift count >= width of type");
5507                 }
5508         }
5509         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5510                 ulong_t left, right;
5511                 left  = read_const(state, ins, &RHS(ins, 0));
5512                 right = read_const(state, ins, &RHS(ins, 1));
5513                 mkconst(state, ins,  left << right);
5514         }
5515 }
5516
5517 static void simplify_usr(struct compile_state *state, struct triple *ins)
5518 {
5519         if (is_const(RHS(ins, 1))) {
5520                 ulong_t right;
5521                 right = read_const(state, ins, &RHS(ins, 1));
5522                 if (right >= (size_of(state, ins->type)*8)) {
5523                         warning(state, ins, "right shift count >= width of type");
5524                 }
5525         }
5526         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5527                 ulong_t left, right;
5528                 left  = read_const(state, ins, &RHS(ins, 0));
5529                 right = read_const(state, ins, &RHS(ins, 1));
5530                 mkconst(state, ins, left >> right);
5531         }
5532 }
5533
5534 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5535 {
5536         if (is_const(RHS(ins, 1))) {
5537                 ulong_t right;
5538                 right = read_const(state, ins, &RHS(ins, 1));
5539                 if (right >= (size_of(state, ins->type)*8)) {
5540                         warning(state, ins, "right shift count >= width of type");
5541                 }
5542         }
5543         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5544                 long_t left, right;
5545                 left  = read_sconst(ins, &RHS(ins, 0));
5546                 right = read_sconst(ins, &RHS(ins, 1));
5547                 mkconst(state, ins, left >> right);
5548         }
5549 }
5550
5551 static void simplify_and(struct compile_state *state, struct triple *ins)
5552 {
5553         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5554                 ulong_t left, right;
5555                 left  = read_const(state, ins, &RHS(ins, 0));
5556                 right = read_const(state, ins, &RHS(ins, 1));
5557                 mkconst(state, ins, left & right);
5558         }
5559 }
5560
5561 static void simplify_or(struct compile_state *state, struct triple *ins)
5562 {
5563         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5564                 ulong_t left, right;
5565                 left  = read_const(state, ins, &RHS(ins, 0));
5566                 right = read_const(state, ins, &RHS(ins, 1));
5567                 mkconst(state, ins, left | right);
5568         }
5569 }
5570
5571 static void simplify_xor(struct compile_state *state, struct triple *ins)
5572 {
5573         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5574                 ulong_t left, right;
5575                 left  = read_const(state, ins, &RHS(ins, 0));
5576                 right = read_const(state, ins, &RHS(ins, 1));
5577                 mkconst(state, ins, left ^ right);
5578         }
5579 }
5580
5581 static void simplify_pos(struct compile_state *state, struct triple *ins)
5582 {
5583         if (is_const(RHS(ins, 0))) {
5584                 mkconst(state, ins, RHS(ins, 0)->u.cval);
5585         }
5586         else {
5587                 mkcopy(state, ins, RHS(ins, 0));
5588         }
5589 }
5590
5591 static void simplify_neg(struct compile_state *state, struct triple *ins)
5592 {
5593         if (is_const(RHS(ins, 0))) {
5594                 ulong_t left;
5595                 left = read_const(state, ins, &RHS(ins, 0));
5596                 mkconst(state, ins, -left);
5597         }
5598         else if (RHS(ins, 0)->op == OP_NEG) {
5599                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5600         }
5601 }
5602
5603 static void simplify_invert(struct compile_state *state, struct triple *ins)
5604 {
5605         if (is_const(RHS(ins, 0))) {
5606                 ulong_t left;
5607                 left = read_const(state, ins, &RHS(ins, 0));
5608                 mkconst(state, ins, ~left);
5609         }
5610 }
5611
5612 static void simplify_eq(struct compile_state *state, struct triple *ins)
5613 {
5614         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5615                 ulong_t left, right;
5616                 left  = read_const(state, ins, &RHS(ins, 0));
5617                 right = read_const(state, ins, &RHS(ins, 1));
5618                 mkconst(state, ins, left == right);
5619         }
5620         else if (RHS(ins, 0) == RHS(ins, 1)) {
5621                 mkconst(state, ins, 1);
5622         }
5623 }
5624
5625 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5626 {
5627         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5628                 ulong_t left, right;
5629                 left  = read_const(state, ins, &RHS(ins, 0));
5630                 right = read_const(state, ins, &RHS(ins, 1));
5631                 mkconst(state, ins, left != right);
5632         }
5633         else if (RHS(ins, 0) == RHS(ins, 1)) {
5634                 mkconst(state, ins, 0);
5635         }
5636 }
5637
5638 static void simplify_sless(struct compile_state *state, struct triple *ins)
5639 {
5640         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5641                 long_t left, right;
5642                 left  = read_sconst(ins, &RHS(ins, 0));
5643                 right = read_sconst(ins, &RHS(ins, 1));
5644                 mkconst(state, ins, left < right);
5645         }
5646         else if (RHS(ins, 0) == RHS(ins, 1)) {
5647                 mkconst(state, ins, 0);
5648         }
5649 }
5650
5651 static void simplify_uless(struct compile_state *state, struct triple *ins)
5652 {
5653         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5654                 ulong_t left, right;
5655                 left  = read_const(state, ins, &RHS(ins, 0));
5656                 right = read_const(state, ins, &RHS(ins, 1));
5657                 mkconst(state, ins, left < right);
5658         }
5659         else if (is_zero(RHS(ins, 0))) {
5660                 mkconst(state, ins, 1);
5661         }
5662         else if (RHS(ins, 0) == RHS(ins, 1)) {
5663                 mkconst(state, ins, 0);
5664         }
5665 }
5666
5667 static void simplify_smore(struct compile_state *state, struct triple *ins)
5668 {
5669         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5670                 long_t left, right;
5671                 left  = read_sconst(ins, &RHS(ins, 0));
5672                 right = read_sconst(ins, &RHS(ins, 1));
5673                 mkconst(state, ins, left > right);
5674         }
5675         else if (RHS(ins, 0) == RHS(ins, 1)) {
5676                 mkconst(state, ins, 0);
5677         }
5678 }
5679
5680 static void simplify_umore(struct compile_state *state, struct triple *ins)
5681 {
5682         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5683                 ulong_t left, right;
5684                 left  = read_const(state, ins, &RHS(ins, 0));
5685                 right = read_const(state, ins, &RHS(ins, 1));
5686                 mkconst(state, ins, left > right);
5687         }
5688         else if (is_zero(RHS(ins, 1))) {
5689                 mkconst(state, ins, 1);
5690         }
5691         else if (RHS(ins, 0) == RHS(ins, 1)) {
5692                 mkconst(state, ins, 0);
5693         }
5694 }
5695
5696
5697 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5698 {
5699         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5700                 long_t left, right;
5701                 left  = read_sconst(ins, &RHS(ins, 0));
5702                 right = read_sconst(ins, &RHS(ins, 1));
5703                 mkconst(state, ins, left <= right);
5704         }
5705         else if (RHS(ins, 0) == RHS(ins, 1)) {
5706                 mkconst(state, ins, 1);
5707         }
5708 }
5709
5710 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5711 {
5712         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5713                 ulong_t left, right;
5714                 left  = read_const(state, ins, &RHS(ins, 0));
5715                 right = read_const(state, ins, &RHS(ins, 1));
5716                 mkconst(state, ins, left <= right);
5717         }
5718         else if (is_zero(RHS(ins, 0))) {
5719                 mkconst(state, ins, 1);
5720         }
5721         else if (RHS(ins, 0) == RHS(ins, 1)) {
5722                 mkconst(state, ins, 1);
5723         }
5724 }
5725
5726 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5727 {
5728         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5729                 long_t left, right;
5730                 left  = read_sconst(ins, &RHS(ins, 0));
5731                 right = read_sconst(ins, &RHS(ins, 1));
5732                 mkconst(state, ins, left >= right);
5733         }
5734         else if (RHS(ins, 0) == RHS(ins, 1)) {
5735                 mkconst(state, ins, 1);
5736         }
5737 }
5738
5739 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5740 {
5741         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5742                 ulong_t left, right;
5743                 left  = read_const(state, ins, &RHS(ins, 0));
5744                 right = read_const(state, ins, &RHS(ins, 1));
5745                 mkconst(state, ins, left >= right);
5746         }
5747         else if (is_zero(RHS(ins, 1))) {
5748                 mkconst(state, ins, 1);
5749         }
5750         else if (RHS(ins, 0) == RHS(ins, 1)) {
5751                 mkconst(state, ins, 1);
5752         }
5753 }
5754
5755 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5756 {
5757         if (is_const(RHS(ins, 0))) {
5758                 ulong_t left;
5759                 left = read_const(state, ins, &RHS(ins, 0));
5760                 mkconst(state, ins, left == 0);
5761         }
5762         /* Otherwise if I am the only user... */
5763         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5764                 int need_copy = 1;
5765                 /* Invert a boolean operation */
5766                 switch(RHS(ins, 0)->op) {
5767                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
5768                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
5769                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
5770                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
5771                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
5772                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
5773                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
5774                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
5775                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
5776                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
5777                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
5778                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
5779                 default:
5780                         need_copy = 0;
5781                         break;
5782                 }
5783                 if (need_copy) {
5784                         mkcopy(state, ins, RHS(ins, 0));
5785                 }
5786         }
5787 }
5788
5789 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5790 {
5791         if (is_const(RHS(ins, 0))) {
5792                 ulong_t left;
5793                 left = read_const(state, ins, &RHS(ins, 0));
5794                 mkconst(state, ins, left != 0);
5795         }
5796         else switch(RHS(ins, 0)->op) {
5797         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
5798         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
5799         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
5800                 mkcopy(state, ins, RHS(ins, 0));
5801         }
5802
5803 }
5804
5805 static void simplify_copy(struct compile_state *state, struct triple *ins)
5806 {
5807         if (is_const(RHS(ins, 0))) {
5808                 switch(RHS(ins, 0)->op) {
5809                 case OP_INTCONST:
5810                 {
5811                         ulong_t left;
5812                         left = read_const(state, ins, &RHS(ins, 0));
5813                         mkconst(state, ins, left);
5814                         break;
5815                 }
5816                 case OP_ADDRCONST:
5817                 {
5818                         struct triple *sdecl;
5819                         ulong_t offset;
5820                         sdecl  = RHS(ins, 0);
5821                         offset = ins->u.cval;
5822                         mkaddr_const(state, ins, sdecl, offset);
5823                         break;
5824                 }
5825                 default:
5826                         internal_error(state, ins, "uknown constant");
5827                         break;
5828                 }
5829         }
5830 }
5831
5832 static void simplify_branch(struct compile_state *state, struct triple *ins)
5833 {
5834         struct block *block;
5835         if (ins->op != OP_BRANCH) {
5836                 internal_error(state, ins, "not branch");
5837         }
5838         if (ins->use != 0) {
5839                 internal_error(state, ins, "branch use");
5840         }
5841 #warning "FIXME implement simplify branch."
5842         /* The challenge here with simplify branch is that I need to 
5843          * make modifications to the control flow graph as well
5844          * as to the branch instruction itself.
5845          */
5846         block = ins->u.block;
5847         
5848         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
5849                 struct triple *targ;
5850                 ulong_t value;
5851                 value = read_const(state, ins, &RHS(ins, 0));
5852                 unuse_triple(RHS(ins, 0), ins);
5853                 targ = TARG(ins, 0);
5854                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
5855                 if (value) {
5856                         unuse_triple(ins->next, ins);
5857                         TARG(ins, 0) = targ;
5858                 }
5859                 else {
5860                         unuse_triple(targ, ins);
5861                         TARG(ins, 0) = ins->next;
5862                 }
5863 #warning "FIXME handle the case of making a branch unconditional"
5864         }
5865         if (TARG(ins, 0) == ins->next) {
5866                 unuse_triple(ins->next, ins);
5867                 if (TRIPLE_RHS(ins->sizes)) {
5868                         unuse_triple(RHS(ins, 0), ins);
5869                         unuse_triple(ins->next, ins);
5870                 }
5871                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5872                 ins->op = OP_NOOP;
5873                 if (ins->use) {
5874                         internal_error(state, ins, "noop use != 0");
5875                 }
5876 #warning "FIXME handle the case of killing a branch"
5877         }
5878 }
5879
5880 static void simplify_phi(struct compile_state *state, struct triple *ins)
5881 {
5882         struct triple **expr;
5883         ulong_t value;
5884         expr = triple_rhs(state, ins, 0);
5885         if (!*expr || !is_const(*expr)) {
5886                 return;
5887         }
5888         value = read_const(state, ins, expr);
5889         for(;expr;expr = triple_rhs(state, ins, expr)) {
5890                 if (!*expr || !is_const(*expr)) {
5891                         return;
5892                 }
5893                 if (value != read_const(state, ins, expr)) {
5894                         return;
5895                 }
5896         }
5897         mkconst(state, ins, value);
5898 }
5899
5900
5901 static void simplify_bsf(struct compile_state *state, struct triple *ins)
5902 {
5903         if (is_const(RHS(ins, 0))) {
5904                 ulong_t left;
5905                 left = read_const(state, ins, &RHS(ins, 0));
5906                 mkconst(state, ins, bsf(left));
5907         }
5908 }
5909
5910 static void simplify_bsr(struct compile_state *state, struct triple *ins)
5911 {
5912         if (is_const(RHS(ins, 0))) {
5913                 ulong_t left;
5914                 left = read_const(state, ins, &RHS(ins, 0));
5915                 mkconst(state, ins, bsr(left));
5916         }
5917 }
5918
5919
5920 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
5921 static const simplify_t table_simplify[] = {
5922 #if 0
5923 #define simplify_smul     simplify_noop
5924 #define simplify_umul     simplify_noop
5925 #define simplify_sdiv     simplify_noop
5926 #define simplify_udiv     simplify_noop
5927 #define simplify_smod     simplify_noop
5928 #define simplify_umod     simplify_noop
5929 #endif
5930 #if 0
5931 #define simplify_add      simplify_noop
5932 #define simplify_sub      simplify_noop
5933 #endif
5934 #if 0
5935 #define simplify_sl       simplify_noop
5936 #define simplify_usr      simplify_noop
5937 #define simplify_ssr      simplify_noop
5938 #endif
5939 #if 0
5940 #define simplify_and      simplify_noop
5941 #define simplify_xor      simplify_noop
5942 #define simplify_or       simplify_noop
5943 #endif
5944 #if 0
5945 #define simplify_pos      simplify_noop
5946 #define simplify_neg      simplify_noop
5947 #define simplify_invert   simplify_noop
5948 #endif
5949
5950 #if 0
5951 #define simplify_eq       simplify_noop
5952 #define simplify_noteq    simplify_noop
5953 #endif
5954 #if 0
5955 #define simplify_sless    simplify_noop
5956 #define simplify_uless    simplify_noop
5957 #define simplify_smore    simplify_noop
5958 #define simplify_umore    simplify_noop
5959 #endif
5960 #if 0
5961 #define simplify_slesseq  simplify_noop
5962 #define simplify_ulesseq  simplify_noop
5963 #define simplify_smoreeq  simplify_noop
5964 #define simplify_umoreeq  simplify_noop
5965 #endif
5966 #if 0
5967 #define simplify_lfalse   simplify_noop
5968 #endif
5969 #if 0
5970 #define simplify_ltrue    simplify_noop
5971 #endif
5972
5973 #if 0
5974 #define simplify_copy     simplify_noop
5975 #endif
5976
5977 #if 0
5978 #define simplify_branch   simplify_noop
5979 #endif
5980
5981 #if 0
5982 #define simplify_phi      simplify_noop
5983 #endif
5984
5985 #if 0
5986 #define simplify_bsf      simplify_noop
5987 #define simplify_bsr      simplify_noop
5988 #endif
5989
5990 [OP_SMUL       ] = simplify_smul,
5991 [OP_UMUL       ] = simplify_umul,
5992 [OP_SDIV       ] = simplify_sdiv,
5993 [OP_UDIV       ] = simplify_udiv,
5994 [OP_SMOD       ] = simplify_smod,
5995 [OP_UMOD       ] = simplify_umod,
5996 [OP_ADD        ] = simplify_add,
5997 [OP_SUB        ] = simplify_sub,
5998 [OP_SL         ] = simplify_sl,
5999 [OP_USR        ] = simplify_usr,
6000 [OP_SSR        ] = simplify_ssr,
6001 [OP_AND        ] = simplify_and,
6002 [OP_XOR        ] = simplify_xor,
6003 [OP_OR         ] = simplify_or,
6004 [OP_POS        ] = simplify_pos,
6005 [OP_NEG        ] = simplify_neg,
6006 [OP_INVERT     ] = simplify_invert,
6007
6008 [OP_EQ         ] = simplify_eq,
6009 [OP_NOTEQ      ] = simplify_noteq,
6010 [OP_SLESS      ] = simplify_sless,
6011 [OP_ULESS      ] = simplify_uless,
6012 [OP_SMORE      ] = simplify_smore,
6013 [OP_UMORE      ] = simplify_umore,
6014 [OP_SLESSEQ    ] = simplify_slesseq,
6015 [OP_ULESSEQ    ] = simplify_ulesseq,
6016 [OP_SMOREEQ    ] = simplify_smoreeq,
6017 [OP_UMOREEQ    ] = simplify_umoreeq,
6018 [OP_LFALSE     ] = simplify_lfalse,
6019 [OP_LTRUE      ] = simplify_ltrue,
6020
6021 [OP_LOAD       ] = simplify_noop,
6022 [OP_STORE      ] = simplify_noop,
6023
6024 [OP_NOOP       ] = simplify_noop,
6025
6026 [OP_INTCONST   ] = simplify_noop,
6027 [OP_BLOBCONST  ] = simplify_noop,
6028 [OP_ADDRCONST  ] = simplify_noop,
6029
6030 [OP_WRITE      ] = simplify_noop,
6031 [OP_READ       ] = simplify_noop,
6032 [OP_COPY       ] = simplify_copy,
6033 [OP_PIECE      ] = simplify_noop,
6034
6035 [OP_DOT        ] = simplify_noop,
6036 [OP_VAL_VEC    ] = simplify_noop,
6037
6038 [OP_LIST       ] = simplify_noop,
6039 [OP_BRANCH     ] = simplify_branch,
6040 [OP_LABEL      ] = simplify_noop,
6041 [OP_ADECL      ] = simplify_noop,
6042 [OP_SDECL      ] = simplify_noop,
6043 [OP_PHI        ] = simplify_phi,
6044
6045 [OP_INB        ] = simplify_noop,
6046 [OP_INW        ] = simplify_noop,
6047 [OP_INL        ] = simplify_noop,
6048 [OP_OUTB       ] = simplify_noop,
6049 [OP_OUTW       ] = simplify_noop,
6050 [OP_OUTL       ] = simplify_noop,
6051 [OP_BSF        ] = simplify_bsf,
6052 [OP_BSR        ] = simplify_bsr,
6053 [OP_RDMSR      ] = simplify_noop,
6054 [OP_WRMSR      ] = simplify_noop,                    
6055 [OP_HLT        ] = simplify_noop,
6056 };
6057
6058 static void simplify(struct compile_state *state, struct triple *ins)
6059 {
6060         int op;
6061         simplify_t do_simplify;
6062         do {
6063                 op = ins->op;
6064                 do_simplify = 0;
6065                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6066                         do_simplify = 0;
6067                 }
6068                 else {
6069                         do_simplify = table_simplify[op];
6070                 }
6071                 if (!do_simplify) {
6072                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6073                                 op, tops(op));
6074                         return;
6075                 }
6076                 do_simplify(state, ins);
6077         } while(ins->op != op);
6078 }
6079
6080 static void simplify_all(struct compile_state *state)
6081 {
6082         struct triple *ins, *first;
6083         first = RHS(state->main_function, 0);
6084         ins = first;
6085         do {
6086                 simplify(state, ins);
6087                 ins = ins->next;
6088         } while(ins != first);
6089 }
6090
6091 /*
6092  * Builtins....
6093  * ============================
6094  */
6095
6096 static void register_builtin_function(struct compile_state *state,
6097         const char *name, int op, struct type *rtype, ...)
6098 {
6099         struct type *ftype, *atype, *param, **next;
6100         struct triple *def, *arg, *result, *work, *last, *first;
6101         struct hash_entry *ident;
6102         struct file_state file;
6103         int parameters;
6104         int name_len;
6105         va_list args;
6106         int i;
6107
6108         /* Dummy file state to get debug handling right */
6109         memset(&file, 0, sizeof(file));
6110         file.basename = name;
6111         file.line = 1;
6112         file.prev = state->file;
6113         state->file = &file;
6114
6115         /* Find the Parameter count */
6116         valid_op(state, op);
6117         parameters = table_ops[op].rhs;
6118         if (parameters < 0 ) {
6119                 internal_error(state, 0, "Invalid builtin parameter count");
6120         }
6121
6122         /* Find the function type */
6123         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6124         next = &ftype->right;
6125         va_start(args, rtype);
6126         for(i = 0; i < parameters; i++) {
6127                 atype = va_arg(args, struct type *);
6128                 if (!*next) {
6129                         *next = atype;
6130                 } else {
6131                         *next = new_type(TYPE_PRODUCT, *next, atype);
6132                         next = &((*next)->right);
6133                 }
6134         }
6135         if (!*next) {
6136                 *next = &void_type;
6137         }
6138         va_end(args);
6139
6140         /* Generate the needed triples */
6141         def = triple(state, OP_LIST, ftype, 0, 0);
6142         first = label(state);
6143         RHS(def, 0) = first;
6144
6145         /* Now string them together */
6146         param = ftype->right;
6147         for(i = 0; i < parameters; i++) {
6148                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6149                         atype = param->left;
6150                 } else {
6151                         atype = param;
6152                 }
6153                 arg = flatten(state, first, variable(state, atype));
6154                 param = param->right;
6155         }
6156         result = 0;
6157         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6158                 result = flatten(state, first, variable(state, rtype));
6159         }
6160         MISC(def, 0) = result;
6161         work = new_triple(state, op, rtype, parameters);
6162         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6163                 RHS(work, i) = read_expr(state, arg);
6164         }
6165         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6166                 struct triple *val;
6167                 /* Populate the LHS with the target registers */
6168                 work = flatten(state, first, work);
6169                 work->type = &void_type;
6170                 param = rtype->left;
6171                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6172                         internal_error(state, 0, "Invalid result type");
6173                 }
6174                 val = new_triple(state, OP_VAL_VEC, rtype, -1);
6175                 for(i = 0; i < rtype->elements; i++) {
6176                         struct triple *piece;
6177                         atype = param;
6178                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6179                                 atype = param->left;
6180                         }
6181                         if (!TYPE_ARITHMETIC(atype->type) &&
6182                                 !TYPE_PTR(atype->type)) {
6183                                 internal_error(state, 0, "Invalid lhs type");
6184                         }
6185                         piece = triple(state, OP_PIECE, atype, work, 0);
6186                         piece->u.cval = i;
6187                         LHS(work, i) = piece;
6188                         RHS(val, i) = piece;
6189                 }
6190                 work = val;
6191         }
6192         if (result) {
6193                 work = write_expr(state, result, work);
6194         }
6195         work = flatten(state, first, work);
6196         last = flatten(state, first, label(state));
6197         name_len = strlen(name);
6198         ident = lookup(state, name, name_len);
6199         symbol(state, ident, &ident->sym_ident, def, ftype);
6200         
6201         state->file = file.prev;
6202 #if 0
6203         fprintf(stdout, "\n");
6204         loc(stdout, state, 0);
6205         fprintf(stdout, "\n__________ builtin_function _________\n");
6206         print_triple(state, def);
6207         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6208 #endif
6209 }
6210
6211 static struct type *partial_struct(struct compile_state *state,
6212         const char *field_name, struct type *type, struct type *rest)
6213 {
6214         struct hash_entry *field_ident;
6215         struct type *result;
6216         int field_name_len;
6217
6218         field_name_len = strlen(field_name);
6219         field_ident = lookup(state, field_name, field_name_len);
6220
6221         result = clone_type(0, type);
6222         result->field_ident = field_ident;
6223
6224         if (rest) {
6225                 result = new_type(TYPE_PRODUCT, result, rest);
6226         }
6227         return result;
6228 }
6229
6230 static struct type *register_builtin_type(struct compile_state *state,
6231         const char *name, struct type *type)
6232 {
6233         struct hash_entry *ident;
6234         int name_len;
6235
6236         name_len = strlen(name);
6237         ident = lookup(state, name, name_len);
6238         
6239         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6240                 ulong_t elements = 0;
6241                 struct type *field;
6242                 type = new_type(TYPE_STRUCT, type, 0);
6243                 field = type->left;
6244                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6245                         elements++;
6246                         field = field->right;
6247                 }
6248                 elements++;
6249                 symbol(state, ident, &ident->sym_struct, 0, type);
6250                 type->type_ident = ident;
6251                 type->elements = elements;
6252         }
6253         symbol(state, ident, &ident->sym_ident, 0, type);
6254         ident->tok = TOK_TYPE_NAME;
6255         return type;
6256 }
6257
6258
6259 static void register_builtins(struct compile_state *state)
6260 {
6261         struct type *msr_type;
6262
6263         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6264                 &ushort_type);
6265         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6266                 &ushort_type);
6267         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6268                 &ushort_type);
6269
6270         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6271                 &uchar_type, &ushort_type);
6272         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6273                 &ushort_type, &ushort_type);
6274         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6275                 &uint_type, &ushort_type);
6276         
6277         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6278                 &int_type);
6279         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6280                 &int_type);
6281
6282         msr_type = register_builtin_type(state, "__builtin_msr_t",
6283                 partial_struct(state, "lo", &ulong_type,
6284                 partial_struct(state, "hi", &ulong_type, 0)));
6285
6286         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6287                 &ulong_type);
6288         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6289                 &ulong_type, &ulong_type, &ulong_type);
6290         
6291         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6292                 &void_type);
6293 }
6294
6295 static struct type *declarator(
6296         struct compile_state *state, struct type *type, 
6297         struct hash_entry **ident, int need_ident);
6298 static void decl(struct compile_state *state, struct triple *first);
6299 static struct type *specifier_qualifier_list(struct compile_state *state);
6300 static int isdecl_specifier(int tok);
6301 static struct type *decl_specifiers(struct compile_state *state);
6302 static int istype(int tok);
6303 static struct triple *expr(struct compile_state *state);
6304 static struct triple *assignment_expr(struct compile_state *state);
6305 static struct type *type_name(struct compile_state *state);
6306 static void statement(struct compile_state *state, struct triple *fist);
6307
6308 static struct triple *call_expr(
6309         struct compile_state *state, struct triple *func)
6310 {
6311         struct triple *def;
6312         struct type *param, *type;
6313         ulong_t pvals, index;
6314
6315         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6316                 error(state, 0, "Called object is not a function");
6317         }
6318         if (func->op != OP_LIST) {
6319                 internal_error(state, 0, "improper function");
6320         }
6321         eat(state, TOK_LPAREN);
6322         /* Find the return type without any specifiers */
6323         type = clone_type(0, func->type->left);
6324         def = new_triple(state, OP_CALL, func->type, -1);
6325         def->type = type;
6326
6327         pvals = TRIPLE_RHS(def->sizes);
6328         MISC(def, 0) = func;
6329
6330         param = func->type->right;
6331         for(index = 0; index < pvals; index++) {
6332                 struct triple *val;
6333                 struct type *arg_type;
6334                 val = read_expr(state, assignment_expr(state));
6335                 arg_type = param;
6336                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6337                         arg_type = param->left;
6338                 }
6339                 write_compatible(state, arg_type, val->type);
6340                 RHS(def, index) = val;
6341                 if (index != (pvals - 1)) {
6342                         eat(state, TOK_COMMA);
6343                         param = param->right;
6344                 }
6345         }
6346         eat(state, TOK_RPAREN);
6347         return def;
6348 }
6349
6350
6351 static struct triple *character_constant(struct compile_state *state)
6352 {
6353         struct triple *def;
6354         struct token *tk;
6355         const signed char *str, *end;
6356         int c;
6357         int str_len;
6358         eat(state, TOK_LIT_CHAR);
6359         tk = &state->token[0];
6360         str = tk->val.str + 1;
6361         str_len = tk->str_len - 2;
6362         if (str_len <= 0) {
6363                 error(state, 0, "empty character constant");
6364         }
6365         end = str + str_len;
6366         c = char_value(state, &str, end);
6367         if (str != end) {
6368                 error(state, 0, "multibyte character constant not supported");
6369         }
6370         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6371         return def;
6372 }
6373
6374 static struct triple *string_constant(struct compile_state *state)
6375 {
6376         struct triple *def;
6377         struct token *tk;
6378         struct type *type;
6379         const signed char *str, *end;
6380         signed char *buf, *ptr;
6381         int str_len;
6382
6383         buf = 0;
6384         type = new_type(TYPE_ARRAY, &char_type, 0);
6385         type->elements = 0;
6386         /* The while loop handles string concatenation */
6387         do {
6388                 eat(state, TOK_LIT_STRING);
6389                 tk = &state->token[0];
6390                 str = tk->val.str + 1;
6391                 str_len = tk->str_len - 2;
6392                 if (str_len < 0) {
6393                         error(state, 0, "negative string constant length");
6394                 }
6395                 end = str + str_len;
6396                 ptr = buf;
6397                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6398                 memcpy(buf, ptr, type->elements);
6399                 ptr = buf + type->elements;
6400                 do {
6401                         *ptr++ = char_value(state, &str, end);
6402                 } while(str < end);
6403                 type->elements = ptr - buf;
6404         } while(peek(state) == TOK_LIT_STRING);
6405         *ptr = '\0';
6406         type->elements += 1;
6407         def = triple(state, OP_BLOBCONST, type, 0, 0);
6408         def->u.blob = buf;
6409         return def;
6410 }
6411
6412
6413 static struct triple *integer_constant(struct compile_state *state)
6414 {
6415         struct triple *def;
6416         unsigned long val;
6417         struct token *tk;
6418         char *end;
6419         int u, l, decimal;
6420         struct type *type;
6421
6422         eat(state, TOK_LIT_INT);
6423         tk = &state->token[0];
6424         errno = 0;
6425         decimal = (tk->val.str[0] != '0');
6426         val = strtoul(tk->val.str, &end, 0);
6427         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6428                 error(state, 0, "Integer constant to large");
6429         }
6430         u = l = 0;
6431         if ((*end == 'u') || (*end == 'U')) {
6432                 u = 1;
6433                         end++;
6434         }
6435         if ((*end == 'l') || (*end == 'L')) {
6436                 l = 1;
6437                 end++;
6438         }
6439         if ((*end == 'u') || (*end == 'U')) {
6440                 u = 1;
6441                 end++;
6442         }
6443         if (*end) {
6444                 error(state, 0, "Junk at end of integer constant");
6445         }
6446         if (u && l)  {
6447                 type = &ulong_type;
6448         }
6449         else if (l) {
6450                 type = &long_type;
6451                 if (!decimal && (val > LONG_MAX)) {
6452                         type = &ulong_type;
6453                 }
6454         }
6455         else if (u) {
6456                 type = &uint_type;
6457                 if (val > UINT_MAX) {
6458                         type = &ulong_type;
6459                 }
6460         }
6461         else {
6462                 type = &int_type;
6463                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6464                         type = &uint_type;
6465                 }
6466                 else if (!decimal && (val > LONG_MAX)) {
6467                         type = &ulong_type;
6468                 }
6469                 else if (val > INT_MAX) {
6470                         type = &long_type;
6471                 }
6472         }
6473         def = int_const(state, type, val);
6474         return def;
6475 }
6476
6477 static struct triple *primary_expr(struct compile_state *state)
6478 {
6479         struct triple *def;
6480         int tok;
6481         tok = peek(state);
6482         switch(tok) {
6483         case TOK_IDENT:
6484         {
6485                 struct hash_entry *ident;
6486                 /* Here ident is either:
6487                  * a varable name
6488                  * a function name
6489                  * an enumeration constant.
6490                  */
6491                 eat(state, TOK_IDENT);
6492                 ident = state->token[0].ident;
6493                 if (!ident->sym_ident) {
6494                         error(state, 0, "%s undeclared", ident->name);
6495                 }
6496                 def = ident->sym_ident->def;
6497                 break;
6498         }
6499         case TOK_ENUM_CONST:
6500                 /* Here ident is an enumeration constant */
6501                 eat(state, TOK_ENUM_CONST);
6502                 def = 0;
6503                 FINISHME();
6504                 break;
6505         case TOK_LPAREN:
6506                 eat(state, TOK_LPAREN);
6507                 def = expr(state);
6508                 eat(state, TOK_RPAREN);
6509                 break;
6510         case TOK_LIT_INT:
6511                 def = integer_constant(state);
6512                 break;
6513         case TOK_LIT_FLOAT:
6514                 eat(state, TOK_LIT_FLOAT);
6515                 error(state, 0, "Floating point constants not supported");
6516                 def = 0;
6517                 FINISHME();
6518                 break;
6519         case TOK_LIT_CHAR:
6520                 def = character_constant(state);
6521                 break;
6522         case TOK_LIT_STRING:
6523                 def = string_constant(state);
6524                 break;
6525         default:
6526                 def = 0;
6527                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6528         }
6529         return def;
6530 }
6531
6532 static struct triple *postfix_expr(struct compile_state *state)
6533 {
6534         struct triple *def;
6535         int postfix;
6536         def = primary_expr(state);
6537         do {
6538                 struct triple *left;
6539                 int tok;
6540                 postfix = 1;
6541                 left = def;
6542                 switch((tok = peek(state))) {
6543                 case TOK_LBRACKET:
6544                         eat(state, TOK_LBRACKET);
6545                         def = mk_subscript_expr(state, left, expr(state));
6546                         eat(state, TOK_RBRACKET);
6547                         break;
6548                 case TOK_LPAREN:
6549                         def = call_expr(state, def);
6550                         break;
6551                 case TOK_DOT:
6552                 {
6553                         struct hash_entry *field;
6554                         eat(state, TOK_DOT);
6555                         eat(state, TOK_IDENT);
6556                         field = state->token[0].ident;
6557                         def = deref_field(state, def, field);
6558                         break;
6559                 }
6560                 case TOK_ARROW:
6561                 {
6562                         struct hash_entry *field;
6563                         eat(state, TOK_ARROW);
6564                         eat(state, TOK_IDENT);
6565                         field = state->token[0].ident;
6566                         def = mk_deref_expr(state, read_expr(state, def));
6567                         def = deref_field(state, def, field);
6568                         break;
6569                 }
6570                 case TOK_PLUSPLUS:
6571                         eat(state, TOK_PLUSPLUS);
6572                         def = mk_post_inc_expr(state, left);
6573                         break;
6574                 case TOK_MINUSMINUS:
6575                         eat(state, TOK_MINUSMINUS);
6576                         def = mk_post_dec_expr(state, left);
6577                         break;
6578                 default:
6579                         postfix = 0;
6580                         break;
6581                 }
6582         } while(postfix);
6583         return def;
6584 }
6585
6586 static struct triple *cast_expr(struct compile_state *state);
6587
6588 static struct triple *unary_expr(struct compile_state *state)
6589 {
6590         struct triple *def, *right;
6591         int tok;
6592         switch((tok = peek(state))) {
6593         case TOK_PLUSPLUS:
6594                 eat(state, TOK_PLUSPLUS);
6595                 def = mk_pre_inc_expr(state, unary_expr(state));
6596                 break;
6597         case TOK_MINUSMINUS:
6598                 eat(state, TOK_MINUSMINUS);
6599                 def = mk_pre_dec_expr(state, unary_expr(state));
6600                 break;
6601         case TOK_AND:
6602                 eat(state, TOK_AND);
6603                 def = mk_addr_expr(state, cast_expr(state), 0);
6604                 break;
6605         case TOK_STAR:
6606                 eat(state, TOK_STAR);
6607                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6608                 break;
6609         case TOK_PLUS:
6610                 eat(state, TOK_PLUS);
6611                 right = read_expr(state, cast_expr(state));
6612                 arithmetic(state, right);
6613                 def = integral_promotion(state, right);
6614                 break;
6615         case TOK_MINUS:
6616                 eat(state, TOK_MINUS);
6617                 right = read_expr(state, cast_expr(state));
6618                 arithmetic(state, right);
6619                 def = integral_promotion(state, right);
6620                 def = triple(state, OP_NEG, def->type, def, 0);
6621                 break;
6622         case TOK_TILDE:
6623                 eat(state, TOK_TILDE);
6624                 right = read_expr(state, cast_expr(state));
6625                 integral(state, right);
6626                 def = integral_promotion(state, right);
6627                 def = triple(state, OP_INVERT, def->type, def, 0);
6628                 break;
6629         case TOK_BANG:
6630                 eat(state, TOK_BANG);
6631                 right = read_expr(state, cast_expr(state));
6632                 bool(state, right);
6633                 def = lfalse_expr(state, right);
6634                 break;
6635         case TOK_SIZEOF:
6636         {
6637                 struct type *type;
6638                 int tok1, tok2;
6639                 eat(state, TOK_SIZEOF);
6640                 tok1 = peek(state);
6641                 tok2 = peek2(state);
6642                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6643                         eat(state, TOK_LPAREN);
6644                         type = type_name(state);
6645                         eat(state, TOK_RPAREN);
6646                 }
6647                 else {
6648                         struct triple *expr;
6649                         expr = unary_expr(state);
6650                         type = expr->type;
6651                         release_expr(state, expr);
6652                 }
6653                 def = int_const(state, &ulong_type, size_of(state, type));
6654                 break;
6655         }
6656         case TOK_ALIGNOF:
6657         {
6658                 struct type *type;
6659                 int tok1, tok2;
6660                 eat(state, TOK_ALIGNOF);
6661                 tok1 = peek(state);
6662                 tok2 = peek2(state);
6663                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6664                         eat(state, TOK_LPAREN);
6665                         type = type_name(state);
6666                         eat(state, TOK_RPAREN);
6667                 }
6668                 else {
6669                         struct triple *expr;
6670                         expr = unary_expr(state);
6671                         type = expr->type;
6672                         release_expr(state, expr);
6673                 }
6674                 def = int_const(state, &ulong_type, align_of(state, type));
6675                 break;
6676         }
6677         default:
6678                 def = postfix_expr(state);
6679                 break;
6680         }
6681         return def;
6682 }
6683
6684 static struct triple *cast_expr(struct compile_state *state)
6685 {
6686         struct triple *def;
6687         int tok1, tok2;
6688         tok1 = peek(state);
6689         tok2 = peek2(state);
6690         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6691                 struct type *type;
6692                 eat(state, TOK_LPAREN);
6693                 type = type_name(state);
6694                 eat(state, TOK_RPAREN);
6695                 def = read_expr(state, cast_expr(state));
6696                 def = triple(state, OP_COPY, type, def, 0);
6697 #warning "FIXME do I need an OP_CAST expr to be semantically correct here?"
6698         }
6699         else {
6700                 def = unary_expr(state);
6701         }
6702         return def;
6703 }
6704
6705 static struct triple *mult_expr(struct compile_state *state)
6706 {
6707         struct triple *def;
6708         int done;
6709         def = cast_expr(state);
6710         do {
6711                 struct triple *left, *right;
6712                 struct type *result_type;
6713                 int tok, op, sign;
6714                 done = 0;
6715                 switch(tok = (peek(state))) {
6716                 case TOK_STAR:
6717                 case TOK_DIV:
6718                 case TOK_MOD:
6719                         left = read_expr(state, def);
6720                         arithmetic(state, left);
6721
6722                         eat(state, tok);
6723
6724                         right = read_expr(state, cast_expr(state));
6725                         arithmetic(state, right);
6726
6727                         result_type = arithmetic_result(state, left, right);
6728                         sign = is_signed(result_type);
6729                         op = -1;
6730                         switch(tok) {
6731                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6732                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
6733                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
6734                         }
6735                         def = triple(state, op, result_type, left, right);
6736                         break;
6737                 default:
6738                         done = 1;
6739                         break;
6740                 }
6741         } while(!done);
6742         return def;
6743 }
6744
6745 static struct triple *add_expr(struct compile_state *state)
6746 {
6747         struct triple *def;
6748         int done;
6749         def = mult_expr(state);
6750         do {
6751                 done = 0;
6752                 switch( peek(state)) {
6753                 case TOK_PLUS:
6754                         eat(state, TOK_PLUS);
6755                         def = mk_add_expr(state, def, mult_expr(state));
6756                         break;
6757                 case TOK_MINUS:
6758                         eat(state, TOK_MINUS);
6759                         def = mk_sub_expr(state, def, mult_expr(state));
6760                         break;
6761                 default:
6762                         done = 1;
6763                         break;
6764                 }
6765         } while(!done);
6766         return def;
6767 }
6768
6769 static struct triple *shift_expr(struct compile_state *state)
6770 {
6771         struct triple *def;
6772         int done;
6773         def = add_expr(state);
6774         do {
6775                 struct triple *left, *right;
6776                 int tok, op;
6777                 done = 0;
6778                 switch((tok = peek(state))) {
6779                 case TOK_SL:
6780                 case TOK_SR:
6781                         left = read_expr(state, def);
6782                         integral(state, left);
6783                         left = integral_promotion(state, left);
6784
6785                         eat(state, tok);
6786
6787                         right = read_expr(state, add_expr(state));
6788                         integral(state, right);
6789                         right = integral_promotion(state, right);
6790                         
6791                         op = (tok == TOK_SL)? OP_SL : 
6792                                 is_signed(left->type)? OP_SSR: OP_USR;
6793
6794                         def = triple(state, op, left->type, left, right);
6795                         break;
6796                 default:
6797                         done = 1;
6798                         break;
6799                 }
6800         } while(!done);
6801         return def;
6802 }
6803
6804 static struct triple *relational_expr(struct compile_state *state)
6805 {
6806 #warning "Extend relational exprs to work on more than arithmetic types"
6807         struct triple *def;
6808         int done;
6809         def = shift_expr(state);
6810         do {
6811                 struct triple *left, *right;
6812                 struct type *arg_type;
6813                 int tok, op, sign;
6814                 done = 0;
6815                 switch((tok = peek(state))) {
6816                 case TOK_LESS:
6817                 case TOK_MORE:
6818                 case TOK_LESSEQ:
6819                 case TOK_MOREEQ:
6820                         left = read_expr(state, def);
6821                         arithmetic(state, left);
6822
6823                         eat(state, tok);
6824
6825                         right = read_expr(state, shift_expr(state));
6826                         arithmetic(state, right);
6827
6828                         arg_type = arithmetic_result(state, left, right);
6829                         sign = is_signed(arg_type);
6830                         op = -1;
6831                         switch(tok) {
6832                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
6833                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
6834                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
6835                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
6836                         }
6837                         def = triple(state, op, &int_type, left, right);
6838                         break;
6839                 default:
6840                         done = 1;
6841                         break;
6842                 }
6843         } while(!done);
6844         return def;
6845 }
6846
6847 static struct triple *equality_expr(struct compile_state *state)
6848 {
6849 #warning "Extend equality exprs to work on more than arithmetic types"
6850         struct triple *def;
6851         int done;
6852         def = relational_expr(state);
6853         do {
6854                 struct triple *left, *right;
6855                 int tok, op;
6856                 done = 0;
6857                 switch((tok = peek(state))) {
6858                 case TOK_EQEQ:
6859                 case TOK_NOTEQ:
6860                         left = read_expr(state, def);
6861                         arithmetic(state, left);
6862                         eat(state, tok);
6863                         right = read_expr(state, relational_expr(state));
6864                         arithmetic(state, right);
6865                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
6866                         def = triple(state, op, &int_type, left, right);
6867                         break;
6868                 default:
6869                         done = 1;
6870                         break;
6871                 }
6872         } while(!done);
6873         return def;
6874 }
6875
6876 static struct triple *and_expr(struct compile_state *state)
6877 {
6878         struct triple *def;
6879         def = equality_expr(state);
6880         while(peek(state) == TOK_AND) {
6881                 struct triple *left, *right;
6882                 struct type *result_type;
6883                 left = read_expr(state, def);
6884                 integral(state, left);
6885                 eat(state, TOK_AND);
6886                 right = read_expr(state, equality_expr(state));
6887                 integral(state, right);
6888                 result_type = arithmetic_result(state, left, right);
6889                 def = triple(state, OP_AND, result_type, left, right);
6890         }
6891         return def;
6892 }
6893
6894 static struct triple *xor_expr(struct compile_state *state)
6895 {
6896         struct triple *def;
6897         def = and_expr(state);
6898         while(peek(state) == TOK_XOR) {
6899                 struct triple *left, *right;
6900                 struct type *result_type;
6901                 left = read_expr(state, def);
6902                 integral(state, left);
6903                 eat(state, TOK_XOR);
6904                 right = read_expr(state, and_expr(state));
6905                 integral(state, right);
6906                 result_type = arithmetic_result(state, left, right);
6907                 def = triple(state, OP_XOR, result_type, left, right);
6908         }
6909         return def;
6910 }
6911
6912 static struct triple *or_expr(struct compile_state *state)
6913 {
6914         struct triple *def;
6915         def = xor_expr(state);
6916         while(peek(state) == TOK_OR) {
6917                 struct triple *left, *right;
6918                 struct type *result_type;
6919                 left = read_expr(state, def);
6920                 integral(state, left);
6921                 eat(state, TOK_OR);
6922                 right = read_expr(state, xor_expr(state));
6923                 integral(state, right);
6924                 result_type = arithmetic_result(state, left, right);
6925                 def = triple(state, OP_OR, result_type, left, right);
6926         }
6927         return def;
6928 }
6929
6930 static struct triple *land_expr(struct compile_state *state)
6931 {
6932         struct triple *def;
6933         def = or_expr(state);
6934         while(peek(state) == TOK_LOGAND) {
6935                 struct triple *left, *right;
6936                 left = read_expr(state, def);
6937                 bool(state, left);
6938                 eat(state, TOK_LOGAND);
6939                 right = read_expr(state, or_expr(state));
6940                 bool(state, right);
6941
6942                 def = triple(state, OP_LAND, &int_type,
6943                         ltrue_expr(state, left),
6944                         ltrue_expr(state, right));
6945         }
6946         return def;
6947 }
6948
6949 static struct triple *lor_expr(struct compile_state *state)
6950 {
6951         struct triple *def;
6952         def = land_expr(state);
6953         while(peek(state) == TOK_LOGOR) {
6954                 struct triple *left, *right;
6955                 left = read_expr(state, def);
6956                 bool(state, left);
6957                 eat(state, TOK_LOGOR);
6958                 right = read_expr(state, land_expr(state));
6959                 bool(state, right);
6960                 
6961                 def = triple(state, OP_LOR, &int_type,
6962                         ltrue_expr(state, left),
6963                         ltrue_expr(state, right));
6964         }
6965         return def;
6966 }
6967
6968 static struct triple *conditional_expr(struct compile_state *state)
6969 {
6970         struct triple *def;
6971         def = lor_expr(state);
6972         if (peek(state) == TOK_QUEST) {
6973                 struct triple *test, *left, *right;
6974                 bool(state, def);
6975                 test = ltrue_expr(state, read_expr(state, def));
6976                 eat(state, TOK_QUEST);
6977                 left = read_expr(state, expr(state));
6978                 eat(state, TOK_COLON);
6979                 right = read_expr(state, conditional_expr(state));
6980
6981                 def = cond_expr(state, test, left, right);
6982         }
6983         return def;
6984 }
6985
6986 static struct triple *eval_const_expr(
6987         struct compile_state *state, struct triple *expr)
6988 {
6989         struct triple *def;
6990         struct triple *head, *ptr;
6991         head = label(state); /* dummy initial triple */
6992         flatten(state, head, expr);
6993         for(ptr = head->next; ptr != head; ptr = ptr->next) {
6994                 simplify(state, ptr);
6995         }
6996         /* Remove the constant value the tail of the list */
6997         def = head->prev;
6998         def->prev->next = def->next;
6999         def->next->prev = def->prev;
7000         def->next = def->prev = def;
7001         if (!is_const(def)) {
7002                 internal_error(state, 0, "Not a constant expression");
7003         }
7004         /* Free the intermediate expressions */
7005         while(head->next != head) {
7006                 release_triple(state, head->next);
7007         }
7008         free_triple(state, head);
7009         return def;
7010 }
7011
7012 static struct triple *constant_expr(struct compile_state *state)
7013 {
7014         return eval_const_expr(state, conditional_expr(state));
7015 }
7016
7017 static struct triple *assignment_expr(struct compile_state *state)
7018 {
7019         struct triple *def, *left, *right;
7020         int tok, op, sign;
7021         /* The C grammer in K&R shows assignment expressions
7022          * only taking unary expressions as input on their
7023          * left hand side.  But specifies the precedence of
7024          * assignemnt as the lowest operator except for comma.
7025          *
7026          * Allowing conditional expressions on the left hand side
7027          * of an assignement results in a grammar that accepts
7028          * a larger set of statements than standard C.   As long
7029          * as the subset of the grammar that is standard C behaves
7030          * correctly this should cause no problems.
7031          * 
7032          * For the extra token strings accepted by the grammar
7033          * none of them should produce a valid lvalue, so they
7034          * should not produce functioning programs.
7035          *
7036          * GCC has this bug as well, so surprises should be minimal.
7037          */
7038         def = conditional_expr(state);
7039         left = def;
7040         switch((tok = peek(state))) {
7041         case TOK_EQ:
7042                 lvalue(state, left);
7043                 eat(state, TOK_EQ);
7044                 def = write_expr(state, left, 
7045                         read_expr(state, assignment_expr(state)));
7046                 break;
7047         case TOK_TIMESEQ:
7048         case TOK_DIVEQ:
7049         case TOK_MODEQ:
7050         case TOK_PLUSEQ:
7051         case TOK_MINUSEQ:
7052                 lvalue(state, left);
7053                 arithmetic(state, left);
7054                 eat(state, tok);
7055                 right = read_expr(state, assignment_expr(state));
7056                 arithmetic(state, right);
7057
7058                 sign = is_signed(left->type);
7059                 op = -1;
7060                 switch(tok) {
7061                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7062                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7063                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7064                 case TOK_PLUSEQ:  op = OP_ADD; break;
7065                 case TOK_MINUSEQ: op = OP_SUB; break;
7066                 }
7067                 def = write_expr(state, left,
7068                         triple(state, op, left->type, 
7069                                 read_expr(state, left), right));
7070                 break;
7071         case TOK_SLEQ:
7072         case TOK_SREQ:
7073         case TOK_ANDEQ:
7074         case TOK_XOREQ:
7075         case TOK_OREQ:
7076                 lvalue(state, left);
7077                 integral(state, left);
7078                 eat(state, tok);
7079                 right = read_expr(state, assignment_expr(state));
7080                 integral(state, right);
7081                 right = integral_promotion(state, right);
7082                 sign = is_signed(left->type);
7083                 op = -1;
7084                 switch(tok) {
7085                 case TOK_SLEQ:  op = OP_SL; break;
7086                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7087                 case TOK_ANDEQ: op = OP_AND; break;
7088                 case TOK_XOREQ: op = OP_XOR; break;
7089                 case TOK_OREQ:  op = OP_OR; break;
7090                 }
7091                 def = write_expr(state, left,
7092                         triple(state, op, left->type, 
7093                                 read_expr(state, left), right));
7094                 break;
7095         }
7096         return def;
7097 }
7098
7099 static struct triple *expr(struct compile_state *state)
7100 {
7101         struct triple *def;
7102         def = assignment_expr(state);
7103         while(peek(state) == TOK_COMMA) {
7104                 struct triple *left, *right;
7105                 left = def;
7106                 eat(state, TOK_COMMA);
7107                 right = assignment_expr(state);
7108                 def = triple(state, OP_COMMA, right->type, left, right);
7109         }
7110         return def;
7111 }
7112
7113 static void expr_statement(struct compile_state *state, struct triple *first)
7114 {
7115         if (peek(state) != TOK_SEMI) {
7116                 flatten(state, first, expr(state));
7117         }
7118         eat(state, TOK_SEMI);
7119 }
7120
7121 static void if_statement(struct compile_state *state, struct triple *first)
7122 {
7123         struct triple *test, *jmp1, *jmp2, *middle, *end;
7124
7125         jmp1 = jmp2 = middle = 0;
7126         eat(state, TOK_IF);
7127         eat(state, TOK_LPAREN);
7128         test = expr(state);
7129         bool(state, test);
7130         /* Cleanup and invert the test */
7131         test = lfalse_expr(state, read_expr(state, test));
7132         eat(state, TOK_RPAREN);
7133         /* Generate the needed pieces */
7134         middle = label(state);
7135         jmp1 = branch(state, middle, test);
7136         /* Thread the pieces together */
7137         flatten(state, first, test);
7138         flatten(state, first, jmp1);
7139         flatten(state, first, label(state));
7140         statement(state, first);
7141         if (peek(state) == TOK_ELSE) {
7142                 eat(state, TOK_ELSE);
7143                 /* Generate the rest of the pieces */
7144                 end = label(state);
7145                 jmp2 = branch(state, end, 0);
7146                 /* Thread them together */
7147                 flatten(state, first, jmp2);
7148                 flatten(state, first, middle);
7149                 statement(state, first);
7150                 flatten(state, first, end);
7151         }
7152         else {
7153                 flatten(state, first, middle);
7154         }
7155 }
7156
7157 static void for_statement(struct compile_state *state, struct triple *first)
7158 {
7159         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7160         struct triple *label1, *label2, *label3;
7161         struct hash_entry *ident;
7162
7163         eat(state, TOK_FOR);
7164         eat(state, TOK_LPAREN);
7165         head = test = tail = jmp1 = jmp2 = 0;
7166         if (peek(state) != TOK_SEMI) {
7167                 head = expr(state);
7168         } 
7169         eat(state, TOK_SEMI);
7170         if (peek(state) != TOK_SEMI) {
7171                 test = expr(state);
7172                 bool(state, test);
7173                 test = ltrue_expr(state, read_expr(state, test));
7174         }
7175         eat(state, TOK_SEMI);
7176         if (peek(state) != TOK_RPAREN) {
7177                 tail = expr(state);
7178         }
7179         eat(state, TOK_RPAREN);
7180         /* Generate the needed pieces */
7181         label1 = label(state);
7182         label2 = label(state);
7183         label3 = label(state);
7184         if (test) {
7185                 jmp1 = branch(state, label3, 0);
7186                 jmp2 = branch(state, label1, test);
7187         }
7188         else {
7189                 jmp2 = branch(state, label1, 0);
7190         }
7191         end = label(state);
7192         /* Remember where break and continue go */
7193         start_scope(state);
7194         ident = state->i_break;
7195         symbol(state, ident, &ident->sym_ident, end, end->type);
7196         ident = state->i_continue;
7197         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7198         /* Now include the body */
7199         flatten(state, first, head);
7200         flatten(state, first, jmp1);
7201         flatten(state, first, label1);
7202         statement(state, first);
7203         flatten(state, first, label2);
7204         flatten(state, first, tail);
7205         flatten(state, first, label3);
7206         flatten(state, first, test);
7207         flatten(state, first, jmp2);
7208         flatten(state, first, end);
7209         /* Cleanup the break/continue scope */
7210         end_scope(state);
7211 }
7212
7213 static void while_statement(struct compile_state *state, struct triple *first)
7214 {
7215         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7216         struct hash_entry *ident;
7217         eat(state, TOK_WHILE);
7218         eat(state, TOK_LPAREN);
7219         test = expr(state);
7220         bool(state, test);
7221         test = ltrue_expr(state, read_expr(state, test));
7222         eat(state, TOK_RPAREN);
7223         /* Generate the needed pieces */
7224         label1 = label(state);
7225         label2 = label(state);
7226         jmp1 = branch(state, label2, 0);
7227         jmp2 = branch(state, label1, test);
7228         end = label(state);
7229         /* Remember where break and continue go */
7230         start_scope(state);
7231         ident = state->i_break;
7232         symbol(state, ident, &ident->sym_ident, end, end->type);
7233         ident = state->i_continue;
7234         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7235         /* Thread them together */
7236         flatten(state, first, jmp1);
7237         flatten(state, first, label1);
7238         statement(state, first);
7239         flatten(state, first, label2);
7240         flatten(state, first, test);
7241         flatten(state, first, jmp2);
7242         flatten(state, first, end);
7243         /* Cleanup the break/continue scope */
7244         end_scope(state);
7245 }
7246
7247 static void do_statement(struct compile_state *state, struct triple *first)
7248 {
7249         struct triple *label1, *label2, *test, *end;
7250         struct hash_entry *ident;
7251         eat(state, TOK_DO);
7252         /* Generate the needed pieces */
7253         label1 = label(state);
7254         label2 = label(state);
7255         end = label(state);
7256         /* Remember where break and continue go */
7257         start_scope(state);
7258         ident = state->i_break;
7259         symbol(state, ident, &ident->sym_ident, end, end->type);
7260         ident = state->i_continue;
7261         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7262         /* Now include the body */
7263         flatten(state, first, label1);
7264         statement(state, first);
7265         /* Cleanup the break/continue scope */
7266         end_scope(state);
7267         /* Eat the rest of the loop */
7268         eat(state, TOK_WHILE);
7269         eat(state, TOK_LPAREN);
7270         test = read_expr(state, expr(state));
7271         bool(state, test);
7272         eat(state, TOK_RPAREN);
7273         eat(state, TOK_SEMI);
7274         /* Thread the pieces together */
7275         test = ltrue_expr(state, test);
7276         flatten(state, first, label2);
7277         flatten(state, first, test);
7278         flatten(state, first, branch(state, label1, test));
7279         flatten(state, first, end);
7280 }
7281
7282
7283 static void return_statement(struct compile_state *state, struct triple *first)
7284 {
7285         struct triple *jmp, *mv, *dest, *var, *val;
7286         int last;
7287         eat(state, TOK_RETURN);
7288
7289 #warning "FIXME implement a more general excess branch elimination"
7290         val = 0;
7291         /* If we have a return value do some more work */
7292         if (peek(state) != TOK_SEMI) {
7293                 val = read_expr(state, expr(state));
7294         }
7295         eat(state, TOK_SEMI);
7296
7297         /* See if this last statement in a function */
7298         last = ((peek(state) == TOK_RBRACE) && 
7299                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7300
7301         /* Find the return variable */
7302         var = MISC(state->main_function, 0);
7303         /* Find the return destination */
7304         dest = RHS(state->main_function, 0)->prev;
7305         mv = jmp = 0;
7306         /* If needed generate a jump instruction */
7307         if (!last) {
7308                 jmp = branch(state, dest, 0);
7309         }
7310         /* If needed generate an assignment instruction */
7311         if (val) {
7312                 mv = write_expr(state, var, val);
7313         }
7314         /* Now put the code together */
7315         if (mv) {
7316                 flatten(state, first, mv);
7317                 flatten(state, first, jmp);
7318         }
7319         else if (jmp) {
7320                 flatten(state, first, jmp);
7321         }
7322 }
7323
7324 static void break_statement(struct compile_state *state, struct triple *first)
7325 {
7326         struct triple *dest;
7327         eat(state, TOK_BREAK);
7328         eat(state, TOK_SEMI);
7329         if (!state->i_break->sym_ident) {
7330                 error(state, 0, "break statement not within loop or switch");
7331         }
7332         dest = state->i_break->sym_ident->def;
7333         flatten(state, first, branch(state, dest, 0));
7334 }
7335
7336 static void continue_statement(struct compile_state *state, struct triple *first)
7337 {
7338         struct triple *dest;
7339         eat(state, TOK_CONTINUE);
7340         eat(state, TOK_SEMI);
7341         if (!state->i_continue->sym_ident) {
7342                 error(state, 0, "continue statement outside of a loop");
7343         }
7344         dest = state->i_continue->sym_ident->def;
7345         flatten(state, first, branch(state, dest, 0));
7346 }
7347
7348 static void goto_statement(struct compile_state *state, struct triple *first)
7349 {
7350         FINISHME();
7351         eat(state, TOK_GOTO);
7352         eat(state, TOK_IDENT);
7353         eat(state, TOK_SEMI);
7354         error(state, 0, "goto is not implemeted");
7355         FINISHME();
7356 }
7357
7358 static void labeled_statement(struct compile_state *state, struct triple *first)
7359 {
7360         FINISHME();
7361         eat(state, TOK_IDENT);
7362         eat(state, TOK_COLON);
7363         statement(state, first);
7364         error(state, 0, "labeled statements are not implemented");
7365         FINISHME();
7366 }
7367
7368 static void switch_statement(struct compile_state *state, struct triple *first)
7369 {
7370         FINISHME();
7371         eat(state, TOK_SWITCH);
7372         eat(state, TOK_LPAREN);
7373         expr(state);
7374         eat(state, TOK_RPAREN);
7375         statement(state, first);
7376         error(state, 0, "switch statements are not implemented");
7377         FINISHME();
7378 }
7379
7380 static void case_statement(struct compile_state *state, struct triple *first)
7381 {
7382         FINISHME();
7383         eat(state, TOK_CASE);
7384         constant_expr(state);
7385         eat(state, TOK_COLON);
7386         statement(state, first);
7387         error(state, 0, "case statements are not implemented");
7388         FINISHME();
7389 }
7390
7391 static void default_statement(struct compile_state *state, struct triple *first)
7392 {
7393         FINISHME();
7394         eat(state, TOK_DEFAULT);
7395         eat(state, TOK_COLON);
7396         statement(state, first);
7397         error(state, 0, "default statements are not implemented");
7398         FINISHME();
7399 }
7400
7401 static void asm_statement(struct compile_state *state, struct triple *first)
7402 {
7403         FINISHME();
7404         error(state, 0, "FIXME finish asm_statement");
7405 }
7406
7407
7408 static int isdecl(int tok)
7409 {
7410         switch(tok) {
7411         case TOK_AUTO:
7412         case TOK_REGISTER:
7413         case TOK_STATIC:
7414         case TOK_EXTERN:
7415         case TOK_TYPEDEF:
7416         case TOK_CONST:
7417         case TOK_RESTRICT:
7418         case TOK_VOLATILE:
7419         case TOK_VOID:
7420         case TOK_CHAR:
7421         case TOK_SHORT:
7422         case TOK_INT:
7423         case TOK_LONG:
7424         case TOK_FLOAT:
7425         case TOK_DOUBLE:
7426         case TOK_SIGNED:
7427         case TOK_UNSIGNED:
7428         case TOK_STRUCT:
7429         case TOK_UNION:
7430         case TOK_ENUM:
7431         case TOK_TYPE_NAME: /* typedef name */
7432                 return 1;
7433         default:
7434                 return 0;
7435         }
7436 }
7437
7438 static void compound_statement(struct compile_state *state, struct triple *first)
7439 {
7440         eat(state, TOK_LBRACE);
7441         start_scope(state);
7442
7443         /* statement-list opt */
7444         while (peek(state) != TOK_RBRACE) {
7445                 statement(state, first);
7446         }
7447         end_scope(state);
7448         eat(state, TOK_RBRACE);
7449 }
7450
7451 static void statement(struct compile_state *state, struct triple *first)
7452 {
7453         int tok;
7454         tok = peek(state);
7455         if (tok == TOK_LBRACE) {
7456                 compound_statement(state, first);
7457         }
7458         else if (tok == TOK_IF) {
7459                 if_statement(state, first); 
7460         }
7461         else if (tok == TOK_FOR) {
7462                 for_statement(state, first);
7463         }
7464         else if (tok == TOK_WHILE) {
7465                 while_statement(state, first);
7466         }
7467         else if (tok == TOK_DO) {
7468                 do_statement(state, first);
7469         }
7470         else if (tok == TOK_RETURN) {
7471                 return_statement(state, first);
7472         }
7473         else if (tok == TOK_BREAK) {
7474                 break_statement(state, first);
7475         }
7476         else if (tok == TOK_CONTINUE) {
7477                 continue_statement(state, first);
7478         }
7479         else if (tok == TOK_GOTO) {
7480                 goto_statement(state, first);
7481         }
7482         else if (tok == TOK_SWITCH) {
7483                 switch_statement(state, first);
7484         }
7485         else if (tok == TOK_ASM) {
7486                 asm_statement(state, first);
7487         }
7488         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7489                 labeled_statement(state, first); 
7490         }
7491         else if (tok == TOK_CASE) {
7492                 case_statement(state, first);
7493         }
7494         else if (tok == TOK_DEFAULT) {
7495                 default_statement(state, first);
7496         }
7497         else if (isdecl(tok)) {
7498                 /* This handles C99 intermixing of statements and decls */
7499                 decl(state, first);
7500         }
7501         else {
7502                 expr_statement(state, first);
7503         }
7504 }
7505
7506 static struct type *param_decl(struct compile_state *state)
7507 {
7508         struct type *type;
7509         struct hash_entry *ident;
7510         /* Cheat so the declarator will know we are not global */
7511         start_scope(state); 
7512         ident = 0;
7513         type = decl_specifiers(state);
7514         type = declarator(state, type, &ident, 0);
7515         type->field_ident = ident;
7516         end_scope(state);
7517         return type;
7518 }
7519
7520 static struct type *param_type_list(struct compile_state *state, struct type *type)
7521 {
7522         struct type *ftype, **next;
7523         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7524         next = &ftype->right;
7525         while(peek(state) == TOK_COMMA) {
7526                 eat(state, TOK_COMMA);
7527                 if (peek(state) == TOK_DOTS) {
7528                         eat(state, TOK_DOTS);
7529                         error(state, 0, "variadic functions not supported");
7530                 }
7531                 else {
7532                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7533                         next = &((*next)->right);
7534                 }
7535         }
7536         return ftype;
7537 }
7538
7539
7540 static struct type *type_name(struct compile_state *state)
7541 {
7542         struct type *type;
7543         type = specifier_qualifier_list(state);
7544         /* abstract-declarator (may consume no tokens) */
7545         type = declarator(state, type, 0, 0);
7546         return type;
7547 }
7548
7549 static struct type *direct_declarator(
7550         struct compile_state *state, struct type *type, 
7551         struct hash_entry **ident, int need_ident)
7552 {
7553         struct type *outer;
7554         int op;
7555         outer = 0;
7556         arrays_complete(state, type);
7557         switch(peek(state)) {
7558         case TOK_IDENT:
7559                 eat(state, TOK_IDENT);
7560                 if (!ident) {
7561                         error(state, 0, "Unexpected identifier found");
7562                 }
7563                 /* The name of what we are declaring */
7564                 *ident = state->token[0].ident;
7565                 break;
7566         case TOK_LPAREN:
7567                 eat(state, TOK_LPAREN);
7568                 outer = declarator(state, type, ident, need_ident);
7569                 eat(state, TOK_RPAREN);
7570                 break;
7571         default:
7572                 if (need_ident) {
7573                         error(state, 0, "Identifier expected");
7574                 }
7575                 break;
7576         }
7577         do {
7578                 op = 1;
7579                 arrays_complete(state, type);
7580                 switch(peek(state)) {
7581                 case TOK_LPAREN:
7582                         eat(state, TOK_LPAREN);
7583                         type = param_type_list(state, type);
7584                         eat(state, TOK_RPAREN);
7585                         break;
7586                 case TOK_LBRACKET:
7587                 {
7588                         unsigned int qualifiers;
7589                         struct triple *value;
7590                         value = 0;
7591                         eat(state, TOK_LBRACKET);
7592                         if (peek(state) != TOK_RBRACKET) {
7593                                 value = constant_expr(state);
7594                                 integral(state, value);
7595                         }
7596                         eat(state, TOK_RBRACKET);
7597
7598                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7599                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7600                         if (value) {
7601                                 type->elements = value->u.cval;
7602                                 free_triple(state, value);
7603                         } else {
7604                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7605                                 op = 0;
7606                         }
7607                 }
7608                         break;
7609                 default:
7610                         op = 0;
7611                         break;
7612                 }
7613         } while(op);
7614         if (outer) {
7615                 struct type *inner;
7616                 arrays_complete(state, type);
7617                 FINISHME();
7618                 for(inner = outer; inner->left; inner = inner->left)
7619                         ;
7620                 inner->left = type;
7621                 type = outer;
7622         }
7623         return type;
7624 }
7625
7626 static struct type *declarator(
7627         struct compile_state *state, struct type *type, 
7628         struct hash_entry **ident, int need_ident)
7629 {
7630         while(peek(state) == TOK_STAR) {
7631                 eat(state, TOK_STAR);
7632                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7633         }
7634         type = direct_declarator(state, type, ident, need_ident);
7635         return type;
7636 }
7637
7638
7639 static struct type *typedef_name(
7640         struct compile_state *state, unsigned int specifiers)
7641 {
7642         struct hash_entry *ident;
7643         struct type *type;
7644         eat(state, TOK_TYPE_NAME);
7645         ident = state->token[0].ident;
7646         type = ident->sym_ident->type;
7647         specifiers |= type->type & QUAL_MASK;
7648         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
7649                 (type->type & (STOR_MASK | QUAL_MASK))) {
7650                 type = clone_type(specifiers, type);
7651         }
7652         return type;
7653 }
7654
7655 static struct type *enum_specifier(
7656         struct compile_state *state, unsigned int specifiers)
7657 {
7658         int tok;
7659         struct type *type;
7660         type = 0;
7661         FINISHME();
7662         eat(state, TOK_ENUM);
7663         tok = peek(state);
7664         if (tok == TOK_IDENT) {
7665                 eat(state, TOK_IDENT);
7666         }
7667         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
7668                 eat(state, TOK_LBRACE);
7669                 do {
7670                         eat(state, TOK_IDENT);
7671                         if (peek(state) == TOK_EQ) {
7672                                 eat(state, TOK_EQ);
7673                                 constant_expr(state);
7674                         }
7675                         if (peek(state) == TOK_COMMA) {
7676                                 eat(state, TOK_COMMA);
7677                         }
7678                 } while(peek(state) != TOK_RBRACE);
7679                 eat(state, TOK_RBRACE);
7680         }
7681         FINISHME();
7682         return type;
7683 }
7684
7685 #if 0
7686 static struct type *struct_declarator(
7687         struct compile_state *state, struct type *type, struct hash_entry **ident)
7688 {
7689         int tok;
7690 #warning "struct_declarator is complicated because of bitfields, kill them?"
7691         tok = peek(state);
7692         if (tok != TOK_COLON) {
7693                 type = declarator(state, type, ident, 1);
7694         }
7695         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
7696                 eat(state, TOK_COLON);
7697                 constant_expr(state);
7698         }
7699         FINISHME();
7700         return type;
7701 }
7702 #endif
7703
7704 static struct type *struct_or_union_specifier(
7705         struct compile_state *state, unsigned int specifiers)
7706 {
7707         struct type *struct_type;
7708         struct hash_entry *ident;
7709         unsigned int type_join;
7710         int tok;
7711         struct_type = 0;
7712         ident = 0;
7713         switch(peek(state)) {
7714         case TOK_STRUCT:
7715                 eat(state, TOK_STRUCT);
7716                 type_join = TYPE_PRODUCT;
7717                 break;
7718         case TOK_UNION:
7719                 eat(state, TOK_UNION);
7720                 type_join = TYPE_OVERLAP;
7721                 error(state, 0, "unions not yet supported\n");
7722                 break;
7723         default:
7724                 eat(state, TOK_STRUCT);
7725                 type_join = TYPE_PRODUCT;
7726                 break;
7727         }
7728         tok = peek(state);
7729         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
7730                 eat(state, tok);
7731                 ident = state->token[0].ident;
7732         }
7733         if (!ident || (peek(state) == TOK_LBRACE)) {
7734                 ulong_t elements;
7735                 elements = 0;
7736                 eat(state, TOK_LBRACE);
7737                 do {
7738                         struct type *base_type;
7739                         struct type **next;
7740                         int done;
7741                         base_type = specifier_qualifier_list(state);
7742                         next = &struct_type;
7743                         do {
7744                                 struct type *type;
7745                                 struct hash_entry *fident;
7746                                 done = 1;
7747                                 type = declarator(state, base_type, &fident, 1);
7748                                 elements++;
7749                                 if (peek(state) == TOK_COMMA) {
7750                                         done = 0;
7751                                         eat(state, TOK_COMMA);
7752                                 }
7753                                 type = clone_type(0, type);
7754                                 type->field_ident = fident;
7755                                 if (*next) {
7756                                         *next = new_type(type_join, *next, type);
7757                                         next = &((*next)->right);
7758                                 } else {
7759                                         *next = type;
7760                                 }
7761                         } while(!done);
7762                         eat(state, TOK_SEMI);
7763                 } while(peek(state) != TOK_RBRACE);
7764                 eat(state, TOK_RBRACE);
7765                 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
7766                 struct_type->type_ident = ident;
7767                 struct_type->elements = elements;
7768                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
7769         }
7770         if (ident && ident->sym_struct) {
7771                 struct_type = ident->sym_struct->type;
7772         }
7773         else if (ident && !ident->sym_struct) {
7774                 error(state, 0, "struct %s undeclared", ident->name);
7775         }
7776         return struct_type;
7777 }
7778
7779 static unsigned int storage_class_specifier_opt(struct compile_state *state)
7780 {
7781         unsigned int specifiers;
7782         switch(peek(state)) {
7783         case TOK_AUTO:
7784                 eat(state, TOK_AUTO);
7785                 specifiers = STOR_AUTO;
7786                 break;
7787         case TOK_REGISTER:
7788                 eat(state, TOK_REGISTER);
7789                 specifiers = STOR_REGISTER;
7790                 break;
7791         case TOK_STATIC:
7792                 eat(state, TOK_STATIC);
7793                 specifiers = STOR_STATIC;
7794                 break;
7795         case TOK_EXTERN:
7796                 eat(state, TOK_EXTERN);
7797                 specifiers = STOR_EXTERN;
7798                 break;
7799         case TOK_TYPEDEF:
7800                 eat(state, TOK_TYPEDEF);
7801                 specifiers = STOR_TYPEDEF;
7802                 break;
7803         default:
7804                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
7805                         specifiers = STOR_STATIC;
7806                 }
7807                 else {
7808                         specifiers = STOR_AUTO;
7809                 }
7810         }
7811         return specifiers;
7812 }
7813
7814 static unsigned int function_specifier_opt(struct compile_state *state)
7815 {
7816         /* Ignore the inline keyword */
7817         unsigned int specifiers;
7818         specifiers = 0;
7819         switch(peek(state)) {
7820         case TOK_INLINE:
7821                 eat(state, TOK_INLINE);
7822                 specifiers = STOR_INLINE;
7823         }
7824         return specifiers;
7825 }
7826
7827 static unsigned int type_qualifiers(struct compile_state *state)
7828 {
7829         unsigned int specifiers;
7830         int done;
7831         done = 0;
7832         specifiers = QUAL_NONE;
7833         do {
7834                 switch(peek(state)) {
7835                 case TOK_CONST:
7836                         eat(state, TOK_CONST);
7837                         specifiers = QUAL_CONST;
7838                         break;
7839                 case TOK_VOLATILE:
7840                         eat(state, TOK_VOLATILE);
7841                         specifiers = QUAL_VOLATILE;
7842                         break;
7843                 case TOK_RESTRICT:
7844                         eat(state, TOK_RESTRICT);
7845                         specifiers = QUAL_RESTRICT;
7846                         break;
7847                 default:
7848                         done = 1;
7849                         break;
7850                 }
7851         } while(!done);
7852         return specifiers;
7853 }
7854
7855 static struct type *type_specifier(
7856         struct compile_state *state, unsigned int spec)
7857 {
7858         struct type *type;
7859         type = 0;
7860         switch(peek(state)) {
7861         case TOK_VOID:
7862                 eat(state, TOK_VOID);
7863                 type = new_type(TYPE_VOID | spec, 0, 0);
7864                 break;
7865         case TOK_CHAR:
7866                 eat(state, TOK_CHAR);
7867                 type = new_type(TYPE_CHAR | spec, 0, 0);
7868                 break;
7869         case TOK_SHORT:
7870                 eat(state, TOK_SHORT);
7871                 if (peek(state) == TOK_INT) {
7872                         eat(state, TOK_INT);
7873                 }
7874                 type = new_type(TYPE_SHORT | spec, 0, 0);
7875                 break;
7876         case TOK_INT:
7877                 eat(state, TOK_INT);
7878                 type = new_type(TYPE_INT | spec, 0, 0);
7879                 break;
7880         case TOK_LONG:
7881                 eat(state, TOK_LONG);
7882                 switch(peek(state)) {
7883                 case TOK_LONG:
7884                         eat(state, TOK_LONG);
7885                         error(state, 0, "long long not supported");
7886                         break;
7887                 case TOK_DOUBLE:
7888                         eat(state, TOK_DOUBLE);
7889                         error(state, 0, "long double not supported");
7890                         break;
7891                 case TOK_INT:
7892                         eat(state, TOK_INT);
7893                         type = new_type(TYPE_LONG | spec, 0, 0);
7894                         break;
7895                 default:
7896                         type = new_type(TYPE_LONG | spec, 0, 0);
7897                         break;
7898                 }
7899                 break;
7900         case TOK_FLOAT:
7901                 eat(state, TOK_FLOAT);
7902                 error(state, 0, "type float not supported");
7903                 break;
7904         case TOK_DOUBLE:
7905                 eat(state, TOK_DOUBLE);
7906                 error(state, 0, "type double not supported");
7907                 break;
7908         case TOK_SIGNED:
7909                 eat(state, TOK_SIGNED);
7910                 switch(peek(state)) {
7911                 case TOK_LONG:
7912                         eat(state, TOK_LONG);
7913                         switch(peek(state)) {
7914                         case TOK_LONG:
7915                                 eat(state, TOK_LONG);
7916                                 error(state, 0, "type long long not supported");
7917                                 break;
7918                         case TOK_INT:
7919                                 eat(state, TOK_INT);
7920                                 type = new_type(TYPE_LONG | spec, 0, 0);
7921                                 break;
7922                         default:
7923                                 type = new_type(TYPE_LONG | spec, 0, 0);
7924                                 break;
7925                         }
7926                         break;
7927                 case TOK_INT:
7928                         eat(state, TOK_INT);
7929                         type = new_type(TYPE_INT | spec, 0, 0);
7930                         break;
7931                 case TOK_SHORT:
7932                         eat(state, TOK_SHORT);
7933                         type = new_type(TYPE_SHORT | spec, 0, 0);
7934                         break;
7935                 case TOK_CHAR:
7936                         eat(state, TOK_CHAR);
7937                         type = new_type(TYPE_CHAR | spec, 0, 0);
7938                         break;
7939                 default:
7940                         type = new_type(TYPE_INT | spec, 0, 0);
7941                         break;
7942                 }
7943                 break;
7944         case TOK_UNSIGNED:
7945                 eat(state, TOK_UNSIGNED);
7946                 switch(peek(state)) {
7947                 case TOK_LONG:
7948                         eat(state, TOK_LONG);
7949                         switch(peek(state)) {
7950                         case TOK_LONG:
7951                                 eat(state, TOK_LONG);
7952                                 error(state, 0, "unsigned long long not supported");
7953                                 break;
7954                         case TOK_INT:
7955                                 eat(state, TOK_INT);
7956                                 type = new_type(TYPE_ULONG | spec, 0, 0);
7957                                 break;
7958                         default:
7959                                 type = new_type(TYPE_ULONG | spec, 0, 0);
7960                                 break;
7961                         }
7962                         break;
7963                 case TOK_INT:
7964                         eat(state, TOK_INT);
7965                         type = new_type(TYPE_UINT | spec, 0, 0);
7966                         break;
7967                 case TOK_SHORT:
7968                         eat(state, TOK_SHORT);
7969                         type = new_type(TYPE_USHORT | spec, 0, 0);
7970                         break;
7971                 case TOK_CHAR:
7972                         eat(state, TOK_CHAR);
7973                         type = new_type(TYPE_UCHAR | spec, 0, 0);
7974                         break;
7975                 default:
7976                         type = new_type(TYPE_UINT | spec, 0, 0);
7977                         break;
7978                 }
7979                 break;
7980                 /* struct or union specifier */
7981         case TOK_STRUCT:
7982         case TOK_UNION:
7983                 type = struct_or_union_specifier(state, spec);
7984                 break;
7985                 /* enum-spefifier */
7986         case TOK_ENUM:
7987                 type = enum_specifier(state, spec);
7988                 break;
7989                 /* typedef name */
7990         case TOK_TYPE_NAME:
7991                 type = typedef_name(state, spec);
7992                 break;
7993         default:
7994                 error(state, 0, "bad type specifier %s", 
7995                         tokens[peek(state)]);
7996                 break;
7997         }
7998         return type;
7999 }
8000
8001 static int istype(int tok)
8002 {
8003         switch(tok) {
8004         case TOK_CONST:
8005         case TOK_RESTRICT:
8006         case TOK_VOLATILE:
8007         case TOK_VOID:
8008         case TOK_CHAR:
8009         case TOK_SHORT:
8010         case TOK_INT:
8011         case TOK_LONG:
8012         case TOK_FLOAT:
8013         case TOK_DOUBLE:
8014         case TOK_SIGNED:
8015         case TOK_UNSIGNED:
8016         case TOK_STRUCT:
8017         case TOK_UNION:
8018         case TOK_ENUM:
8019         case TOK_TYPE_NAME:
8020                 return 1;
8021         default:
8022                 return 0;
8023         }
8024 }
8025
8026
8027 static struct type *specifier_qualifier_list(struct compile_state *state)
8028 {
8029         struct type *type;
8030         unsigned int specifiers = 0;
8031
8032         /* type qualifiers */
8033         specifiers |= type_qualifiers(state);
8034
8035         /* type specifier */
8036         type = type_specifier(state, specifiers);
8037
8038         return type;
8039 }
8040
8041 static int isdecl_specifier(int tok)
8042 {
8043         switch(tok) {
8044                 /* storage class specifier */
8045         case TOK_AUTO:
8046         case TOK_REGISTER:
8047         case TOK_STATIC:
8048         case TOK_EXTERN:
8049         case TOK_TYPEDEF:
8050                 /* type qualifier */
8051         case TOK_CONST:
8052         case TOK_RESTRICT:
8053         case TOK_VOLATILE:
8054                 /* type specifiers */
8055         case TOK_VOID:
8056         case TOK_CHAR:
8057         case TOK_SHORT:
8058         case TOK_INT:
8059         case TOK_LONG:
8060         case TOK_FLOAT:
8061         case TOK_DOUBLE:
8062         case TOK_SIGNED:
8063         case TOK_UNSIGNED:
8064                 /* struct or union specifier */
8065         case TOK_STRUCT:
8066         case TOK_UNION:
8067                 /* enum-spefifier */
8068         case TOK_ENUM:
8069                 /* typedef name */
8070         case TOK_TYPE_NAME:
8071                 /* function specifiers */
8072         case TOK_INLINE:
8073                 return 1;
8074         default:
8075                 return 0;
8076         }
8077 }
8078
8079 static struct type *decl_specifiers(struct compile_state *state)
8080 {
8081         struct type *type;
8082         unsigned int specifiers;
8083         /* I am overly restrictive in the arragement of specifiers supported.
8084          * C is overly flexible in this department it makes interpreting
8085          * the parse tree difficult.
8086          */
8087         specifiers = 0;
8088
8089         /* storage class specifier */
8090         specifiers |= storage_class_specifier_opt(state);
8091
8092         /* function-specifier */
8093         specifiers |= function_specifier_opt(state);
8094
8095         /* type qualifier */
8096         specifiers |= type_qualifiers(state);
8097
8098         /* type specifier */
8099         type = type_specifier(state, specifiers);
8100         return type;
8101 }
8102
8103 static unsigned designator(struct compile_state *state)
8104 {
8105         int tok;
8106         unsigned index;
8107         index = -1U;
8108         do {
8109                 switch(peek(state)) {
8110                 case TOK_LBRACKET:
8111                 {
8112                         struct triple *value;
8113                         eat(state, TOK_LBRACKET);
8114                         value = constant_expr(state);
8115                         eat(state, TOK_RBRACKET);
8116                         index = value->u.cval;
8117                         break;
8118                 }
8119                 case TOK_DOT:
8120                         eat(state, TOK_DOT);
8121                         eat(state, TOK_IDENT);
8122                         error(state, 0, "Struct Designators not currently supported");
8123                         break;
8124                 default:
8125                         error(state, 0, "Invalid designator");
8126                 }
8127                 tok = peek(state);
8128         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8129         eat(state, TOK_EQ);
8130         return index;
8131 }
8132
8133 static struct triple *initializer(
8134         struct compile_state *state, struct type *type)
8135 {
8136         struct triple *result;
8137         if (peek(state) != TOK_LBRACE) {
8138                 result = assignment_expr(state);
8139         }
8140         else {
8141                 int comma;
8142                 unsigned index, max_index;
8143                 void *buf;
8144                 max_index = index = 0;
8145                 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8146                         max_index = type->elements;
8147                         if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8148                                 type->elements = 0;
8149                         }
8150                 } else {
8151                         error(state, 0, "Struct initializers not currently supported");
8152                 }
8153                 buf = xcmalloc(size_of(state, type), "initializer");
8154                 eat(state, TOK_LBRACE);
8155                 do {
8156                         struct triple *value;
8157                         struct type *value_type;
8158                         size_t value_size;
8159                         int tok;
8160                         comma = 0;
8161                         tok = peek(state);
8162                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8163                                 index = designator(state);
8164                         }
8165                         if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8166                                 (index > max_index)) {
8167                                 error(state, 0, "element beyond bounds");
8168                         }
8169                         value_type = 0;
8170                         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8171                                 value_type = type->left;
8172                         }
8173                         value = eval_const_expr(state, initializer(state, value_type));
8174                         value_size = size_of(state, value_type);
8175                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8176                                 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8177                                 (type->elements <= index)) {
8178                                 void *old_buf;
8179                                 size_t old_size;
8180                                 old_buf = buf;
8181                                 old_size = size_of(state, type);
8182                                 type->elements = index + 1;
8183                                 buf = xmalloc(size_of(state, type), "initializer");
8184                                 memcpy(buf, old_buf, old_size);
8185                                 xfree(old_buf);
8186                         }
8187                         if (value->op == OP_BLOBCONST) {
8188                                 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8189                         }
8190                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8191                                 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8192                         }
8193                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8194                                 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8195                         }
8196                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8197                                 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8198                         }
8199                         else {
8200                                 fprintf(stderr, "%d %d\n",
8201                                         value->op, value_size);
8202                                 internal_error(state, 0, "unhandled constant initializer");
8203                         }
8204                         if (peek(state) == TOK_COMMA) {
8205                                 eat(state, TOK_COMMA);
8206                                 comma = 1;
8207                         }
8208                         index += 1;
8209                 } while(comma && (peek(state) != TOK_RBRACE));
8210                 eat(state, TOK_RBRACE);
8211                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8212                 result->u.blob = buf;
8213         }
8214         return result;
8215 }
8216
8217 static struct triple *function_definition(
8218         struct compile_state *state, struct type *type)
8219 {
8220         struct triple *def, *tmp, *first, *end;
8221         struct hash_entry *ident;
8222         struct type *param;
8223         int i;
8224         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8225                 error(state, 0, "Invalid function header");
8226         }
8227
8228         /* Verify the function type */
8229         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8230                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8231                 (type->right->field_ident == 0)) {
8232                 error(state, 0, "Invalid function parameters");
8233         }
8234         param = type->right;
8235         i = 0;
8236         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8237                 i++;
8238                 if (!param->left->field_ident) {
8239                         error(state, 0, "No identifier for parameter %d\n", i);
8240                 }
8241                 param = param->right;
8242         }
8243         i++;
8244         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8245                 error(state, 0, "No identifier for paramter %d\n", i);
8246         }
8247         
8248         /* Get a list of statements for this function. */
8249         def = triple(state, OP_LIST, type, 0, 0);
8250
8251         /* Start a new scope for the passed parameters */
8252         start_scope(state);
8253
8254         /* Put a label at the very start of a function */
8255         first = label(state);
8256         RHS(def, 0) = first;
8257
8258         /* Put a label at the very end of a function */
8259         end = label(state);
8260         flatten(state, first, end);
8261
8262         /* Walk through the parameters and create symbol table entries
8263          * for them.
8264          */
8265         param = type->right;
8266         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8267                 ident = param->left->field_ident;
8268                 tmp = variable(state, param->left);
8269                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8270                 flatten(state, end, tmp);
8271                 param = param->right;
8272         }
8273         if ((param->type & TYPE_MASK) != TYPE_VOID) {
8274                 /* And don't forget the last parameter */
8275                 ident = param->field_ident;
8276                 tmp = variable(state, param);
8277                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8278                 flatten(state, end, tmp);
8279         }
8280         /* Add a variable for the return value */
8281         MISC(def, 0) = 0;
8282         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8283                 /* Remove all type qualifiers from the return type */
8284                 tmp = variable(state, clone_type(0, type->left));
8285                 flatten(state, end, tmp);
8286                 /* Remember where the return value is */
8287                 MISC(def, 0) = tmp;
8288         }
8289
8290         /* Remember which function I am compiling.
8291          * Also assume the last defined function is the main function.
8292          */
8293         state->main_function = def;
8294
8295         /* Now get the actual function definition */
8296         compound_statement(state, end);
8297
8298         /* Remove the parameter scope */
8299         end_scope(state);
8300 #if 0
8301         fprintf(stdout, "\n");
8302         loc(stdout, state, 0);
8303         fprintf(stdout, "\n__________ function_definition _________\n");
8304         print_triple(state, def);
8305         fprintf(stdout, "__________ function_definition _________ done\n\n");
8306 #endif
8307
8308         return def;
8309 }
8310
8311 static struct triple *do_decl(struct compile_state *state, 
8312         struct type *type, struct hash_entry *ident)
8313 {
8314         struct triple *def;
8315         def = 0;
8316         /* Clean up the storage types used */
8317         switch (type->type & STOR_MASK) {
8318         case STOR_AUTO:
8319         case STOR_STATIC:
8320                 /* These are the good types I am aiming for */
8321                 break;
8322         case STOR_REGISTER:
8323                 type->type &= ~STOR_MASK;
8324                 type->type |= STOR_AUTO;
8325                 break;
8326         case STOR_EXTERN:
8327                 type->type &= ~STOR_MASK;
8328                 type->type |= STOR_STATIC;
8329                 break;
8330         case STOR_TYPEDEF:
8331                 if (!ident) {
8332                         error(state, 0, "typedef without name");
8333                 }
8334                 symbol(state, ident, &ident->sym_ident, 0, type);
8335                 ident->tok = TOK_TYPE_NAME;
8336                 return 0;
8337                 break;
8338         default:
8339                 internal_error(state, 0, "Undefined storage class");
8340         }
8341         if (((type->type & STOR_MASK) == STOR_STATIC) &&
8342                 ((type->type & QUAL_CONST) == 0)) {
8343                 error(state, 0, "non const static variables not supported");
8344         }
8345         if (ident) {
8346                 def = variable(state, type);
8347                 symbol(state, ident, &ident->sym_ident, def, type);
8348         }
8349         return def;
8350 }
8351
8352 static void decl(struct compile_state *state, struct triple *first)
8353 {
8354         struct type *base_type, *type;
8355         struct hash_entry *ident;
8356         struct triple *def;
8357         int global;
8358         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8359         base_type = decl_specifiers(state);
8360         ident = 0;
8361         type = declarator(state, base_type, &ident, 0);
8362         if (global && ident && (peek(state) == TOK_LBRACE)) {
8363                 /* function */
8364                 def = function_definition(state, type);
8365                 symbol(state, ident, &ident->sym_ident, def, type);
8366         }
8367         else {
8368                 int done;
8369                 flatten(state, first, do_decl(state, type, ident));
8370                 /* type or variable definition */
8371                 do {
8372                         done = 1;
8373                         if (peek(state) == TOK_EQ) {
8374                                 if (!ident) {
8375                                         error(state, 0, "cannot assign to a type");
8376                                 }
8377                                 eat(state, TOK_EQ);
8378                                 flatten(state, first,
8379                                         init_expr(state, 
8380                                                 ident->sym_ident->def, 
8381                                                 initializer(state, type)));
8382                         }
8383                         arrays_complete(state, type);
8384                         if (peek(state) == TOK_COMMA) {
8385                                 eat(state, TOK_COMMA);
8386                                 ident = 0;
8387                                 type = declarator(state, base_type, &ident, 0);
8388                                 flatten(state, first, do_decl(state, type, ident));
8389                                 done = 0;
8390                         }
8391                 } while(!done);
8392                 eat(state, TOK_SEMI);
8393         }
8394 }
8395
8396 static void decls(struct compile_state *state)
8397 {
8398         struct triple *list;
8399         int tok;
8400         list = label(state);
8401         while(1) {
8402                 tok = peek(state);
8403                 if (tok == TOK_EOF) {
8404                         return;
8405                 }
8406                 if (tok == TOK_SPACE) {
8407                         eat(state, TOK_SPACE);
8408                 }
8409                 decl(state, list);
8410                 if (list->next != list) {
8411                         error(state, 0, "global variables not supported");
8412                 }
8413         }
8414 }
8415
8416 /*
8417  * Data structurs for optimation.
8418  */
8419
8420 static void do_use_block(
8421         struct block *used, struct block_set **head, struct block *user, 
8422         int front)
8423 {
8424         struct block_set **ptr, *new;
8425         if (!used)
8426                 return;
8427         if (!user)
8428                 return;
8429         ptr = head;
8430         while(*ptr) {
8431                 if ((*ptr)->member == user) {
8432                         return;
8433                 }
8434                 ptr = &(*ptr)->next;
8435         }
8436         new = xcmalloc(sizeof(*new), "block_set");
8437         new->member = user;
8438         if (front) {
8439                 new->next = *head;
8440                 *head = new;
8441         }
8442         else {
8443                 new->next = 0;
8444                 *ptr = new;
8445         }
8446 }
8447 static void do_unuse_block(
8448         struct block *used, struct block_set **head, struct block *unuser)
8449 {
8450         struct block_set *use, **ptr;
8451         ptr = head;
8452         while(*ptr) {
8453                 use = *ptr;
8454                 if (use->member == unuser) {
8455                         *ptr = use->next;
8456                         memset(use, -1, sizeof(*use));
8457                         xfree(use);
8458                 }
8459                 else {
8460                         ptr = &use->next;
8461                 }
8462         }
8463 }
8464
8465 static void use_block(struct block *used, struct block *user)
8466 {
8467         /* Append new to the head of the list, print_block
8468          * depends on this.
8469          */
8470         do_use_block(used, &used->use, user, 1); 
8471         used->users++;
8472 }
8473 static void unuse_block(struct block *used, struct block *unuser)
8474 {
8475         do_unuse_block(used, &used->use, unuser); 
8476         used->users--;
8477 }
8478
8479 static void idom_block(struct block *idom, struct block *user)
8480 {
8481         do_use_block(idom, &idom->idominates, user, 0);
8482 }
8483
8484 static void unidom_block(struct block *idom, struct block *unuser)
8485 {
8486         do_unuse_block(idom, &idom->idominates, unuser);
8487 }
8488
8489 static void domf_block(struct block *block, struct block *domf)
8490 {
8491         do_use_block(block, &block->domfrontier, domf, 0);
8492 }
8493
8494 static void undomf_block(struct block *block, struct block *undomf)
8495 {
8496         do_unuse_block(block, &block->domfrontier, undomf);
8497 }
8498
8499 static void ipdom_block(struct block *ipdom, struct block *user)
8500 {
8501         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8502 }
8503
8504 static void unipdom_block(struct block *ipdom, struct block *unuser)
8505 {
8506         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8507 }
8508
8509 static void ipdomf_block(struct block *block, struct block *ipdomf)
8510 {
8511         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8512 }
8513
8514 static void unipdomf_block(struct block *block, struct block *unipdomf)
8515 {
8516         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8517 }
8518
8519
8520
8521 static int do_walk_triple(struct compile_state *state,
8522         struct triple *ptr, int depth,
8523         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
8524 {
8525         int result;
8526         result = cb(state, ptr, depth);
8527         if ((result == 0) && (ptr->op == OP_LIST)) {
8528                 struct triple *list;
8529                 list = ptr;
8530                 ptr = RHS(list, 0);
8531                 do {
8532                         result = do_walk_triple(state, ptr, depth + 1, cb);
8533                         if (ptr->next->prev != ptr) {
8534                                 internal_error(state, ptr->next, "bad prev");
8535                         }
8536                         ptr = ptr->next;
8537                         
8538                 } while((result == 0) && (ptr != RHS(list, 0)));
8539         }
8540         return result;
8541 }
8542
8543 static int walk_triple(
8544         struct compile_state *state, 
8545         struct triple *ptr, 
8546         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8547 {
8548         return do_walk_triple(state, ptr, 0, cb);
8549 }
8550
8551 static void do_print_prefix(int depth)
8552 {
8553         int i;
8554         for(i = 0; i < depth; i++) {
8555                 printf("  ");
8556         }
8557 }
8558
8559 #define PRINT_LIST 1
8560 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8561 {
8562         int op;
8563         op = ins->op;
8564         if (op == OP_LIST) {
8565 #if !PRINT_LIST
8566                 return 0;
8567 #endif
8568         }
8569         if ((op == OP_LABEL) && (ins->use)) {
8570                 printf("\n%p:\n", ins);
8571         }
8572         do_print_prefix(depth);
8573         display_triple(stdout, ins);
8574
8575         if ((ins->op == OP_BRANCH) && ins->use) {
8576                 internal_error(state, ins, "branch used?");
8577         }
8578 #if 0
8579         {
8580                 struct triple_set *user;
8581                 for(user = ins->use; user; user = user->next) {
8582                         printf("use: %p\n", user->member);
8583                 }
8584         }
8585 #endif
8586         if (triple_is_branch(state, ins)) {
8587                 printf("\n");
8588         }
8589         return 0;
8590 }
8591
8592 static void print_triple(struct compile_state *state, struct triple *ins)
8593 {
8594         walk_triple(state, ins, do_print_triple);
8595 }
8596
8597 static void print_triples(struct compile_state *state)
8598 {
8599         print_triple(state, state->main_function);
8600 }
8601
8602 struct cf_block {
8603         struct block *block;
8604 };
8605 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8606 {
8607         if (!block || (cf[block->vertex].block == block)) {
8608                 return;
8609         }
8610         cf[block->vertex].block = block;
8611         find_cf_blocks(cf, block->left);
8612         find_cf_blocks(cf, block->right);
8613 }
8614
8615 static void print_control_flow(struct compile_state *state)
8616 {
8617         struct cf_block *cf;
8618         int i;
8619         printf("\ncontrol flow\n");
8620         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8621         find_cf_blocks(cf, state->first_block);
8622
8623         for(i = 1; i <= state->last_vertex; i++) {
8624                 struct block *block;
8625                 block = cf[i].block;
8626                 if (!block)
8627                         continue;
8628                 printf("(%p) %d:", block, block->vertex);
8629                 if (block->left) {
8630                         printf(" %d", block->left->vertex);
8631                 }
8632                 if (block->right && (block->right != block->left)) {
8633                         printf(" %d", block->right->vertex);
8634                 }
8635                 printf("\n");
8636         }
8637
8638         xfree(cf);
8639 }
8640
8641
8642 static struct block *basic_block(struct compile_state *state,
8643         struct triple *first)
8644 {
8645         struct block *block;
8646         struct triple *ptr;
8647         int op;
8648         if (first->op != OP_LABEL) {
8649                 internal_error(state, 0, "block does not start with a label");
8650         }
8651         /* See if this basic block has already been setup */
8652         if (first->u.block != 0) {
8653                 return first->u.block;
8654         }
8655         /* Allocate another basic block structure */
8656         state->last_vertex += 1;
8657         block = xcmalloc(sizeof(*block), "block");
8658         block->first = block->last = first;
8659         block->vertex = state->last_vertex;
8660         ptr = first;
8661         do {
8662                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
8663                         break;
8664                 }
8665                 block->last = ptr;
8666                 /* If ptr->u is not used remember where the baic block is */
8667                 if (!is_const(ptr)) {
8668                         ptr->u.block = block;
8669                 }
8670                 if (ptr->op == OP_BRANCH) {
8671                         break;
8672                 }
8673                 ptr = ptr->next;
8674         } while (ptr != RHS(state->main_function, 0));
8675         if (ptr == RHS(state->main_function, 0))
8676                 return block;
8677         op = ptr->op;
8678         if (op == OP_LABEL) {
8679                 block->left = basic_block(state, ptr);
8680                 block->right = 0;
8681                 use_block(block->left, block);
8682         }
8683         else if (op == OP_BRANCH) {
8684                 block->left = 0;
8685                 /* Trace the branch target */
8686                 block->right = basic_block(state, TARG(ptr, 0));
8687                 use_block(block->right, block);
8688                 /* If there is a test trace the branch as well */
8689                 if (TRIPLE_RHS(ptr->sizes)) {
8690                         block->left = basic_block(state, ptr->next);
8691                         use_block(block->left, block);
8692                 }
8693         }
8694         else {
8695                 internal_error(state, 0, "Bad basic block split");
8696         }
8697         return block;
8698 }
8699
8700
8701 static void walk_blocks(struct compile_state *state,
8702         void (*cb)(struct compile_state *state, struct block *block, void *arg),
8703         void *arg)
8704 {
8705         struct triple *ptr, *first;
8706         struct block *last_block;
8707         last_block = 0;
8708         first = RHS(state->main_function, 0);
8709         ptr = first;
8710         do {
8711                 struct block *block;
8712                 if (ptr->op == OP_LABEL) {
8713                         block = ptr->u.block;
8714                         if (block && (block != last_block)) {
8715                                 cb(state, block, arg);
8716                         }
8717                         last_block = block;
8718                 }
8719                 ptr = ptr->next;
8720         } while(ptr != first);
8721 }
8722
8723 static void print_block(
8724         struct compile_state *state, struct block *block, void *arg)
8725 {
8726         struct triple *ptr;
8727
8728         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
8729                 block, 
8730                 block->vertex,
8731                 block->left, 
8732                 block->left && block->left->use?block->left->use->member : 0,
8733                 block->right, 
8734                 block->right && block->right->use?block->right->use->member : 0);
8735         if (block->first->op == OP_LABEL) {
8736                 printf("%p:\n", block->first);
8737         }
8738         for(ptr = block->first; ; ptr = ptr->next) {
8739                 struct triple_set *user;
8740                 int op = ptr->op;
8741                 
8742                 if (!IS_CONST_OP(op)) {
8743                         if (ptr->u.block != block) {
8744                                 internal_error(state, ptr, 
8745                                         "Wrong block pointer: %p\n",
8746                                         ptr->u.block);
8747                         }
8748                 }
8749                 if (op == OP_ADECL) {
8750                         for(user = ptr->use; user; user = user->next) {
8751                                 if (!user->member->u.block) {
8752                                         internal_error(state, user->member, 
8753                                                 "Use %p not in a block?\n",
8754                                                 user->member);
8755                                 }
8756                         }
8757                 }
8758                 display_triple(stdout, ptr);
8759
8760                 /* Sanity checks... */
8761                 valid_ins(state, ptr);
8762                 for(user = ptr->use; user; user = user->next) {
8763                         struct triple *use;
8764                         use = user->member;
8765                         valid_ins(state, use);
8766                         if (!IS_CONST_OP(user->member->op) &&
8767                                 !user->member->u.block) {
8768                                 internal_error(state, user->member,
8769                                         "Use %p not in a block?",
8770                                         user->member);
8771                         }
8772                 }
8773
8774                 if (ptr == block->last)
8775                         break;
8776         }
8777         printf("\n");
8778 }
8779
8780
8781 static void print_blocks(struct compile_state *state)
8782 {
8783         printf("--------------- blocks ---------------\n");
8784         walk_blocks(state, print_block, 0);
8785 }
8786
8787 static void prune_nonblock_triples(struct compile_state *state)
8788 {
8789         struct block *block;
8790         struct triple *first, *ins;
8791         /* Delete the triples not in a basic block */
8792         first = RHS(state->main_function, 0);
8793         block = 0;
8794         ins = first;
8795         do {
8796                 if (ins->op == OP_LABEL) {
8797                         block = ins->u.block;
8798                 }
8799                 ins = ins->next;
8800                 if (!block) {
8801                         release_triple(state, ins->prev);
8802                 }
8803         } while(ins != first);
8804 }
8805
8806 static void setup_basic_blocks(struct compile_state *state)
8807 {
8808         /* Find the basic blocks */
8809         state->last_vertex = 0;
8810         state->first_block = basic_block(state, RHS(state->main_function,0));
8811         /* Delete the triples not in a basic block */
8812         prune_nonblock_triples(state);
8813         /* Find the last basic block */
8814         state->last_block = RHS(state->main_function, 0)->prev->u.block;
8815         if (!state->last_block) {
8816                 internal_error(state, 0, "end not used?");
8817         }
8818         /* Insert an extra unused edge from start to the end 
8819          * This helps with reverse control flow calculations.
8820          */
8821         use_block(state->first_block, state->last_block);
8822         /* If we are debugging print what I have just done */
8823         if (state->debug & DEBUG_BASIC_BLOCKS) {
8824                 print_blocks(state);
8825                 print_control_flow(state);
8826         }
8827 }
8828
8829 static void free_basic_block(struct compile_state *state, struct block *block)
8830 {
8831         struct block_set *entry, *next;
8832         struct block *child;
8833         if (!block) {
8834                 return;
8835         }
8836         if (block->vertex == -1) {
8837                 return;
8838         }
8839         block->vertex = -1;
8840         if (block->left) {
8841                 unuse_block(block->left, block);
8842         }
8843         if (block->right) {
8844                 unuse_block(block->right, block);
8845         }
8846         if (block->idom) {
8847                 unidom_block(block->idom, block);
8848         }
8849         block->idom = 0;
8850         if (block->ipdom) {
8851                 unipdom_block(block->ipdom, block);
8852         }
8853         block->ipdom = 0;
8854         for(entry = block->use; entry; entry = next) {
8855                 next = entry->next;
8856                 child = entry->member;
8857                 unuse_block(block, child);
8858                 if (child->left == block) {
8859                         child->left = 0;
8860                 }
8861                 if (child->right == block) {
8862                         child->right = 0;
8863                 }
8864         }
8865         for(entry = block->idominates; entry; entry = next) {
8866                 next = entry->next;
8867                 child = entry->member;
8868                 unidom_block(block, child);
8869                 child->idom = 0;
8870         }
8871         for(entry = block->domfrontier; entry; entry = next) {
8872                 next = entry->next;
8873                 child = entry->member;
8874                 undomf_block(block, child);
8875         }
8876         for(entry = block->ipdominates; entry; entry = next) {
8877                 next = entry->next;
8878                 child = entry->member;
8879                 unipdom_block(block, child);
8880                 child->ipdom = 0;
8881         }
8882         for(entry = block->ipdomfrontier; entry; entry = next) {
8883                 next = entry->next;
8884                 child = entry->member;
8885                 unipdomf_block(block, child);
8886         }
8887         if (block->users != 0) {
8888                 internal_error(state, 0, "block still has users");
8889         }
8890         free_basic_block(state, block->left);
8891         block->left = 0;
8892         free_basic_block(state, block->right);
8893         block->right = 0;
8894         memset(block, -1, sizeof(*block));
8895         xfree(block);
8896 }
8897
8898 static void free_basic_blocks(struct compile_state *state)
8899 {
8900         struct triple *first, *ins;
8901         free_basic_block(state, state->first_block);
8902         state->last_vertex = 0;
8903         state->first_block = state->last_block = 0;
8904         first = RHS(state->main_function, 0);
8905         ins = first;
8906         do {
8907                 if (!is_const(ins)) {
8908                         ins->u.block = 0;
8909                 }
8910                 ins = ins->next;
8911         } while(ins != first);
8912         
8913 }
8914
8915 struct sdom_block {
8916         struct block *block;
8917         struct sdom_block *sdominates;
8918         struct sdom_block *sdom_next;
8919         struct sdom_block *sdom;
8920         struct sdom_block *label;
8921         struct sdom_block *parent;
8922         struct sdom_block *ancestor;
8923         int vertex;
8924 };
8925
8926
8927 static void unsdom_block(struct sdom_block *block)
8928 {
8929         struct sdom_block **ptr;
8930         if (!block->sdom_next) {
8931                 return;
8932         }
8933         ptr = &block->sdom->sdominates;
8934         while(*ptr) {
8935                 if ((*ptr) == block) {
8936                         *ptr = block->sdom_next;
8937                         return;
8938                 }
8939                 ptr = &(*ptr)->sdom_next;
8940         }
8941 }
8942
8943 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
8944 {
8945         unsdom_block(block);
8946         block->sdom = sdom;
8947         block->sdom_next = sdom->sdominates;
8948         sdom->sdominates = block;
8949 }
8950
8951
8952
8953 static int initialize_sdblock(struct sdom_block *sd,
8954         struct block *parent, struct block *block, int vertex)
8955 {
8956         if (!block || (sd[block->vertex].block == block)) {
8957                 return vertex;
8958         }
8959         vertex += 1;
8960         /* Renumber the blocks in a convinient fashion */
8961         block->vertex = vertex;
8962         sd[vertex].block    = block;
8963         sd[vertex].sdom     = &sd[vertex];
8964         sd[vertex].label    = &sd[vertex];
8965         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
8966         sd[vertex].ancestor = 0;
8967         sd[vertex].vertex   = vertex;
8968         vertex = initialize_sdblock(sd, block, block->left, vertex);
8969         vertex = initialize_sdblock(sd, block, block->right, vertex);
8970         return vertex;
8971 }
8972
8973 static int initialize_sdpblock(struct sdom_block *sd,
8974         struct block *parent, struct block *block, int vertex)
8975 {
8976         struct block_set *user;
8977         if (!block || (sd[block->vertex].block == block)) {
8978                 return vertex;
8979         }
8980         vertex += 1;
8981         /* Renumber the blocks in a convinient fashion */
8982         block->vertex = vertex;
8983         sd[vertex].block    = block;
8984         sd[vertex].sdom     = &sd[vertex];
8985         sd[vertex].label    = &sd[vertex];
8986         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
8987         sd[vertex].ancestor = 0;
8988         sd[vertex].vertex   = vertex;
8989         for(user = block->use; user; user = user->next) {
8990                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
8991         }
8992         return vertex;
8993 }
8994
8995 static void compress_ancestors(struct sdom_block *v)
8996 {
8997         /* This procedure assumes ancestor(v) != 0 */
8998         /* if (ancestor(ancestor(v)) != 0) {
8999          *      compress(ancestor(ancestor(v)));
9000          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9001          *              label(v) = label(ancestor(v));
9002          *      }
9003          *      ancestor(v) = ancestor(ancestor(v));
9004          * }
9005          */
9006         if (!v->ancestor) {
9007                 return;
9008         }
9009         if (v->ancestor->ancestor) {
9010                 compress_ancestors(v->ancestor->ancestor);
9011                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9012                         v->label = v->ancestor->label;
9013                 }
9014                 v->ancestor = v->ancestor->ancestor;
9015         }
9016 }
9017
9018 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9019 {
9020         int i;
9021         /* // step 2 
9022          *  for each v <= pred(w) {
9023          *      u = EVAL(v);
9024          *      if (semi[u] < semi[w] { 
9025          *              semi[w] = semi[u]; 
9026          *      } 
9027          * }
9028          * add w to bucket(vertex(semi[w]));
9029          * LINK(parent(w), w);
9030          *
9031          * // step 3
9032          * for each v <= bucket(parent(w)) {
9033          *      delete v from bucket(parent(w));
9034          *      u = EVAL(v);
9035          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9036          * }
9037          */
9038         for(i = state->last_vertex; i >= 2; i--) {
9039                 struct sdom_block *v, *parent, *next;
9040                 struct block_set *user;
9041                 struct block *block;
9042                 block = sd[i].block;
9043                 parent = sd[i].parent;
9044                 /* Step 2 */
9045                 for(user = block->use; user; user = user->next) {
9046                         struct sdom_block *v, *u;
9047                         v = &sd[user->member->vertex];
9048                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9049                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9050                                 sd[i].sdom = u->sdom;
9051                         }
9052                 }
9053                 sdom_block(sd[i].sdom, &sd[i]);
9054                 sd[i].ancestor = parent;
9055                 /* Step 3 */
9056                 for(v = parent->sdominates; v; v = next) {
9057                         struct sdom_block *u;
9058                         next = v->sdom_next;
9059                         unsdom_block(v);
9060                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9061                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9062                                 u->block : parent->block;
9063                 }
9064         }
9065 }
9066
9067 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9068 {
9069         int i;
9070         /* // step 2 
9071          *  for each v <= pred(w) {
9072          *      u = EVAL(v);
9073          *      if (semi[u] < semi[w] { 
9074          *              semi[w] = semi[u]; 
9075          *      } 
9076          * }
9077          * add w to bucket(vertex(semi[w]));
9078          * LINK(parent(w), w);
9079          *
9080          * // step 3
9081          * for each v <= bucket(parent(w)) {
9082          *      delete v from bucket(parent(w));
9083          *      u = EVAL(v);
9084          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9085          * }
9086          */
9087         for(i = state->last_vertex; i >= 2; i--) {
9088                 struct sdom_block *u, *v, *parent, *next;
9089                 struct block *block;
9090                 block = sd[i].block;
9091                 parent = sd[i].parent;
9092                 /* Step 2 */
9093                 if (block->left) {
9094                         v = &sd[block->left->vertex];
9095                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9096                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9097                                 sd[i].sdom = u->sdom;
9098                         }
9099                 }
9100                 if (block->right && (block->right != block->left)) {
9101                         v = &sd[block->right->vertex];
9102                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9103                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9104                                 sd[i].sdom = u->sdom;
9105                         }
9106                 }
9107                 sdom_block(sd[i].sdom, &sd[i]);
9108                 sd[i].ancestor = parent;
9109                 /* Step 3 */
9110                 for(v = parent->sdominates; v; v = next) {
9111                         struct sdom_block *u;
9112                         next = v->sdom_next;
9113                         unsdom_block(v);
9114                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9115                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9116                                 u->block : parent->block;
9117                 }
9118         }
9119 }
9120
9121 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9122 {
9123         int i;
9124         for(i = 2; i <= state->last_vertex; i++) {
9125                 struct block *block;
9126                 block = sd[i].block;
9127                 if (block->idom->vertex != sd[i].sdom->vertex) {
9128                         block->idom = block->idom->idom;
9129                 }
9130                 idom_block(block->idom, block);
9131         }
9132         sd[1].block->idom = 0;
9133 }
9134
9135 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9136 {
9137         int i;
9138         for(i = 2; i <= state->last_vertex; i++) {
9139                 struct block *block;
9140                 block = sd[i].block;
9141                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9142                         block->ipdom = block->ipdom->ipdom;
9143                 }
9144                 ipdom_block(block->ipdom, block);
9145         }
9146         sd[1].block->ipdom = 0;
9147 }
9148
9149         /* Theorem 1:
9150          *   Every vertex of a flowgraph G = (V, E, r) except r has
9151          *   a unique immediate dominator.  
9152          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9153          *   rooted at r, called the dominator tree of G, such that 
9154          *   v dominates w if and only if v is a proper ancestor of w in
9155          *   the dominator tree.
9156          */
9157         /* Lemma 1:  
9158          *   If v and w are vertices of G such that v <= w,
9159          *   than any path from v to w must contain a common ancestor
9160          *   of v and w in T.
9161          */
9162         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9163         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9164         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9165         /* Theorem 2:
9166          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9167          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9168          */
9169         /* Theorem 3:
9170          *   Let w != r and let u be a vertex for which sdom(u) is 
9171          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9172          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9173          */
9174         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9175          *           Then v -> idom(w) or idom(w) -> idom(v)
9176          */
9177
9178 static void find_immediate_dominators(struct compile_state *state)
9179 {
9180         struct sdom_block *sd;
9181         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9182          *           vi > w for (1 <= i <= k - 1}
9183          */
9184         /* Theorem 4:
9185          *   For any vertex w != r.
9186          *   sdom(w) = min(
9187          *                 {v|(v,w) <= E  and v < w } U 
9188          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9189          */
9190         /* Corollary 1:
9191          *   Let w != r and let u be a vertex for which sdom(u) is 
9192          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9193          *   Then:
9194          *                   { sdom(w) if sdom(w) = sdom(u),
9195          *        idom(w) = {
9196          *                   { idom(u) otherwise
9197          */
9198         /* The algorithm consists of the following 4 steps.
9199          * Step 1.  Carry out a depth-first search of the problem graph.  
9200          *    Number the vertices from 1 to N as they are reached during
9201          *    the search.  Initialize the variables used in succeeding steps.
9202          * Step 2.  Compute the semidominators of all vertices by applying
9203          *    theorem 4.   Carry out the computation vertex by vertex in
9204          *    decreasing order by number.
9205          * Step 3.  Implicitly define the immediate dominator of each vertex
9206          *    by applying Corollary 1.
9207          * Step 4.  Explicitly define the immediate dominator of each vertex,
9208          *    carrying out the computation vertex by vertex in increasing order
9209          *    by number.
9210          */
9211         /* Step 1 initialize the basic block information */
9212         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9213         initialize_sdblock(sd, 0, state->first_block, 0);
9214 #if 0
9215         sd[1].size  = 0;
9216         sd[1].label = 0;
9217         sd[1].sdom  = 0;
9218 #endif
9219         /* Step 2 compute the semidominators */
9220         /* Step 3 implicitly define the immediate dominator of each vertex */
9221         compute_sdom(state, sd);
9222         /* Step 4 explicitly define the immediate dominator of each vertex */
9223         compute_idom(state, sd);
9224         xfree(sd);
9225 }
9226
9227 static void find_post_dominators(struct compile_state *state)
9228 {
9229         struct sdom_block *sd;
9230         /* Step 1 initialize the basic block information */
9231         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9232
9233         initialize_sdpblock(sd, 0, state->last_block, 0);
9234
9235         /* Step 2 compute the semidominators */
9236         /* Step 3 implicitly define the immediate dominator of each vertex */
9237         compute_spdom(state, sd);
9238         /* Step 4 explicitly define the immediate dominator of each vertex */
9239         compute_ipdom(state, sd);
9240         xfree(sd);
9241 }
9242
9243
9244
9245 static void find_block_domf(struct compile_state *state, struct block *block)
9246 {
9247         struct block *child;
9248         struct block_set *user;
9249         if (block->domfrontier != 0) {
9250                 internal_error(state, block->first, "domfrontier present?");
9251         }
9252         for(user = block->idominates; user; user = user->next) {
9253                 child = user->member;
9254                 if (child->idom != block) {
9255                         internal_error(state, block->first, "bad idom");
9256                 }
9257                 find_block_domf(state, child);
9258         }
9259         if (block->left && block->left->idom != block) {
9260                 domf_block(block, block->left);
9261         }
9262         if (block->right && block->right->idom != block) {
9263                 domf_block(block, block->right);
9264         }
9265         for(user = block->idominates; user; user = user->next) {
9266                 struct block_set *frontier;
9267                 child = user->member;
9268                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9269                         if (frontier->member->idom != block) {
9270                                 domf_block(block, frontier->member);
9271                         }
9272                 }
9273         }
9274 }
9275
9276 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9277 {
9278         struct block *child;
9279         struct block_set *user;
9280         if (block->ipdomfrontier != 0) {
9281                 internal_error(state, block->first, "ipdomfrontier present?");
9282         }
9283         for(user = block->ipdominates; user; user = user->next) {
9284                 child = user->member;
9285                 if (child->ipdom != block) {
9286                         internal_error(state, block->first, "bad ipdom");
9287                 }
9288                 find_block_ipdomf(state, child);
9289         }
9290         if (block->left && block->left->ipdom != block) {
9291                 ipdomf_block(block, block->left);
9292         }
9293         if (block->right && block->right->ipdom != block) {
9294                 ipdomf_block(block, block->right);
9295         }
9296         for(user = block->idominates; user; user = user->next) {
9297                 struct block_set *frontier;
9298                 child = user->member;
9299                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9300                         if (frontier->member->ipdom != block) {
9301                                 ipdomf_block(block, frontier->member);
9302                         }
9303                 }
9304         }
9305 }
9306
9307 static int print_dominated(
9308         struct compile_state *state, struct block *block, int vertex)
9309 {
9310         struct block_set *user;
9311
9312         if (!block || (block->vertex != vertex + 1)) {
9313                 return vertex;
9314         }
9315         vertex += 1;
9316
9317         printf("%d:", block->vertex);
9318         for(user = block->idominates; user; user = user->next) {
9319                 printf(" %d", user->member->vertex);
9320                 if (user->member->idom != block) {
9321                         internal_error(state, user->member->first, "bad idom");
9322                 }
9323         }
9324         printf("\n");
9325         vertex = print_dominated(state, block->left, vertex);
9326         vertex = print_dominated(state, block->right, vertex);
9327         return vertex;
9328 }
9329
9330 static void print_dominators(struct compile_state *state)
9331 {
9332         printf("\ndominates\n");
9333         print_dominated(state, state->first_block, 0);
9334 }
9335
9336
9337 static int print_frontiers(
9338         struct compile_state *state, struct block *block, int vertex)
9339 {
9340         struct block_set *user;
9341
9342         if (!block || (block->vertex != vertex + 1)) {
9343                 return vertex;
9344         }
9345         vertex += 1;
9346
9347         printf("%d:", block->vertex);
9348         for(user = block->domfrontier; user; user = user->next) {
9349                 printf(" %d", user->member->vertex);
9350         }
9351         printf("\n");
9352
9353         vertex = print_frontiers(state, block->left, vertex);
9354         vertex = print_frontiers(state, block->right, vertex);
9355         return vertex;
9356 }
9357 static void print_dominance_frontiers(struct compile_state *state)
9358 {
9359         printf("\ndominance frontiers\n");
9360         print_frontiers(state, state->first_block, 0);
9361         
9362 }
9363
9364 static void analyze_idominators(struct compile_state *state)
9365 {
9366         /* Find the immediate dominators */
9367         find_immediate_dominators(state);
9368         /* Find the dominance frontiers */
9369         find_block_domf(state, state->first_block);
9370         /* If debuging print the print what I have just found */
9371         if (state->debug & DEBUG_FDOMINATORS) {
9372                 print_dominators(state);
9373                 print_dominance_frontiers(state);
9374                 print_control_flow(state);
9375         }
9376 }
9377
9378
9379
9380 static int print_ipdominated(
9381         struct compile_state *state, struct block *block, int vertex)
9382 {
9383         struct block_set *user;
9384
9385         if (!block || (block->vertex != vertex + 1)) {
9386                 return vertex;
9387         }
9388         vertex += 1;
9389
9390         printf("%d:", block->vertex);
9391         for(user = block->ipdominates; user; user = user->next) {
9392                 printf(" %d", user->member->vertex);
9393                 if (user->member->ipdom != block) {
9394                         internal_error(state, user->member->first, "bad ipdom");
9395                 }
9396         }
9397         printf("\n");
9398         for(user = block->use; user; user = user->next) {
9399                 vertex = print_ipdominated(state, user->member, vertex);
9400         }
9401         return vertex;
9402 }
9403
9404 static void print_ipdominators(struct compile_state *state)
9405 {
9406         printf("\nipdominates\n");
9407         print_ipdominated(state, state->last_block, 0);
9408 }
9409
9410 static int print_pfrontiers(
9411         struct compile_state *state, struct block *block, int vertex)
9412 {
9413         struct block_set *user;
9414
9415         if (!block || (block->vertex != vertex + 1)) {
9416                 return vertex;
9417         }
9418         vertex += 1;
9419
9420         printf("%d:", block->vertex);
9421         for(user = block->ipdomfrontier; user; user = user->next) {
9422                 printf(" %d", user->member->vertex);
9423         }
9424         printf("\n");
9425         for(user = block->use; user; user = user->next) {
9426                 vertex = print_pfrontiers(state, user->member, vertex);
9427         }
9428         return vertex;
9429 }
9430 static void print_ipdominance_frontiers(struct compile_state *state)
9431 {
9432         printf("\nipdominance frontiers\n");
9433         print_pfrontiers(state, state->last_block, 0);
9434         
9435 }
9436
9437 static void analyze_ipdominators(struct compile_state *state)
9438 {
9439         /* Find the post dominators */
9440         find_post_dominators(state);
9441         /* Find the control dependencies (post dominance frontiers) */
9442         find_block_ipdomf(state, state->last_block);
9443         /* If debuging print the print what I have just found */
9444         if (state->debug & DEBUG_RDOMINATORS) {
9445                 print_ipdominators(state);
9446                 print_ipdominance_frontiers(state);
9447                 print_control_flow(state);
9448         }
9449 }
9450
9451
9452 static void insert_phi_operations(struct compile_state *state)
9453 {
9454         size_t size;
9455         struct triple *first;
9456         int *has_already, *work;
9457         struct block *work_list, **work_list_tail;
9458         int iter;
9459         struct triple *var;
9460
9461         size = sizeof(int) * (state->last_vertex + 1);
9462         has_already = xcmalloc(size, "has_already");
9463         work =        xcmalloc(size, "work");
9464         iter = 0;
9465
9466         first = RHS(state->main_function, 0);
9467         for(var = first->next; var != first ; var = var->next) {
9468                 struct block *block;
9469                 struct triple_set *user;
9470                 if ((var->op != OP_ADECL) || !var->use) {
9471                         continue;
9472                 }
9473                 iter += 1;
9474                 work_list = 0;
9475                 work_list_tail = &work_list;
9476                 for(user = var->use; user; user = user->next) {
9477                         if (user->member->op == OP_READ) {
9478                                 continue;
9479                         }
9480                         if (user->member->op != OP_WRITE) {
9481                                 internal_error(state, user->member, 
9482                                         "bad variable access");
9483                         }
9484                         block = user->member->u.block;
9485                         if (!block) {
9486                                 warning(state, user->member, "dead code");
9487                         }
9488                         work[block->vertex] = iter;
9489                         *work_list_tail = block;
9490                         block->work_next = 0;
9491                         work_list_tail = &block->work_next;
9492                 }
9493                 for(block = work_list; block; block = block->work_next) {
9494                         struct block_set *df;
9495                         for(df = block->domfrontier; df; df = df->next) {
9496                                 struct triple *phi;
9497                                 struct block *front;
9498                                 int in_edges;
9499                                 front = df->member;
9500
9501                                 if (has_already[front->vertex] >= iter) {
9502                                         continue;
9503                                 }
9504                                 /* Count how many edges flow into this block */
9505                                 in_edges = front->users;
9506                                 /* Insert a phi function for this variable */
9507                                 phi = alloc_triple(
9508                                         state, OP_PHI, var->type, in_edges, 
9509                                         front->first->filename, 
9510                                         front->first->line,
9511                                         front->first->col);
9512                                 phi->u.block = front;
9513                                 MISC(phi, 0) = var;
9514                                 use_triple(var, phi);
9515                                 /* Insert the phi functions immediately after the label */
9516                                 insert_triple(state, front->first->next, phi);
9517                                 if (front->first == front->last) {
9518                                         front->last = front->first->next;
9519                                 }
9520                                 has_already[front->vertex] = iter;
9521                                 
9522                                 /* If necessary plan to visit the basic block */
9523                                 if (work[front->vertex] >= iter) {
9524                                         continue;
9525                                 }
9526                                 work[front->vertex] = iter;
9527                                 *work_list_tail = front;
9528                                 front->work_next = 0;
9529                                 work_list_tail = &front->work_next;
9530                         }
9531                 }
9532         }
9533         xfree(has_already);
9534         xfree(work);
9535 }
9536
9537 /*
9538  * C(V)
9539  * S(V)
9540  */
9541 static void fixup_block_phi_variables(
9542         struct compile_state *state, struct block *parent, struct block *block)
9543 {
9544         struct block_set *set;
9545         struct triple *ptr;
9546         int edge;
9547         if (!parent || !block)
9548                 return;
9549         /* Find the edge I am coming in on */
9550         edge = 0;
9551         for(set = block->use; set; set = set->next, edge++) {
9552                 if (set->member == parent) {
9553                         break;
9554                 }
9555         }
9556         if (!set) {
9557                 internal_error(state, 0, "phi input is not on a control predecessor");
9558         }
9559         for(ptr = block->first; ; ptr = ptr->next) {
9560                 if (ptr->op == OP_PHI) {
9561                         struct triple *var, *val, **slot;
9562                         var = MISC(ptr, 0);
9563                         /* Find the current value of the variable */
9564                         val = var->use->member;
9565                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9566                                 internal_error(state, val, "bad value in phi");
9567                         }
9568                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
9569                                 internal_error(state, ptr, "edges > phi rhs");
9570                         }
9571                         slot = &RHS(ptr, edge);
9572                         if ((*slot != 0) && (*slot != val)) {
9573                                 internal_error(state, ptr, "phi already bound on this edge");
9574                         }
9575                         *slot = val;
9576                         use_triple(val, ptr);
9577                 }
9578                 if (ptr == block->last) {
9579                         break;
9580                 }
9581         }
9582 }
9583
9584
9585 static void rename_block_variables(
9586         struct compile_state *state, struct block *block)
9587 {
9588         struct block_set *user;
9589         struct triple *ptr, *next, *last;
9590         int done;
9591         if (!block)
9592                 return;
9593         last = block->first;
9594         done = 0;
9595         for(ptr = block->first; !done; ptr = next) {
9596                 next = ptr->next;
9597                 if (ptr == block->last) {
9598                         done = 1;
9599                 }
9600                 /* RHS(A) */
9601                 if (ptr->op == OP_READ) {
9602                         struct triple *var, *val;
9603                         var = RHS(ptr, 0);
9604                         unuse_triple(var, ptr);
9605                         if (!var->use) {
9606                                 error(state, ptr, "variable used without being set");
9607                         }
9608                         /* Find the current value of the variable */
9609                         val = var->use->member;
9610                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9611                                 internal_error(state, val, "bad value in read");
9612                         }
9613                         propogate_use(state, ptr, val);
9614                         release_triple(state, ptr);
9615                         continue;
9616                 }
9617                 /* LHS(A) */
9618                 if (ptr->op == OP_WRITE) {
9619                         struct triple *var, *val;
9620                         var = LHS(ptr, 0);
9621                         val = RHS(ptr, 0);
9622                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9623                                 internal_error(state, val, "bad value in write");
9624                         }
9625                         propogate_use(state, ptr, val);
9626                         unuse_triple(var, ptr);
9627                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
9628                         push_triple(var, val);
9629                 }
9630                 if (ptr->op == OP_PHI) {
9631                         struct triple *var;
9632                         var = MISC(ptr, 0);
9633                         /* Push OP_PHI onto a stack of variable uses */
9634                         push_triple(var, ptr);
9635                 }
9636                 last = ptr;
9637         }
9638         block->last = last;
9639
9640         /* Fixup PHI functions in the cf successors */
9641         fixup_block_phi_variables(state, block, block->left);
9642         fixup_block_phi_variables(state, block, block->right);
9643         /* rename variables in the dominated nodes */
9644         for(user = block->idominates; user; user = user->next) {
9645                 rename_block_variables(state, user->member);
9646         }
9647         /* pop the renamed variable stack */
9648         last = block->first;
9649         done = 0;
9650         for(ptr = block->first; !done ; ptr = next) {
9651                 next = ptr->next;
9652                 if (ptr == block->last) {
9653                         done = 1;
9654                 }
9655                 if (ptr->op == OP_WRITE) {
9656                         struct triple *var;
9657                         var = LHS(ptr, 0);
9658                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
9659                         pop_triple(var, RHS(ptr, 0));
9660                         release_triple(state, ptr);
9661                         continue;
9662                 }
9663                 if (ptr->op == OP_PHI) {
9664                         struct triple *var;
9665                         var = MISC(ptr, 0);
9666                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
9667                         pop_triple(var, ptr);
9668                 }
9669                 last = ptr;
9670         }
9671         block->last = last;
9672 }
9673
9674 static void prune_block_variables(struct compile_state *state,
9675         struct block *block)
9676 {
9677         struct block_set *user;
9678         struct triple *next, *last, *ptr;
9679         int done;
9680         last = block->first;
9681         done = 0;
9682         for(ptr = block->first; !done; ptr = next) {
9683                 next = ptr->next;
9684                 if (ptr == block->last) {
9685                         done = 1;
9686                 }
9687                 if (ptr->op == OP_ADECL) {
9688                         struct triple_set *user, *next;
9689                         for(user = ptr->use; user; user = next) {
9690                                 struct triple *use;
9691                                 next = user->next;
9692                                 use = user->member;
9693                                 if (use->op != OP_PHI) {
9694                                         internal_error(state, use, "decl still used");
9695                                 }
9696                                 if (MISC(use, 0) != ptr) {
9697                                         internal_error(state, use, "bad phi use of decl");
9698                                 }
9699                                 unuse_triple(ptr, use);
9700                                 MISC(use, 0) = 0;
9701                         }
9702                         release_triple(state, ptr);
9703                         continue;
9704                 }
9705                 last = ptr;
9706         }
9707         block->last = last;
9708         for(user = block->idominates; user; user = user->next) {
9709                 prune_block_variables(state, user->member);
9710         }
9711 }
9712
9713 static void transform_to_ssa_form(struct compile_state *state)
9714 {
9715         insert_phi_operations(state);
9716 #if 0
9717         printf("@%s:%d\n", __FILE__, __LINE__);
9718         print_blocks(state);
9719 #endif
9720         rename_block_variables(state, state->first_block);
9721         prune_block_variables(state, state->first_block);
9722 }
9723
9724
9725 static void transform_from_ssa_form(struct compile_state *state)
9726 {
9727         /* To get out of ssa form we insert moves on the incoming
9728          * edges to blocks containting phi functions.
9729          */
9730         struct triple *first;
9731         struct triple *phi, *next;
9732
9733         /* Walk all of the operations to find the phi functions */
9734         first = RHS(state->main_function, 0);
9735         for(phi = first->next; phi != first ; phi = next) {
9736                 struct block_set *set;
9737                 struct block *block;
9738                 struct triple **slot;
9739                 struct triple *var, *read;
9740                 int edge;
9741                 next = phi->next;
9742                 if (phi->op != OP_PHI) {
9743                         continue;
9744                 }
9745                 block = phi->u.block;
9746                 slot  = &RHS(phi, 0);
9747
9748                 /* A variable to replace the phi function */
9749                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
9750                 /* A read of the single value that is set into the variable */
9751                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
9752                 use_triple(var, read);
9753
9754                 /* Replaces uses of the phi with variable reads */
9755                 propogate_use(state, phi, read);
9756
9757                 /* Walk all of the incoming edges/blocks and insert moves.
9758                  */
9759                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9760                         struct block *eblock;
9761                         struct triple *move;
9762                         struct triple *val;
9763                         eblock = set->member;
9764                         val = slot[edge];
9765                         unuse_triple(val, phi);
9766
9767                         if (val == phi) {
9768                                 continue;
9769                         }
9770
9771                         move = post_triple(state, 
9772                                 val, OP_WRITE, phi->type, var, val);
9773                         use_triple(val, move);
9774                         use_triple(var, move);
9775                 }
9776                 release_triple(state, phi);
9777         }
9778         
9779 }
9780
9781 static void insert_copies_to_phi(struct compile_state *state)
9782 {
9783         /* To get out of ssa form we insert moves on the incoming
9784          * edges to blocks containting phi functions.
9785          */
9786         struct triple *first;
9787         struct triple *phi;
9788
9789         /* Walk all of the operations to find the phi functions */
9790         first = RHS(state->main_function, 0);
9791         for(phi = first->next; phi != first ; phi = phi->next) {
9792                 struct block_set *set;
9793                 struct block *block;
9794                 struct triple **slot;
9795                 int edge;
9796                 if (phi->op != OP_PHI) {
9797                         continue;
9798                 }
9799                 if (ID_REG(phi->id) == REG_UNSET) {
9800                         phi->id = MK_REG_ID(alloc_virtual_reg(), 
9801                                 ID_REG_CLASSES(phi->id));
9802                 }
9803                 block = phi->u.block;
9804                 slot  = &RHS(phi, 0);
9805                 /* Walk all of the incoming edges/blocks and insert moves.
9806                  */
9807                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9808                         struct block *eblock;
9809                         struct triple *move;
9810                         struct triple *val;
9811                         struct triple *ptr;
9812                         eblock = set->member;
9813                         val = slot[edge];
9814
9815                         if (val == phi) {
9816                                 continue;
9817                         }
9818
9819                         move = build_triple(state, OP_COPY, phi->type, val, 0,
9820                                 val->filename, val->line, val->col);
9821                         move->u.block = eblock;
9822                         move->id = phi->id;
9823                         use_triple(val, move);
9824                         
9825                         slot[edge] = move;
9826                         unuse_triple(val, phi);
9827                         use_triple(move, phi);
9828
9829                         /* Walk through the block backwards to find
9830                          * an appropriate location for the OP_COPY.
9831                          */
9832                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
9833                                 struct triple **expr;
9834                                 if ((ptr == phi) || (ptr == val)) {
9835                                         goto out;
9836                                 }
9837                                 expr = triple_rhs(state, ptr, 0);
9838                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
9839                                         if ((*expr) == phi) {
9840                                                 goto out;
9841                                         }
9842                                 }
9843                         }
9844                 out:
9845                         if (triple_is_branch(state, ptr)) {
9846                                 internal_error(state, ptr,
9847                                         "Could not insert write to phi");
9848                         }
9849                         insert_triple(state, ptr->next, move);
9850                         if (eblock->last == ptr) {
9851                                 eblock->last = move;
9852                         }
9853                 }
9854         }
9855 }
9856
9857 struct triple_reg_set {
9858         struct triple_reg_set *next;
9859         struct triple *member;
9860         struct triple *new;
9861 };
9862
9863 struct reg_block {
9864         struct block *block;
9865         struct triple_reg_set *in;
9866         struct triple_reg_set *out;
9867         int vertex;
9868 };
9869
9870 static int do_triple_set(struct triple_reg_set **head, 
9871         struct triple *member, struct triple *new_member)
9872 {
9873         struct triple_reg_set **ptr, *new;
9874         if (!member)
9875                 return 0;
9876         ptr = head;
9877         while(*ptr) {
9878                 if ((*ptr)->member == member) {
9879                         return 0;
9880                 }
9881                 ptr = &(*ptr)->next;
9882         }
9883         new = xcmalloc(sizeof(*new), "triple_set");
9884         new->member = member;
9885         new->new    = new_member;
9886         new->next   = *head;
9887         *head       = new;
9888         return 1;
9889 }
9890
9891 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
9892 {
9893         struct triple_reg_set *entry, **ptr;
9894         ptr = head;
9895         while(*ptr) {
9896                 entry = *ptr;
9897                 if (entry->member == member) {
9898                         *ptr = entry->next;
9899                         xfree(entry);
9900                         return;
9901                 }
9902                 else {
9903                         ptr = &entry->next;
9904                 }
9905         }
9906 }
9907
9908 static int in_triple(struct reg_block *rb, struct triple *in)
9909 {
9910         return do_triple_set(&rb->in, in, 0);
9911 }
9912 static void unin_triple(struct reg_block *rb, struct triple *unin)
9913 {
9914         do_triple_unset(&rb->in, unin);
9915 }
9916
9917 static int out_triple(struct reg_block *rb, struct triple *out)
9918 {
9919         return do_triple_set(&rb->out, out, 0);
9920 }
9921 static void unout_triple(struct reg_block *rb, struct triple *unout)
9922 {
9923         do_triple_unset(&rb->out, unout);
9924 }
9925
9926 static int initialize_regblock(struct reg_block *blocks,
9927         struct block *block, int vertex)
9928 {
9929         struct block_set *user;
9930         if (!block || (blocks[block->vertex].block == block)) {
9931                 return vertex;
9932         }
9933         vertex += 1;
9934         /* Renumber the blocks in a convinient fashion */
9935         block->vertex = vertex;
9936         blocks[vertex].block    = block;
9937         blocks[vertex].vertex   = vertex;
9938         for(user = block->use; user; user = user->next) {
9939                 vertex = initialize_regblock(blocks, user->member, vertex);
9940         }
9941         return vertex;
9942 }
9943
9944 static int phi_in(struct compile_state *state, struct reg_block *blocks,
9945         struct reg_block *rb, struct block *suc)
9946 {
9947         /* Read the conditional input set of a successor block
9948          * (i.e. the input to the phi nodes) and place it in the
9949          * current blocks output set.
9950          */
9951         struct block_set *set;
9952         struct triple *ptr;
9953         int edge;
9954         int done, change;
9955         change = 0;
9956         /* Find the edge I am coming in on */
9957         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
9958                 if (set->member == rb->block) {
9959                         break;
9960                 }
9961         }
9962         if (!set) {
9963                 internal_error(state, 0, "Not coming on a control edge?");
9964         }
9965         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
9966                 struct triple **slot, *expr, *ptr2;
9967                 int out_change, done2;
9968                 done = (ptr == suc->last);
9969                 if (ptr->op != OP_PHI) {
9970                         continue;
9971                 }
9972                 slot = &RHS(ptr, 0);
9973                 expr = slot[edge];
9974                 out_change = out_triple(rb, expr);
9975                 if (!out_change) {
9976                         continue;
9977                 }
9978                 /* If we don't define the variable also plast it
9979                  * in the current blocks input set.
9980                  */
9981                 ptr2 = rb->block->first;
9982                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
9983                         if (ptr2 == expr) {
9984                                 break;
9985                         }
9986                         done2 = (ptr2 == rb->block->last);
9987                 }
9988                 if (!done2) {
9989                         continue;
9990                 }
9991                 change |= in_triple(rb, expr);
9992         }
9993         return change;
9994 }
9995
9996 static int reg_in(struct compile_state *state, struct reg_block *blocks,
9997         struct reg_block *rb, struct block *suc)
9998 {
9999         struct triple_reg_set *in_set;
10000         int change;
10001         change = 0;
10002         /* Read the input set of a successor block
10003          * and place it in the current blocks output set.
10004          */
10005         in_set = blocks[suc->vertex].in;
10006         for(; in_set; in_set = in_set->next) {
10007                 int out_change, done;
10008                 struct triple *first, *last, *ptr;
10009                 out_change = out_triple(rb, in_set->member);
10010                 if (!out_change) {
10011                         continue;
10012                 }
10013                 /* If we don't define the variable also place it
10014                  * in the current blocks input set.
10015                  */
10016                 first = rb->block->first;
10017                 last = rb->block->last;
10018                 done = 0;
10019                 for(ptr = first; !done; ptr = ptr->next) {
10020                         if (ptr == in_set->member) {
10021                                 break;
10022                         }
10023                         done = (ptr == last);
10024                 }
10025                 if (!done) {
10026                         continue;
10027                 }
10028                 change |= in_triple(rb, in_set->member);
10029         }
10030         change |= phi_in(state, blocks, rb, suc);
10031         return change;
10032 }
10033
10034
10035 static int use_in(struct compile_state *state, struct reg_block *rb)
10036 {
10037         /* Find the variables we use but don't define and add
10038          * it to the current blocks input set.
10039          */
10040 #warning "FIXME is this O(N^2) algorithm bad?"
10041         struct block *block;
10042         struct triple *ptr;
10043         int done;
10044         int change;
10045         block = rb->block;
10046         change = 0;
10047         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10048                 struct triple **expr;
10049                 done = (ptr == block->first);
10050                 /* The variable a phi function uses depends on the
10051                  * control flow, and is handled in phi_in, not
10052                  * here.
10053                  */
10054                 if (ptr->op == OP_PHI) {
10055                         continue;
10056                 }
10057                 expr = triple_rhs(state, ptr, 0);
10058                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10059                         struct triple *rhs, *test;
10060                         int tdone;
10061                         rhs = *expr;
10062                         if (!rhs) {
10063                                 continue;
10064                         }
10065                         /* See if rhs is defined in this block */
10066                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10067                                 tdone = (test == block->first);
10068                                 if (test == rhs) {
10069                                         rhs = 0;
10070                                         break;
10071                                 }
10072                         }
10073                         /* If the triple is not a definition skip it. */
10074                         if (!triple_is_def(state, ptr)) {
10075                                 continue;
10076                         }
10077                         /* If I still have a valid rhs add it to in */
10078                         change |= in_triple(rb, rhs);
10079                 }
10080         }
10081         return change;
10082 }
10083
10084 static struct reg_block *compute_variable_lifetimes(
10085         struct compile_state *state)
10086 {
10087         struct reg_block *blocks;
10088         int change;
10089         blocks = xcmalloc(
10090                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10091         initialize_regblock(blocks, state->last_block, 0);
10092         do {
10093                 int i;
10094                 change = 0;
10095                 for(i = 1; i <= state->last_vertex; i++) {
10096                         struct reg_block *rb;
10097                         rb = &blocks[i];
10098                         /* Add the left successor's input set to in */
10099                         if (rb->block->left) {
10100                                 change |= reg_in(state, blocks, rb, rb->block->left);
10101                         }
10102                         /* Add the right successor's input set to in */
10103                         if ((rb->block->right) && 
10104                                 (rb->block->right != rb->block->left)) {
10105                                 change |= reg_in(state, blocks, rb, rb->block->right);
10106                         }
10107                         /* Add use to in... */
10108                         change |= use_in(state, rb);
10109                 }
10110         } while(change);
10111         return blocks;
10112 }
10113
10114 static void free_variable_lifetimes(
10115         struct compile_state *state, struct reg_block *blocks)
10116 {
10117         int i;
10118         /* free in_set && out_set on each block */
10119         for(i = 1; i <= state->last_vertex; i++) {
10120                 struct triple_reg_set *entry, *next;
10121                 struct reg_block *rb;
10122                 rb = &blocks[i];
10123                 for(entry = rb->in; entry ; entry = next) {
10124                         next = entry->next;
10125                         do_triple_unset(&rb->in, entry->member);
10126                 }
10127                 for(entry = rb->out; entry; entry = next) {
10128                         next = entry->next;
10129                         do_triple_unset(&rb->out, entry->member);
10130                 }
10131         }
10132         xfree(blocks);
10133
10134 }
10135
10136 typedef struct triple *(*wvl_cb_t)(
10137         struct compile_state *state, 
10138         struct reg_block *blocks, struct triple_reg_set *live, 
10139         struct reg_block *rb, struct triple *ins, void *arg);
10140
10141 static void walk_variable_lifetimes(struct compile_state *state,
10142         struct reg_block *blocks, wvl_cb_t cb, void *arg)
10143 {
10144         int i;
10145         
10146         for(i = 1; i <= state->last_vertex; i++) {
10147                 struct triple_reg_set *live;
10148                 struct triple_reg_set *entry, *next;
10149                 struct triple *ptr, *prev;
10150                 struct reg_block *rb;
10151                 struct block *block;
10152                 int done;
10153
10154                 /* Get the blocks */
10155                 rb = &blocks[i];
10156                 block = rb->block;
10157
10158                 /* Copy out into live */
10159                 live = 0;
10160                 for(entry = rb->out; entry; entry = next) {
10161                         next = entry->next;
10162                         do_triple_set(&live, entry->member, entry->new);
10163                 }
10164                 /* Walk through the basic block calculating live */
10165                 for(done = 0, ptr = block->last; !done; ptr = prev) {
10166                         struct triple **expr;
10167
10168                         prev = ptr->prev;
10169                         done = (ptr == block->first);
10170                         
10171                         /* Remove the current definition from live */
10172                         do_triple_unset(&live, ptr);
10173                         
10174                         /* If the current instruction was deleted continue */
10175                         if (!cb(state, blocks, live, rb, ptr, arg)) {
10176                                 if (block->last == ptr) {
10177                                         block->last = prev;
10178                                 }
10179                                 continue;
10180                         }
10181                         
10182                         /* Add the current uses to live.
10183                          *
10184                          * It is safe to skip phi functions because they do
10185                          * not have any block local uses, and the block
10186                          * output sets already properly account for what
10187                          * control flow depedent uses phi functions do have.
10188                          */
10189                         if (ptr->op == OP_PHI) {
10190                                 continue;
10191                         }
10192                         expr = triple_rhs(state, ptr, 0);
10193                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
10194                                 /* If the triple is not a definition skip it. */
10195                                 if (!*expr || !triple_is_def(state, *expr)) {
10196                                         continue;
10197                                 }
10198                                 do_triple_set(&live, *expr, 0);
10199                         }
10200                         expr = triple_lhs(state, ptr, 0);
10201                         for(;expr; expr = triple_lhs(state, ptr, expr)) {
10202                                 /* If the triple is not a definition skip it. */
10203                                 if (!*expr || !triple_is_def(state, *expr)) {
10204                                         continue;
10205                                 }
10206                                 do_triple_set(&live, *expr, 0);
10207                         }
10208
10209                 }
10210                 /* Free live */
10211                 for(entry = live; entry; entry = next) {
10212                         next = entry->next;
10213                         do_triple_unset(&live, entry->member);
10214                 }
10215         }
10216 }
10217
10218 static int count_triples(struct compile_state *state)
10219 {
10220         struct triple *first, *ins;
10221         int triples = 0;
10222         first = RHS(state->main_function, 0);
10223         ins = first;
10224         do {
10225                 triples++;
10226                 ins = ins->next;
10227         } while (ins != first);
10228         return triples;
10229 }
10230 struct dead_triple {
10231         struct triple *triple;
10232         struct dead_triple *work_next;
10233         struct block *block;
10234         int color;
10235         int flags;
10236 #define TRIPLE_FLAG_ALIVE 1
10237 };
10238
10239
10240 static void awaken(
10241         struct compile_state *state,
10242         struct dead_triple *dtriple, struct triple **expr,
10243         struct dead_triple ***work_list_tail)
10244 {
10245         struct triple *triple;
10246         struct dead_triple *dt;
10247         if (!expr) {
10248                 return;
10249         }
10250         triple = *expr;
10251         if (!triple) {
10252                 return;
10253         }
10254         if (triple->id <= 0)  {
10255                 internal_error(state, triple, "bad triple id: %d",
10256                         triple->id);
10257         }
10258         if (triple->op == OP_NOOP) {
10259                 internal_warning(state, triple, "awakening noop?");
10260                 return;
10261         }
10262         dt = &dtriple[triple->id];
10263         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10264                 dt->flags |= TRIPLE_FLAG_ALIVE;
10265                 if (!dt->work_next) {
10266                         **work_list_tail = dt;
10267                         *work_list_tail = &dt->work_next;
10268                 }
10269         }
10270 }
10271
10272 static void eliminate_inefectual_code(struct compile_state *state)
10273 {
10274         struct block *block;
10275         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10276         int triples, i;
10277         struct triple *first, *ins;
10278
10279         /* Setup the work list */
10280         work_list = 0;
10281         work_list_tail = &work_list;
10282
10283         first = RHS(state->main_function, 0);
10284
10285         /* Count how many triples I have */
10286         triples = count_triples(state);
10287
10288         /* Now put then in an array and mark all of the triples dead */
10289         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
10290         
10291         ins = first;
10292         i = 1;
10293         block = 0;
10294         do {
10295                 if (ins->op == OP_LABEL) {
10296                         block = ins->u.block;
10297                 }
10298                 dtriple[i].triple = ins;
10299                 dtriple[i].block  = block;
10300                 dtriple[i].flags  = 0;
10301                 dtriple[i].color  = ins->id;
10302                 ins->id = i;
10303                 /* See if it is an operation we always keep */
10304 #warning "FIXME handle the case of killing a branch instruction"
10305                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
10306                         awaken(state, dtriple, &ins, &work_list_tail);
10307                 }
10308                 i++;
10309                 ins = ins->next;
10310         } while(ins != first);
10311         while(work_list) {
10312                 struct dead_triple *dt;
10313                 struct block_set *user;
10314                 struct triple **expr;
10315                 dt = work_list;
10316                 work_list = dt->work_next;
10317                 if (!work_list) {
10318                         work_list_tail = &work_list;
10319                 }
10320                 /* Wake up the data depencencies of this triple */
10321                 expr = 0;
10322                 do {
10323                         expr = triple_rhs(state, dt->triple, expr);
10324                         awaken(state, dtriple, expr, &work_list_tail);
10325                 } while(expr);
10326                 do {
10327                         expr = triple_lhs(state, dt->triple, expr);
10328                         awaken(state, dtriple, expr, &work_list_tail);
10329                 } while(expr);
10330                 /* Wake up the forward control dependencies */
10331                 do {
10332                         expr = triple_targ(state, dt->triple, expr);
10333                         awaken(state, dtriple, expr, &work_list_tail);
10334                 } while(expr);
10335                 /* Wake up the reverse control dependencies of this triple */
10336                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
10337                         awaken(state, dtriple, &user->member->last, &work_list_tail);
10338                 }
10339         }
10340         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
10341                 if ((dt->triple->op == OP_NOOP) && 
10342                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
10343                         internal_error(state, dt->triple, "noop effective?");
10344                 }
10345                 dt->triple->id = dt->color;     /* Restore the color */
10346                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10347 #warning "FIXME handle the case of killing a basic block"
10348                         if (dt->block->first == dt->triple) {
10349                                 continue;
10350                         }
10351                         if (dt->block->last == dt->triple) {
10352                                 dt->block->last = dt->triple->prev;
10353                         }
10354                         release_triple(state, dt->triple);
10355                 }
10356         }
10357         xfree(dtriple);
10358 }
10359
10360
10361 struct live_range_edge;
10362 struct live_range {
10363         struct live_range_edge *edges;
10364         struct triple *def;
10365         unsigned color;
10366         unsigned classes;
10367         unsigned degree;
10368         struct live_range *group_next, **group_prev;
10369 };
10370
10371 struct live_range_edge {
10372         struct live_range_edge *next;
10373         struct live_range *node;
10374 };
10375
10376 #define LRE_HASH_SIZE 2048
10377 struct lre_hash {
10378         struct lre_hash *next;
10379         struct live_range *left;
10380         struct live_range *right;
10381 };
10382
10383
10384 struct reg_state {
10385         struct lre_hash *hash[LRE_HASH_SIZE];
10386         struct reg_block *blocks;
10387         struct live_range *lr;
10388         struct live_range *low, **low_tail;
10389         struct live_range *high, **high_tail;
10390         unsigned ranges;
10391 };
10392
10393
10394 static unsigned regc_max_size(struct compile_state *state, int classes)
10395 {
10396         unsigned max_size;
10397         int i;
10398         max_size = 0;
10399         for(i = 0; i < MAX_REGC; i++) {
10400                 if (classes & (1 << i)) {
10401                         unsigned size;
10402                         size = arch_regc_size(state, i);
10403                         if (size > max_size) {
10404                                 max_size = size;
10405                         }
10406                 }
10407         }
10408         return max_size;
10409 }
10410
10411 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
10412 {
10413         unsigned equivs[MAX_REG_EQUIVS];
10414         int i;
10415         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
10416                 internal_error(state, 0, "invalid register");
10417         }
10418         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
10419                 internal_error(state, 0, "invalid register");
10420         }
10421         arch_reg_equivs(state, equivs, reg1);
10422         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10423                 if (equivs[i] == reg2) {
10424                         return 1;
10425                 }
10426         }
10427         return 0;
10428 }
10429
10430 static void reg_fill_used(struct compile_state *state, char *used, int reg)
10431 {
10432         unsigned equivs[MAX_REG_EQUIVS];
10433         int i;
10434         arch_reg_equivs(state, equivs, reg);
10435         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10436                 used[equivs[i]] = 1;
10437         }
10438         return;
10439 }
10440
10441 static unsigned int hash_live_edge(
10442         struct live_range *left, struct live_range *right)
10443 {
10444         unsigned int hash, val;
10445         unsigned long lval, rval;
10446         lval = ((unsigned long)left)/sizeof(struct live_range);
10447         rval = ((unsigned long)right)/sizeof(struct live_range);
10448         hash = 0;
10449         while(lval) {
10450                 val = lval & 0xff;
10451                 lval >>= 8;
10452                 hash = (hash *263) + val;
10453         }
10454         while(rval) {
10455                 val = rval & 0xff;
10456                 rval >>= 8;
10457                 hash = (hash *263) + val;
10458         }
10459         hash = hash & (LRE_HASH_SIZE - 1);
10460         return hash;
10461 }
10462
10463 static struct lre_hash **lre_probe(struct reg_state *rstate,
10464         struct live_range *left, struct live_range *right)
10465 {
10466         struct lre_hash **ptr;
10467         unsigned int index;
10468         /* Ensure left <= right */
10469         if (left > right) {
10470                 struct live_range *tmp;
10471                 tmp = left;
10472                 left = right;
10473                 right = tmp;
10474         }
10475         index = hash_live_edge(left, right);
10476         
10477         ptr = &rstate->hash[index];
10478         while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
10479                 ptr = &(*ptr)->next;
10480         }
10481         return ptr;
10482 }
10483
10484 static int interfere(struct reg_state *rstate,
10485         struct live_range *left, struct live_range *right)
10486 {
10487         struct lre_hash **ptr;
10488         ptr = lre_probe(rstate, left, right);
10489         return ptr && *ptr;
10490 }
10491
10492 static void add_live_edge(struct reg_state *rstate, 
10493         struct live_range *left, struct live_range *right)
10494 {
10495         /* FIXME the memory allocation overhead is noticeable here... */
10496         struct lre_hash **ptr, *new_hash;
10497         struct live_range_edge *edge;
10498
10499         if (left == right) {
10500                 return;
10501         }
10502         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
10503                 return;
10504         }
10505         /* Ensure left <= right */
10506         if (left > right) {
10507                 struct live_range *tmp;
10508                 tmp = left;
10509                 left = right;
10510                 right = tmp;
10511         }
10512         ptr = lre_probe(rstate, left, right);
10513         if (*ptr) {
10514                 return;
10515         }
10516         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
10517         new_hash->next  = *ptr;
10518         new_hash->left  = left;
10519         new_hash->right = right;
10520         *ptr = new_hash;
10521
10522         edge = xmalloc(sizeof(*edge), "live_range_edge");
10523         edge->next   = left->edges;
10524         edge->node   = right;
10525         left->edges  = edge;
10526         left->degree += 1;
10527         
10528         edge = xmalloc(sizeof(*edge), "live_range_edge");
10529         edge->next    = right->edges;
10530         edge->node    = left;
10531         right->edges  = edge;
10532         right->degree += 1;
10533 }
10534
10535 static void remove_live_edge(struct reg_state *rstate,
10536         struct live_range *left, struct live_range *right)
10537 {
10538         struct live_range_edge *edge, **ptr;
10539         struct lre_hash **hptr, *entry;
10540         hptr = lre_probe(rstate, left, right);
10541         if (!hptr || !*hptr) {
10542                 return;
10543         }
10544         entry = *hptr;
10545         *hptr = entry->next;
10546         xfree(entry);
10547
10548         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
10549                 edge = *ptr;
10550                 if (edge->node == right) {
10551                         *ptr = edge->next;
10552                         memset(edge, 0, sizeof(*edge));
10553                         xfree(edge);
10554                         break;
10555                 }
10556         }
10557         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
10558                 edge = *ptr;
10559                 if (edge->node == left) {
10560                         *ptr = edge->next;
10561                         memset(edge, 0, sizeof(*edge));
10562                         xfree(edge);
10563                         break;
10564                 }
10565         }
10566 }
10567
10568 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
10569 {
10570         struct live_range_edge *edge, *next;
10571         for(edge = range->edges; edge; edge = next) {
10572                 next = edge->next;
10573                 remove_live_edge(rstate, range, edge->node);
10574         }
10575 }
10576
10577
10578 /* Interference graph...
10579  * 
10580  * new(n) --- Return a graph with n nodes but no edges.
10581  * add(g,x,y) --- Return a graph including g with an between x and y
10582  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
10583  *                x and y in the graph g
10584  * degree(g, x) --- Return the degree of the node x in the graph g
10585  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
10586  *
10587  * Implement with a hash table && a set of adjcency vectors.
10588  * The hash table supports constant time implementations of add and interfere.
10589  * The adjacency vectors support an efficient implementation of neighbors.
10590  */
10591
10592 /* 
10593  *     +---------------------------------------------------+
10594  *     |         +--------------+                          |
10595  *     v         v              |                          |
10596  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
10597  *
10598  * -- In simplify implment optimistic coloring... (No backtracking)
10599  * -- Implement Rematerialization it is the only form of spilling we can perform
10600  *    Essentially this means dropping a constant from a register because
10601  *    we can regenerate it later.
10602  *
10603  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
10604  *     coalesce at phi points...
10605  * --- Bias coloring if at all possible do the coalesing a compile time.
10606  *
10607  *
10608  */
10609
10610 static void different_colored(
10611         struct compile_state *state, struct reg_state *rstate, 
10612         struct triple *parent, struct triple *ins)
10613 {
10614         struct live_range *lr;
10615         struct triple **expr;
10616         lr = &rstate->lr[ins->id];
10617         expr = triple_rhs(state, ins, 0);
10618         for(;expr; expr = triple_rhs(state, ins, expr)) {
10619                 struct live_range *lr2;
10620                 if (!*expr || (*expr == parent) || (*expr == ins)) {
10621                         continue;
10622                 }
10623                 lr2 = &rstate->lr[(*expr)->id];
10624                 if (lr->color == lr2->color) {
10625                         internal_error(state, ins, "live range too big");
10626                 }
10627         }
10628 }
10629
10630 static void initialize_live_ranges(
10631         struct compile_state *state, struct reg_state *rstate)
10632 {
10633         struct triple *ins, *first;
10634         size_t size;
10635         int i;
10636
10637         first = RHS(state->main_function, 0);
10638         /* First count how many live ranges I will need.
10639          */
10640         rstate->ranges = count_triples(state);
10641         size = sizeof(rstate->lr[0]) * (rstate->ranges + 1);
10642         rstate->lr = xcmalloc(size, "live_range");
10643         /* Setup the dummy live range */
10644         rstate->lr[0].classes = 0;
10645         rstate->lr[0].color = REG_UNSET;
10646         rstate->lr[0].def = 0;
10647         i = 0;
10648         ins = first;
10649         do {
10650                 unsigned color, classes;
10651                 /* Find the architecture specific color information */
10652                 color = ID_REG(ins->id);
10653                 classes = ID_REG_CLASSES(ins->id);
10654                 if ((color != REG_UNSET) && (color < MAX_REGISTERS)) {
10655                         classes = arch_reg_regcm(state, color);
10656                 }
10657
10658                 /* If the triple is a variable definition give it a live range. */
10659                 if (triple_is_def(state, ins)) {
10660                         i++;
10661                         ins->id = i;
10662                         rstate->lr[i].def     = ins;
10663                         rstate->lr[i].color   = color;
10664                         rstate->lr[i].classes = classes;
10665                         rstate->lr[i].degree  = 0;
10666                         if (!classes) {
10667                                 internal_error(state, ins, 
10668                                         "live range without a class");
10669                         }
10670                 }
10671                 /* Otherwise give the triple the dummy live range. */
10672                 else {
10673                         ins->id = 0;
10674                 }
10675                 ins = ins->next;
10676         } while(ins != first);
10677         rstate->ranges = i;
10678         /* Make a second pass to handle achitecture specific register
10679          * constraints.
10680          */
10681         ins = first;
10682         do {
10683                 struct live_range *lr;
10684                 lr = &rstate->lr[ins->id];
10685                 if (lr->color != REG_UNSET) {
10686                         struct triple **expr;
10687                         /* This assumes the virtual register is only
10688                          * used by one input operation.
10689                          */
10690                         expr = triple_rhs(state, ins, 0);
10691                         for(;expr; expr = triple_rhs(state, ins, expr)) {
10692                                 struct live_range *lr2;
10693                                 if (!*expr || (ins == *expr)) {
10694                                         continue;
10695                                 }
10696                                 lr2 = &rstate->lr[(*expr)->id];
10697                                 if (lr->color == lr2->color) {
10698                                         different_colored(state, rstate, 
10699                                                 ins, *expr);
10700                                         (*expr)->id = ins->id;
10701                                         
10702                                 }
10703                         }
10704                 }
10705                 ins = ins->next;
10706         } while(ins != first);
10707
10708         /* Make a third pass and forget the virtual registers */
10709         for(i = 1; i <= rstate->ranges; i++) {
10710                 if (rstate->lr[i].color >= MAX_REGISTERS) {
10711                         rstate->lr[i].color = REG_UNSET;
10712                 }
10713         }
10714 }
10715
10716 static struct triple *graph_ins(
10717         struct compile_state *state, 
10718         struct reg_block *blocks, struct triple_reg_set *live, 
10719         struct reg_block *rb, struct triple *ins, void *arg)
10720 {
10721         struct reg_state *rstate = arg;
10722         struct live_range *def;
10723         struct triple_reg_set *entry;
10724
10725         /* If the triple does not start a live range
10726          * we do not have a definition to add to
10727          * the interference graph.
10728          */
10729         if (ins->id <= 0) {
10730                 return ins;
10731         }
10732         def = &rstate->lr[ins->id];
10733         
10734         /* Create an edge between ins and everything that is
10735          * alive, unless the live_range cannot share
10736          * a physical register with ins.
10737          */
10738         for(entry = live; entry; entry = entry->next) {
10739                 struct live_range *lr;
10740                 lr= &rstate->lr[entry->member->id];
10741                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
10742                         continue;
10743                 }
10744                 add_live_edge(rstate, def, lr);
10745         }
10746         return ins;
10747 }
10748
10749
10750 static struct triple *print_interference_ins(
10751         struct compile_state *state, 
10752         struct reg_block *blocks, struct triple_reg_set *live, 
10753         struct reg_block *rb, struct triple *ins, void *arg)
10754 {
10755         struct reg_state *rstate = arg;
10756         struct live_range *lr;
10757
10758         lr = &rstate->lr[ins->id];
10759         display_triple(stdout, ins);
10760         if (live) {
10761                 struct triple_reg_set *entry;
10762                 printf("        live:");
10763                 for(entry = live; entry; entry = entry->next) {
10764                         printf(" %-10p", entry->member);
10765                 }
10766                 printf("\n");
10767         }
10768         if (lr->edges) {
10769                 struct live_range_edge *entry;
10770                 printf("        edges:");
10771                 for(entry = lr->edges; entry; entry = entry->next) {
10772                         printf(" %-10p", entry->node->def);
10773                 }
10774                 printf("\n");
10775         }
10776         if (triple_is_branch(state, ins)) {
10777                 printf("\n");
10778         }
10779         return ins;
10780 }
10781
10782 #if DEBUG_COLOR_GRAPH > 1
10783 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
10784 #define cgdebug_flush() fflush(stdout)
10785 #elif DEBUG_COLOR_GRAPH == 1
10786 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
10787 #define cgdebug_flush() fflush(stderr)
10788 #else
10789 #define cgdebug_printf(...)
10790 #define cgdebug_flush()
10791 #endif
10792
10793 static void select_free_color(struct compile_state *state, 
10794         struct reg_state *rstate, struct live_range *range)
10795 {
10796         struct triple_set *entry;
10797         struct live_range *phi;
10798         struct live_range_edge *edge;
10799         char used[MAX_REGISTERS];
10800         struct triple **expr;
10801
10802         /* If a color is already assigned don't change it */
10803         if (range->color != REG_UNSET) {
10804                 return;
10805         }
10806         /* Instead of doing just the trivial color select here I try
10807          * a few extra things because a good color selection will help reduce
10808          * copies.
10809          */
10810
10811         /* Find the registers currently in use */
10812         memset(used, 0, sizeof(used));
10813         for(edge = range->edges; edge; edge = edge->next) {
10814                 if (edge->node->color == REG_UNSET) {
10815                         continue;
10816                 }
10817                 reg_fill_used(state, used, edge->node->color);
10818         }
10819 #if DEBUG_COLOR_GRAPH > 1
10820         {
10821                 int i;
10822                 i = 0;
10823                 for(edge = range->edges; edge; edge = edge->next) {
10824                         i++;
10825                 }
10826                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
10827                         tops(range->def->op), i, 
10828                         range->def->filename, range->def->line, range->def->col);
10829                 for(i = 0; i < MAX_REGISTERS; i++) {
10830                         if (used[i]) {
10831                                 cgdebug_printf("used: %s\n",
10832                                         arch_reg_str(i));
10833                         }
10834                 }
10835         }       
10836 #endif
10837
10838         /* If I feed into an expression reuse it's color.
10839          * This should help remove copies in the case of 2 register instructions
10840          * and phi functions.
10841          */
10842         phi = 0;
10843         entry = range->def->use;
10844         for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
10845                 struct live_range *lr;
10846                 lr = &rstate->lr[entry->member->id];
10847                 if (entry->member->id == 0) {
10848                         continue;
10849                 }
10850                 if (!phi && (lr->def->op == OP_PHI) && 
10851                         !interfere(rstate, range, lr)) {
10852                         phi = lr;
10853                 }
10854                 if ((lr->color == REG_UNSET) ||
10855                         ((lr->classes & range->classes) == 0) ||
10856                         (used[lr->color])) {
10857                         continue;
10858                 }
10859                 if (interfere(rstate, range, lr)) {
10860                         continue;
10861                 }
10862                 range->color = lr->color;
10863         }
10864         /* If I feed into a phi function reuse it's color of the color
10865          * of something else that feeds into the phi function.
10866          */
10867         if (phi) {
10868                 if (phi->color != REG_UNSET) {
10869                         if (used[phi->color]) {
10870                                 range->color = phi->color;
10871                         }
10872                 }
10873                 else {
10874                         expr = triple_rhs(state, phi->def, 0);
10875                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
10876                                 struct live_range *lr;
10877                                 if (!*expr) {
10878                                         continue;
10879                                 }
10880                                 lr = &rstate->lr[(*expr)->id];
10881                                 if ((lr->color == REG_UNSET) || 
10882                                         ((lr->classes & range->classes) == 0) ||
10883                                         (used[lr->color])) {
10884                                         continue;
10885                                 }
10886                                 if (interfere(rstate, range, lr)) {
10887                                         continue;
10888                                 }
10889                                 range->color = lr->color;
10890                         }
10891                 }
10892         }
10893         /* If I don't interfere with a rhs node reuse it's color */
10894         if (range->color == REG_UNSET) {
10895                 expr = triple_rhs(state, range->def, 0);
10896                 for(; expr; expr = triple_rhs(state, range->def, expr)) {
10897                         struct live_range *lr;
10898                         if (!*expr) {
10899                                 continue;
10900                         }
10901                         lr = &rstate->lr[(*expr)->id];
10902                         if ((lr->color == -1) || 
10903                                 ((lr->classes & range->classes) == 0) ||
10904                                 (used[lr->color])) {
10905                                 continue;
10906                         }
10907                         if (interfere(rstate, range, lr)) {
10908                                 continue;
10909                         }
10910                         range->color = lr->color;
10911                         break;
10912                 }
10913         }
10914         /* If I have not opportunitically picked a useful color
10915          * pick the first color that is free.
10916          */
10917         if (range->color == REG_UNSET) {
10918                 range->color = 
10919                         arch_select_free_register(state, used, range->classes);
10920         }
10921         if (range->color == REG_UNSET) {
10922                 int i;
10923                 for(edge = range->edges; edge; edge = edge->next) {
10924                         if (edge->node->color == REG_UNSET) {
10925                                 continue;
10926                         }
10927                         warning(state, edge->node->def, "reg %s", 
10928                                 arch_reg_str(edge->node->color));
10929                 }
10930                 warning(state, range->def, "classes: %x",
10931                         range->classes);
10932                 for(i = 0; i < MAX_REGISTERS; i++) {
10933                         if (used[i]) {
10934                                 warning(state, range->def, "used: %s",
10935                                         arch_reg_str(i));
10936                         }
10937                 }
10938 #if DEBUG_COLOR_GRAPH < 2
10939                 error(state, range->def, "too few registers");
10940 #else
10941                 internal_error(state, range->def, "too few registers");
10942 #endif
10943         }
10944         range->classes = arch_reg_regcm(state, range->color);
10945         return;
10946 }
10947
10948 static void color_graph(struct compile_state *state, struct reg_state *rstate)
10949 {
10950         struct live_range_edge *edge;
10951         struct live_range *range;
10952         if (rstate->low) {
10953                 cgdebug_printf("Lo: ");
10954                 range = rstate->low;
10955                 if (*range->group_prev != range) {
10956                         internal_error(state, 0, "lo: *prev != range?");
10957                 }
10958                 *range->group_prev = range->group_next;
10959                 if (range->group_next) {
10960                         range->group_next->group_prev = range->group_prev;
10961                 }
10962                 if (&range->group_next == rstate->low_tail) {
10963                         rstate->low_tail = range->group_prev;
10964                 }
10965                 if (rstate->low == range) {
10966                         internal_error(state, 0, "low: next != prev?");
10967                 }
10968         }
10969         else if (rstate->high) {
10970                 cgdebug_printf("Hi: ");
10971                 range = rstate->high;
10972                 if (*range->group_prev != range) {
10973                         internal_error(state, 0, "hi: *prev != range?");
10974                 }
10975                 *range->group_prev = range->group_next;
10976                 if (range->group_next) {
10977                         range->group_next->group_prev = range->group_prev;
10978                 }
10979                 if (&range->group_next == rstate->high_tail) {
10980                         rstate->high_tail = range->group_prev;
10981                 }
10982                 if (rstate->high == range) {
10983                         internal_error(state, 0, "high: next != prev?");
10984                 }
10985         }
10986         else {
10987                 return;
10988         }
10989         cgdebug_printf(" %d\n", range - rstate->lr);
10990         range->group_prev = 0;
10991         for(edge = range->edges; edge; edge = edge->next) {
10992                 struct live_range *node;
10993                 node = edge->node;
10994                 /* Move nodes from the high to the low list */
10995                 if (node->group_prev && (node->color == REG_UNSET) &&
10996                         (node->degree == regc_max_size(state, node->classes))) {
10997                         if (*node->group_prev != node) {
10998                                 internal_error(state, 0, "move: *prev != node?");
10999                         }
11000                         *node->group_prev = node->group_next;
11001                         if (node->group_next) {
11002                                 node->group_next->group_prev = node->group_prev;
11003                         }
11004                         if (&node->group_next == rstate->high_tail) {
11005                                 rstate->high_tail = node->group_prev;
11006                         }
11007                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
11008                         node->group_prev  = rstate->low_tail;
11009                         node->group_next  = 0;
11010                         *rstate->low_tail = node;
11011                         rstate->low_tail  = &node->group_next;
11012                         if (*node->group_prev != node) {
11013                                 internal_error(state, 0, "move2: *prev != node?");
11014                         }
11015                 }
11016                 node->degree -= 1;
11017         }
11018         color_graph(state, rstate);
11019         cgdebug_printf("Coloring %d @%s:%d.%d:", 
11020                 range - rstate->lr,
11021                 range->def->filename, range->def->line, range->def->col);
11022         cgdebug_flush();
11023         select_free_color(state, rstate, range);
11024         if (range->color == -1) {
11025                 internal_error(state, range->def, "select_free_color did not?");
11026         }
11027         cgdebug_printf(" %s\n", arch_reg_str(range->color));
11028 }
11029
11030 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
11031 {
11032         struct live_range *lr;
11033         struct live_range_edge *edge;
11034         struct triple *ins, *first;
11035         char used[MAX_REGISTERS];
11036         first = RHS(state->main_function, 0);
11037         ins = first;
11038         do {
11039                 if (triple_is_def(state, ins)) {
11040                         if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11041                                 internal_error(state, ins, 
11042                                         "triple without a live range");
11043                         }
11044                         lr = &rstate->lr[ins->id];
11045                         if (lr->color == REG_UNSET) {
11046                                 internal_error(state, ins,
11047                                         "triple without a color");
11048                         }
11049                         /* Find the registers used by the edges */
11050                         memset(used, 0, sizeof(used));
11051                         for(edge = lr->edges; edge; edge = edge->next) {
11052                                 if (edge->node->color == REG_UNSET) {
11053                                         internal_error(state, 0,
11054                                                 "live range without a color");
11055                         }
11056                                 reg_fill_used(state, used, edge->node->color);
11057                         }
11058                         if (used[lr->color]) {
11059                                 internal_error(state, ins,
11060                                         "triple with already used color");
11061                         }
11062                 }
11063                 ins = ins->next;
11064         } while(ins != first);
11065 }
11066
11067 static void color_triples(struct compile_state *state, struct reg_state *rstate)
11068 {
11069         struct live_range *lr;
11070         struct triple *first, *ins;
11071         first = RHS(state->main_function, 0);
11072         ins = first;
11073         do {
11074                 if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11075                         internal_error(state, ins, 
11076                                 "triple without a live range");
11077                 }
11078                 lr = &rstate->lr[ins->id];
11079                 ins->id = MK_REG_ID(lr->color, 0);
11080                 ins = ins->next;
11081         } while (ins != first);
11082 }
11083
11084 static void print_interference_block(
11085         struct compile_state *state, struct block *block, void *arg)
11086
11087 {
11088         struct reg_state *rstate = arg;
11089         struct reg_block *rb;
11090         struct triple *ptr;
11091         int phi_present;
11092         int done;
11093         rb = &rstate->blocks[block->vertex];
11094
11095         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
11096                 block, 
11097                 block->vertex,
11098                 block->left, 
11099                 block->left && block->left->use?block->left->use->member : 0,
11100                 block->right, 
11101                 block->right && block->right->use?block->right->use->member : 0);
11102         if (rb->in) {
11103                 struct triple_reg_set *in_set;
11104                 printf("        in:");
11105                 for(in_set = rb->in; in_set; in_set = in_set->next) {
11106                         printf(" %-10p", in_set->member);
11107                 }
11108                 printf("\n");
11109         }
11110         phi_present = 0;
11111         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11112                 done = (ptr == block->last);
11113                 if (ptr->op == OP_PHI) {
11114                         phi_present = 1;
11115                         break;
11116                 }
11117         }
11118         if (phi_present) {
11119                 int edge;
11120                 for(edge = 0; edge < block->users; edge++) {
11121                         printf("     in(%d):", edge);
11122                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11123                                 struct triple **slot;
11124                                 done = (ptr == block->last);
11125                                 if (ptr->op != OP_PHI) {
11126                                         continue;
11127                                 }
11128                                 slot = &RHS(ptr, 0);
11129                                 printf(" %-10p", slot[edge]);
11130                         }
11131                         printf("\n");
11132                 }
11133         }
11134         if (block->first->op == OP_LABEL) {
11135                 printf("%p:\n", block->first);
11136         }
11137         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11138                 struct triple_set *user;
11139                 struct live_range *lr;
11140                 unsigned id;
11141                 int op;
11142                 op = ptr->op;
11143                 done = (ptr == block->last);
11144                 lr = &rstate->lr[ptr->id];
11145                 
11146                 if (!IS_CONST_OP(op)) {
11147                         if (ptr->u.block != block) {
11148                                 internal_error(state, ptr, 
11149                                         "Wrong block pointer: %p",
11150                                         ptr->u.block);
11151                         }
11152                 }
11153                 if (op == OP_ADECL) {
11154                         for(user = ptr->use; user; user = user->next) {
11155                                 struct live_range *lr;
11156                                 lr = &rstate->lr[user->member->id];
11157                                 if (!user->member->u.block) {
11158                                         internal_error(state, user->member, 
11159                                                 "Use %p not in a block?",
11160                                                 user->member);
11161                                 }
11162                                 
11163                         }
11164                 }
11165                 id = ptr->id;
11166                 ptr->id = MK_REG_ID(lr->color, 0);
11167                 display_triple(stdout, ptr);
11168                 ptr->id = id;
11169
11170                 if (lr->edges > 0) {
11171                         struct live_range_edge *edge;
11172                         printf("           ");
11173                         for(edge = lr->edges; edge; edge = edge->next) {
11174                                 printf(" %-10p", edge->node->def);
11175                         }
11176                         printf("\n");
11177                 }
11178                 /* Do a bunch of sanity checks */
11179                 valid_ins(state, ptr);
11180                 if ((ptr->id < 0) || (ptr->id > rstate->ranges)) {
11181                         internal_error(state, ptr, "Invalid triple id: %d",
11182                                 ptr->id);
11183                 }
11184                 for(user = ptr->use; user; user = user->next) {
11185                         struct triple *use;
11186                         struct live_range *ulr;
11187                         use = user->member;
11188                         valid_ins(state, use);
11189                         if ((use->id < 0) || (use->id > rstate->ranges)) {
11190                                 internal_error(state, use, "Invalid triple id: %d",
11191                                         use->id);
11192                         }
11193                         ulr = &rstate->lr[user->member->id];
11194                         if (!IS_CONST_OP(user->member->op) &&
11195                                 !user->member->u.block) {
11196                                 internal_error(state, user->member,
11197                                         "Use %p not in a block?",
11198                                         user->member);
11199                         }
11200                 }
11201         }
11202         if (rb->out) {
11203                 struct triple_reg_set *out_set;
11204                 printf("       out:");
11205                 for(out_set = rb->out; out_set; out_set = out_set->next) {
11206                         printf(" %-10p", out_set->member);
11207                 }
11208                 printf("\n");
11209         }
11210         printf("\n");
11211 }
11212
11213 static struct live_range *merge_sort_lr(
11214         struct live_range *first, struct live_range *last)
11215 {
11216         struct live_range *mid, *join, **join_tail, *pick;
11217         size_t size;
11218         size = (last - first) + 1;
11219         if (size >= 2) {
11220                 mid = first + size/2;
11221                 first = merge_sort_lr(first, mid -1);
11222                 mid   = merge_sort_lr(mid, last);
11223                 
11224                 join = 0;
11225                 join_tail = &join;
11226                 /* merge the two lists */
11227                 while(first && mid) {
11228                         if (first->degree <= mid->degree) {
11229                                 pick = first;
11230                                 first = first->group_next;
11231                                 if (first) {
11232                                         first->group_prev = 0;
11233                                 }
11234                         }
11235                         else {
11236                                 pick = mid;
11237                                 mid = mid->group_next;
11238                                 if (mid) {
11239                                         mid->group_prev = 0;
11240                                 }
11241                         }
11242                         pick->group_next = 0;
11243                         pick->group_prev = join_tail;
11244                         *join_tail = pick;
11245                         join_tail = &pick->group_next;
11246                 }
11247                 /* Splice the remaining list */
11248                 pick = (first)? first : mid;
11249                 *join_tail = pick;
11250                 pick->group_prev = join_tail;
11251         }
11252         else {
11253                 if (!first->def) {
11254                         first = 0;
11255                 }
11256                 join = first;
11257         }
11258         return join;
11259 }
11260
11261 static void allocate_registers(struct compile_state *state)
11262 {
11263         struct reg_state rstate;
11264         struct live_range **point, **next;
11265         int i;
11266
11267         /* Clear out the reg_state */
11268         memset(&rstate, 0, sizeof(rstate));
11269
11270         /* Compute the variable lifetimes */
11271         rstate.blocks = compute_variable_lifetimes(state);
11272
11273         /* Allocate and initialize the live ranges */
11274         initialize_live_ranges(state, &rstate);
11275
11276         /* Compute the interference graph */
11277         walk_variable_lifetimes(
11278                 state, rstate.blocks, graph_ins, &rstate);
11279
11280         /* Display the interference graph if desired */
11281         if (state->debug & DEBUG_INTERFERENCE) {
11282                 printf("\nlive variables by block\n");
11283                 walk_blocks(state, print_interference_block, &rstate);
11284                 printf("\nlive variables by instruction\n");
11285                 walk_variable_lifetimes(
11286                         state, rstate.blocks, 
11287                         print_interference_ins, &rstate);
11288         }
11289
11290         /* Do not perform coalescing!  It is a neat idea but it limits what
11291          * we can do later.  It has no benefits that decrease register pressure.
11292          * It only decreases instruction count.
11293          *
11294          * It might be worth testing this reducing the number of
11295          * live_ragnes as opposed to splitting them seems to help.
11296          */
11297
11298         /* Build the groups low and high.  But with the nodes
11299          * first sorted by degree order.
11300          */
11301         rstate.low_tail  = &rstate.low;
11302         rstate.high_tail = &rstate.high;
11303         rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
11304         if (rstate.high) {
11305                 rstate.high->group_prev = &rstate.high;
11306         }
11307         for(point = &rstate.high; *point; point = &(*point)->group_next)
11308                 ;
11309         rstate.high_tail = point;
11310         /* Walk through the high list and move everything that needs
11311          * to be onto low.
11312          */
11313         for(point = &rstate.high; *point; point = next) {
11314                 struct live_range *range;
11315                 next = &(*point)->group_next;
11316                 range = *point;
11317
11318                 /* If it has a low degree or it already has a color
11319                  * place the node in low.
11320                  */
11321                 if ((range->degree < regc_max_size(state, range->classes)) ||
11322                         (range->color != REG_UNSET)) {
11323                         cgdebug_printf("Lo: %5d degree %5d%s\n", 
11324                                 range - rstate.lr, range->degree,
11325                                 (range->color != REG_UNSET) ? " (colored)": "");
11326                         *range->group_prev = range->group_next;
11327                         if (range->group_next) {
11328                                 range->group_next->group_prev = range->group_prev;
11329                         }
11330                         if (&range->group_next == rstate.high_tail) {
11331                                 rstate.high_tail = range->group_prev;
11332                         }
11333                         range->group_prev  = rstate.low_tail;
11334                         range->group_next  = 0;
11335                         *rstate.low_tail   = range;
11336                         rstate.low_tail    = &range->group_next;
11337                         next = point;
11338                 }
11339                 else {
11340                         cgdebug_printf("hi: %5d degree %5d%s\n", 
11341                                 range - rstate.lr, range->degree,
11342                                 (range->color != REG_UNSET) ? " (colored)": "");
11343                 }
11344                 
11345         }
11346         /* Color the live_ranges */
11347         color_graph(state, &rstate);
11348
11349         /* Verify the graph was properly colored */
11350         verify_colors(state, &rstate);
11351
11352         /* Move the colors from the graph to the triples */
11353         color_triples(state, &rstate);
11354
11355         /* Free the edges on each node */
11356         for(i = 1; i <= rstate.ranges; i++) {
11357                 remove_live_edges(&rstate, &rstate.lr[i]);
11358         }
11359         xfree(rstate.lr);
11360
11361         /* Free the variable lifetime information */
11362         free_variable_lifetimes(state, rstate.blocks);
11363
11364 }
11365
11366 /* Sparce Conditional Constant Propogation
11367  * =========================================
11368  */
11369 struct ssa_edge;
11370 struct flow_block;
11371 struct lattice_node {
11372         struct triple *def;
11373         struct ssa_edge *out;
11374         struct flow_block *fblock;
11375         struct triple *val;
11376         /* lattice high   val && !is_const(val) 
11377          * lattice const  is_const(val)
11378          * lattice low    val == 0
11379          */
11380 };
11381 struct ssa_edge {
11382         struct lattice_node *src;
11383         struct lattice_node *dst;
11384         struct ssa_edge *work_next;
11385         struct ssa_edge *work_prev;
11386         struct ssa_edge *out_next;
11387 };
11388 struct flow_edge {
11389         struct flow_block *src;
11390         struct flow_block *dst;
11391         struct flow_edge *work_next;
11392         struct flow_edge *work_prev;
11393         struct flow_edge *in_next;
11394         struct flow_edge *out_next;
11395         int executable;
11396 };
11397 struct flow_block {
11398         struct block *block;
11399         struct flow_edge *in;
11400         struct flow_edge *out;
11401         struct flow_edge left, right;
11402 };
11403
11404 struct scc_state {
11405         int ins_count;
11406         struct lattice_node *lattice;
11407         struct ssa_edge     *ssa_edges;
11408         struct flow_block   *flow_blocks;
11409         struct flow_edge    *flow_work_list;
11410         struct ssa_edge     *ssa_work_list;
11411 };
11412
11413
11414 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
11415         struct flow_edge *fedge)
11416 {
11417         if (!scc->flow_work_list) {
11418                 scc->flow_work_list = fedge;
11419                 fedge->work_next = fedge->work_prev = fedge;
11420         }
11421         else {
11422                 struct flow_edge *ftail;
11423                 ftail = scc->flow_work_list->work_prev;
11424                 fedge->work_next = ftail->work_next;
11425                 fedge->work_prev = ftail;
11426                 fedge->work_next->work_prev = fedge;
11427                 fedge->work_prev->work_next = fedge;
11428         }
11429 }
11430
11431 static struct flow_edge *scc_next_fedge(
11432         struct compile_state *state, struct scc_state *scc)
11433 {
11434         struct flow_edge *fedge;
11435         fedge = scc->flow_work_list;
11436         if (fedge) {
11437                 fedge->work_next->work_prev = fedge->work_prev;
11438                 fedge->work_prev->work_next = fedge->work_next;
11439                 if (fedge->work_next != fedge) {
11440                         scc->flow_work_list = fedge->work_next;
11441                 } else {
11442                         scc->flow_work_list = 0;
11443                 }
11444         }
11445         return fedge;
11446 }
11447
11448 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
11449         struct ssa_edge *sedge)
11450 {
11451         if (!scc->ssa_work_list) {
11452                 scc->ssa_work_list = sedge;
11453                 sedge->work_next = sedge->work_prev = sedge;
11454         }
11455         else {
11456                 struct ssa_edge *stail;
11457                 stail = scc->ssa_work_list->work_prev;
11458                 sedge->work_next = stail->work_next;
11459                 sedge->work_prev = stail;
11460                 sedge->work_next->work_prev = sedge;
11461                 sedge->work_prev->work_next = sedge;
11462         }
11463 }
11464
11465 static struct ssa_edge *scc_next_sedge(
11466         struct compile_state *state, struct scc_state *scc)
11467 {
11468         struct ssa_edge *sedge;
11469         sedge = scc->ssa_work_list;
11470         if (sedge) {
11471                 sedge->work_next->work_prev = sedge->work_prev;
11472                 sedge->work_prev->work_next = sedge->work_next;
11473                 if (sedge->work_next != sedge) {
11474                         scc->ssa_work_list = sedge->work_next;
11475                 } else {
11476                         scc->ssa_work_list = 0;
11477                 }
11478         }
11479         return sedge;
11480 }
11481
11482 static void initialize_scc_state(
11483         struct compile_state *state, struct scc_state *scc)
11484 {
11485         int ins_count, ssa_edge_count;
11486         int ins_index, ssa_edge_index, fblock_index;
11487         struct triple *first, *ins;
11488         struct block *block;
11489         struct flow_block *fblock;
11490
11491         memset(scc, 0, sizeof(*scc));
11492
11493         /* Inialize pass zero find out how much memory we need */
11494         first = RHS(state->main_function, 0);
11495         ins = first;
11496         ins_count = ssa_edge_count = 0;
11497         do {
11498                 struct triple_set *edge;
11499                 ins_count += 1;
11500                 for(edge = ins->use; edge; edge = edge->next) {
11501                         ssa_edge_count++;
11502                 }
11503                 ins = ins->next;
11504         } while(ins != first);
11505 #if DEBUG_SCC
11506         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
11507                 ins_count, ssa_edge_count, state->last_vertex);
11508 #endif
11509         scc->ins_count   = ins_count;
11510         scc->lattice     = 
11511                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
11512         scc->ssa_edges   = 
11513                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
11514         scc->flow_blocks = 
11515                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
11516                         "flow_blocks");
11517
11518         /* Initialize pass one collect up the nodes */
11519         fblock = 0;
11520         block = 0;
11521         ins_index = ssa_edge_index = fblock_index = 0;
11522         ins = first;
11523         do {
11524                 ins->id = 0;
11525                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11526                         block = ins->u.block;
11527                         if (!block) {
11528                                 internal_error(state, ins, "label without block");
11529                         }
11530                         fblock_index += 1;
11531                         block->vertex = fblock_index;
11532                         fblock = &scc->flow_blocks[fblock_index];
11533                         fblock->block = block;
11534                 }
11535                 {
11536                         struct lattice_node *lnode;
11537                         ins_index += 1;
11538                         ins->id = ins_index;
11539                         lnode = &scc->lattice[ins_index];
11540                         lnode->def = ins;
11541                         lnode->out = 0;
11542                         lnode->fblock = fblock;
11543                         lnode->val = ins; /* LATTICE HIGH */
11544                 }
11545                 ins = ins->next;
11546         } while(ins != first);
11547         /* Initialize pass two collect up the edges */
11548         block = 0;
11549         fblock = 0;
11550         ins = first;
11551         do {
11552                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11553                         struct flow_edge *fedge, **ftail;
11554                         struct block_set *bedge;
11555                         block = ins->u.block;
11556                         fblock = &scc->flow_blocks[block->vertex];
11557                         fblock->in = 0;
11558                         fblock->out = 0;
11559                         ftail = &fblock->out;
11560                         if (block->left) {
11561                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
11562                                 if (fblock->left.dst->block != block->left) {
11563                                         internal_error(state, 0, "block mismatch");
11564                                 }
11565                                 fblock->left.out_next = 0;
11566                                 *ftail = &fblock->left;
11567                                 ftail = &fblock->left.out_next;
11568                         }
11569                         if (block->right) {
11570                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
11571                                 if (fblock->right.dst->block != block->right) {
11572                                         internal_error(state, 0, "block mismatch");
11573                                 }
11574                                 fblock->right.out_next = 0;
11575                                 *ftail = &fblock->right;
11576                                 ftail = &fblock->right.out_next;
11577                         }
11578                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
11579                                 fedge->src = fblock;
11580                                 fedge->work_next = fedge->work_prev = fedge;
11581                                 fedge->executable = 0;
11582                         }
11583                         ftail = &fblock->in;
11584                         for(bedge = block->use; bedge; bedge = bedge->next) {
11585                                 struct block *src_block;
11586                                 struct flow_block *sfblock;
11587                                 struct flow_edge *sfedge;
11588                                 src_block = bedge->member;
11589                                 sfblock = &scc->flow_blocks[src_block->vertex];
11590                                 sfedge = 0;
11591                                 if (src_block->left == block) {
11592                                         sfedge = &sfblock->left;
11593                                 } else {
11594                                         sfedge = &sfblock->right;
11595                                 }
11596                                 *ftail = sfedge;
11597                                 ftail = &sfedge->in_next;
11598                                 sfedge->in_next = 0;
11599                         }
11600                 }
11601                 {
11602                         struct triple_set *edge;
11603                         struct ssa_edge **stail;
11604                         struct lattice_node *lnode;
11605                         lnode = &scc->lattice[ins->id];
11606                         lnode->out = 0;
11607                         stail = &lnode->out;
11608                         for(edge = ins->use; edge; edge = edge->next) {
11609                                 struct ssa_edge *sedge;
11610                                 ssa_edge_index += 1;
11611                                 sedge = &scc->ssa_edges[ssa_edge_index];
11612                                 *stail = sedge;
11613                                 stail = &sedge->out_next;
11614                                 sedge->src = lnode;
11615                                 sedge->dst = &scc->lattice[edge->member->id];
11616                                 sedge->work_next = sedge->work_prev = sedge;
11617                                 sedge->out_next = 0;
11618                         }
11619                 }
11620                 ins = ins->next;
11621         } while(ins != first);
11622         /* Setup a dummy block 0 as a node above the start node */
11623         {
11624                 struct flow_block *fblock, *dst;
11625                 struct flow_edge *fedge;
11626                 fblock = &scc->flow_blocks[0];
11627                 fblock->block = 0;
11628                 fblock->in = 0;
11629                 fblock->out = &fblock->left;
11630                 dst = &scc->flow_blocks[state->first_block->vertex];
11631                 fedge = &fblock->left;
11632                 fedge->src        = fblock;
11633                 fedge->dst        = dst;
11634                 fedge->work_next  = fedge;
11635                 fedge->work_prev  = fedge;
11636                 fedge->in_next    = fedge->dst->in;
11637                 fedge->out_next   = 0;
11638                 fedge->executable = 0;
11639                 fedge->dst->in = fedge;
11640                 
11641                 /* Initialize the work lists */
11642                 scc->flow_work_list = 0;
11643                 scc->ssa_work_list  = 0;
11644                 scc_add_fedge(state, scc, fedge);
11645         }
11646 #if DEBUG_SCC
11647         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
11648                 ins_index, ssa_edge_index, fblock_index);
11649 #endif
11650 }
11651
11652         
11653 static void free_scc_state(
11654         struct compile_state *state, struct scc_state *scc)
11655 {
11656         int i;
11657         for(i = 0; i < scc->ins_count; i++) {
11658                 if (scc->lattice[i].val && 
11659                         (scc->lattice[i].val != scc->lattice[i].def)) {
11660                         xfree(scc->lattice[i].val);
11661                 }
11662         }
11663         xfree(scc->flow_blocks);
11664         xfree(scc->ssa_edges);
11665         xfree(scc->lattice);
11666         
11667 }
11668
11669 static struct lattice_node *triple_to_lattice(
11670         struct compile_state *state, struct scc_state *scc, struct triple *ins)
11671 {
11672         if (ins->id <= 0) {
11673                 internal_error(state, ins, "bad id");
11674         }
11675         return &scc->lattice[ins->id];
11676 }
11677
11678 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
11679         struct lattice_node *lnode)
11680 {
11681         struct lattice_node *tmp;
11682         struct triple **slot;
11683         struct flow_edge *fedge;
11684         int index;
11685         if (lnode->def->op != OP_PHI) {
11686                 internal_error(state, lnode->def, "not phi");
11687         }
11688         /* default to lattice high */
11689         lnode->val = lnode->def;
11690         slot = &RHS(lnode->def, 0);
11691         index = 0;
11692         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
11693                 if (!fedge->executable) {
11694                         continue;
11695                 }
11696                 if (!slot[index]) {
11697                         internal_error(state, lnode->def, "no phi value");
11698                 }
11699                 tmp = triple_to_lattice(state, scc, slot[index]);
11700                 /* meet(X, lattice low) = lattice low */
11701                 if (!tmp->val) {
11702                         lnode->val = 0;
11703                 }
11704                 /* meet(X, lattice high) = X */
11705                 else if (!tmp->val) {
11706                         lnode->val = lnode->val;
11707                 }
11708                 /* meet(lattice high, X) = X */
11709                 else if (!is_const(lnode->val)) {
11710                         lnode->val = tmp->val;
11711                 }
11712                 /* meet(const, const) = const or lattice low */
11713                 else if (!constants_equal(state, lnode->val, tmp->val)) {
11714                         lnode->val = 0;
11715                 }
11716                 if (!lnode->val) {
11717                         break;
11718                 }
11719         }
11720         /* Do I need to update any work lists here? */
11721 #if DEBUG_SCC
11722         fprintf(stderr, "phi: %d -> %s\n",
11723                 lnode->def->id,
11724                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11725 #endif
11726 }
11727
11728 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
11729         struct lattice_node *lnode)
11730 {
11731         int changed;
11732         struct triple *old, *scratch;
11733         struct triple **dexpr, **vexpr;
11734         int count, i;
11735         
11736         if (lnode->def->op != OP_STORE) {
11737                 check_lhs(state,  lnode->def);
11738         }
11739
11740         /* Store the original value */
11741         if (lnode->val) {
11742                 old = dup_triple(state, lnode->val);
11743                 if (lnode->val != lnode->def) {
11744                         xfree(lnode->val);
11745                 }
11746                 lnode->val = 0;
11747
11748         } else {
11749                 old = 0;
11750         }
11751         /* Reinitialize the value */
11752         lnode->val = scratch = dup_triple(state, lnode->def);
11753         scratch->next     = scratch;
11754         scratch->prev     = scratch;
11755         scratch->use      = 0;
11756
11757         count = TRIPLE_SIZE(scratch->sizes);
11758         for(i = 0; i < count; i++) {
11759                 struct lattice_node *tmp;
11760                 dexpr = &lnode->def->param[i];
11761                 vexpr = &scratch->param[i];
11762                 *vexpr = 0;
11763                 if (*dexpr) {
11764                         tmp = triple_to_lattice(state, scc, *dexpr);
11765                         *vexpr = (tmp->val)? tmp->val : tmp->def;
11766                 }
11767         }
11768         if (scratch->op == OP_BRANCH) {
11769                 scratch->next = lnode->def->next;
11770         }
11771         /* Recompute the value */
11772 #warning "FIXME see if simplify does anything bad"
11773         /* So far it looks like only the strength reduction
11774          * optimization are things I need to worry about.
11775          */
11776         simplify(state, scratch);
11777         /* Cleanup my value */
11778         if (scratch->use) {
11779                 internal_error(state, lnode->def, "scratch used?");
11780         }
11781         if ((scratch->prev != scratch) ||
11782                 ((scratch->next != scratch) &&
11783                         ((lnode->def->op != OP_BRANCH) ||
11784                                 (scratch->next != lnode->def->next)))) {
11785                 internal_error(state, lnode->def, "scratch in list?");
11786         }
11787         /* undo any uses... */
11788         count = TRIPLE_SIZE(scratch->sizes);
11789         for(i = 0; i < count; i++) {
11790                 vexpr = &scratch->param[i];
11791                 if (*vexpr) {
11792                         unuse_triple(*vexpr, scratch);
11793                 }
11794         }
11795         if (!is_const(scratch)) {
11796                 for(i = 0; i < count; i++) {
11797                         dexpr = &lnode->def->param[i];
11798                         if (*dexpr) {
11799                                 struct lattice_node *tmp;
11800                                 tmp = triple_to_lattice(state, scc, *dexpr);
11801                                 if (!tmp->val) {
11802                                         lnode->val = 0;
11803                                 }
11804                         }
11805                 }
11806         }
11807         if (lnode->val && 
11808                 (lnode->val->op == lnode->def->op) &&
11809                 (memcmp(lnode->val->param, lnode->def->param, 
11810                         count * sizeof(lnode->val->param[0])) == 0) &&
11811                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
11812                 lnode->val = lnode->def;
11813         }
11814         /* Find the cases that are always lattice lo */
11815         if (lnode->val && 
11816                 triple_is_def(state, lnode->val) &&
11817                 !triple_is_pure(state, lnode->val)) {
11818                 lnode->val = 0;
11819         }
11820 #if 1
11821         if (lnode->val && 
11822                 (lnode->val->op == OP_SDECL) && 
11823                 (lnode->val != lnode->def)) {
11824                 internal_error(state, lnode->def, "bad sdecl");
11825         }
11826 #endif
11827         /* See if the lattice value has changed */
11828         changed = 1;
11829         if (!old && !lnode->val) {
11830                 changed = 0;
11831         }
11832         if (changed && lnode->val && !is_const(lnode->val)) {
11833                 changed = 0;
11834         }
11835         if (changed &&
11836                 lnode->val && old &&
11837                 (lnode->val->op == old->op) &&
11838                 (memcmp(lnode->val->param, old->param,
11839                         count * sizeof(lnode->val->param[0])) == 0) &&
11840                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
11841                 changed = 0;
11842         }
11843         if (old) {
11844                 xfree(old);
11845         }
11846         if (lnode->val != scratch) {
11847                 xfree(scratch);
11848         }
11849         return changed;
11850 }
11851
11852 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
11853         struct lattice_node *lnode)
11854 {
11855         struct lattice_node *cond;
11856 #if DEBUG_SCC
11857         {
11858                 struct flow_edge *fedge;
11859                 fprintf(stderr, "branch: %d (",
11860                         lnode->def->id);
11861                 
11862                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
11863                         fprintf(stderr, " %d", fedge->dst->block->vertex);
11864                 }
11865                 fprintf(stderr, " )");
11866                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
11867                         fprintf(stderr, " <- %d",
11868                                 RHS(lnode->def)->id);
11869                 }
11870                 fprintf(stderr, "\n");
11871         }
11872 #endif
11873         if (lnode->def->op != OP_BRANCH) {
11874                 internal_error(state, lnode->def, "not branch");
11875         }
11876         /* This only applies to conditional branches */
11877         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
11878                 return;
11879         }
11880         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
11881         if (cond->val && !is_const(cond->val)) {
11882 #warning "FIXME do I need to do something here?"
11883                 warning(state, cond->def, "condition not constant?");
11884                 return;
11885         }
11886         if (cond->val == 0) {
11887                 scc_add_fedge(state, scc, cond->fblock->out);
11888                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11889         }
11890         else if (cond->val->u.cval) {
11891                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11892                 
11893         } else {
11894                 scc_add_fedge(state, scc, cond->fblock->out);
11895         }
11896
11897 }
11898
11899 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
11900         struct lattice_node *lnode)
11901 {
11902         int changed;
11903
11904         changed = compute_lnode_val(state, scc, lnode);
11905 #if DEBUG_SCC
11906         {
11907                 struct triple **expr;
11908                 fprintf(stderr, "expr: %3d %10s (",
11909                         lnode->def->id, tops(lnode->def->op));
11910                 expr = triple_rhs(state, lnode->def, 0);
11911                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
11912                         if (*expr) {
11913                                 fprintf(stderr, " %d", (*expr)->id);
11914                         }
11915                 }
11916                 fprintf(stderr, " ) -> %s\n",
11917                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11918         }
11919 #endif
11920         if (lnode->def->op == OP_BRANCH) {
11921                 scc_visit_branch(state, scc, lnode);
11922
11923         }
11924         else if (changed) {
11925                 struct ssa_edge *sedge;
11926                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
11927                         scc_add_sedge(state, scc, sedge);
11928                 }
11929         }
11930 }
11931
11932 static void scc_writeback_values(
11933         struct compile_state *state, struct scc_state *scc)
11934 {
11935         struct triple *first, *ins;
11936         first = RHS(state->main_function, 0);
11937         ins = first;
11938         do {
11939                 struct lattice_node *lnode;
11940                 lnode = triple_to_lattice(state, scc, ins);
11941 #if DEBUG_SCC
11942                 if (lnode->val && !is_const(lnode->val)) {
11943                         warning(state, lnode->def, 
11944                                 "lattice node still high?");
11945                 }
11946 #endif
11947                 if (lnode->val && (lnode->val != ins)) {
11948                         /* See if it something I know how to write back */
11949                         switch(lnode->val->op) {
11950                         case OP_INTCONST:
11951                                 mkconst(state, ins, lnode->val->u.cval);
11952                                 break;
11953                         case OP_ADDRCONST:
11954                                 mkaddr_const(state, ins, 
11955                                         RHS(lnode->val, 0), lnode->val->u.cval);
11956                                 break;
11957                         default:
11958                                 /* By default don't copy the changes,
11959                                  * recompute them in place instead.
11960                                  */
11961                                 simplify(state, ins);
11962                                 break;
11963                         }
11964                 }
11965                 ins = ins->next;
11966         } while(ins != first);
11967 }
11968
11969 static void scc_transform(struct compile_state *state)
11970 {
11971         struct scc_state scc;
11972
11973         initialize_scc_state(state, &scc);
11974
11975         while(scc.flow_work_list || scc.ssa_work_list) {
11976                 struct flow_edge *fedge;
11977                 struct ssa_edge *sedge;
11978                 struct flow_edge *fptr;
11979                 while((fedge = scc_next_fedge(state, &scc))) {
11980                         struct block *block;
11981                         struct triple *ptr;
11982                         struct flow_block *fblock;
11983                         int time;
11984                         int done;
11985                         if (fedge->executable) {
11986                                 continue;
11987                         }
11988                         if (!fedge->dst) {
11989                                 internal_error(state, 0, "fedge without dst");
11990                         }
11991                         if (!fedge->src) {
11992                                 internal_error(state, 0, "fedge without src");
11993                         }
11994                         fedge->executable = 1;
11995                         fblock = fedge->dst;
11996                         block = fblock->block;
11997                         time = 0;
11998                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11999                                 if (fptr->executable) {
12000                                         time++;
12001                                 }
12002                         }
12003 #if DEBUG_SCC
12004                         fprintf(stderr, "vertex: %d time: %d\n", 
12005                                 block->vertex, time);
12006                         
12007 #endif
12008                         done = 0;
12009                         for(ptr = block->first; !done; ptr = ptr->next) {
12010                                 struct lattice_node *lnode;
12011                                 done = (ptr == block->last);
12012                                 lnode = &scc.lattice[ptr->id];
12013                                 if (ptr->op == OP_PHI) {
12014                                         scc_visit_phi(state, &scc, lnode);
12015                                 }
12016                                 else if (time == 1) {
12017                                         scc_visit_expr(state, &scc, lnode);
12018                                 }
12019                         }
12020                         if (fblock->out && !fblock->out->out_next) {
12021                                 scc_add_fedge(state, &scc, fblock->out);
12022                         }
12023                 }
12024                 while((sedge = scc_next_sedge(state, &scc))) {
12025                         struct lattice_node *lnode;
12026                         struct flow_block *fblock;
12027                         lnode = sedge->dst;
12028                         fblock = lnode->fblock;
12029 #if DEBUG_SCC
12030                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
12031                                 sedge - scc.ssa_edges,
12032                                 sedge->src->def->id,
12033                                 sedge->dst->def->id);
12034 #endif
12035                         if (lnode->def->op == OP_PHI) {
12036                                 scc_visit_phi(state, &scc, lnode);
12037                         }
12038                         else {
12039                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
12040                                         if (fptr->executable) {
12041                                                 break;
12042                                         }
12043                                 }
12044                                 if (fptr) {
12045                                         scc_visit_expr(state, &scc, lnode);
12046                                 }
12047                         }
12048                 }
12049         }
12050         
12051         scc_writeback_values(state, &scc);
12052         free_scc_state(state, &scc);
12053 }
12054
12055
12056 static void transform_to_arch_instructions(struct compile_state *state);
12057
12058
12059 static void optimize(struct compile_state *state)
12060 {
12061         if (state->debug & DEBUG_TRIPLES) {
12062                 print_triples(state);
12063         }
12064         /* Replace structures with simpler data types */
12065         flatten_structures(state);
12066         if (state->debug & DEBUG_TRIPLES) {
12067                 print_triples(state);
12068         }
12069         /* Analize the intermediate code */
12070         setup_basic_blocks(state);
12071         analyze_idominators(state);
12072         analyze_ipdominators(state);
12073         /* Transform the code to ssa form */
12074         transform_to_ssa_form(state);
12075         /* Do strength reduction and simple constant optimizations */
12076         if (state->optimize >= 1) {
12077                 simplify_all(state);
12078         }
12079         /* Propogate constants throughout the code */
12080         if (state->optimize >= 2) {
12081                 scc_transform(state);
12082                 transform_from_ssa_form(state);
12083                 free_basic_blocks(state);
12084                 setup_basic_blocks(state);
12085                 analyze_idominators(state);
12086                 analyze_ipdominators(state);
12087                 transform_to_ssa_form(state);
12088                 
12089         }
12090 #warning "WISHLIST implement single use constants (least possible register pressure)"
12091 #warning "WISHLIST implement induction variable elimination"
12092 #warning "WISHLIST implement strength reduction"
12093         /* Select architecture instructions and an initial partial
12094          * coloring based on architecture constraints.
12095          */
12096         transform_to_arch_instructions(state);
12097         if (state->debug & DEBUG_ARCH_CODE) {
12098                 printf("After transform_to_arch_instructions\n");
12099                 print_blocks(state);
12100                 print_control_flow(state);
12101         }
12102         eliminate_inefectual_code(state);
12103         if (state->debug & DEBUG_CODE_ELIMINATION) {
12104                 printf("After eliminate_inefectual_code\n");
12105                 print_blocks(state);
12106                 print_control_flow(state);
12107         }
12108         /* Color all of the variables to see if they will fit in registers */
12109         insert_copies_to_phi(state);
12110         allocate_registers(state);
12111         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
12112                 print_blocks(state);
12113         }
12114         if (state->debug & DEBUG_CONTROL_FLOW) {
12115                 print_control_flow(state);
12116         }
12117         /* Remove the optimization information.
12118          * This is more to check for memory consistency than to free memory.
12119          */
12120         free_basic_blocks(state);
12121 }
12122
12123 /* The x86 register classes */
12124 #define REGC_FLAGS   0
12125 #define REGC_GPR8    1
12126 #define REGC_GPR16   2
12127 #define REGC_GPR32   3
12128 #define REGC_GPR64   4
12129 #define REGC_MMX     5
12130 #define REGC_XMM     6
12131 #define REGC_GPR32_8 7
12132 #define REGC_GPR16_8 8
12133 #define LAST_REGC  REGC_GPR16_8
12134 #if LAST_REGC >= MAX_REGC
12135 #error "MAX_REGC is to low"
12136 #endif
12137
12138 /* Register class masks */
12139 #define REGCM_FLAGS   (1 << REGC_FLAGS)
12140 #define REGCM_GPR8    (1 << REGC_GPR8)
12141 #define REGCM_GPR16   (1 << REGC_GPR16)
12142 #define REGCM_GPR32   (1 << REGC_GPR32)
12143 #define REGCM_GPR64   (1 << REGC_GPR64)
12144 #define REGCM_MMX     (1 << REGC_MMX)
12145 #define REGCM_XMM     (1 << REGC_XMM)
12146 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
12147 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
12148
12149 /* The x86 registers */
12150 #define REG_EFLAGS  1
12151 #define REGC_FLAGS_FIRST REG_EFLAGS
12152 #define REGC_FLAGS_LAST  REG_EFLAGS
12153 #define REG_AL      2
12154 #define REG_BL      3
12155 #define REG_CL      4
12156 #define REG_DL      5
12157 #define REG_AH      6
12158 #define REG_BH      7
12159 #define REG_CH      8
12160 #define REG_DH      9
12161 #define REGC_GPR8_FIRST  REG_AL
12162 #if X86_4_8BIT_GPRS
12163 #define REGC_GPR8_LAST   REG_DL
12164 #else 
12165 #define REGC_GPR8_LAST   REG_DH
12166 #endif
12167 #define REG_AX     10
12168 #define REG_BX     11
12169 #define REG_CX     12
12170 #define REG_DX     13
12171 #define REG_SI     14
12172 #define REG_DI     15
12173 #define REG_BP     16
12174 #define REG_SP     17
12175 #define REGC_GPR16_FIRST REG_AX
12176 #define REGC_GPR16_LAST  REG_SP
12177 #define REG_EAX    18
12178 #define REG_EBX    19
12179 #define REG_ECX    20
12180 #define REG_EDX    21
12181 #define REG_ESI    22
12182 #define REG_EDI    23
12183 #define REG_EBP    24
12184 #define REG_ESP    25
12185 #define REGC_GPR32_FIRST REG_EAX
12186 #define REGC_GPR32_LAST  REG_ESP
12187 #define REG_EDXEAX 26
12188 #define REGC_GPR64_FIRST REG_EDXEAX
12189 #define REGC_GPR64_LAST  REG_EDXEAX
12190 #define REG_MMX0   27
12191 #define REG_MMX1   28
12192 #define REG_MMX2   29
12193 #define REG_MMX3   30
12194 #define REG_MMX4   31
12195 #define REG_MMX5   32
12196 #define REG_MMX6   33
12197 #define REG_MMX7   34
12198 #define REGC_MMX_FIRST REG_MMX0
12199 #define REGC_MMX_LAST  REG_MMX7
12200 #define REG_XMM0   35
12201 #define REG_XMM1   36
12202 #define REG_XMM2   37
12203 #define REG_XMM3   38
12204 #define REG_XMM4   39
12205 #define REG_XMM5   40
12206 #define REG_XMM6   41
12207 #define REG_XMM7   42
12208 #define REGC_XMM_FIRST REG_XMM0
12209 #define REGC_XMM_LAST  REG_XMM7
12210 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
12211 #define LAST_REG   REG_XMM7
12212
12213 #define REGC_GPR32_8_FIRST REG_EAX
12214 #define REGC_GPR32_8_LAST  REG_EDX
12215 #define REGC_GPR16_8_FIRST REG_AX
12216 #define REGC_GPR16_8_LAST  REG_DX
12217
12218 #if LAST_REG >= MAX_REGISTERS
12219 #error "MAX_REGISTERS to low"
12220 #endif
12221
12222 static unsigned arch_regc_size(struct compile_state *state, int class)
12223 {
12224         static unsigned regc_size[LAST_REGC +1] = {
12225                 [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
12226                 [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
12227                 [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
12228                 [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
12229                 [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
12230                 [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
12231                 [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
12232                 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
12233                 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
12234         };
12235         if ((class < 0) || (class > LAST_REGC)) {
12236                 return 0;
12237         }
12238         return regc_size[class];
12239 }
12240 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
12241 {
12242         /* See if two register classes may have overlapping registers */
12243         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12244                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
12245
12246         return (regcm1 & regcm2) ||
12247                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
12248 }
12249
12250 static void arch_reg_equivs(
12251         struct compile_state *state, unsigned *equiv, int reg)
12252 {
12253         if ((reg < 0) || (reg > LAST_REG)) {
12254                 internal_error(state, 0, "invalid register");
12255         }
12256         *equiv++ = reg;
12257         switch(reg) {
12258         case REG_AL:
12259         case REG_AH:
12260                 *equiv++ = REG_AX;
12261                 *equiv++ = REG_EAX;
12262                 *equiv++ = REG_EDXEAX;
12263                 break;
12264         case REG_BL:  
12265         case REG_BH:
12266                 *equiv++ = REG_BX;
12267                 *equiv++ = REG_EBX;
12268                 break;
12269         case REG_CL:
12270         case REG_CH:
12271                 *equiv++ = REG_CX;
12272                 *equiv++ = REG_ECX;
12273                 break;
12274         case REG_DL:
12275         case REG_DH:
12276                 *equiv++ = REG_DX;
12277                 *equiv++ = REG_EDX;
12278                 *equiv++ = REG_EDXEAX;
12279                 break;
12280         case REG_AX:
12281                 *equiv++ = REG_AL;
12282                 *equiv++ = REG_AH;
12283                 *equiv++ = REG_EAX;
12284                 *equiv++ = REG_EDXEAX;
12285                 break;
12286         case REG_BX:
12287                 *equiv++ = REG_BL;
12288                 *equiv++ = REG_BH;
12289                 *equiv++ = REG_EBX;
12290                 break;
12291         case REG_CX:  
12292                 *equiv++ = REG_CL;
12293                 *equiv++ = REG_CH;
12294                 *equiv++ = REG_ECX;
12295                 break;
12296         case REG_DX:  
12297                 *equiv++ = REG_DL;
12298                 *equiv++ = REG_DH;
12299                 *equiv++ = REG_EDX;
12300                 *equiv++ = REG_EDXEAX;
12301                 break;
12302         case REG_SI:  
12303                 *equiv++ = REG_ESI;
12304                 break;
12305         case REG_DI:
12306                 *equiv++ = REG_EDI;
12307                 break;
12308         case REG_BP:
12309                 *equiv++ = REG_EBP;
12310                 break;
12311         case REG_SP:
12312                 *equiv++ = REG_ESP;
12313                 break;
12314         case REG_EAX:
12315                 *equiv++ = REG_AL;
12316                 *equiv++ = REG_AH;
12317                 *equiv++ = REG_AX;
12318                 *equiv++ = REG_EDXEAX;
12319                 break;
12320         case REG_EBX:
12321                 *equiv++ = REG_BL;
12322                 *equiv++ = REG_BH;
12323                 *equiv++ = REG_BX;
12324                 break;
12325         case REG_ECX:
12326                 *equiv++ = REG_CL;
12327                 *equiv++ = REG_CH;
12328                 *equiv++ = REG_CX;
12329                 break;
12330         case REG_EDX:
12331                 *equiv++ = REG_DL;
12332                 *equiv++ = REG_DH;
12333                 *equiv++ = REG_DX;
12334                 *equiv++ = REG_EDXEAX;
12335                 break;
12336         case REG_ESI: 
12337                 *equiv++ = REG_SI;
12338                 break;
12339         case REG_EDI: 
12340                 *equiv++ = REG_DI;
12341                 break;
12342         case REG_EBP: 
12343                 *equiv++ = REG_BP;
12344                 break;
12345         case REG_ESP: 
12346                 *equiv++ = REG_SP;
12347                 break;
12348         case REG_EDXEAX: 
12349                 *equiv++ = REG_AL;
12350                 *equiv++ = REG_AH;
12351                 *equiv++ = REG_DL;
12352                 *equiv++ = REG_DH;
12353                 *equiv++ = REG_AX;
12354                 *equiv++ = REG_DX;
12355                 *equiv++ = REG_EAX;
12356                 *equiv++ = REG_EDX;
12357                 break;
12358         }
12359         *equiv++ = REG_UNSET; 
12360 }
12361
12362
12363 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
12364 {
12365         static const struct {
12366                 int first, last;
12367         } bound[LAST_REGC + 1] = {
12368                 [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
12369                 [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
12370                 [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
12371                 [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
12372                 [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
12373                 [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
12374                 [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
12375                 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
12376                 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
12377         };
12378         unsigned mask;
12379         int class;
12380         mask = 0;
12381         for(class = 0; class <= LAST_REGC; class++) {
12382                 if ((reg >= bound[class].first) &&
12383                         (reg <= bound[class].last)) {
12384                         mask |= (1 << class);
12385                 }
12386         }
12387         if (!mask) {
12388                 internal_error(state, 0, "reg %d not in any class", reg);
12389         }
12390         return mask;
12391 }
12392
12393 static int do_select_reg(struct compile_state *state, 
12394         char *used, int reg, unsigned classes)
12395 {
12396         unsigned mask;
12397         if (used[reg]) {
12398                 return REG_UNSET;
12399         }
12400         mask = arch_reg_regcm(state, reg);
12401         return (classes & mask) ? reg : REG_UNSET;
12402 }
12403
12404 static int arch_select_free_register(
12405         struct compile_state *state, char *used, int classes)
12406 {
12407         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
12408          * other types of registers.
12409          */
12410         int i, reg;
12411         reg = REG_UNSET;
12412         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
12413                 reg = do_select_reg(state, used, i, classes);
12414         }
12415         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
12416                 reg = do_select_reg(state, used, i, classes);
12417         }
12418         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
12419                 reg = do_select_reg(state, used, i, classes);
12420         }
12421         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
12422                 reg = do_select_reg(state, used, i, classes);
12423         }
12424         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
12425                 reg = do_select_reg(state, used, i, classes);
12426         }
12427         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
12428                 reg = do_select_reg(state, used, i, classes);
12429         }
12430         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
12431                 reg = do_select_reg(state, used, i, classes);
12432         }
12433         return reg;
12434 }
12435
12436 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
12437 {
12438 #warning "FIXME force types smaller (if legal) before I get here"
12439         int use_mmx = 0;
12440         int use_sse = 0;
12441         unsigned avail_mask;
12442         unsigned mask;
12443         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
12444                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64;
12445 #if 1
12446         /* Don't enable 8 bit values until I can force both operands
12447          * to be 8bits simultaneously.
12448          */
12449         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
12450 #endif
12451         if (use_mmx) {
12452                 avail_mask |= REGCM_MMX;
12453         }
12454         if (use_sse) {
12455                 avail_mask |= REGCM_XMM;
12456         }
12457         mask = 0;
12458         switch(type->type & TYPE_MASK) {
12459         case TYPE_ARRAY:
12460         case TYPE_VOID: 
12461                 mask = 0; 
12462                 break;
12463         case TYPE_CHAR:
12464         case TYPE_UCHAR:
12465                 mask = REGCM_GPR8 | 
12466                         REGCM_GPR16_8 | REGCM_GPR16 | 
12467                         REGCM_GPR32 | REGCM_GPR32_8 |
12468                         REGCM_GPR64 |
12469                         REGCM_MMX | REGCM_XMM;
12470                 break;
12471         case TYPE_SHORT:
12472         case TYPE_USHORT:
12473                 mask = REGCM_GPR16 | REGCM_GPR16_8 |
12474                         REGCM_GPR32 | REGCM_GPR32_8 |
12475                         REGCM_GPR64 |
12476                         REGCM_MMX | REGCM_XMM;
12477                 break;
12478         case TYPE_INT:
12479         case TYPE_UINT:
12480         case TYPE_LONG:
12481         case TYPE_ULONG:
12482         case TYPE_POINTER:
12483                 mask = REGCM_GPR32 | REGCM_GPR32_8 |
12484                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM;
12485                 break;
12486         default:
12487                 internal_error(state, 0, "no register class for type");
12488                 break;
12489         }
12490         mask &= avail_mask;
12491         return mask;
12492 }
12493
12494 static void get_imm32(struct triple *ins, struct triple **expr)
12495 {
12496         struct triple *imm;
12497         if ((*expr)->op != OP_COPY) {
12498                 return;
12499         }
12500         imm = RHS((*expr), 0);
12501         while(imm->op == OP_COPY) {
12502                 imm = RHS(imm, 0);
12503         }
12504         if (imm->op != OP_INTCONST) {
12505                 return;
12506         }
12507         *expr = imm;
12508         unuse_triple(*expr, ins);
12509         use_triple(*expr, ins);
12510 }
12511
12512 static void get_imm8(struct triple *ins, struct triple **expr)
12513 {
12514         struct triple *imm;
12515         if ((*expr)->op != OP_COPY) {
12516                 return;
12517         }
12518         imm = RHS((*expr), 0);
12519         while(imm->op == OP_COPY) {
12520                 imm = RHS(imm, 0);
12521         }
12522         if (imm->op != OP_INTCONST) {
12523                 return;
12524         }
12525         /* For imm8 only a sufficienlty small constant can be used */
12526         if (imm->u.cval > 0xff) {
12527                 return;
12528         }
12529         *expr = imm;
12530         unuse_triple(*expr, ins);
12531         use_triple(*expr, ins);
12532 }
12533
12534 static struct triple *pre_copy(struct compile_state *state, 
12535         struct triple *ins, struct triple **expr,
12536         unsigned reg, unsigned mask)
12537 {
12538         /* Carefully insert enough operations so that I can
12539          * enter any operation with a GPR32.
12540          */
12541         struct triple *in;
12542         /* See if I can directly reach the result from a GPR32 */
12543         if (mask & (REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)) {
12544                 in = triple(state, OP_COPY, (*expr)->type, *expr,  0);
12545         }
12546         /* If it is a byte value force a earlier copy to a GPR32_8 */
12547         else if (mask & REGCM_GPR8) {
12548                 struct triple *tmp;
12549                 tmp = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12550                 tmp->filename = ins->filename;
12551                 tmp->line     = ins->line;
12552                 tmp->col      = ins->col;
12553                 tmp->u.block  = ins->u.block;
12554                 tmp->id = MK_REG_ID(REG_UNSET, REGCM_GPR32_8 | REGCM_GPR16_8);
12555                 use_triple(RHS(tmp, 0), tmp);
12556                 insert_triple(state, ins, tmp);
12557
12558                 in = triple(state, OP_COPY, tmp->type, tmp, 0);
12559         }
12560         else {
12561                 internal_error(state, ins, "bad copy type");
12562                 in = 0;
12563         }
12564         in->filename  = ins->filename;
12565         in->line      = ins->line;
12566         in->col       = ins->col;
12567         in->u.block   = ins->u.block;
12568         in->id        = MK_REG_ID(reg, mask);
12569         unuse_triple(*expr, ins);
12570         *expr = in;
12571         use_triple(RHS(in, 0), in);
12572         use_triple(in, ins);
12573         insert_triple(state, ins, in);
12574         return in;
12575 }
12576
12577 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
12578 {
12579         struct triple_set *entry, *next;
12580         struct triple *out, *label;
12581         struct block *block;
12582         label = ins;
12583         while(label->op != OP_LABEL) {
12584                 label = label->prev;
12585         }
12586         block = label->u.block;
12587         out = triple(state, OP_COPY, ins->type, ins, 0);
12588         out->filename = ins->filename;
12589         out->line     = ins->line;
12590         out->col      = ins->col;
12591         out->u.block  = block;
12592         out->id       = MK_REG_ID(REG_UNSET, 
12593                 arch_type_to_regcm(state, ins->type));
12594         use_triple(ins, out);
12595         insert_triple(state, ins->next, out);
12596         if (block->last == ins) {
12597                 block->last = out;
12598         }
12599         /* Get the users of ins to use out instead */
12600         for(entry = ins->use; entry; entry = next) {
12601                 next = entry->next;
12602                 if (entry->member == out) {
12603                         continue;
12604                 }
12605                 replace_rhs_use(state, ins, out, entry->member);
12606         }
12607         return out;
12608 }
12609
12610 static void fixup_branches(struct compile_state *state,
12611         struct triple *cmp, struct triple *use, int jmp_op)
12612 {
12613         struct triple_set *entry, *next;
12614         for(entry = use->use; entry; entry = next) {
12615                 next = entry->next;
12616                 if (entry->member->op == OP_COPY) {
12617                         fixup_branches(state, cmp, entry->member, jmp_op);
12618                 }
12619                 else if (entry->member->op == OP_BRANCH) {
12620                         struct triple *branch, *test;
12621                         struct triple *left, *right;
12622                         left = right = 0;
12623                         left = RHS(cmp, 0);
12624                         if (TRIPLE_RHS(cmp->sizes) > 1) {
12625                                 right = RHS(cmp, 1);
12626                         }
12627                         branch = entry->member;
12628                         test = pre_triple(state, branch,
12629                                 cmp->op, cmp->type, left, right);
12630                         test->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12631                         unuse_triple(RHS(branch, 0), branch);
12632                         RHS(branch, 0) = test;
12633                         branch->op = jmp_op;
12634                         use_triple(RHS(branch, 0), branch);
12635                 }
12636         }
12637 }
12638
12639 static void bool_cmp(struct compile_state *state, 
12640         struct triple *ins, int cmp_op, int jmp_op, int set_op)
12641 {
12642         struct block *block;
12643         struct triple_set *entry, *next;
12644         struct triple *set, *tmp1, *tmp2;
12645
12646 #warning "WISHLIST implement an expression simplifier to reduce the use of set?"
12647
12648         block = ins->u.block;
12649
12650         /* Put a barrier up before the cmp which preceeds the
12651          * copy instruction.  If a set actually occurs this gives
12652          * us a chance to move variables in registers out of the way.
12653          */
12654
12655         /* Modify the comparison operator */
12656         ins->op = cmp_op;
12657         ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12658         if (cmp_op == OP_CMP) {
12659                 get_imm32(ins, &RHS(ins, 1));
12660         }
12661         /* Generate the instruction sequence that will transform the
12662          * result of the comparison into a logical value.
12663          */
12664         tmp1 = triple(state, set_op, ins->type, ins, 0);
12665         tmp1->filename = ins->filename;
12666         tmp1->line     = ins->line;
12667         tmp1->col      = ins->col;
12668         tmp1->u.block  = block;
12669         tmp1->id       = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12670         use_triple(ins, tmp1);
12671         insert_triple(state, ins->next, tmp1);
12672         
12673         tmp2 = triple(state, OP_COPY, ins->type, tmp1, 0);
12674         tmp2->filename = ins->filename;
12675         tmp2->line     = ins->line;
12676         tmp2->col      = ins->col;
12677         tmp2->u.block  = block;
12678         tmp2->id       = MK_REG_ID(REG_UNSET, 
12679                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR16 | REGCM_GPR16_8 | REGCM_GPR8);
12680         use_triple(tmp1, tmp2);
12681         insert_triple(state, tmp1->next, tmp2);
12682
12683         if (block->last == ins) {
12684                 block->last = tmp2;
12685         }
12686
12687         set = tmp2;
12688         for(entry = ins->use; entry; entry = next) {
12689                 next = entry->next;
12690                 if (entry->member == tmp1) {
12691                         continue;
12692                 }
12693                 replace_rhs_use(state, ins, set, entry->member);
12694         }
12695         fixup_branches(state, ins, set, jmp_op);
12696 }
12697
12698 static void verify_lhs(struct compile_state *state, struct triple *ins)
12699 {
12700         struct triple *next;
12701         int lhs, i;
12702         lhs = TRIPLE_LHS(ins->sizes);
12703         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
12704                 if (next != LHS(ins, i)) {
12705                         internal_error(state, ins, "malformed lhs on %s",
12706                                 tops(ins->op));
12707                 }
12708         }
12709 }
12710
12711 static void transform_to_arch_instructions(struct compile_state *state)
12712 {
12713         /* Transform from generic 3 address instructions
12714          * to archtecture specific instructions.
12715          * And apply architecture specific constrains to instructions.
12716          * Copies are inserted to preserve the register flexibility
12717          * of 3 address instructions.
12718          */
12719         struct triple *ins, *first, *next;
12720         struct triple *in, *in2;
12721         first = RHS(state->main_function, 0);
12722         ins = first;
12723         do {
12724                 next = ins->next;
12725                 ins->id = MK_REG_ID(REG_UNSET, arch_type_to_regcm(state, ins->type));
12726                 switch(ins->op) {
12727                 case OP_INTCONST:
12728                 case OP_ADDRCONST:
12729                         ins->id = 0;
12730                         post_copy(state, ins);
12731                         break;
12732                 case OP_NOOP:
12733                 case OP_SDECL:
12734                 case OP_BLOBCONST:
12735                 case OP_LABEL:
12736                         ins->id = 0;
12737                         break;
12738                         /* instructions that can be used as is */
12739                 case OP_COPY:
12740                 case OP_PHI:
12741                         break;
12742                 case OP_STORE:
12743                 {
12744                         unsigned mask;
12745                         ins->id = 0;
12746                         switch(ins->type->type & TYPE_MASK) {
12747                         case TYPE_CHAR:    case TYPE_UCHAR:
12748                                 mask = REGCM_GPR8;
12749                                 break;
12750                         case TYPE_SHORT:   case TYPE_USHORT:
12751                                 mask = REGCM_GPR16;
12752                                 break;
12753                         case TYPE_INT:     case TYPE_UINT:
12754                         case TYPE_LONG:    case TYPE_ULONG:
12755                         case TYPE_POINTER:
12756                                 mask  = REGCM_GPR32;
12757                                 break;
12758                         default:
12759                                 internal_error(state, ins, "unknown type in store");
12760                                 mask = 0;
12761                                 break;
12762                         }
12763                         in = pre_copy(state, ins, &RHS(ins, 0), REG_UNSET, mask);
12764                         break;
12765                 }
12766                 case OP_LOAD:
12767                         switch(ins->type->type & TYPE_MASK) {
12768                         case TYPE_CHAR:   case TYPE_UCHAR:
12769                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12770                                 break;
12771                         case TYPE_SHORT:
12772                         case TYPE_USHORT:
12773                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR16);
12774                                 break;
12775                         case TYPE_INT:
12776                         case TYPE_UINT:
12777                         case TYPE_LONG:
12778                         case TYPE_ULONG:
12779                         case TYPE_POINTER:
12780                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32);
12781                                 break;
12782                         default:
12783                                 internal_error(state, ins, "unknown type in load");
12784                                 break;
12785                         }
12786                         break;
12787                 case OP_ADD:
12788                 case OP_SUB:
12789                 case OP_AND:
12790                 case OP_XOR:
12791                 case OP_OR:
12792                         get_imm32(ins, &RHS(ins, 1));
12793                         in = pre_copy(state, ins, &RHS(ins, 0),
12794                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12795                         ins->id = in->id;
12796                         break;
12797                 case OP_SL:
12798                 case OP_SSR:
12799                 case OP_USR:
12800                         get_imm8(ins, &RHS(ins, 1));
12801                         in = pre_copy(state, ins, &RHS(ins, 0),
12802                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12803                         ins->id = in->id;
12804                         if (!is_const(RHS(ins, 1))) {
12805                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12806                                         REG_CL, REGCM_GPR8);
12807                         }
12808                         break;
12809                 case OP_INVERT:
12810                 case OP_NEG:
12811                         in = pre_copy(state, ins, &RHS(ins, 0),
12812                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12813                         ins->id = in->id;
12814                         break;
12815                 case OP_SMUL:
12816                         get_imm32(ins, &RHS(ins, 1));
12817                         in = pre_copy(state, ins, &RHS(ins, 0),
12818                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12819                         ins->id = in->id;
12820                         if (!is_const(RHS(ins, 1))) {
12821                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12822                                         REG_UNSET, REGCM_GPR32);
12823                         }
12824                         break;
12825                 case OP_EQ: 
12826                         bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
12827                         break;
12828                 case OP_NOTEQ:
12829                         bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12830                         break;
12831                 case OP_SLESS:
12832                         bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
12833                         break;
12834                 case OP_ULESS:
12835                         bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
12836                         break;
12837                 case OP_SMORE:
12838                         bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
12839                         break;
12840                 case OP_UMORE:
12841                         bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
12842                         break;
12843                 case OP_SLESSEQ:
12844                         bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
12845                         break;
12846                 case OP_ULESSEQ:
12847                         bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
12848                         break;
12849                 case OP_SMOREEQ:
12850                         bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
12851                         break;
12852                 case OP_UMOREEQ:
12853                         bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
12854                         break;
12855                 case OP_LTRUE:
12856                         bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12857                         break;
12858                 case OP_LFALSE:
12859                         bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
12860                         break;
12861                 case OP_BRANCH:
12862                         if (TRIPLE_RHS(ins->sizes) > 0) {
12863                                 internal_error(state, ins, "bad branch test");
12864                         }
12865                         ins->op = OP_JMP;
12866                         break;
12867
12868                 case OP_INB:
12869                 case OP_INW:
12870                 case OP_INL:
12871                         get_imm8(ins, &RHS(ins, 0));
12872                         switch(ins->op) {
12873                         case OP_INB: ins->id = MK_REG_ID(REG_AL,  REGCM_GPR8); break;
12874                         case OP_INW: ins->id = MK_REG_ID(REG_AX,  REGCM_GPR16); break;
12875                         case OP_INL: ins->id = MK_REG_ID(REG_EAX, REGCM_GPR32); break;
12876                         }
12877                         if (!is_const(RHS(ins, 0))) {
12878                                 in = pre_copy(state, ins, &RHS(ins, 0),
12879                                         REG_DX, REGCM_GPR16);
12880                         }
12881                         post_copy(state, ins);
12882                         break;
12883                 case OP_OUTB:
12884                 case OP_OUTW:
12885                 case OP_OUTL:
12886                 {
12887                         unsigned reg, mask;
12888                         get_imm8(ins, &RHS(ins, 1));
12889                         switch(ins->op) {
12890                         case OP_OUTB: reg = REG_AL;  mask = REGCM_GPR8; break;
12891                         case OP_OUTW: reg = REG_AX;  mask = REGCM_GPR16; break;
12892                         case OP_OUTL: reg = REG_EAX; mask = REGCM_GPR32; break;
12893                         default: reg = REG_UNSET; mask = 0; break;
12894                         }
12895                         in = pre_copy(state, ins, &RHS(ins, 0), reg, mask);
12896                         if (!is_const(RHS(ins, 1))) {
12897                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12898                                         REG_DX, REGCM_GPR16);
12899                         }
12900                         break;
12901                 }
12902                 case OP_BSF:
12903                 case OP_BSR:
12904                         in = pre_copy(state, ins, &RHS(ins, 0),
12905                                 REG_UNSET, REGCM_GPR32);
12906                         ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32 | REGCM_GPR32_8);
12907                         break;
12908                 case OP_RDMSR:
12909                         in = pre_copy(state, ins, &RHS(ins, 0),
12910                                 REG_ECX, REGCM_GPR32);
12911                         verify_lhs(state, ins);
12912                         LHS(ins,0)->id = MK_REG_ID(REG_EAX, REGCM_GPR32);
12913                         LHS(ins,1)->id = MK_REG_ID(REG_EDX, REGCM_GPR32);
12914                         next = ins->next->next->next;
12915                         break;
12916                 case OP_WRMSR:
12917                         pre_copy(state, ins, &RHS(ins, 0), REG_ECX, REGCM_GPR32);
12918                         pre_copy(state, ins, &RHS(ins, 1), REG_EAX, REGCM_GPR32);
12919                         pre_copy(state, ins, &RHS(ins, 2), REG_EDX, REGCM_GPR32);
12920                         break;
12921                 case OP_HLT:
12922                         break;
12923                         /* Already transformed instructions */
12924                 case OP_CMP:
12925                 case OP_TEST:
12926                         ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12927                         break;
12928                 case OP_JMP_EQ:      case OP_JMP_NOTEQ:
12929                 case OP_JMP_SLESS:   case OP_JMP_ULESS:
12930                 case OP_JMP_SMORE:   case OP_JMP_UMORE:
12931                 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
12932                 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
12933                 case OP_SET_EQ:      case OP_SET_NOTEQ:
12934                 case OP_SET_SLESS:   case OP_SET_ULESS:
12935                 case OP_SET_SMORE:   case OP_SET_UMORE:
12936                 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
12937                 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
12938                         break;
12939                         /* Unhandled instructions */
12940                 case OP_PIECE:
12941                 default:
12942                         internal_error(state, ins, "unhandled ins: %d %s\n",
12943                                 ins->op, tops(ins->op));
12944                         break;
12945                 }
12946                 ins = next;
12947         } while(ins != first);
12948 }
12949
12950 static void generate_local_labels(struct compile_state *state)
12951 {
12952         struct triple *first, *label;
12953         int label_counter;
12954         label_counter = 0;
12955         first = RHS(state->main_function, 0);
12956         label = first;
12957         do {
12958                 if ((label->op == OP_LABEL) || 
12959                         (label->op == OP_SDECL)) {
12960                         if (label->use) {
12961                                 label->u.cval = ++label_counter;
12962                         } else {
12963                                 label->u.cval = 0;
12964                         }
12965                         
12966                 }
12967                 label = label->next;
12968         } while(label != first);
12969 }
12970
12971 static int check_reg(struct compile_state *state, 
12972         struct triple *triple, int classes)
12973 {
12974         unsigned mask;
12975         int reg;
12976         reg = ID_REG(triple->id);
12977         if (reg == REG_UNSET) {
12978                 internal_error(state, triple, "register not set");
12979         }
12980         if (ID_REG_CLASSES(triple->id)) {
12981                 internal_error(state, triple, "class specifier present");
12982         }
12983         mask = arch_reg_regcm(state, reg);
12984         if (!(classes & mask)) {
12985                 internal_error(state, triple, "reg %d in wrong class",
12986                         reg);
12987         }
12988         return reg;
12989 }
12990
12991 static const char *arch_reg_str(int reg)
12992 {
12993         static const char *regs[] = {
12994                 "%bad_register",
12995                 "%eflags",
12996                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
12997                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
12998                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
12999                 "%edx:%eax",
13000                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
13001                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
13002                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
13003         };
13004         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
13005                 reg = 0;
13006         }
13007         return regs[reg];
13008 }
13009
13010 static const char *reg(struct compile_state *state, struct triple *triple,
13011         int classes)
13012 {
13013         int reg;
13014         reg = check_reg(state, triple, classes);
13015         return arch_reg_str(reg);
13016 }
13017
13018 const char *type_suffix(struct compile_state *state, struct type *type)
13019 {
13020         const char *suffix;
13021         switch(size_of(state, type)) {
13022         case 1: suffix = "b"; break;
13023         case 2: suffix = "w"; break;
13024         case 4: suffix = "l"; break;
13025         default:
13026                 internal_error(state, 0, "unknown suffix");
13027                 suffix = 0;
13028                 break;
13029         }
13030         return suffix;
13031 }
13032
13033 static void print_binary_op(struct compile_state *state,
13034         const char *op, struct triple *ins, FILE *fp) 
13035 {
13036         unsigned mask;
13037         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13038         if (RHS(ins, 0)->id != ins->id) {
13039                 internal_error(state, ins, "invalid register assignment");
13040         }
13041         if (is_const(RHS(ins, 1))) {
13042                 fprintf(fp, "\t%s $%lu, %s\n",
13043                         op,
13044                         RHS(ins, 1)->u.cval,
13045                         reg(state, RHS(ins, 0), mask));
13046                 
13047         }
13048         else {
13049                 unsigned lmask, rmask;
13050                 int lreg, rreg;
13051                 lreg = check_reg(state, RHS(ins, 0), mask);
13052                 rreg = check_reg(state, RHS(ins, 1), mask);
13053                 lmask = arch_reg_regcm(state, lreg);
13054                 rmask = arch_reg_regcm(state, rreg);
13055                 mask = lmask & rmask;
13056                 fprintf(fp, "\t%s %s, %s\n",
13057                         op,
13058                         reg(state, RHS(ins, 1), mask),
13059                         reg(state, RHS(ins, 0), mask));
13060         }
13061 }
13062 static void print_unary_op(struct compile_state *state, 
13063         const char *op, struct triple *ins, FILE *fp)
13064 {
13065         unsigned mask;
13066         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13067         fprintf(fp, "\t%s %s\n",
13068                 op,
13069                 reg(state, RHS(ins, 0), mask));
13070 }
13071
13072 static void print_op_shift(struct compile_state *state,
13073         const char *op, struct triple *ins, FILE *fp)
13074 {
13075         unsigned mask;
13076         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13077         if (RHS(ins, 0)->id != ins->id) {
13078                 internal_error(state, ins, "invalid register assignment");
13079         }
13080         if (is_const(RHS(ins, 1))) {
13081                 fprintf(fp, "\t%s $%lu, %s\n",
13082                         op,
13083                         RHS(ins, 1)->u.cval,
13084                         reg(state, RHS(ins, 0), mask));
13085                 
13086         }
13087         else {
13088                 fprintf(fp, "\t%s %s, %s\n",
13089                         op,
13090                         reg(state, RHS(ins, 1), REGCM_GPR8),
13091                         reg(state, RHS(ins, 0), mask));
13092         }
13093 }
13094
13095 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
13096 {
13097         const char *op;
13098         int mask;
13099         int dreg;
13100         mask = 0;
13101         switch(ins->op) {
13102         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
13103         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
13104         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
13105         default:
13106                 internal_error(state, ins, "not an in operation");
13107                 op = 0;
13108                 break;
13109         }
13110         dreg = check_reg(state, ins, mask);
13111         if (!reg_is_reg(state, dreg, REG_EAX)) {
13112                 internal_error(state, ins, "dst != %%eax");
13113         }
13114         if (is_const(RHS(ins, 0))) {
13115                 fprintf(fp, "\t%s $%lu, %s\n",
13116                         op, RHS(ins, 0)->u.cval, 
13117                         reg(state, ins, mask));
13118         }
13119         else {
13120                 int addr_reg;
13121                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
13122                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13123                         internal_error(state, ins, "src != %%dx");
13124                 }
13125                 fprintf(fp, "\t%s %s, %s\n",
13126                         op, 
13127                         reg(state, RHS(ins, 0), REGCM_GPR16),
13128                         reg(state, ins, mask));
13129         }
13130 }
13131
13132 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
13133 {
13134         const char *op;
13135         int mask;
13136         int lreg;
13137         mask = 0;
13138         switch(ins->op) {
13139         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
13140         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
13141         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
13142         default:
13143                 internal_error(state, ins, "not an out operation");
13144                 op = 0;
13145                 break;
13146         }
13147         lreg = check_reg(state, RHS(ins, 0), mask);
13148         if (!reg_is_reg(state, lreg, REG_EAX)) {
13149                 internal_error(state, ins, "src != %%eax");
13150         }
13151         if (is_const(RHS(ins, 1))) {
13152                 fprintf(fp, "\t%s %s, $%lu\n",
13153                         op, reg(state, RHS(ins, 0), mask),
13154                         RHS(ins, 1)->u.cval);
13155         }
13156         else {
13157                 int addr_reg;
13158                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
13159                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13160                         internal_error(state, ins, "dst != %%dx");
13161                 }
13162                 fprintf(fp, "\t%s %s, %s\n",
13163                         op, 
13164                         reg(state, RHS(ins, 0), mask),
13165                         reg(state, RHS(ins, 1), REGCM_GPR16));
13166         }
13167 }
13168
13169 static void print_op_move(struct compile_state *state,
13170         struct triple *ins, FILE *fp)
13171 {
13172         /* op_move is complex because there are many types
13173          * of registers we can move between.
13174          */
13175         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
13176         struct triple *dst, *src;
13177         if (ins->op == OP_COPY) {
13178                 src = RHS(ins, 0);
13179                 dst = ins;
13180         }
13181         else if (ins->op == OP_WRITE) {
13182                 dst = LHS(ins, 0);
13183                 src = RHS(ins, 0);
13184         }
13185         else {
13186                 internal_error(state, ins, "unknown move operation");
13187                 src = dst = 0;
13188         }
13189         if (!is_const(src)) {
13190                 int src_reg, dst_reg;
13191                 int src_regcm, dst_regcm;
13192                 src_reg = ID_REG(src->id);
13193                 dst_reg   = ID_REG(dst->id);
13194                 src_regcm = arch_reg_regcm(state, src_reg);
13195                 dst_regcm   = arch_reg_regcm(state, dst_reg);
13196                 /* If the class is the same just move the register */
13197                 if (src_regcm & dst_regcm & 
13198                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
13199                         if ((src_reg != dst_reg) || !omit_copy) {
13200                                 fprintf(fp, "\tmov %s, %s\n",
13201                                         reg(state, src, src_regcm),
13202                                         reg(state, dst, dst_regcm));
13203                         }
13204                 }
13205                 /* Move 32bit to 16bit */
13206                 else if ((src_regcm & REGCM_GPR32) &&
13207                         (dst_regcm & REGCM_GPR16)) {
13208                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
13209                         if ((src_reg != dst_reg) || !omit_copy) {
13210                                 fprintf(fp, "\tmovw %s, %s\n",
13211                                         arch_reg_str(src_reg), 
13212                                         arch_reg_str(dst_reg));
13213                         }
13214                 }
13215                 /* Move 32bit to 8bit */
13216                 else if ((src_regcm & REGCM_GPR32_8) &&
13217                         (dst_regcm & REGCM_GPR8))
13218                 {
13219                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
13220                         if ((src_reg != dst_reg) || !omit_copy) {
13221                                 fprintf(fp, "\tmovb %s, %s\n",
13222                                         arch_reg_str(src_reg),
13223                                         arch_reg_str(dst_reg));
13224                         }
13225                 }
13226                 /* Move 16bit to 8bit */
13227                 else if ((src_regcm & REGCM_GPR16_8) &&
13228                         (dst_regcm & REGCM_GPR8))
13229                 {
13230                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
13231                         if ((src_reg != dst_reg) || !omit_copy) {
13232                                 fprintf(fp, "\tmovb %s, %s\n",
13233                                         arch_reg_str(src_reg),
13234                                         arch_reg_str(dst_reg));
13235                         }
13236                 }
13237                 /* Move 8/16bit to 16/32bit */
13238                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
13239                         (dst_regcm & (REGC_GPR16 | REGCM_GPR32))) {
13240                         const char *op;
13241                         op = is_signed(src->type)? "movsx": "movzx";
13242                         fprintf(fp, "\t%s %s, %s\n",
13243                                 op,
13244                                 reg(state, src, src_regcm),
13245                                 reg(state, dst, dst_regcm));
13246                 }
13247                 /* Move between sse registers */
13248                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
13249                         if ((src_reg != dst_reg) || !omit_copy) {
13250                                 fprintf(fp, "\tmovdqa %s %s\n",
13251                                         reg(state, src, src_regcm),
13252                                         reg(state, dst, dst_regcm));
13253                         }
13254                 }
13255                 /* Move between mmx registers or mmx & sse  registers */
13256                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
13257                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
13258                         if ((src_reg != dst_reg) || !omit_copy) {
13259                                 fprintf(fp, "\tmovq %s %s\n",
13260                                         reg(state, src, src_regcm),
13261                                         reg(state, dst, dst_regcm));
13262                         }
13263                 }
13264                 /* Move between 32bit gprs & mmx/sse registers */
13265                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
13266                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
13267                         fprintf(fp, "\tmovd %s, %s\n",
13268                                 reg(state, src, src_regcm),
13269                                 reg(state, dst, dst_regcm));
13270                 }
13271                 else {
13272                         internal_error(state, ins, "unknown copy type");
13273                 }
13274         }
13275         else switch(src->op) {
13276         case OP_INTCONST:
13277         {
13278                 long_t value;
13279                 value = (long_t)(src->u.cval);
13280                 fprintf(fp, "\tmov $%ld, %s\n",
13281                         value,
13282                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
13283                 break;
13284         }
13285         case OP_ADDRCONST:
13286                 fprintf(fp, "\tmov $L%lu+%lu, %s\n",
13287                         RHS(src, 0)->u.cval,
13288                         src->u.cval,
13289                         reg(state, dst, REGCM_GPR32));
13290                 break;
13291         default:
13292                 internal_error(state, ins, "uknown copy operation");
13293         }
13294 }
13295
13296 static void print_op_load(struct compile_state *state,
13297         struct triple *ins, FILE *fp)
13298 {
13299         struct triple *dst, *src;
13300         dst = ins;
13301         src = RHS(ins, 0);
13302         if (is_const(src) || is_const(dst)) {
13303                 internal_error(state, ins, "unknown load operation");
13304         }
13305         fprintf(fp, "\tmov (%s), %s\n",
13306                 reg(state, src, REGCM_GPR32),
13307                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
13308 }
13309
13310
13311 static void print_op_store(struct compile_state *state,
13312         struct triple *ins, FILE *fp)
13313 {
13314         struct triple *dst, *src;
13315         dst = LHS(ins, 0);
13316         src = RHS(ins, 0);
13317         if (is_const(src) && (src->op == OP_INTCONST)) {
13318                 long_t value;
13319                 value = (long_t)(src->u.cval);
13320                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
13321                         type_suffix(state, src->type),
13322                         value,
13323                         reg(state, dst, REGCM_GPR32));
13324         }
13325         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
13326                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
13327                         type_suffix(state, src->type),
13328                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13329                         dst->u.cval);
13330         }
13331         else {
13332                 if (is_const(src) || is_const(dst)) {
13333                         internal_error(state, ins, "unknown store operation");
13334                 }
13335                 fprintf(fp, "\tmov%s %s, (%s)\n",
13336                         type_suffix(state, src->type),
13337                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13338                         reg(state, dst, REGCM_GPR32));
13339         }
13340         
13341         
13342 }
13343
13344 static void print_op_smul(struct compile_state *state,
13345         struct triple *ins, FILE *fp)
13346 {
13347         if (!is_const(RHS(ins, 1))) {
13348                 fprintf(fp, "\timul %s, %s\n",
13349                         reg(state, RHS(ins, 1), REGCM_GPR32),
13350                         reg(state, RHS(ins, 0), REGCM_GPR32));
13351         }
13352         else {
13353                 fprintf(fp, "\timul $%ld, %s\n",
13354                         RHS(ins, 1)->u.cval,
13355                         reg(state, RHS(ins, 0), REGCM_GPR32));
13356         }
13357 }
13358
13359 static void print_op_cmp(struct compile_state *state,
13360         struct triple *ins, FILE *fp)
13361 {
13362         unsigned mask;
13363         int dreg;
13364         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13365         dreg = check_reg(state, ins, REGCM_FLAGS);
13366         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
13367                 internal_error(state, ins, "bad dest register for cmp");
13368         }
13369         if (is_const(RHS(ins, 1))) {
13370                 fprintf(fp, "\tcmp $%lu, %s\n",
13371                         RHS(ins, 1)->u.cval,
13372                         reg(state, RHS(ins, 0), mask));
13373         }
13374         else {
13375                 unsigned lmask, rmask;
13376                 int lreg, rreg;
13377                 lreg = check_reg(state, RHS(ins, 0), mask);
13378                 rreg = check_reg(state, RHS(ins, 1), mask);
13379                 lmask = arch_reg_regcm(state, lreg);
13380                 rmask = arch_reg_regcm(state, rreg);
13381                 mask = lmask & rmask;
13382                 fprintf(fp, "\tcmp %s, %s\n",
13383                         reg(state, RHS(ins, 1), mask),
13384                         reg(state, RHS(ins, 0), mask));
13385         }
13386 }
13387
13388 static void print_op_test(struct compile_state *state,
13389         struct triple *ins, FILE *fp)
13390 {
13391         unsigned mask;
13392         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13393         fprintf(fp, "\ttest %s, %s\n",
13394                 reg(state, RHS(ins, 0), mask),
13395                 reg(state, RHS(ins, 0), mask));
13396 }
13397
13398 static void print_op_branch(struct compile_state *state,
13399         struct triple *branch, FILE *fp)
13400 {
13401         const char *bop = "j";
13402         if (branch->op == OP_JMP) {
13403                 if (TRIPLE_RHS(branch->sizes) != 0) {
13404                         internal_error(state, branch, "jmp with condition?");
13405                 }
13406                 bop = "jmp";
13407         }
13408         else {
13409                 if (TRIPLE_RHS(branch->sizes) != 1) {
13410                         internal_error(state, branch, "jmpcc without condition?");
13411                 }
13412                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
13413                 if ((RHS(branch, 0)->op != OP_CMP) &&
13414                         (RHS(branch, 0)->op != OP_TEST)) {
13415                         internal_error(state, branch, "bad branch test");
13416                 }
13417 #warning "FIXME I have observed instructions between the test and branch instructions"
13418                 if (RHS(branch, 0)->next != branch) {
13419                         internal_error(state, branch, "branch does not follow test");
13420                 }
13421                 switch(branch->op) {
13422                 case OP_JMP_EQ:       bop = "jz";  break;
13423                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
13424                 case OP_JMP_SLESS:    bop = "jl";  break;
13425                 case OP_JMP_ULESS:    bop = "jb";  break;
13426                 case OP_JMP_SMORE:    bop = "jg";  break;
13427                 case OP_JMP_UMORE:    bop = "ja";  break;
13428                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
13429                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
13430                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
13431                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
13432                 default:
13433                         internal_error(state, branch, "Invalid branch op");
13434                         break;
13435                 }
13436                 
13437         }
13438         fprintf(fp, "\t%s L%lu\n",
13439                 bop, TARG(branch, 0)->u.cval);
13440 }
13441
13442 static void print_op_set(struct compile_state *state,
13443         struct triple *set, FILE *fp)
13444 {
13445         const char *sop = "set";
13446         if (TRIPLE_RHS(set->sizes) != 1) {
13447                 internal_error(state, set, "setcc without condition?");
13448         }
13449         check_reg(state, RHS(set, 0), REGCM_FLAGS);
13450         if ((RHS(set, 0)->op != OP_CMP) &&
13451                 (RHS(set, 0)->op != OP_TEST)) {
13452                 internal_error(state, set, "bad set test");
13453         }
13454         if (RHS(set, 0)->next != set) {
13455                 internal_error(state, set, "set does not follow test");
13456         }
13457         switch(set->op) {
13458         case OP_SET_EQ:       sop = "setz";  break;
13459         case OP_SET_NOTEQ:    sop = "setnz"; break;
13460         case OP_SET_SLESS:    sop = "setl";  break;
13461         case OP_SET_ULESS:    sop = "setb";  break;
13462         case OP_SET_SMORE:    sop = "setg";  break;
13463         case OP_SET_UMORE:    sop = "seta";  break;
13464         case OP_SET_SLESSEQ:  sop = "setle"; break;
13465         case OP_SET_ULESSEQ:  sop = "setbe"; break;
13466         case OP_SET_SMOREEQ:  sop = "setge"; break;
13467         case OP_SET_UMOREEQ:  sop = "setae"; break;
13468         default:
13469                 internal_error(state, set, "Invalid set op");
13470                 break;
13471         }
13472         fprintf(fp, "\t%s %s\n",
13473                 sop, reg(state, set, REGCM_GPR8));
13474 }
13475
13476 static void print_op_bit_scan(struct compile_state *state, 
13477         struct triple *ins, FILE *fp) 
13478 {
13479         const char *op;
13480         switch(ins->op) {
13481         case OP_BSF: op = "bsf"; break;
13482         case OP_BSR: op = "bsr"; break;
13483         default: 
13484                 internal_error(state, ins, "unknown bit scan");
13485                 op = 0;
13486                 break;
13487         }
13488         fprintf(fp, 
13489                 "\t%s %s, %s\n"
13490                 "\tjnz 1f\n"
13491                 "\tmovl $-1, %s\n"
13492                 "1:\n",
13493                 op,
13494                 reg(state, RHS(ins, 0), REGCM_GPR32),
13495                 reg(state, ins, REGCM_GPR32),
13496                 reg(state, ins, REGCM_GPR32));
13497 }
13498
13499 static void print_const(struct compile_state *state,
13500         struct triple *ins, FILE *fp)
13501 {
13502         switch(ins->op) {
13503         case OP_INTCONST:
13504                 switch(ins->type->type & TYPE_MASK) {
13505                 case TYPE_CHAR:
13506                 case TYPE_UCHAR:
13507                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
13508                         break;
13509                 case TYPE_SHORT:
13510                 case TYPE_USHORT:
13511                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
13512                         break;
13513                 case TYPE_INT:
13514                 case TYPE_UINT:
13515                 case TYPE_LONG:
13516                 case TYPE_ULONG:
13517                         fprintf(fp, ".int %lu\n", ins->u.cval);
13518                         break;
13519                 default:
13520                         internal_error(state, ins, "Unknown constant type");
13521                 }
13522                 break;
13523         case OP_BLOBCONST:
13524         {
13525                 unsigned char *blob;
13526                 size_t size, i;
13527                 size = size_of(state, ins->type);
13528                 blob = ins->u.blob;
13529                 for(i = 0; i < size; i++) {
13530                         fprintf(fp, ".byte 0x%02x\n",
13531                                 blob[i]);
13532                 }
13533                 break;
13534         }
13535 #if 0
13536         case OP_ADDRCONST:
13537                 fprintf(fp, ".int $L%lu+%lu",
13538                         ins->left->u.cval,
13539                         ins->u.cval);
13540                 break;
13541 #endif
13542         default:
13543                 internal_error(state, ins, "Unknown constant type");
13544                 break;
13545         }
13546 }
13547
13548 static void print_sdecl(struct compile_state *state,
13549         struct triple *ins, FILE *fp)
13550 {
13551         fprintf(fp, ".section \".rom.data\"\n");
13552         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
13553         fprintf(fp, "L%lu:\n", ins->u.cval);
13554         print_const(state, MISC(ins, 0), fp);
13555         fprintf(fp, ".section \".rom.text\"\n");
13556                 
13557 }
13558
13559 static void print_instruction(struct compile_state *state,
13560         struct triple *ins, FILE *fp)
13561 {
13562         /* Assumption: after I have exted the register allocator
13563          * everything is in a valid register. 
13564          */
13565         switch(ins->op) {
13566         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
13567         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
13568         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
13569         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
13570         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
13571         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
13572         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
13573         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
13574         case OP_POS:    break;
13575         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
13576         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
13577         case OP_INTCONST:
13578         case OP_ADDRCONST:
13579                 /* Don't generate anything here for constants */
13580         case OP_PHI:
13581                 /* Don't generate anything for variable declarations. */
13582                 break;
13583         case OP_SDECL:
13584                 print_sdecl(state, ins, fp);
13585                 break;
13586         case OP_WRITE: 
13587         case OP_COPY:   
13588                 print_op_move(state, ins, fp);
13589                 break;
13590         case OP_LOAD:
13591                 print_op_load(state, ins, fp);
13592                 break;
13593         case OP_STORE:
13594                 print_op_store(state, ins, fp);
13595                 break;
13596         case OP_SMUL:
13597                 print_op_smul(state, ins, fp);
13598                 break;
13599         case OP_CMP:    print_op_cmp(state, ins, fp); break;
13600         case OP_TEST:   print_op_test(state, ins, fp); break;
13601         case OP_JMP:
13602         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
13603         case OP_JMP_SLESS:   case OP_JMP_ULESS:
13604         case OP_JMP_SMORE:   case OP_JMP_UMORE:
13605         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
13606         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
13607                 print_op_branch(state, ins, fp);
13608                 break;
13609         case OP_SET_EQ:      case OP_SET_NOTEQ:
13610         case OP_SET_SLESS:   case OP_SET_ULESS:
13611         case OP_SET_SMORE:   case OP_SET_UMORE:
13612         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
13613         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
13614                 print_op_set(state, ins, fp);
13615                 break;
13616         case OP_INB:  case OP_INW:  case OP_INL:
13617                 print_op_in(state, ins, fp); 
13618                 break;
13619         case OP_OUTB: case OP_OUTW: case OP_OUTL:
13620                 print_op_out(state, ins, fp); 
13621                 break;
13622         case OP_BSF:
13623         case OP_BSR:
13624                 print_op_bit_scan(state, ins, fp);
13625                 break;
13626         case OP_RDMSR:
13627                 verify_lhs(state, ins);
13628                 fprintf(fp, "\trdmsr\n");
13629                 break;
13630         case OP_WRMSR:
13631                 fprintf(fp, "\twrmsr\n");
13632                 break;
13633         case OP_HLT:
13634                 fprintf(fp, "\thlt\n");
13635                 break;
13636         case OP_LABEL:
13637                 if (!ins->use) {
13638                         return;
13639                 }
13640                 fprintf(fp, "L%lu:\n", ins->u.cval);
13641                 break;
13642                 /* Ignore OP_PIECE */
13643         case OP_PIECE:
13644                 break;
13645                 /* Operations I am not yet certain how to handle */
13646         case OP_UMUL:
13647         case OP_SDIV: case OP_UDIV:
13648         case OP_SMOD: case OP_UMOD:
13649                 /* Operations that should never get here */
13650         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
13651         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
13652         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
13653         default:
13654                 internal_error(state, ins, "unknown op: %d %s",
13655                         ins->op, tops(ins->op));
13656                 break;
13657         }
13658 }
13659
13660 static void print_instructions(struct compile_state *state)
13661 {
13662         struct triple *first, *ins;
13663         int print_location;
13664         int last_line;
13665         int last_col;
13666         const char *last_filename;
13667         FILE *fp;
13668         print_location = 1;
13669         last_line = -1;
13670         last_col  = -1;
13671         last_filename = 0;
13672         fp = stdout;
13673         fprintf(fp, ".section \".rom.text\"\n");
13674         first = RHS(state->main_function, 0);
13675         ins = first;
13676         do {
13677                 if (print_location &&
13678                         ((last_filename != ins->filename) ||
13679                                 (last_line != ins->line) ||
13680                                 (last_col  != ins->col))) {
13681                         fprintf(fp, "\t/* %s:%d */\n",
13682                                 ins->filename, ins->line);
13683                         last_filename = ins->filename;
13684                         last_line = ins->line;
13685                         last_col  = ins->col;
13686                 }
13687
13688                 print_instruction(state, ins, fp);
13689                 ins = ins->next;
13690         } while(ins != first);
13691         
13692 }
13693 static void generate_code(struct compile_state *state)
13694 {
13695         generate_local_labels(state);
13696         print_instructions(state);
13697         
13698 }
13699
13700 static void print_tokens(struct compile_state *state)
13701 {
13702         struct token *tk;
13703         tk = &state->token[0];
13704         do {
13705 #if 1
13706                 token(state, 0);
13707 #else
13708                 next_token(state, 0);
13709 #endif
13710                 loc(stdout, state, 0);
13711                 printf("%s <- `%s'\n",
13712                         tokens[tk->tok],
13713                         tk->ident ? tk->ident->name :
13714                         tk->str_len ? tk->val.str : "");
13715                 
13716         } while(tk->tok != TOK_EOF);
13717 }
13718
13719 static void compile(char *filename, int debug, int opt)
13720 {
13721         int i;
13722         struct compile_state state;
13723         memset(&state, 0, sizeof(state));
13724         state.file = 0;
13725         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
13726                 memset(&state.token[i], 0, sizeof(state.token[i]));
13727                 state.token[i].tok = -1;
13728         }
13729         /* Remember the debug settings */
13730         state.debug = debug;
13731         state.optimize = opt;
13732         /* Prep the preprocessor */
13733         state.if_depth = 0;
13734         state.if_value = 0;
13735         /* register the C keywords */
13736         register_keywords(&state);
13737         /* register the keywords the macro preprocessor knows */
13738         register_macro_keywords(&state);
13739         /* Memorize where some special keywords are. */
13740         state.i_continue = lookup(&state, "continue", 8);
13741         state.i_break    = lookup(&state, "break", 5);
13742         /* Enter the globl definition scope */
13743         start_scope(&state);
13744         register_builtins(&state);
13745         compile_file(&state, filename, 1);
13746 #if 0
13747         print_tokens(&state);
13748 #endif  
13749         decls(&state);
13750         /* Exit the global definition scope */
13751         end_scope(&state);
13752
13753         /* Now that basic compilation has happened 
13754          * optimize the intermediate code 
13755          */
13756         optimize(&state);
13757         generate_code(&state);
13758         if (state.debug) {
13759                 fprintf(stderr, "done\n");
13760         }
13761 }
13762
13763 static void version(void)
13764 {
13765         printf("romcc " VERSION " released " RELEASE_DATE "\n");
13766 }
13767
13768 static void usage(void)
13769 {
13770         version();
13771         printf(
13772                 "Usage: romcc <source>.c\n"
13773                 "Compile a C source file without using ram\n"
13774         );
13775 }
13776
13777 static void arg_error(char *fmt, ...)
13778 {
13779         va_list args;
13780         va_start(args, fmt);
13781         vfprintf(stderr, fmt, args);
13782         va_end(args);
13783         usage();
13784         exit(1);
13785 }
13786
13787 int main(int argc, char **argv)
13788 {
13789         char *filename;
13790         int last_argc;
13791         int debug;
13792         int optimize;
13793         optimize = 0;
13794         debug = 0;
13795         last_argc = -1;
13796         while((argc > 1) && (argc != last_argc)) {
13797                 last_argc = argc;
13798                 if (strncmp(argv[1], "--debug=", 8) == 0) {
13799                         debug = atoi(argv[1] + 8);
13800                         argv++;
13801                         argc--;
13802                 }
13803                 else if ((strcmp(argv[1],"-O") == 0) ||
13804                         (strcmp(argv[1], "-O1") == 0)) {
13805                         optimize = 1;
13806                         argv++;
13807                         argc--;
13808                 }
13809                 else if (strcmp(argv[1],"-O2") == 0) {
13810                         optimize = 2;
13811                         argv++;
13812                         argc--;
13813                 }
13814         }
13815         if (argc != 2) {
13816                 arg_error("Wrong argument count %d\n", argc);
13817         }
13818         filename = argv[1];
13819         compile(filename, debug, optimize);
13820
13821         return 0;
13822 }