- Update romcc so that it more successfully spills registers to the xmm registers
[coreboot.git] / util / romcc / romcc.c
1 #include <stdarg.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <limits.h>
13
14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
16 #define DEBUG_SCC 0
17 #define DEBUG_CONSISTENCY 2
18 #define DEBUG_RANGE_CONFLICTS 0
19 #define DEBUG_COALESCING 0
20
21 #warning "FIXME boundary cases with small types in larger registers"
22 #warning "FIXME give clear error messages about unused variables"
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         int report_line;
221         const char *report_name;
222         const char *report_dir;
223 };
224 struct hash_entry;
225 struct token {
226         int tok;
227         struct hash_entry *ident;
228         int str_len;
229         union {
230                 ulong_t integer;
231                 const char *str;
232         } val;
233 };
234
235 /* I have two classes of types:
236  * Operational types.
237  * Logical types.  (The type the C standard says the operation is of)
238  *
239  * The operational types are:
240  * chars
241  * shorts
242  * ints
243  * longs
244  *
245  * floats
246  * doubles
247  * long doubles
248  *
249  * pointer
250  */
251
252
253 /* Machine model.
254  * No memory is useable by the compiler.
255  * There is no floating point support.
256  * All operations take place in general purpose registers.
257  * There is one type of general purpose register.
258  * Unsigned longs are stored in that general purpose register.
259  */
260
261 /* Operations on general purpose registers.
262  */
263
264 #define OP_SMUL       0
265 #define OP_UMUL       1
266 #define OP_SDIV       2
267 #define OP_UDIV       3
268 #define OP_SMOD       4
269 #define OP_UMOD       5
270 #define OP_ADD        6
271 #define OP_SUB        7
272 #define OP_SL         8
273 #define OP_USR        9
274 #define OP_SSR       10 
275 #define OP_AND       11 
276 #define OP_XOR       12
277 #define OP_OR        13
278 #define OP_POS       14 /* Dummy positive operator don't use it */
279 #define OP_NEG       15
280 #define OP_INVERT    16
281                      
282 #define OP_EQ        20
283 #define OP_NOTEQ     21
284 #define OP_SLESS     22
285 #define OP_ULESS     23
286 #define OP_SMORE     24
287 #define OP_UMORE     25
288 #define OP_SLESSEQ   26
289 #define OP_ULESSEQ   27
290 #define OP_SMOREEQ   28
291 #define OP_UMOREEQ   29
292                      
293 #define OP_LFALSE    30  /* Test if the expression is logically false */
294 #define OP_LTRUE     31  /* Test if the expression is logcially true */
295
296 #define OP_LOAD      32
297 #define OP_STORE     33
298
299 #define OP_NOOP      34
300
301 #define OP_MIN_CONST 50
302 #define OP_MAX_CONST 59
303 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
304 #define OP_INTCONST  50
305 /* For OP_INTCONST ->type holds the type.
306  * ->u.cval holds the constant value.
307  */
308 #define OP_BLOBCONST 51
309 /* For OP_BLOBCONST ->type holds the layout and size
310  * information.  u.blob holds a pointer to the raw binary
311  * data for the constant initializer.
312  */
313 #define OP_ADDRCONST 52
314 /* For OP_ADDRCONST ->type holds the type.
315  * MISC(0) holds the reference to the static variable.
316  * ->u.cval holds an offset from that value.
317  */
318
319 #define OP_WRITE     60 
320 /* OP_WRITE moves one pseudo register to another.
321  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
322  * RHS(0) holds the psuedo to move.
323  */
324
325 #define OP_READ      61
326 /* OP_READ reads the value of a variable and makes
327  * it available for the pseudo operation.
328  * Useful for things like def-use chains.
329  * RHS(0) holds points to the triple to read from.
330  */
331 #define OP_COPY      62
332 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
333  */
334 #define OP_PIECE     63
335 /* OP_PIECE returns one piece of a instruction that returns a structure.
336  * MISC(0) is the instruction
337  * u.cval is the LHS piece of the instruction to return.
338  */
339 #define OP_ASM       64
340 /* OP_ASM holds a sequence of assembly instructions, the result
341  * of a C asm directive.
342  * RHS(x) holds input value x to the assembly sequence.
343  * LHS(x) holds the output value x from the assembly sequence.
344  * u.blob holds the string of assembly instructions.
345  */
346
347 #define OP_DEREF     65
348 /* OP_DEREF generates an lvalue from a pointer.
349  * RHS(0) holds the pointer value.
350  * OP_DEREF serves as a place holder to indicate all necessary
351  * checks have been done to indicate a value is an lvalue.
352  */
353 #define OP_DOT       66
354 /* OP_DOT references a submember of a structure lvalue.
355  * RHS(0) holds the lvalue.
356  * ->u.field holds the name of the field we want.
357  *
358  * Not seen outside of expressions.
359  */
360 #define OP_VAL       67
361 /* OP_VAL returns the value of a subexpression of the current expression.
362  * Useful for operators that have side effects.
363  * RHS(0) holds the expression.
364  * MISC(0) holds the subexpression of RHS(0) that is the
365  * value of the expression.
366  *
367  * Not seen outside of expressions.
368  */
369 #define OP_LAND      68
370 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
371  * Not seen outside of expressions.
372  */
373 #define OP_LOR       69
374 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
375  * Not seen outside of expressions.
376  */
377 #define OP_COND      70
378 /* OP_CODE performas a C ? : operation. 
379  * RHS(0) holds the test.
380  * RHS(1) holds the expression to evaluate if the test returns true.
381  * RHS(2) holds the expression to evaluate if the test returns false.
382  * Not seen outside of expressions.
383  */
384 #define OP_COMMA     71
385 /* OP_COMMA performacs a C comma operation.
386  * That is RHS(0) is evaluated, then RHS(1)
387  * and the value of RHS(1) is returned.
388  * Not seen outside of expressions.
389  */
390
391 #define OP_CALL      72
392 /* OP_CALL performs a procedure call. 
393  * MISC(0) holds a pointer to the OP_LIST of a function
394  * RHS(x) holds argument x of a function
395  * 
396  * Currently not seen outside of expressions.
397  */
398 #define OP_VAL_VEC   74
399 /* OP_VAL_VEC is an array of triples that are either variable
400  * or values for a structure or an array.
401  * RHS(x) holds element x of the vector.
402  * triple->type->elements holds the size of the vector.
403  */
404
405 /* statements */
406 #define OP_LIST      80
407 /* OP_LIST Holds a list of statements, and a result value.
408  * RHS(0) holds the list of statements.
409  * MISC(0) holds the value of the statements.
410  */
411
412 #define OP_BRANCH    81 /* branch */
413 /* For branch instructions
414  * TARG(0) holds the branch target.
415  * RHS(0) if present holds the branch condition.
416  * ->next holds where to branch to if the branch is not taken.
417  * The branch target can only be a decl...
418  */
419
420 #define OP_LABEL     83
421 /* OP_LABEL is a triple that establishes an target for branches.
422  * ->use is the list of all branches that use this label.
423  */
424
425 #define OP_ADECL     84 
426 /* OP_DECL is a triple that establishes an lvalue for assignments.
427  * ->use is a list of statements that use the variable.
428  */
429
430 #define OP_SDECL     85
431 /* OP_SDECL is a triple that establishes a variable of static
432  * storage duration.
433  * ->use is a list of statements that use the variable.
434  * MISC(0) holds the initializer expression.
435  */
436
437
438 #define OP_PHI       86
439 /* OP_PHI is a triple used in SSA form code.  
440  * It is used when multiple code paths merge and a variable needs
441  * a single assignment from any of those code paths.
442  * The operation is a cross between OP_DECL and OP_WRITE, which
443  * is what OP_PHI is geneared from.
444  * 
445  * RHS(x) points to the value from code path x
446  * The number of RHS entries is the number of control paths into the block
447  * in which OP_PHI resides.  The elements of the array point to point
448  * to the variables OP_PHI is derived from.
449  *
450  * MISC(0) holds a pointer to the orginal OP_DECL node.
451  */
452
453 /* Architecture specific instructions */
454 #define OP_CMP         100
455 #define OP_TEST        101
456 #define OP_SET_EQ      102
457 #define OP_SET_NOTEQ   103
458 #define OP_SET_SLESS   104
459 #define OP_SET_ULESS   105
460 #define OP_SET_SMORE   106
461 #define OP_SET_UMORE   107
462 #define OP_SET_SLESSEQ 108
463 #define OP_SET_ULESSEQ 109
464 #define OP_SET_SMOREEQ 110
465 #define OP_SET_UMOREEQ 111
466
467 #define OP_JMP         112
468 #define OP_JMP_EQ      113
469 #define OP_JMP_NOTEQ   114
470 #define OP_JMP_SLESS   115
471 #define OP_JMP_ULESS   116
472 #define OP_JMP_SMORE   117
473 #define OP_JMP_UMORE   118
474 #define OP_JMP_SLESSEQ 119
475 #define OP_JMP_ULESSEQ 120
476 #define OP_JMP_SMOREEQ 121
477 #define OP_JMP_UMOREEQ 122
478
479 /* Builtin operators that it is just simpler to use the compiler for */
480 #define OP_INB         130
481 #define OP_INW         131
482 #define OP_INL         132
483 #define OP_OUTB        133
484 #define OP_OUTW        134
485 #define OP_OUTL        135
486 #define OP_BSF         136
487 #define OP_BSR         137
488 #define OP_RDMSR       138
489 #define OP_WRMSR       139
490 #define OP_HLT         140
491
492 struct op_info {
493         const char *name;
494         unsigned flags;
495 #define PURE   1
496 #define IMPURE 2
497 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
498 #define DEF    4
499 #define BLOCK  8 /* Triple stores the current block */
500         unsigned char lhs, rhs, misc, targ;
501 };
502
503 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
504         .name = (NAME), \
505         .flags = (FLAGS), \
506         .lhs = (LHS), \
507         .rhs = (RHS), \
508         .misc = (MISC), \
509         .targ = (TARG), \
510          }
511 static const struct op_info table_ops[] = {
512 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
513 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
514 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
515 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
516 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
517 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
518 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
519 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
520 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
521 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
522 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
523 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
524 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
525 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
526 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
527 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
528 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
529
530 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
531 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
532 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
533 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
534 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
535 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
536 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
537 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
538 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
539 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
540 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
541 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
542
543 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
544 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE | BLOCK , "store"),
545
546 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
547
548 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
549 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
550 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
551
552 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE | BLOCK, "write"),
553 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
554 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
555 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
556 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
557 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
558 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
559
560 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
561 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
562 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
563 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
564 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
565 /* Call is special most it can stand in for anything so it depends on context */
566 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
567 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
568 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
569
570 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
571 /* The number of targets for OP_BRANCH depends on context */
572 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
573 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
574 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
575 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
576 /* The number of RHS elements of OP_PHI depend upon context */
577 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
578
579 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
580 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
581 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
582 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
583 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
584 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
585 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
586 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
587 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
588 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
589 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
590 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
591 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
592 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
593 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
594 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
595 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
596 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
597 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
598 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
599 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
600 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
601 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
602
603 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
604 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
605 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
606 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
607 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
608 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
609 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
610 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
611 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
612 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
613 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
614 };
615 #undef OP
616 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
617
618 static const char *tops(int index) 
619 {
620         static const char unknown[] = "unknown op";
621         if (index < 0) {
622                 return unknown;
623         }
624         if (index > OP_MAX) {
625                 return unknown;
626         }
627         return table_ops[index].name;
628 }
629
630 struct asm_info;
631 struct triple;
632 struct block;
633 struct triple_set {
634         struct triple_set *next;
635         struct triple *member;
636 };
637
638 #define MAX_LHS  15
639 #define MAX_RHS  15
640 #define MAX_MISC 15
641 #define MAX_TARG 15
642
643 struct occurance {
644         int count;
645         const char *filename;
646         const char *function;
647         int line;
648         int col;
649         struct occurance *parent;
650 };
651 struct triple {
652         struct triple *next, *prev;
653         struct triple_set *use;
654         struct type *type;
655         unsigned char op;
656         unsigned char template_id;
657         unsigned short sizes;
658 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
659 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
660 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
661 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
662 #define TRIPLE_SIZE(SIZES) \
663         ((((SIZES) >> 0) & 0x0f) + \
664         (((SIZES) >>  4) & 0x0f) + \
665         (((SIZES) >>  8) & 0x0f) + \
666         (((SIZES) >> 12) & 0x0f))
667 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
668         ((((LHS) & 0x0f) <<  0) | \
669         (((RHS) & 0x0f)  <<  4) | \
670         (((MISC) & 0x0f) <<  8) | \
671         (((TARG) & 0x0f) << 12))
672 #define TRIPLE_LHS_OFF(SIZES)  (0)
673 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
674 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
675 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
676 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
677 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
678 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
679 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
680         unsigned id; /* A scratch value and finally the register */
681 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
682 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
683 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
684         struct occurance *occurance;
685         union {
686                 ulong_t cval;
687                 struct block  *block;
688                 void *blob;
689                 struct hash_entry *field;
690                 struct asm_info *ainfo;
691         } u;
692         struct triple *param[2];
693 };
694
695 struct reg_info {
696         unsigned reg;
697         unsigned regcm;
698 };
699 struct ins_template {
700         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
701 };
702
703 struct asm_info {
704         struct ins_template tmpl;
705         char *str;
706 };
707
708 struct block_set {
709         struct block_set *next;
710         struct block *member;
711 };
712 struct block {
713         struct block *work_next;
714         struct block *left, *right;
715         struct triple *first, *last;
716         int users;
717         struct block_set *use;
718         struct block_set *idominates;
719         struct block_set *domfrontier;
720         struct block *idom;
721         struct block_set *ipdominates;
722         struct block_set *ipdomfrontier;
723         struct block *ipdom;
724         int vertex;
725         
726 };
727
728 struct symbol {
729         struct symbol *next;
730         struct hash_entry *ident;
731         struct triple *def;
732         struct type *type;
733         int scope_depth;
734 };
735
736 struct macro {
737         struct hash_entry *ident;
738         char *buf;
739         int buf_len;
740 };
741
742 struct hash_entry {
743         struct hash_entry *next;
744         const char *name;
745         int name_len;
746         int tok;
747         struct macro *sym_define;
748         struct symbol *sym_label;
749         struct symbol *sym_struct;
750         struct symbol *sym_ident;
751 };
752
753 #define HASH_TABLE_SIZE 2048
754
755 struct compile_state {
756         const char *label_prefix;
757         const char *ofilename;
758         FILE *output;
759         struct file_state *file;
760         struct occurance *last_occurance;
761         const char *function;
762         struct token token[4];
763         struct hash_entry *hash_table[HASH_TABLE_SIZE];
764         struct hash_entry *i_continue;
765         struct hash_entry *i_break;
766         int scope_depth;
767         int if_depth, if_value;
768         int macro_line;
769         struct file_state *macro_file;
770         struct triple *main_function;
771         struct block *first_block, *last_block;
772         int last_vertex;
773         int cpu;
774         int debug;
775         int optimize;
776 };
777
778 /* visibility global/local */
779 /* static/auto duration */
780 /* typedef, register, inline */
781 #define STOR_SHIFT         0
782 #define STOR_MASK     0x000f
783 /* Visibility */
784 #define STOR_GLOBAL   0x0001
785 /* Duration */
786 #define STOR_PERM     0x0002
787 /* Storage specifiers */
788 #define STOR_AUTO     0x0000
789 #define STOR_STATIC   0x0002
790 #define STOR_EXTERN   0x0003
791 #define STOR_REGISTER 0x0004
792 #define STOR_TYPEDEF  0x0008
793 #define STOR_INLINE   0x000c
794
795 #define QUAL_SHIFT         4
796 #define QUAL_MASK     0x0070
797 #define QUAL_NONE     0x0000
798 #define QUAL_CONST    0x0010
799 #define QUAL_VOLATILE 0x0020
800 #define QUAL_RESTRICT 0x0040
801
802 #define TYPE_SHIFT         8
803 #define TYPE_MASK     0x1f00
804 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
805 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
806 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
807 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
808 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
809 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
810 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
811 #define TYPE_DEFAULT  0x0000
812 #define TYPE_VOID     0x0100
813 #define TYPE_CHAR     0x0200
814 #define TYPE_UCHAR    0x0300
815 #define TYPE_SHORT    0x0400
816 #define TYPE_USHORT   0x0500
817 #define TYPE_INT      0x0600
818 #define TYPE_UINT     0x0700
819 #define TYPE_LONG     0x0800
820 #define TYPE_ULONG    0x0900
821 #define TYPE_LLONG    0x0a00 /* long long */
822 #define TYPE_ULLONG   0x0b00
823 #define TYPE_FLOAT    0x0c00
824 #define TYPE_DOUBLE   0x0d00
825 #define TYPE_LDOUBLE  0x0e00 /* long double */
826 #define TYPE_STRUCT   0x1000
827 #define TYPE_ENUM     0x1100
828 #define TYPE_POINTER  0x1200 
829 /* For TYPE_POINTER:
830  * type->left holds the type pointed to.
831  */
832 #define TYPE_FUNCTION 0x1300 
833 /* For TYPE_FUNCTION:
834  * type->left holds the return type.
835  * type->right holds the...
836  */
837 #define TYPE_PRODUCT  0x1400
838 /* TYPE_PRODUCT is a basic building block when defining structures
839  * type->left holds the type that appears first in memory.
840  * type->right holds the type that appears next in memory.
841  */
842 #define TYPE_OVERLAP  0x1500
843 /* TYPE_OVERLAP is a basic building block when defining unions
844  * type->left and type->right holds to types that overlap
845  * each other in memory.
846  */
847 #define TYPE_ARRAY    0x1600
848 /* TYPE_ARRAY is a basic building block when definitng arrays.
849  * type->left holds the type we are an array of.
850  * type-> holds the number of elements.
851  */
852
853 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
854
855 struct type {
856         unsigned int type;
857         struct type *left, *right;
858         ulong_t elements;
859         struct hash_entry *field_ident;
860         struct hash_entry *type_ident;
861 };
862
863 #define MAX_REGISTERS      75
864 #define MAX_REG_EQUIVS     16
865 #define REGISTER_BITS      16
866 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
867 #define TEMPLATE_BITS      6
868 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
869 #define MAX_REGC           12
870 #define REG_UNSET          0
871 #define REG_UNNEEDED       1
872 #define REG_VIRT0          (MAX_REGISTERS + 0)
873 #define REG_VIRT1          (MAX_REGISTERS + 1)
874 #define REG_VIRT2          (MAX_REGISTERS + 2)
875 #define REG_VIRT3          (MAX_REGISTERS + 3)
876 #define REG_VIRT4          (MAX_REGISTERS + 4)
877 #define REG_VIRT5          (MAX_REGISTERS + 5)
878 #define REG_VIRT6          (MAX_REGISTERS + 5)
879 #define REG_VIRT7          (MAX_REGISTERS + 5)
880 #define REG_VIRT8          (MAX_REGISTERS + 5)
881 #define REG_VIRT9          (MAX_REGISTERS + 5)
882
883 /* Provision for 8 register classes */
884 #define REG_SHIFT  0
885 #define REGC_SHIFT REGISTER_BITS
886 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
887 #define REG_MASK (MAX_VIRT_REGISTERS -1)
888 #define ID_REG(ID)              ((ID) & REG_MASK)
889 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
890 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
891 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
892 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
893                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
894
895 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
896 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
897 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
898 static void arch_reg_equivs(
899         struct compile_state *state, unsigned *equiv, int reg);
900 static int arch_select_free_register(
901         struct compile_state *state, char *used, int classes);
902 static unsigned arch_regc_size(struct compile_state *state, int class);
903 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
904 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
905 static const char *arch_reg_str(int reg);
906 static struct reg_info arch_reg_constraint(
907         struct compile_state *state, struct type *type, const char *constraint);
908 static struct reg_info arch_reg_clobber(
909         struct compile_state *state, const char *clobber);
910 static struct reg_info arch_reg_lhs(struct compile_state *state, 
911         struct triple *ins, int index);
912 static struct reg_info arch_reg_rhs(struct compile_state *state, 
913         struct triple *ins, int index);
914 static struct triple *transform_to_arch_instruction(
915         struct compile_state *state, struct triple *ins);
916
917
918
919 #define DEBUG_ABORT_ON_ERROR    0x0001
920 #define DEBUG_INTERMEDIATE_CODE 0x0002
921 #define DEBUG_CONTROL_FLOW      0x0004
922 #define DEBUG_BASIC_BLOCKS      0x0008
923 #define DEBUG_FDOMINATORS       0x0010
924 #define DEBUG_RDOMINATORS       0x0020
925 #define DEBUG_TRIPLES           0x0040
926 #define DEBUG_INTERFERENCE      0x0080
927 #define DEBUG_ARCH_CODE         0x0100
928 #define DEBUG_CODE_ELIMINATION  0x0200
929 #define DEBUG_INSERTED_COPIES   0x0400
930
931 #define GLOBAL_SCOPE_DEPTH   1
932 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
933
934 static void compile_file(struct compile_state *old_state, const char *filename, int local);
935
936 static void do_cleanup(struct compile_state *state)
937 {
938         if (state->output) {
939                 fclose(state->output);
940                 unlink(state->ofilename);
941         }
942 }
943
944 static int get_col(struct file_state *file)
945 {
946         int col;
947         char *ptr, *end;
948         ptr = file->line_start;
949         end = file->pos;
950         for(col = 0; ptr < end; ptr++) {
951                 if (*ptr != '\t') {
952                         col++;
953                 } 
954                 else {
955                         col = (col & ~7) + 8;
956                 }
957         }
958         return col;
959 }
960
961 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
962 {
963         int col;
964         if (triple) {
965                 struct occurance *spot;
966                 spot = triple->occurance;
967                 while(spot->parent) {
968                         spot = spot->parent;
969                 }
970                 fprintf(fp, "%s:%d.%d: ", 
971                         spot->filename, spot->line, spot->col);
972                 return;
973         }
974         if (!state->file) {
975                 return;
976         }
977         col = get_col(state->file);
978         fprintf(fp, "%s:%d.%d: ", 
979                 state->file->report_name, state->file->report_line, col);
980 }
981
982 static void __internal_error(struct compile_state *state, struct triple *ptr, 
983         char *fmt, ...)
984 {
985         va_list args;
986         va_start(args, fmt);
987         loc(stderr, state, ptr);
988         if (ptr) {
989                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
990         }
991         fprintf(stderr, "Internal compiler error: ");
992         vfprintf(stderr, fmt, args);
993         fprintf(stderr, "\n");
994         va_end(args);
995         do_cleanup(state);
996         abort();
997 }
998
999
1000 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
1001         char *fmt, ...)
1002 {
1003         va_list args;
1004         va_start(args, fmt);
1005         loc(stderr, state, ptr);
1006         fprintf(stderr, "Internal compiler warning: ");
1007         vfprintf(stderr, fmt, args);
1008         fprintf(stderr, "\n");
1009         va_end(args);
1010 }
1011
1012
1013
1014 static void __error(struct compile_state *state, struct triple *ptr, 
1015         char *fmt, ...)
1016 {
1017         va_list args;
1018         va_start(args, fmt);
1019         loc(stderr, state, ptr);
1020         vfprintf(stderr, fmt, args);
1021         va_end(args);
1022         fprintf(stderr, "\n");
1023         do_cleanup(state);
1024         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1025                 abort();
1026         }
1027         exit(1);
1028 }
1029
1030 static void __warning(struct compile_state *state, struct triple *ptr, 
1031         char *fmt, ...)
1032 {
1033         va_list args;
1034         va_start(args, fmt);
1035         loc(stderr, state, ptr);
1036         fprintf(stderr, "warning: "); 
1037         vfprintf(stderr, fmt, args);
1038         fprintf(stderr, "\n");
1039         va_end(args);
1040 }
1041
1042 #if DEBUG_ERROR_MESSAGES 
1043 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1044 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1045 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1046 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1047 #else
1048 #  define internal_error __internal_error
1049 #  define internal_warning __internal_warning
1050 #  define error __error
1051 #  define warning __warning
1052 #endif
1053 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1054
1055 static void valid_op(struct compile_state *state, int op)
1056 {
1057         char *fmt = "invalid op: %d";
1058         if (op >= OP_MAX) {
1059                 internal_error(state, 0, fmt, op);
1060         }
1061         if (op < 0) {
1062                 internal_error(state, 0, fmt, op);
1063         }
1064 }
1065
1066 static void valid_ins(struct compile_state *state, struct triple *ptr)
1067 {
1068         valid_op(state, ptr->op);
1069 }
1070
1071 static void process_trigraphs(struct compile_state *state)
1072 {
1073         char *src, *dest, *end;
1074         struct file_state *file;
1075         file = state->file;
1076         src = dest = file->buf;
1077         end = file->buf + file->size;
1078         while((end - src) >= 3) {
1079                 if ((src[0] == '?') && (src[1] == '?')) {
1080                         int c = -1;
1081                         switch(src[2]) {
1082                         case '=': c = '#'; break;
1083                         case '/': c = '\\'; break;
1084                         case '\'': c = '^'; break;
1085                         case '(': c = '['; break;
1086                         case ')': c = ']'; break;
1087                         case '!': c = '!'; break;
1088                         case '<': c = '{'; break;
1089                         case '>': c = '}'; break;
1090                         case '-': c = '~'; break;
1091                         }
1092                         if (c != -1) {
1093                                 *dest++ = c;
1094                                 src += 3;
1095                         }
1096                         else {
1097                                 *dest++ = *src++;
1098                         }
1099                 }
1100                 else {
1101                         *dest++ = *src++;
1102                 }
1103         }
1104         while(src != end) {
1105                 *dest++ = *src++;
1106         }
1107         file->size = dest - file->buf;
1108 }
1109
1110 static void splice_lines(struct compile_state *state)
1111 {
1112         char *src, *dest, *end;
1113         struct file_state *file;
1114         file = state->file;
1115         src = dest = file->buf;
1116         end = file->buf + file->size;
1117         while((end - src) >= 2) {
1118                 if ((src[0] == '\\') && (src[1] == '\n')) {
1119                         src += 2;
1120                 }
1121                 else {
1122                         *dest++ = *src++;
1123                 }
1124         }
1125         while(src != end) {
1126                 *dest++ = *src++;
1127         }
1128         file->size = dest - file->buf;
1129 }
1130
1131 static struct type void_type;
1132 static void use_triple(struct triple *used, struct triple *user)
1133 {
1134         struct triple_set **ptr, *new;
1135         if (!used)
1136                 return;
1137         if (!user)
1138                 return;
1139         ptr = &used->use;
1140         while(*ptr) {
1141                 if ((*ptr)->member == user) {
1142                         return;
1143                 }
1144                 ptr = &(*ptr)->next;
1145         }
1146         /* Append new to the head of the list, 
1147          * copy_func and rename_block_variables
1148          * depends on this.
1149          */
1150         new = xcmalloc(sizeof(*new), "triple_set");
1151         new->member = user;
1152         new->next   = used->use;
1153         used->use   = new;
1154 }
1155
1156 static void unuse_triple(struct triple *used, struct triple *unuser)
1157 {
1158         struct triple_set *use, **ptr;
1159         if (!used) {
1160                 return;
1161         }
1162         ptr = &used->use;
1163         while(*ptr) {
1164                 use = *ptr;
1165                 if (use->member == unuser) {
1166                         *ptr = use->next;
1167                         xfree(use);
1168                 }
1169                 else {
1170                         ptr = &use->next;
1171                 }
1172         }
1173 }
1174
1175 static void push_triple(struct triple *used, struct triple *user)
1176 {
1177         struct triple_set *new;
1178         if (!used)
1179                 return;
1180         if (!user)
1181                 return;
1182         /* Append new to the head of the list,
1183          * it's the only sensible behavoir for a stack.
1184          */
1185         new = xcmalloc(sizeof(*new), "triple_set");
1186         new->member = user;
1187         new->next   = used->use;
1188         used->use   = new;
1189 }
1190
1191 static void pop_triple(struct triple *used, struct triple *unuser)
1192 {
1193         struct triple_set *use, **ptr;
1194         ptr = &used->use;
1195         while(*ptr) {
1196                 use = *ptr;
1197                 if (use->member == unuser) {
1198                         *ptr = use->next;
1199                         xfree(use);
1200                         /* Only free one occurance from the stack */
1201                         return;
1202                 }
1203                 else {
1204                         ptr = &use->next;
1205                 }
1206         }
1207 }
1208
1209 static void put_occurance(struct occurance *occurance)
1210 {
1211         occurance->count -= 1;
1212         if (occurance->count <= 0) {
1213                 if (occurance->parent) {
1214                         put_occurance(occurance->parent);
1215                 }
1216                 xfree(occurance);
1217         }
1218 }
1219
1220 static void get_occurance(struct occurance *occurance)
1221 {
1222         occurance->count += 1;
1223 }
1224
1225
1226 static struct occurance *new_occurance(struct compile_state *state)
1227 {
1228         struct occurance *result, *last;
1229         const char *filename;
1230         const char *function;
1231         int line, col;
1232
1233         function = "";
1234         filename = 0;
1235         line = 0;
1236         col  = 0;
1237         if (state->file) {
1238                 filename = state->file->report_name;
1239                 line     = state->file->report_line;
1240                 col      = get_col(state->file);
1241         }
1242         if (state->function) {
1243                 function = state->function;
1244         }
1245         last = state->last_occurance;
1246         if (last &&
1247                 (last->col == col) &&
1248                 (last->line == line) &&
1249                 (last->function == function) &&
1250                 (strcmp(last->filename, filename) == 0)) {
1251                 get_occurance(last);
1252                 return last;
1253         }
1254         if (last) {
1255                 state->last_occurance = 0;
1256                 put_occurance(last);
1257         }
1258         result = xmalloc(sizeof(*result), "occurance");
1259         result->count    = 2;
1260         result->filename = filename;
1261         result->function = function;
1262         result->line     = line;
1263         result->col      = col;
1264         result->parent   = 0;
1265         state->last_occurance = result;
1266         return result;
1267 }
1268
1269 static struct occurance *inline_occurance(struct compile_state *state,
1270         struct occurance *new, struct occurance *orig)
1271 {
1272         struct occurance *result, *last;
1273         last = state->last_occurance;
1274         if (last &&
1275                 (last->parent   == orig) &&
1276                 (last->col      == new->col) &&
1277                 (last->line     == new->line) &&
1278                 (last->function == new->function) &&
1279                 (last->filename == new->filename)) {
1280                 get_occurance(last);
1281                 return last;
1282         }
1283         if (last) {
1284                 state->last_occurance = 0;
1285                 put_occurance(last);
1286         }
1287         get_occurance(orig);
1288         result = xmalloc(sizeof(*result), "occurance");
1289         result->count    = 2;
1290         result->filename = new->filename;
1291         result->function = new->function;
1292         result->line     = new->line;
1293         result->col      = new->col;
1294         result->parent   = orig;
1295         state->last_occurance = result;
1296         return result;
1297 }
1298         
1299
1300 static struct occurance dummy_occurance = {
1301         .count    = 2,
1302         .filename = __FILE__,
1303         .function = "",
1304         .line     = __LINE__,
1305         .col      = 0,
1306         .parent   = 0,
1307 };
1308
1309 /* The zero triple is used as a place holder when we are removing pointers
1310  * from a triple.  Having allows certain sanity checks to pass even
1311  * when the original triple that was pointed to is gone.
1312  */
1313 static struct triple zero_triple = {
1314         .next      = &zero_triple,
1315         .prev      = &zero_triple,
1316         .use       = 0,
1317         .op        = OP_INTCONST,
1318         .sizes     = TRIPLE_SIZES(0, 0, 0, 0),
1319         .id        = -1, /* An invalid id */
1320         .u = { .cval   = 0, },
1321         .occurance = &dummy_occurance,
1322         .param { [0] = 0, [1] = 0, },
1323 };
1324
1325
1326 static unsigned short triple_sizes(struct compile_state *state,
1327         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1328 {
1329         int lhs, rhs, misc, targ;
1330         valid_op(state, op);
1331         lhs = table_ops[op].lhs;
1332         rhs = table_ops[op].rhs;
1333         misc = table_ops[op].misc;
1334         targ = table_ops[op].targ;
1335         
1336         
1337         if (op == OP_CALL) {
1338                 struct type *param;
1339                 rhs = 0;
1340                 param = type->right;
1341                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1342                         rhs++;
1343                         param = param->right;
1344                 }
1345                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1346                         rhs++;
1347                 }
1348                 lhs = 0;
1349                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1350                         lhs = type->left->elements;
1351                 }
1352         }
1353         else if (op == OP_VAL_VEC) {
1354                 rhs = type->elements;
1355         }
1356         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1357                 rhs = rhs_wanted;
1358         }
1359         else if (op == OP_ASM) {
1360                 rhs = rhs_wanted;
1361                 lhs = lhs_wanted;
1362         }
1363         if ((rhs < 0) || (rhs > MAX_RHS)) {
1364                 internal_error(state, 0, "bad rhs");
1365         }
1366         if ((lhs < 0) || (lhs > MAX_LHS)) {
1367                 internal_error(state, 0, "bad lhs");
1368         }
1369         if ((misc < 0) || (misc > MAX_MISC)) {
1370                 internal_error(state, 0, "bad misc");
1371         }
1372         if ((targ < 0) || (targ > MAX_TARG)) {
1373                 internal_error(state, 0, "bad targs");
1374         }
1375         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1376 }
1377
1378 static struct triple *alloc_triple(struct compile_state *state, 
1379         int op, struct type *type, int lhs, int rhs,
1380         struct occurance *occurance)
1381 {
1382         size_t size, sizes, extra_count, min_count;
1383         struct triple *ret;
1384         sizes = triple_sizes(state, op, type, lhs, rhs);
1385
1386         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1387         extra_count = TRIPLE_SIZE(sizes);
1388         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1389
1390         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1391         ret = xcmalloc(size, "tripple");
1392         ret->op        = op;
1393         ret->sizes     = sizes;
1394         ret->type      = type;
1395         ret->next      = ret;
1396         ret->prev      = ret;
1397         ret->occurance = occurance;
1398         return ret;
1399 }
1400
1401 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1402 {
1403         struct triple *dup;
1404         int src_lhs, src_rhs, src_size;
1405         src_lhs = TRIPLE_LHS(src->sizes);
1406         src_rhs = TRIPLE_RHS(src->sizes);
1407         src_size = TRIPLE_SIZE(src->sizes);
1408         get_occurance(src->occurance);
1409         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1410                 src->occurance);
1411         memcpy(dup, src, sizeof(*src));
1412         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1413         return dup;
1414 }
1415
1416 static struct triple *new_triple(struct compile_state *state, 
1417         int op, struct type *type, int lhs, int rhs)
1418 {
1419         struct triple *ret;
1420         struct occurance *occurance;
1421         occurance = new_occurance(state);
1422         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1423         return ret;
1424 }
1425
1426 static struct triple *build_triple(struct compile_state *state, 
1427         int op, struct type *type, struct triple *left, struct triple *right,
1428         struct occurance *occurance)
1429 {
1430         struct triple *ret;
1431         size_t count;
1432         ret = alloc_triple(state, op, type, -1, -1, occurance);
1433         count = TRIPLE_SIZE(ret->sizes);
1434         if (count > 0) {
1435                 ret->param[0] = left;
1436         }
1437         if (count > 1) {
1438                 ret->param[1] = right;
1439         }
1440         return ret;
1441 }
1442
1443 static struct triple *triple(struct compile_state *state, 
1444         int op, struct type *type, struct triple *left, struct triple *right)
1445 {
1446         struct triple *ret;
1447         size_t count;
1448         ret = new_triple(state, op, type, -1, -1);
1449         count = TRIPLE_SIZE(ret->sizes);
1450         if (count >= 1) {
1451                 ret->param[0] = left;
1452         }
1453         if (count >= 2) {
1454                 ret->param[1] = right;
1455         }
1456         return ret;
1457 }
1458
1459 static struct triple *branch(struct compile_state *state, 
1460         struct triple *targ, struct triple *test)
1461 {
1462         struct triple *ret;
1463         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1464         if (test) {
1465                 RHS(ret, 0) = test;
1466         }
1467         TARG(ret, 0) = targ;
1468         /* record the branch target was used */
1469         if (!targ || (targ->op != OP_LABEL)) {
1470                 internal_error(state, 0, "branch not to label");
1471                 use_triple(targ, ret);
1472         }
1473         return ret;
1474 }
1475
1476
1477 static void insert_triple(struct compile_state *state,
1478         struct triple *first, struct triple *ptr)
1479 {
1480         if (ptr) {
1481                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1482                         internal_error(state, ptr, "expression already used");
1483                 }
1484                 ptr->next       = first;
1485                 ptr->prev       = first->prev;
1486                 ptr->prev->next = ptr;
1487                 ptr->next->prev = ptr;
1488                 if ((ptr->prev->op == OP_BRANCH) && 
1489                         TRIPLE_RHS(ptr->prev->sizes)) {
1490                         unuse_triple(first, ptr->prev);
1491                         use_triple(ptr, ptr->prev);
1492                 }
1493         }
1494 }
1495
1496 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1497 {
1498         /* This function is used to determine if u.block 
1499          * is utilized to store the current block number.
1500          */
1501         int stores_block;
1502         valid_ins(state, ins);
1503         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1504         return stores_block;
1505 }
1506
1507 static struct block *block_of_triple(struct compile_state *state, 
1508         struct triple *ins)
1509 {
1510         struct triple *first;
1511         first = RHS(state->main_function, 0);
1512         while(ins != first && !triple_stores_block(state, ins)) {
1513                 if (ins == ins->prev) {
1514                         internal_error(state, 0, "ins == ins->prev?");
1515                 }
1516                 ins = ins->prev;
1517         }
1518         if (!triple_stores_block(state, ins)) {
1519                 internal_error(state, ins, "Cannot find block");
1520         }
1521         return ins->u.block;
1522 }
1523
1524 static struct triple *pre_triple(struct compile_state *state,
1525         struct triple *base,
1526         int op, struct type *type, struct triple *left, struct triple *right)
1527 {
1528         struct block *block;
1529         struct triple *ret;
1530         /* If I am an OP_PIECE jump to the real instruction */
1531         if (base->op == OP_PIECE) {
1532                 base = MISC(base, 0);
1533         }
1534         block = block_of_triple(state, base);
1535         get_occurance(base->occurance);
1536         ret = build_triple(state, op, type, left, right, base->occurance);
1537         if (triple_stores_block(state, ret)) {
1538                 ret->u.block = block;
1539         }
1540         insert_triple(state, base, ret);
1541         if (block->first == base) {
1542                 block->first = ret;
1543         }
1544         return ret;
1545 }
1546
1547 static struct triple *post_triple(struct compile_state *state,
1548         struct triple *base,
1549         int op, struct type *type, struct triple *left, struct triple *right)
1550 {
1551         struct block *block;
1552         struct triple *ret;
1553         int zlhs;
1554         /* If I am an OP_PIECE jump to the real instruction */
1555         if (base->op == OP_PIECE) {
1556                 base = MISC(base, 0);
1557         }
1558         /* If I have a left hand side skip over it */
1559         zlhs = TRIPLE_LHS(base->sizes);
1560         if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1561                 base = LHS(base, zlhs - 1);
1562         }
1563
1564         block = block_of_triple(state, base);
1565         get_occurance(base->occurance);
1566         ret = build_triple(state, op, type, left, right, base->occurance);
1567         if (triple_stores_block(state, ret)) {
1568                 ret->u.block = block;
1569         }
1570         insert_triple(state, base->next, ret);
1571         if (block->last == base) {
1572                 block->last = ret;
1573         }
1574         return ret;
1575 }
1576
1577 static struct triple *label(struct compile_state *state)
1578 {
1579         /* Labels don't get a type */
1580         struct triple *result;
1581         result = triple(state, OP_LABEL, &void_type, 0, 0);
1582         return result;
1583 }
1584
1585 static void display_triple(FILE *fp, struct triple *ins)
1586 {
1587         struct occurance *ptr;
1588         const char *reg;
1589         char pre, post;
1590         pre = post = ' ';
1591         if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1592                 pre = '^';
1593         }
1594         if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1595                 post = 'v';
1596         }
1597         reg = arch_reg_str(ID_REG(ins->id));
1598         if (ins->op == OP_INTCONST) {
1599                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx>         ",
1600                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1601                         ins->u.cval);
1602         }
1603         else if (ins->op == OP_ADDRCONST) {
1604                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1605                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1606                         MISC(ins, 0), ins->u.cval);
1607         }
1608         else {
1609                 int i, count;
1610                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s", 
1611                         ins, pre, post, reg, ins->template_id, tops(ins->op));
1612                 count = TRIPLE_SIZE(ins->sizes);
1613                 for(i = 0; i < count; i++) {
1614                         fprintf(fp, " %-10p", ins->param[i]);
1615                 }
1616                 for(; i < 2; i++) {
1617                         fprintf(fp, "           ");
1618                 }
1619         }
1620         fprintf(fp, " @");
1621         for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1622                 fprintf(fp, " %s,%s:%d.%d",
1623                         ptr->function, 
1624                         ptr->filename,
1625                         ptr->line, 
1626                         ptr->col);
1627         }
1628         fprintf(fp, "\n");
1629         fflush(fp);
1630 }
1631
1632 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1633 {
1634         /* Does the triple have no side effects.
1635          * I.e. Rexecuting the triple with the same arguments 
1636          * gives the same value.
1637          */
1638         unsigned pure;
1639         valid_ins(state, ins);
1640         pure = PURE_BITS(table_ops[ins->op].flags);
1641         if ((pure != PURE) && (pure != IMPURE)) {
1642                 internal_error(state, 0, "Purity of %s not known\n",
1643                         tops(ins->op));
1644         }
1645         return pure == PURE;
1646 }
1647
1648 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1649 {
1650         /* This function is used to determine which triples need
1651          * a register.
1652          */
1653         int is_branch;
1654         valid_ins(state, ins);
1655         is_branch = (table_ops[ins->op].targ != 0);
1656         return is_branch;
1657 }
1658
1659 static int triple_is_def(struct compile_state *state, struct triple *ins)
1660 {
1661         /* This function is used to determine which triples need
1662          * a register.
1663          */
1664         int is_def;
1665         valid_ins(state, ins);
1666         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1667         return is_def;
1668 }
1669
1670 static struct triple **triple_iter(struct compile_state *state,
1671         size_t count, struct triple **vector,
1672         struct triple *ins, struct triple **last)
1673 {
1674         struct triple **ret;
1675         ret = 0;
1676         if (count) {
1677                 if (!last) {
1678                         ret = vector;
1679                 }
1680                 else if ((last >= vector) && (last < (vector + count - 1))) {
1681                         ret = last + 1;
1682                 }
1683         }
1684         return ret;
1685         
1686 }
1687
1688 static struct triple **triple_lhs(struct compile_state *state,
1689         struct triple *ins, struct triple **last)
1690 {
1691         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1692                 ins, last);
1693 }
1694
1695 static struct triple **triple_rhs(struct compile_state *state,
1696         struct triple *ins, struct triple **last)
1697 {
1698         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1699                 ins, last);
1700 }
1701
1702 static struct triple **triple_misc(struct compile_state *state,
1703         struct triple *ins, struct triple **last)
1704 {
1705         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1706                 ins, last);
1707 }
1708
1709 static struct triple **triple_targ(struct compile_state *state,
1710         struct triple *ins, struct triple **last)
1711 {
1712         size_t count;
1713         struct triple **ret, **vector;
1714         ret = 0;
1715         count = TRIPLE_TARG(ins->sizes);
1716         vector = &TARG(ins, 0);
1717         if (count) {
1718                 if (!last) {
1719                         ret = vector;
1720                 }
1721                 else if ((last >= vector) && (last < (vector + count - 1))) {
1722                         ret = last + 1;
1723                 }
1724                 else if ((last == (vector + count - 1)) && 
1725                         TRIPLE_RHS(ins->sizes)) {
1726                         ret = &ins->next;
1727                 }
1728         }
1729         return ret;
1730 }
1731
1732
1733 static void verify_use(struct compile_state *state,
1734         struct triple *user, struct triple *used)
1735 {
1736         int size, i;
1737         size = TRIPLE_SIZE(user->sizes);
1738         for(i = 0; i < size; i++) {
1739                 if (user->param[i] == used) {
1740                         break;
1741                 }
1742         }
1743         if (triple_is_branch(state, user)) {
1744                 if (user->next == used) {
1745                         i = -1;
1746                 }
1747         }
1748         if (i == size) {
1749                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1750                         tops(user->op), user, tops(used->op), used);
1751         }
1752 }
1753
1754 static int find_rhs_use(struct compile_state *state, 
1755         struct triple *user, struct triple *used)
1756 {
1757         struct triple **param;
1758         int size, i;
1759         verify_use(state, user, used);
1760         size = TRIPLE_RHS(user->sizes);
1761         param = &RHS(user, 0);
1762         for(i = 0; i < size; i++) {
1763                 if (param[i] == used) {
1764                         return i;
1765                 }
1766         }
1767         return -1;
1768 }
1769
1770 static void free_triple(struct compile_state *state, struct triple *ptr)
1771 {
1772         size_t size;
1773         size = sizeof(*ptr) - sizeof(ptr->param) +
1774                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1775         ptr->prev->next = ptr->next;
1776         ptr->next->prev = ptr->prev;
1777         if (ptr->use) {
1778                 internal_error(state, ptr, "ptr->use != 0");
1779         }
1780         put_occurance(ptr->occurance);
1781         memset(ptr, -1, size);
1782         xfree(ptr);
1783 }
1784
1785 static void release_triple(struct compile_state *state, struct triple *ptr)
1786 {
1787         struct triple_set *set, *next;
1788         struct triple **expr;
1789         /* Remove ptr from use chains where it is the user */
1790         expr = triple_rhs(state, ptr, 0);
1791         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1792                 if (*expr) {
1793                         unuse_triple(*expr, ptr);
1794                 }
1795         }
1796         expr = triple_lhs(state, ptr, 0);
1797         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1798                 if (*expr) {
1799                         unuse_triple(*expr, ptr);
1800                 }
1801         }
1802         expr = triple_misc(state, ptr, 0);
1803         for(; expr; expr = triple_misc(state, ptr, expr)) {
1804                 if (*expr) {
1805                         unuse_triple(*expr, ptr);
1806                 }
1807         }
1808         expr = triple_targ(state, ptr, 0);
1809         for(; expr; expr = triple_targ(state, ptr, expr)) {
1810                 if (*expr) {
1811                         unuse_triple(*expr, ptr);
1812                 }
1813         }
1814         /* Reomve ptr from use chains where it is used */
1815         for(set = ptr->use; set; set = next) {
1816                 next = set->next;
1817                 expr = triple_rhs(state, set->member, 0);
1818                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1819                         if (*expr == ptr) {
1820                                 *expr = &zero_triple;
1821                         }
1822                 }
1823                 expr = triple_lhs(state, set->member, 0);
1824                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1825                         if (*expr == ptr) {
1826                                 *expr = &zero_triple;
1827                         }
1828                 }
1829                 expr = triple_misc(state, set->member, 0);
1830                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1831                         if (*expr == ptr) {
1832                                 *expr = &zero_triple;
1833                         }
1834                 }
1835                 expr = triple_targ(state, set->member, 0);
1836                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1837                         if (*expr == ptr) {
1838                                 *expr = &zero_triple;
1839                         }
1840                 }
1841                 unuse_triple(ptr, set->member);
1842         }
1843         free_triple(state, ptr);
1844 }
1845
1846 static void print_triple(struct compile_state *state, struct triple *ptr);
1847
1848 #define TOK_UNKNOWN     0
1849 #define TOK_SPACE       1
1850 #define TOK_SEMI        2
1851 #define TOK_LBRACE      3
1852 #define TOK_RBRACE      4
1853 #define TOK_COMMA       5
1854 #define TOK_EQ          6
1855 #define TOK_COLON       7
1856 #define TOK_LBRACKET    8
1857 #define TOK_RBRACKET    9
1858 #define TOK_LPAREN      10
1859 #define TOK_RPAREN      11
1860 #define TOK_STAR        12
1861 #define TOK_DOTS        13
1862 #define TOK_MORE        14
1863 #define TOK_LESS        15
1864 #define TOK_TIMESEQ     16
1865 #define TOK_DIVEQ       17
1866 #define TOK_MODEQ       18
1867 #define TOK_PLUSEQ      19
1868 #define TOK_MINUSEQ     20
1869 #define TOK_SLEQ        21
1870 #define TOK_SREQ        22
1871 #define TOK_ANDEQ       23
1872 #define TOK_XOREQ       24
1873 #define TOK_OREQ        25
1874 #define TOK_EQEQ        26
1875 #define TOK_NOTEQ       27
1876 #define TOK_QUEST       28
1877 #define TOK_LOGOR       29
1878 #define TOK_LOGAND      30
1879 #define TOK_OR          31
1880 #define TOK_AND         32
1881 #define TOK_XOR         33
1882 #define TOK_LESSEQ      34
1883 #define TOK_MOREEQ      35
1884 #define TOK_SL          36
1885 #define TOK_SR          37
1886 #define TOK_PLUS        38
1887 #define TOK_MINUS       39
1888 #define TOK_DIV         40
1889 #define TOK_MOD         41
1890 #define TOK_PLUSPLUS    42
1891 #define TOK_MINUSMINUS  43
1892 #define TOK_BANG        44
1893 #define TOK_ARROW       45
1894 #define TOK_DOT         46
1895 #define TOK_TILDE       47
1896 #define TOK_LIT_STRING  48
1897 #define TOK_LIT_CHAR    49
1898 #define TOK_LIT_INT     50
1899 #define TOK_LIT_FLOAT   51
1900 #define TOK_MACRO       52
1901 #define TOK_CONCATENATE 53
1902
1903 #define TOK_IDENT       54
1904 #define TOK_STRUCT_NAME 55
1905 #define TOK_ENUM_CONST  56
1906 #define TOK_TYPE_NAME   57
1907
1908 #define TOK_AUTO        58
1909 #define TOK_BREAK       59
1910 #define TOK_CASE        60
1911 #define TOK_CHAR        61
1912 #define TOK_CONST       62
1913 #define TOK_CONTINUE    63
1914 #define TOK_DEFAULT     64
1915 #define TOK_DO          65
1916 #define TOK_DOUBLE      66
1917 #define TOK_ELSE        67
1918 #define TOK_ENUM        68
1919 #define TOK_EXTERN      69
1920 #define TOK_FLOAT       70
1921 #define TOK_FOR         71
1922 #define TOK_GOTO        72
1923 #define TOK_IF          73
1924 #define TOK_INLINE      74
1925 #define TOK_INT         75
1926 #define TOK_LONG        76
1927 #define TOK_REGISTER    77
1928 #define TOK_RESTRICT    78
1929 #define TOK_RETURN      79
1930 #define TOK_SHORT       80
1931 #define TOK_SIGNED      81
1932 #define TOK_SIZEOF      82
1933 #define TOK_STATIC      83
1934 #define TOK_STRUCT      84
1935 #define TOK_SWITCH      85
1936 #define TOK_TYPEDEF     86
1937 #define TOK_UNION       87
1938 #define TOK_UNSIGNED    88
1939 #define TOK_VOID        89
1940 #define TOK_VOLATILE    90
1941 #define TOK_WHILE       91
1942 #define TOK_ASM         92
1943 #define TOK_ATTRIBUTE   93
1944 #define TOK_ALIGNOF     94
1945 #define TOK_FIRST_KEYWORD TOK_AUTO
1946 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1947
1948 #define TOK_DEFINE      100
1949 #define TOK_UNDEF       101
1950 #define TOK_INCLUDE     102
1951 #define TOK_LINE        103
1952 #define TOK_ERROR       104
1953 #define TOK_WARNING     105
1954 #define TOK_PRAGMA      106
1955 #define TOK_IFDEF       107
1956 #define TOK_IFNDEF      108
1957 #define TOK_ELIF        109
1958 #define TOK_ENDIF       110
1959
1960 #define TOK_FIRST_MACRO TOK_DEFINE
1961 #define TOK_LAST_MACRO  TOK_ENDIF
1962          
1963 #define TOK_EOF         111
1964
1965 static const char *tokens[] = {
1966 [TOK_UNKNOWN     ] = "unknown",
1967 [TOK_SPACE       ] = ":space:",
1968 [TOK_SEMI        ] = ";",
1969 [TOK_LBRACE      ] = "{",
1970 [TOK_RBRACE      ] = "}",
1971 [TOK_COMMA       ] = ",",
1972 [TOK_EQ          ] = "=",
1973 [TOK_COLON       ] = ":",
1974 [TOK_LBRACKET    ] = "[",
1975 [TOK_RBRACKET    ] = "]",
1976 [TOK_LPAREN      ] = "(",
1977 [TOK_RPAREN      ] = ")",
1978 [TOK_STAR        ] = "*",
1979 [TOK_DOTS        ] = "...",
1980 [TOK_MORE        ] = ">",
1981 [TOK_LESS        ] = "<",
1982 [TOK_TIMESEQ     ] = "*=",
1983 [TOK_DIVEQ       ] = "/=",
1984 [TOK_MODEQ       ] = "%=",
1985 [TOK_PLUSEQ      ] = "+=",
1986 [TOK_MINUSEQ     ] = "-=",
1987 [TOK_SLEQ        ] = "<<=",
1988 [TOK_SREQ        ] = ">>=",
1989 [TOK_ANDEQ       ] = "&=",
1990 [TOK_XOREQ       ] = "^=",
1991 [TOK_OREQ        ] = "|=",
1992 [TOK_EQEQ        ] = "==",
1993 [TOK_NOTEQ       ] = "!=",
1994 [TOK_QUEST       ] = "?",
1995 [TOK_LOGOR       ] = "||",
1996 [TOK_LOGAND      ] = "&&",
1997 [TOK_OR          ] = "|",
1998 [TOK_AND         ] = "&",
1999 [TOK_XOR         ] = "^",
2000 [TOK_LESSEQ      ] = "<=",
2001 [TOK_MOREEQ      ] = ">=",
2002 [TOK_SL          ] = "<<",
2003 [TOK_SR          ] = ">>",
2004 [TOK_PLUS        ] = "+",
2005 [TOK_MINUS       ] = "-",
2006 [TOK_DIV         ] = "/",
2007 [TOK_MOD         ] = "%",
2008 [TOK_PLUSPLUS    ] = "++",
2009 [TOK_MINUSMINUS  ] = "--",
2010 [TOK_BANG        ] = "!",
2011 [TOK_ARROW       ] = "->",
2012 [TOK_DOT         ] = ".",
2013 [TOK_TILDE       ] = "~",
2014 [TOK_LIT_STRING  ] = ":string:",
2015 [TOK_IDENT       ] = ":ident:",
2016 [TOK_TYPE_NAME   ] = ":typename:",
2017 [TOK_LIT_CHAR    ] = ":char:",
2018 [TOK_LIT_INT     ] = ":integer:",
2019 [TOK_LIT_FLOAT   ] = ":float:",
2020 [TOK_MACRO       ] = "#",
2021 [TOK_CONCATENATE ] = "##",
2022
2023 [TOK_AUTO        ] = "auto",
2024 [TOK_BREAK       ] = "break",
2025 [TOK_CASE        ] = "case",
2026 [TOK_CHAR        ] = "char",
2027 [TOK_CONST       ] = "const",
2028 [TOK_CONTINUE    ] = "continue",
2029 [TOK_DEFAULT     ] = "default",
2030 [TOK_DO          ] = "do",
2031 [TOK_DOUBLE      ] = "double",
2032 [TOK_ELSE        ] = "else",
2033 [TOK_ENUM        ] = "enum",
2034 [TOK_EXTERN      ] = "extern",
2035 [TOK_FLOAT       ] = "float",
2036 [TOK_FOR         ] = "for",
2037 [TOK_GOTO        ] = "goto",
2038 [TOK_IF          ] = "if",
2039 [TOK_INLINE      ] = "inline",
2040 [TOK_INT         ] = "int",
2041 [TOK_LONG        ] = "long",
2042 [TOK_REGISTER    ] = "register",
2043 [TOK_RESTRICT    ] = "restrict",
2044 [TOK_RETURN      ] = "return",
2045 [TOK_SHORT       ] = "short",
2046 [TOK_SIGNED      ] = "signed",
2047 [TOK_SIZEOF      ] = "sizeof",
2048 [TOK_STATIC      ] = "static",
2049 [TOK_STRUCT      ] = "struct",
2050 [TOK_SWITCH      ] = "switch",
2051 [TOK_TYPEDEF     ] = "typedef",
2052 [TOK_UNION       ] = "union",
2053 [TOK_UNSIGNED    ] = "unsigned",
2054 [TOK_VOID        ] = "void",
2055 [TOK_VOLATILE    ] = "volatile",
2056 [TOK_WHILE       ] = "while",
2057 [TOK_ASM         ] = "asm",
2058 [TOK_ATTRIBUTE   ] = "__attribute__",
2059 [TOK_ALIGNOF     ] = "__alignof__",
2060
2061 [TOK_DEFINE      ] = "define",
2062 [TOK_UNDEF       ] = "undef",
2063 [TOK_INCLUDE     ] = "include",
2064 [TOK_LINE        ] = "line",
2065 [TOK_ERROR       ] = "error",
2066 [TOK_WARNING     ] = "warning",
2067 [TOK_PRAGMA      ] = "pragma",
2068 [TOK_IFDEF       ] = "ifdef",
2069 [TOK_IFNDEF      ] = "ifndef",
2070 [TOK_ELIF        ] = "elif",
2071 [TOK_ENDIF       ] = "endif",
2072
2073 [TOK_EOF         ] = "EOF",
2074 };
2075
2076 static unsigned int hash(const char *str, int str_len)
2077 {
2078         unsigned int hash;
2079         const char *end;
2080         end = str + str_len;
2081         hash = 0;
2082         for(; str < end; str++) {
2083                 hash = (hash *263) + *str;
2084         }
2085         hash = hash & (HASH_TABLE_SIZE -1);
2086         return hash;
2087 }
2088
2089 static struct hash_entry *lookup(
2090         struct compile_state *state, const char *name, int name_len)
2091 {
2092         struct hash_entry *entry;
2093         unsigned int index;
2094         index = hash(name, name_len);
2095         entry = state->hash_table[index];
2096         while(entry && 
2097                 ((entry->name_len != name_len) ||
2098                         (memcmp(entry->name, name, name_len) != 0))) {
2099                 entry = entry->next;
2100         }
2101         if (!entry) {
2102                 char *new_name;
2103                 /* Get a private copy of the name */
2104                 new_name = xmalloc(name_len + 1, "hash_name");
2105                 memcpy(new_name, name, name_len);
2106                 new_name[name_len] = '\0';
2107
2108                 /* Create a new hash entry */
2109                 entry = xcmalloc(sizeof(*entry), "hash_entry");
2110                 entry->next = state->hash_table[index];
2111                 entry->name = new_name;
2112                 entry->name_len = name_len;
2113
2114                 /* Place the new entry in the hash table */
2115                 state->hash_table[index] = entry;
2116         }
2117         return entry;
2118 }
2119
2120 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2121 {
2122         struct hash_entry *entry;
2123         entry = tk->ident;
2124         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2125                 (entry->tok == TOK_ENUM_CONST) ||
2126                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
2127                         (entry->tok <= TOK_LAST_KEYWORD)))) {
2128                 tk->tok = entry->tok;
2129         }
2130 }
2131
2132 static void ident_to_macro(struct compile_state *state, struct token *tk)
2133 {
2134         struct hash_entry *entry;
2135         entry = tk->ident;
2136         if (entry && 
2137                 (entry->tok >= TOK_FIRST_MACRO) &&
2138                 (entry->tok <= TOK_LAST_MACRO)) {
2139                 tk->tok = entry->tok;
2140         }
2141 }
2142
2143 static void hash_keyword(
2144         struct compile_state *state, const char *keyword, int tok)
2145 {
2146         struct hash_entry *entry;
2147         entry = lookup(state, keyword, strlen(keyword));
2148         if (entry && entry->tok != TOK_UNKNOWN) {
2149                 die("keyword %s already hashed", keyword);
2150         }
2151         entry->tok  = tok;
2152 }
2153
2154 static void symbol(
2155         struct compile_state *state, struct hash_entry *ident,
2156         struct symbol **chain, struct triple *def, struct type *type)
2157 {
2158         struct symbol *sym;
2159         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2160                 error(state, 0, "%s already defined", ident->name);
2161         }
2162         sym = xcmalloc(sizeof(*sym), "symbol");
2163         sym->ident = ident;
2164         sym->def   = def;
2165         sym->type  = type;
2166         sym->scope_depth = state->scope_depth;
2167         sym->next = *chain;
2168         *chain    = sym;
2169 }
2170
2171 static void label_symbol(struct compile_state *state, 
2172         struct hash_entry *ident, struct triple *label)
2173 {
2174         struct symbol *sym;
2175         if (ident->sym_label) {
2176                 error(state, 0, "label %s already defined", ident->name);
2177         }
2178         sym = xcmalloc(sizeof(*sym), "label");
2179         sym->ident = ident;
2180         sym->def   = label;
2181         sym->type  = &void_type;
2182         sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2183         sym->next  = 0;
2184         ident->sym_label = sym;
2185 }
2186
2187 static void start_scope(struct compile_state *state)
2188 {
2189         state->scope_depth++;
2190 }
2191
2192 static void end_scope_syms(struct symbol **chain, int depth)
2193 {
2194         struct symbol *sym, *next;
2195         sym = *chain;
2196         while(sym && (sym->scope_depth == depth)) {
2197                 next = sym->next;
2198                 xfree(sym);
2199                 sym = next;
2200         }
2201         *chain = sym;
2202 }
2203
2204 static void end_scope(struct compile_state *state)
2205 {
2206         int i;
2207         int depth;
2208         /* Walk through the hash table and remove all symbols
2209          * in the current scope. 
2210          */
2211         depth = state->scope_depth;
2212         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2213                 struct hash_entry *entry;
2214                 entry = state->hash_table[i];
2215                 while(entry) {
2216                         end_scope_syms(&entry->sym_label,  depth);
2217                         end_scope_syms(&entry->sym_struct, depth);
2218                         end_scope_syms(&entry->sym_ident,  depth);
2219                         entry = entry->next;
2220                 }
2221         }
2222         state->scope_depth = depth - 1;
2223 }
2224
2225 static void register_keywords(struct compile_state *state)
2226 {
2227         hash_keyword(state, "auto",          TOK_AUTO);
2228         hash_keyword(state, "break",         TOK_BREAK);
2229         hash_keyword(state, "case",          TOK_CASE);
2230         hash_keyword(state, "char",          TOK_CHAR);
2231         hash_keyword(state, "const",         TOK_CONST);
2232         hash_keyword(state, "continue",      TOK_CONTINUE);
2233         hash_keyword(state, "default",       TOK_DEFAULT);
2234         hash_keyword(state, "do",            TOK_DO);
2235         hash_keyword(state, "double",        TOK_DOUBLE);
2236         hash_keyword(state, "else",          TOK_ELSE);
2237         hash_keyword(state, "enum",          TOK_ENUM);
2238         hash_keyword(state, "extern",        TOK_EXTERN);
2239         hash_keyword(state, "float",         TOK_FLOAT);
2240         hash_keyword(state, "for",           TOK_FOR);
2241         hash_keyword(state, "goto",          TOK_GOTO);
2242         hash_keyword(state, "if",            TOK_IF);
2243         hash_keyword(state, "inline",        TOK_INLINE);
2244         hash_keyword(state, "int",           TOK_INT);
2245         hash_keyword(state, "long",          TOK_LONG);
2246         hash_keyword(state, "register",      TOK_REGISTER);
2247         hash_keyword(state, "restrict",      TOK_RESTRICT);
2248         hash_keyword(state, "return",        TOK_RETURN);
2249         hash_keyword(state, "short",         TOK_SHORT);
2250         hash_keyword(state, "signed",        TOK_SIGNED);
2251         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2252         hash_keyword(state, "static",        TOK_STATIC);
2253         hash_keyword(state, "struct",        TOK_STRUCT);
2254         hash_keyword(state, "switch",        TOK_SWITCH);
2255         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2256         hash_keyword(state, "union",         TOK_UNION);
2257         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2258         hash_keyword(state, "void",          TOK_VOID);
2259         hash_keyword(state, "volatile",      TOK_VOLATILE);
2260         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2261         hash_keyword(state, "while",         TOK_WHILE);
2262         hash_keyword(state, "asm",           TOK_ASM);
2263         hash_keyword(state, "__asm__",       TOK_ASM);
2264         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2265         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2266 }
2267
2268 static void register_macro_keywords(struct compile_state *state)
2269 {
2270         hash_keyword(state, "define",        TOK_DEFINE);
2271         hash_keyword(state, "undef",         TOK_UNDEF);
2272         hash_keyword(state, "include",       TOK_INCLUDE);
2273         hash_keyword(state, "line",          TOK_LINE);
2274         hash_keyword(state, "error",         TOK_ERROR);
2275         hash_keyword(state, "warning",       TOK_WARNING);
2276         hash_keyword(state, "pragma",        TOK_PRAGMA);
2277         hash_keyword(state, "ifdef",         TOK_IFDEF);
2278         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2279         hash_keyword(state, "elif",          TOK_ELIF);
2280         hash_keyword(state, "endif",         TOK_ENDIF);
2281 }
2282
2283 static int spacep(int c)
2284 {
2285         int ret = 0;
2286         switch(c) {
2287         case ' ':
2288         case '\t':
2289         case '\f':
2290         case '\v':
2291         case '\r':
2292         case '\n':
2293                 ret = 1;
2294                 break;
2295         }
2296         return ret;
2297 }
2298
2299 static int digitp(int c)
2300 {
2301         int ret = 0;
2302         switch(c) {
2303         case '0': case '1': case '2': case '3': case '4': 
2304         case '5': case '6': case '7': case '8': case '9':
2305                 ret = 1;
2306                 break;
2307         }
2308         return ret;
2309 }
2310 static int digval(int c)
2311 {
2312         int val = -1;
2313         if ((c >= '0') && (c <= '9')) {
2314                 val = c - '0';
2315         }
2316         return val;
2317 }
2318
2319 static int hexdigitp(int c)
2320 {
2321         int ret = 0;
2322         switch(c) {
2323         case '0': case '1': case '2': case '3': case '4': 
2324         case '5': case '6': case '7': case '8': case '9':
2325         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2326         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2327                 ret = 1;
2328                 break;
2329         }
2330         return ret;
2331 }
2332 static int hexdigval(int c) 
2333 {
2334         int val = -1;
2335         if ((c >= '0') && (c <= '9')) {
2336                 val = c - '0';
2337         }
2338         else if ((c >= 'A') && (c <= 'F')) {
2339                 val = 10 + (c - 'A');
2340         }
2341         else if ((c >= 'a') && (c <= 'f')) {
2342                 val = 10 + (c - 'a');
2343         }
2344         return val;
2345 }
2346
2347 static int octdigitp(int c)
2348 {
2349         int ret = 0;
2350         switch(c) {
2351         case '0': case '1': case '2': case '3': 
2352         case '4': case '5': case '6': case '7':
2353                 ret = 1;
2354                 break;
2355         }
2356         return ret;
2357 }
2358 static int octdigval(int c)
2359 {
2360         int val = -1;
2361         if ((c >= '0') && (c <= '7')) {
2362                 val = c - '0';
2363         }
2364         return val;
2365 }
2366
2367 static int letterp(int c)
2368 {
2369         int ret = 0;
2370         switch(c) {
2371         case 'a': case 'b': case 'c': case 'd': case 'e':
2372         case 'f': case 'g': case 'h': case 'i': case 'j':
2373         case 'k': case 'l': case 'm': case 'n': case 'o':
2374         case 'p': case 'q': case 'r': case 's': case 't':
2375         case 'u': case 'v': case 'w': case 'x': case 'y':
2376         case 'z':
2377         case 'A': case 'B': case 'C': case 'D': case 'E':
2378         case 'F': case 'G': case 'H': case 'I': case 'J':
2379         case 'K': case 'L': case 'M': case 'N': case 'O':
2380         case 'P': case 'Q': case 'R': case 'S': case 'T':
2381         case 'U': case 'V': case 'W': case 'X': case 'Y':
2382         case 'Z':
2383         case '_':
2384                 ret = 1;
2385                 break;
2386         }
2387         return ret;
2388 }
2389
2390 static int char_value(struct compile_state *state,
2391         const signed char **strp, const signed char *end)
2392 {
2393         const signed char *str;
2394         int c;
2395         str = *strp;
2396         c = *str++;
2397         if ((c == '\\') && (str < end)) {
2398                 switch(*str) {
2399                 case 'n':  c = '\n'; str++; break;
2400                 case 't':  c = '\t'; str++; break;
2401                 case 'v':  c = '\v'; str++; break;
2402                 case 'b':  c = '\b'; str++; break;
2403                 case 'r':  c = '\r'; str++; break;
2404                 case 'f':  c = '\f'; str++; break;
2405                 case 'a':  c = '\a'; str++; break;
2406                 case '\\': c = '\\'; str++; break;
2407                 case '?':  c = '?';  str++; break;
2408                 case '\'': c = '\''; str++; break;
2409                 case '"':  c = '"';  break;
2410                 case 'x': 
2411                         c = 0;
2412                         str++;
2413                         while((str < end) && hexdigitp(*str)) {
2414                                 c <<= 4;
2415                                 c += hexdigval(*str);
2416                                 str++;
2417                         }
2418                         break;
2419                 case '0': case '1': case '2': case '3': 
2420                 case '4': case '5': case '6': case '7':
2421                         c = 0;
2422                         while((str < end) && octdigitp(*str)) {
2423                                 c <<= 3;
2424                                 c += octdigval(*str);
2425                                 str++;
2426                         }
2427                         break;
2428                 default:
2429                         error(state, 0, "Invalid character constant");
2430                         break;
2431                 }
2432         }
2433         *strp = str;
2434         return c;
2435 }
2436
2437 static char *after_digits(char *ptr, char *end)
2438 {
2439         while((ptr < end) && digitp(*ptr)) {
2440                 ptr++;
2441         }
2442         return ptr;
2443 }
2444
2445 static char *after_octdigits(char *ptr, char *end)
2446 {
2447         while((ptr < end) && octdigitp(*ptr)) {
2448                 ptr++;
2449         }
2450         return ptr;
2451 }
2452
2453 static char *after_hexdigits(char *ptr, char *end)
2454 {
2455         while((ptr < end) && hexdigitp(*ptr)) {
2456                 ptr++;
2457         }
2458         return ptr;
2459 }
2460
2461 static void save_string(struct compile_state *state, 
2462         struct token *tk, char *start, char *end, const char *id)
2463 {
2464         char *str;
2465         int str_len;
2466         /* Create a private copy of the string */
2467         str_len = end - start + 1;
2468         str = xmalloc(str_len + 1, id);
2469         memcpy(str, start, str_len);
2470         str[str_len] = '\0';
2471
2472         /* Store the copy in the token */
2473         tk->val.str = str;
2474         tk->str_len = str_len;
2475 }
2476 static void next_token(struct compile_state *state, int index)
2477 {
2478         struct file_state *file;
2479         struct token *tk;
2480         char *token;
2481         int c, c1, c2, c3;
2482         char *tokp, *end;
2483         int tok;
2484 next_token:
2485         file = state->file;
2486         tk = &state->token[index];
2487         tk->str_len = 0;
2488         tk->ident = 0;
2489         token = tokp = file->pos;
2490         end = file->buf + file->size;
2491         tok = TOK_UNKNOWN;
2492         c = -1;
2493         if (tokp < end) {
2494                 c = *tokp;
2495         }
2496         c1 = -1;
2497         if ((tokp + 1) < end) {
2498                 c1 = tokp[1];
2499         }
2500         c2 = -1;
2501         if ((tokp + 2) < end) {
2502                 c2 = tokp[2];
2503         }
2504         c3 = -1;
2505         if ((tokp + 3) < end) {
2506                 c3 = tokp[3];
2507         }
2508         if (tokp >= end) {
2509                 tok = TOK_EOF;
2510                 tokp = end;
2511         }
2512         /* Whitespace */
2513         else if (spacep(c)) {
2514                 tok = TOK_SPACE;
2515                 while ((tokp < end) && spacep(c)) {
2516                         if (c == '\n') {
2517                                 file->line++;
2518                                 file->report_line++;
2519                                 file->line_start = tokp + 1;
2520                         }
2521                         c = *(++tokp);
2522                 }
2523                 if (!spacep(c)) {
2524                         tokp--;
2525                 }
2526         }
2527         /* EOL Comments */
2528         else if ((c == '/') && (c1 == '/')) {
2529                 tok = TOK_SPACE;
2530                 for(tokp += 2; tokp < end; tokp++) {
2531                         c = *tokp;
2532                         if (c == '\n') {
2533                                 file->line++;
2534                                 file->report_line++;
2535                                 file->line_start = tokp +1;
2536                                 break;
2537                         }
2538                 }
2539         }
2540         /* Comments */
2541         else if ((c == '/') && (c1 == '*')) {
2542                 int line;
2543                 char *line_start;
2544                 line = file->line;
2545                 line_start = file->line_start;
2546                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2547                         c = *tokp;
2548                         if (c == '\n') {
2549                                 line++;
2550                                 line_start = tokp +1;
2551                         }
2552                         else if ((c == '*') && (tokp[1] == '/')) {
2553                                 tok = TOK_SPACE;
2554                                 tokp += 1;
2555                                 break;
2556                         }
2557                 }
2558                 if (tok == TOK_UNKNOWN) {
2559                         error(state, 0, "unterminated comment");
2560                 }
2561                 file->report_line += line - file->line;
2562                 file->line = line;
2563                 file->line_start = line_start;
2564         }
2565         /* string constants */
2566         else if ((c == '"') ||
2567                 ((c == 'L') && (c1 == '"'))) {
2568                 int line;
2569                 char *line_start;
2570                 int wchar;
2571                 line = file->line;
2572                 line_start = file->line_start;
2573                 wchar = 0;
2574                 if (c == 'L') {
2575                         wchar = 1;
2576                         tokp++;
2577                 }
2578                 for(tokp += 1; tokp < end; tokp++) {
2579                         c = *tokp;
2580                         if (c == '\n') {
2581                                 line++;
2582                                 line_start = tokp + 1;
2583                         }
2584                         else if ((c == '\\') && (tokp +1 < end)) {
2585                                 tokp++;
2586                         }
2587                         else if (c == '"') {
2588                                 tok = TOK_LIT_STRING;
2589                                 break;
2590                         }
2591                 }
2592                 if (tok == TOK_UNKNOWN) {
2593                         error(state, 0, "unterminated string constant");
2594                 }
2595                 if (line != file->line) {
2596                         warning(state, 0, "multiline string constant");
2597                 }
2598                 file->report_line += line - file->line;
2599                 file->line = line;
2600                 file->line_start = line_start;
2601
2602                 /* Save the string value */
2603                 save_string(state, tk, token, tokp, "literal string");
2604         }
2605         /* character constants */
2606         else if ((c == '\'') ||
2607                 ((c == 'L') && (c1 == '\''))) {
2608                 int line;
2609                 char *line_start;
2610                 int wchar;
2611                 line = file->line;
2612                 line_start = file->line_start;
2613                 wchar = 0;
2614                 if (c == 'L') {
2615                         wchar = 1;
2616                         tokp++;
2617                 }
2618                 for(tokp += 1; tokp < end; tokp++) {
2619                         c = *tokp;
2620                         if (c == '\n') {
2621                                 line++;
2622                                 line_start = tokp + 1;
2623                         }
2624                         else if ((c == '\\') && (tokp +1 < end)) {
2625                                 tokp++;
2626                         }
2627                         else if (c == '\'') {
2628                                 tok = TOK_LIT_CHAR;
2629                                 break;
2630                         }
2631                 }
2632                 if (tok == TOK_UNKNOWN) {
2633                         error(state, 0, "unterminated character constant");
2634                 }
2635                 if (line != file->line) {
2636                         warning(state, 0, "multiline character constant");
2637                 }
2638                 file->report_line += line - file->line;
2639                 file->line = line;
2640                 file->line_start = line_start;
2641
2642                 /* Save the character value */
2643                 save_string(state, tk, token, tokp, "literal character");
2644         }
2645         /* integer and floating constants 
2646          * Integer Constants
2647          * {digits}
2648          * 0[Xx]{hexdigits}
2649          * 0{octdigit}+
2650          * 
2651          * Floating constants
2652          * {digits}.{digits}[Ee][+-]?{digits}
2653          * {digits}.{digits}
2654          * {digits}[Ee][+-]?{digits}
2655          * .{digits}[Ee][+-]?{digits}
2656          * .{digits}
2657          */
2658         
2659         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2660                 char *next, *new;
2661                 int is_float;
2662                 is_float = 0;
2663                 if (c != '.') {
2664                         next = after_digits(tokp, end);
2665                 }
2666                 else {
2667                         next = tokp;
2668                 }
2669                 if (next[0] == '.') {
2670                         new = after_digits(next, end);
2671                         is_float = (new != next);
2672                         next = new;
2673                 }
2674                 if ((next[0] == 'e') || (next[0] == 'E')) {
2675                         if (((next + 1) < end) && 
2676                                 ((next[1] == '+') || (next[1] == '-'))) {
2677                                 next++;
2678                         }
2679                         new = after_digits(next, end);
2680                         is_float = (new != next);
2681                         next = new;
2682                 }
2683                 if (is_float) {
2684                         tok = TOK_LIT_FLOAT;
2685                         if ((next < end) && (
2686                                 (next[0] == 'f') ||
2687                                 (next[0] == 'F') ||
2688                                 (next[0] == 'l') ||
2689                                 (next[0] == 'L'))
2690                                 ) {
2691                                 next++;
2692                         }
2693                 }
2694                 if (!is_float && digitp(c)) {
2695                         tok = TOK_LIT_INT;
2696                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2697                                 next = after_hexdigits(tokp + 2, end);
2698                         }
2699                         else if (c == '0') {
2700                                 next = after_octdigits(tokp, end);
2701                         }
2702                         else {
2703                                 next = after_digits(tokp, end);
2704                         }
2705                         /* crazy integer suffixes */
2706                         if ((next < end) && 
2707                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2708                                 next++;
2709                                 if ((next < end) &&
2710                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2711                                         next++;
2712                                 }
2713                         }
2714                         else if ((next < end) &&
2715                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2716                                 next++;
2717                                 if ((next < end) && 
2718                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2719                                         next++;
2720                                 }
2721                         }
2722                 }
2723                 tokp = next - 1;
2724
2725                 /* Save the integer/floating point value */
2726                 save_string(state, tk, token, tokp, "literal number");
2727         }
2728         /* identifiers */
2729         else if (letterp(c)) {
2730                 tok = TOK_IDENT;
2731                 for(tokp += 1; tokp < end; tokp++) {
2732                         c = *tokp;
2733                         if (!letterp(c) && !digitp(c)) {
2734                                 break;
2735                         }
2736                 }
2737                 tokp -= 1;
2738                 tk->ident = lookup(state, token, tokp +1 - token);
2739         }
2740         /* C99 alternate macro characters */
2741         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2742                 tokp += 3; 
2743                 tok = TOK_CONCATENATE; 
2744         }
2745         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2746         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2747         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2748         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2749         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2750         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2751         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2752         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2753         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2754         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2755         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2756         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2757         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2758         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2759         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2760         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2761         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2762         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2763         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2764         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2765         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2766         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2767         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2768         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2769         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2770         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2771         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2772         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2773         else if (c == ';') { tok = TOK_SEMI; }
2774         else if (c == '{') { tok = TOK_LBRACE; }
2775         else if (c == '}') { tok = TOK_RBRACE; }
2776         else if (c == ',') { tok = TOK_COMMA; }
2777         else if (c == '=') { tok = TOK_EQ; }
2778         else if (c == ':') { tok = TOK_COLON; }
2779         else if (c == '[') { tok = TOK_LBRACKET; }
2780         else if (c == ']') { tok = TOK_RBRACKET; }
2781         else if (c == '(') { tok = TOK_LPAREN; }
2782         else if (c == ')') { tok = TOK_RPAREN; }
2783         else if (c == '*') { tok = TOK_STAR; }
2784         else if (c == '>') { tok = TOK_MORE; }
2785         else if (c == '<') { tok = TOK_LESS; }
2786         else if (c == '?') { tok = TOK_QUEST; }
2787         else if (c == '|') { tok = TOK_OR; }
2788         else if (c == '&') { tok = TOK_AND; }
2789         else if (c == '^') { tok = TOK_XOR; }
2790         else if (c == '+') { tok = TOK_PLUS; }
2791         else if (c == '-') { tok = TOK_MINUS; }
2792         else if (c == '/') { tok = TOK_DIV; }
2793         else if (c == '%') { tok = TOK_MOD; }
2794         else if (c == '!') { tok = TOK_BANG; }
2795         else if (c == '.') { tok = TOK_DOT; }
2796         else if (c == '~') { tok = TOK_TILDE; }
2797         else if (c == '#') { tok = TOK_MACRO; }
2798         if (tok == TOK_MACRO) {
2799                 /* Only match preprocessor directives at the start of a line */
2800                 char *ptr;
2801                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2802                         ;
2803                 if (ptr != tokp) {
2804                         tok = TOK_UNKNOWN;
2805                 }
2806         }
2807         if (tok == TOK_UNKNOWN) {
2808                 error(state, 0, "unknown token");
2809         }
2810
2811         file->pos = tokp + 1;
2812         tk->tok = tok;
2813         if (tok == TOK_IDENT) {
2814                 ident_to_keyword(state, tk);
2815         }
2816         /* Don't return space tokens. */
2817         if (tok == TOK_SPACE) {
2818                 goto next_token;
2819         }
2820 }
2821
2822 static void compile_macro(struct compile_state *state, struct token *tk)
2823 {
2824         struct file_state *file;
2825         struct hash_entry *ident;
2826         ident = tk->ident;
2827         file = xmalloc(sizeof(*file), "file_state");
2828         file->basename = xstrdup(tk->ident->name);
2829         file->dirname = xstrdup("");
2830         file->size = ident->sym_define->buf_len;
2831         file->buf = xmalloc(file->size +2,  file->basename);
2832         memcpy(file->buf, ident->sym_define->buf, file->size);
2833         file->buf[file->size] = '\n';
2834         file->buf[file->size + 1] = '\0';
2835         file->pos = file->buf;
2836         file->line_start = file->pos;
2837         file->line = 1;
2838         file->report_line = 1;
2839         file->report_name = file->basename;
2840         file->report_dir  = file->dirname;
2841         file->prev = state->file;
2842         state->file = file;
2843 }
2844
2845
2846 static int mpeek(struct compile_state *state, int index)
2847 {
2848         struct token *tk;
2849         int rescan;
2850         tk = &state->token[index + 1];
2851         if (tk->tok == -1) {
2852                 next_token(state, index + 1);
2853         }
2854         do {
2855                 rescan = 0;
2856                 if ((tk->tok == TOK_EOF) && 
2857                         (state->file != state->macro_file) &&
2858                         (state->file->prev)) {
2859                         struct file_state *file = state->file;
2860                         state->file = file->prev;
2861                         /* file->basename is used keep it */
2862                         if (file->report_dir != file->dirname) {
2863                                 xfree(file->report_dir);
2864                         }
2865                         xfree(file->dirname);
2866                         xfree(file->buf);
2867                         xfree(file);
2868                         next_token(state, index + 1);
2869                         rescan = 1;
2870                 }
2871                 else if (tk->ident && tk->ident->sym_define) {
2872                         compile_macro(state, tk);
2873                         next_token(state, index + 1);
2874                         rescan = 1;
2875                 }
2876         } while(rescan);
2877         /* Don't show the token on the next line */
2878         if (state->macro_line < state->macro_file->line) {
2879                 return TOK_EOF;
2880         }
2881         return state->token[index +1].tok;
2882 }
2883
2884 static void meat(struct compile_state *state, int index, int tok)
2885 {
2886         int next_tok;
2887         int i;
2888         next_tok = mpeek(state, index);
2889         if (next_tok != tok) {
2890                 const char *name1, *name2;
2891                 name1 = tokens[next_tok];
2892                 name2 = "";
2893                 if (next_tok == TOK_IDENT) {
2894                         name2 = state->token[index + 1].ident->name;
2895                 }
2896                 error(state, 0, "found %s %s expected %s", 
2897                         name1, name2, tokens[tok]);
2898         }
2899         /* Free the old token value */
2900         if (state->token[index].str_len) {
2901                 memset((void *)(state->token[index].val.str), -1, 
2902                         state->token[index].str_len);
2903                 xfree(state->token[index].val.str);
2904         }
2905         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2906                 state->token[i] = state->token[i + 1];
2907         }
2908         memset(&state->token[i], 0, sizeof(state->token[i]));
2909         state->token[i].tok = -1;
2910 }
2911
2912 static long_t mcexpr(struct compile_state *state, int index);
2913
2914 static long_t mprimary_expr(struct compile_state *state, int index)
2915 {
2916         long_t val;
2917         int tok;
2918         tok = mpeek(state, index);
2919         while(state->token[index + 1].ident && 
2920                 state->token[index + 1].ident->sym_define) {
2921                 meat(state, index, tok);
2922                 compile_macro(state, &state->token[index]);
2923                 tok = mpeek(state, index);
2924         }
2925         switch(tok) {
2926         case TOK_LPAREN:
2927                 meat(state, index, TOK_LPAREN);
2928                 val = mcexpr(state, index);
2929                 meat(state, index, TOK_RPAREN);
2930                 break;
2931         case TOK_LIT_INT:
2932         {
2933                 char *end;
2934                 meat(state, index, TOK_LIT_INT);
2935                 errno = 0;
2936                 val = strtol(state->token[index].val.str, &end, 0);
2937                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2938                         (errno == ERANGE)) {
2939                         error(state, 0, "Integer constant to large");
2940                 }
2941                 break;
2942         }
2943         default:
2944                 meat(state, index, TOK_LIT_INT);
2945                 val = 0;
2946         }
2947         return val;
2948 }
2949 static long_t munary_expr(struct compile_state *state, int index)
2950 {
2951         long_t val;
2952         switch(mpeek(state, index)) {
2953         case TOK_PLUS:
2954                 meat(state, index, TOK_PLUS);
2955                 val = munary_expr(state, index);
2956                 val = + val;
2957                 break;
2958         case TOK_MINUS:
2959                 meat(state, index, TOK_MINUS);
2960                 val = munary_expr(state, index);
2961                 val = - val;
2962                 break;
2963         case TOK_TILDE:
2964                 meat(state, index, TOK_BANG);
2965                 val = munary_expr(state, index);
2966                 val = ~ val;
2967                 break;
2968         case TOK_BANG:
2969                 meat(state, index, TOK_BANG);
2970                 val = munary_expr(state, index);
2971                 val = ! val;
2972                 break;
2973         default:
2974                 val = mprimary_expr(state, index);
2975                 break;
2976         }
2977         return val;
2978         
2979 }
2980 static long_t mmul_expr(struct compile_state *state, int index)
2981 {
2982         long_t val;
2983         int done;
2984         val = munary_expr(state, index);
2985         do {
2986                 long_t right;
2987                 done = 0;
2988                 switch(mpeek(state, index)) {
2989                 case TOK_STAR:
2990                         meat(state, index, TOK_STAR);
2991                         right = munary_expr(state, index);
2992                         val = val * right;
2993                         break;
2994                 case TOK_DIV:
2995                         meat(state, index, TOK_DIV);
2996                         right = munary_expr(state, index);
2997                         val = val / right;
2998                         break;
2999                 case TOK_MOD:
3000                         meat(state, index, TOK_MOD);
3001                         right = munary_expr(state, index);
3002                         val = val % right;
3003                         break;
3004                 default:
3005                         done = 1;
3006                         break;
3007                 }
3008         } while(!done);
3009
3010         return val;
3011 }
3012
3013 static long_t madd_expr(struct compile_state *state, int index)
3014 {
3015         long_t val;
3016         int done;
3017         val = mmul_expr(state, index);
3018         do {
3019                 long_t right;
3020                 done = 0;
3021                 switch(mpeek(state, index)) {
3022                 case TOK_PLUS:
3023                         meat(state, index, TOK_PLUS);
3024                         right = mmul_expr(state, index);
3025                         val = val + right;
3026                         break;
3027                 case TOK_MINUS:
3028                         meat(state, index, TOK_MINUS);
3029                         right = mmul_expr(state, index);
3030                         val = val - right;
3031                         break;
3032                 default:
3033                         done = 1;
3034                         break;
3035                 }
3036         } while(!done);
3037
3038         return val;
3039 }
3040
3041 static long_t mshift_expr(struct compile_state *state, int index)
3042 {
3043         long_t val;
3044         int done;
3045         val = madd_expr(state, index);
3046         do {
3047                 long_t right;
3048                 done = 0;
3049                 switch(mpeek(state, index)) {
3050                 case TOK_SL:
3051                         meat(state, index, TOK_SL);
3052                         right = madd_expr(state, index);
3053                         val = val << right;
3054                         break;
3055                 case TOK_SR:
3056                         meat(state, index, TOK_SR);
3057                         right = madd_expr(state, index);
3058                         val = val >> right;
3059                         break;
3060                 default:
3061                         done = 1;
3062                         break;
3063                 }
3064         } while(!done);
3065
3066         return val;
3067 }
3068
3069 static long_t mrel_expr(struct compile_state *state, int index)
3070 {
3071         long_t val;
3072         int done;
3073         val = mshift_expr(state, index);
3074         do {
3075                 long_t right;
3076                 done = 0;
3077                 switch(mpeek(state, index)) {
3078                 case TOK_LESS:
3079                         meat(state, index, TOK_LESS);
3080                         right = mshift_expr(state, index);
3081                         val = val < right;
3082                         break;
3083                 case TOK_MORE:
3084                         meat(state, index, TOK_MORE);
3085                         right = mshift_expr(state, index);
3086                         val = val > right;
3087                         break;
3088                 case TOK_LESSEQ:
3089                         meat(state, index, TOK_LESSEQ);
3090                         right = mshift_expr(state, index);
3091                         val = val <= right;
3092                         break;
3093                 case TOK_MOREEQ:
3094                         meat(state, index, TOK_MOREEQ);
3095                         right = mshift_expr(state, index);
3096                         val = val >= right;
3097                         break;
3098                 default:
3099                         done = 1;
3100                         break;
3101                 }
3102         } while(!done);
3103         return val;
3104 }
3105
3106 static long_t meq_expr(struct compile_state *state, int index)
3107 {
3108         long_t val;
3109         int done;
3110         val = mrel_expr(state, index);
3111         do {
3112                 long_t right;
3113                 done = 0;
3114                 switch(mpeek(state, index)) {
3115                 case TOK_EQEQ:
3116                         meat(state, index, TOK_EQEQ);
3117                         right = mrel_expr(state, index);
3118                         val = val == right;
3119                         break;
3120                 case TOK_NOTEQ:
3121                         meat(state, index, TOK_NOTEQ);
3122                         right = mrel_expr(state, index);
3123                         val = val != right;
3124                         break;
3125                 default:
3126                         done = 1;
3127                         break;
3128                 }
3129         } while(!done);
3130         return val;
3131 }
3132
3133 static long_t mand_expr(struct compile_state *state, int index)
3134 {
3135         long_t val;
3136         val = meq_expr(state, index);
3137         if (mpeek(state, index) == TOK_AND) {
3138                 long_t right;
3139                 meat(state, index, TOK_AND);
3140                 right = meq_expr(state, index);
3141                 val = val & right;
3142         }
3143         return val;
3144 }
3145
3146 static long_t mxor_expr(struct compile_state *state, int index)
3147 {
3148         long_t val;
3149         val = mand_expr(state, index);
3150         if (mpeek(state, index) == TOK_XOR) {
3151                 long_t right;
3152                 meat(state, index, TOK_XOR);
3153                 right = mand_expr(state, index);
3154                 val = val ^ right;
3155         }
3156         return val;
3157 }
3158
3159 static long_t mor_expr(struct compile_state *state, int index)
3160 {
3161         long_t val;
3162         val = mxor_expr(state, index);
3163         if (mpeek(state, index) == TOK_OR) {
3164                 long_t right;
3165                 meat(state, index, TOK_OR);
3166                 right = mxor_expr(state, index);
3167                 val = val | right;
3168         }
3169         return val;
3170 }
3171
3172 static long_t mland_expr(struct compile_state *state, int index)
3173 {
3174         long_t val;
3175         val = mor_expr(state, index);
3176         if (mpeek(state, index) == TOK_LOGAND) {
3177                 long_t right;
3178                 meat(state, index, TOK_LOGAND);
3179                 right = mor_expr(state, index);
3180                 val = val && right;
3181         }
3182         return val;
3183 }
3184 static long_t mlor_expr(struct compile_state *state, int index)
3185 {
3186         long_t val;
3187         val = mland_expr(state, index);
3188         if (mpeek(state, index) == TOK_LOGOR) {
3189                 long_t right;
3190                 meat(state, index, TOK_LOGOR);
3191                 right = mland_expr(state, index);
3192                 val = val || right;
3193         }
3194         return val;
3195 }
3196
3197 static long_t mcexpr(struct compile_state *state, int index)
3198 {
3199         return mlor_expr(state, index);
3200 }
3201 static void preprocess(struct compile_state *state, int index)
3202 {
3203         /* Doing much more with the preprocessor would require
3204          * a parser and a major restructuring.
3205          * Postpone that for later.
3206          */
3207         struct file_state *file;
3208         struct token *tk;
3209         int line;
3210         int tok;
3211         
3212         file = state->file;
3213         tk = &state->token[index];
3214         state->macro_line = line = file->line;
3215         state->macro_file = file;
3216
3217         next_token(state, index);
3218         ident_to_macro(state, tk);
3219         if (tk->tok == TOK_IDENT) {
3220                 error(state, 0, "undefined preprocessing directive `%s'",
3221                         tk->ident->name);
3222         }
3223         switch(tk->tok) {
3224         case TOK_LIT_INT:
3225         {
3226                 int override_line;
3227                 override_line = strtoul(tk->val.str, 0, 10);
3228                 next_token(state, index);
3229                 /* I have a cpp line marker parse it */
3230                 if (tk->tok == TOK_LIT_STRING) {
3231                         const char *token, *base;
3232                         char *name, *dir;
3233                         int name_len, dir_len;
3234                         name = xmalloc(tk->str_len, "report_name");
3235                         token = tk->val.str + 1;
3236                         base = strrchr(token, '/');
3237                         name_len = tk->str_len -2;
3238                         if (base != 0) {
3239                                 dir_len = base - token;
3240                                 base++;
3241                                 name_len -= base - token;
3242                         } else {
3243                                 dir_len = 0;
3244                                 base = token;
3245                         }
3246                         memcpy(name, base, name_len);
3247                         name[name_len] = '\0';
3248                         dir = xmalloc(dir_len + 1, "report_dir");
3249                         memcpy(dir, token, dir_len);
3250                         dir[dir_len] = '\0';
3251                         file->report_line = override_line - 1;
3252                         file->report_name = name;
3253                         file->report_dir = dir;
3254                 }
3255         }
3256                 break;
3257         case TOK_LINE:
3258                 meat(state, index, TOK_LINE);
3259                 meat(state, index, TOK_LIT_INT);
3260                 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3261                 if (mpeek(state, index) == TOK_LIT_STRING) {
3262                         const char *token, *base;
3263                         char *name, *dir;
3264                         int name_len, dir_len;
3265                         meat(state, index, TOK_LIT_STRING);
3266                         name = xmalloc(tk->str_len, "report_name");
3267                         token = tk->val.str + 1;
3268                         name_len = tk->str_len - 2;
3269                         if (base != 0) {
3270                                 dir_len = base - token;
3271                                 base++;
3272                                 name_len -= base - token;
3273                         } else {
3274                                 dir_len = 0;
3275                                 base = token;
3276                         }
3277                         memcpy(name, base, name_len);
3278                         name[name_len] = '\0';
3279                         dir = xmalloc(dir_len + 1, "report_dir");
3280                         memcpy(dir, token, dir_len);
3281                         dir[dir_len] = '\0';
3282                         file->report_name = name;
3283                         file->report_dir = dir;
3284                 }
3285                 break;
3286         case TOK_UNDEF:
3287         case TOK_PRAGMA:
3288                 if (state->if_value < 0) {
3289                         break;
3290                 }
3291                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3292                         tk->ident->name);
3293                 break;
3294         case TOK_ELIF:
3295                 error(state, 0, "#elif not supported");
3296 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3297                 if (state->if_depth == 0) {
3298                         error(state, 0, "#elif without #if");
3299                 }
3300                 /* If the #if was taken the #elif just disables the following code */
3301                 if (state->if_value >= 0) {
3302                         state->if_value = - state->if_value;
3303                 }
3304                 /* If the previous #if was not taken see if the #elif enables the 
3305                  * trailing code.
3306                  */
3307                 else if ((state->if_value < 0) && 
3308                         (state->if_depth == - state->if_value))
3309                 {
3310                         if (mcexpr(state, index) != 0) {
3311                                 state->if_value = state->if_depth;
3312                         }
3313                         else {
3314                                 state->if_value = - state->if_depth;
3315                         }
3316                 }
3317                 break;
3318         case TOK_IF:
3319                 state->if_depth++;
3320                 if (state->if_value < 0) {
3321                         break;
3322                 }
3323                 if (mcexpr(state, index) != 0) {
3324                         state->if_value = state->if_depth;
3325                 }
3326                 else {
3327                         state->if_value = - state->if_depth;
3328                 }
3329                 break;
3330         case TOK_IFNDEF:
3331                 state->if_depth++;
3332                 if (state->if_value < 0) {
3333                         break;
3334                 }
3335                 next_token(state, index);
3336                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3337                         error(state, 0, "Invalid macro name");
3338                 }
3339                 if (tk->ident->sym_define == 0) {
3340                         state->if_value = state->if_depth;
3341                 } 
3342                 else {
3343                         state->if_value = - state->if_depth;
3344                 }
3345                 break;
3346         case TOK_IFDEF:
3347                 state->if_depth++;
3348                 if (state->if_value < 0) {
3349                         break;
3350                 }
3351                 next_token(state, index);
3352                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3353                         error(state, 0, "Invalid macro name");
3354                 }
3355                 if (tk->ident->sym_define != 0) {
3356                         state->if_value = state->if_depth;
3357                 }
3358                 else {
3359                         state->if_value = - state->if_depth;
3360                 }
3361                 break;
3362         case TOK_ELSE:
3363                 if (state->if_depth == 0) {
3364                         error(state, 0, "#else without #if");
3365                 }
3366                 if ((state->if_value >= 0) ||
3367                         ((state->if_value < 0) && 
3368                                 (state->if_depth == -state->if_value)))
3369                 {
3370                         state->if_value = - state->if_value;
3371                 }
3372                 break;
3373         case TOK_ENDIF:
3374                 if (state->if_depth == 0) {
3375                         error(state, 0, "#endif without #if");
3376                 }
3377                 if ((state->if_value >= 0) ||
3378                         ((state->if_value < 0) &&
3379                                 (state->if_depth == -state->if_value))) 
3380                 {
3381                         state->if_value = state->if_depth - 1;
3382                 }
3383                 state->if_depth--;
3384                 break;
3385         case TOK_DEFINE:
3386         {
3387                 struct hash_entry *ident;
3388                 struct macro *macro;
3389                 char *ptr;
3390                 
3391                 if (state->if_value < 0) /* quit early when #if'd out */
3392                         break;
3393
3394                 meat(state, index, TOK_IDENT);
3395                 ident = tk->ident;
3396                 
3397
3398                 if (*file->pos == '(') {
3399 #warning "FIXME macros with arguments not supported"
3400                         error(state, 0, "Macros with arguments not supported");
3401                 }
3402
3403                 /* Find the end of the line to get an estimate of
3404                  * the macro's length.
3405                  */
3406                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3407                         ;
3408
3409                 if (ident->sym_define != 0) {
3410                         error(state, 0, "macro %s already defined\n", ident->name);
3411                 }
3412                 macro = xmalloc(sizeof(*macro), "macro");
3413                 macro->ident = ident;
3414                 macro->buf_len = ptr - file->pos +1;
3415                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3416
3417                 memcpy(macro->buf, file->pos, macro->buf_len);
3418                 macro->buf[macro->buf_len] = '\n';
3419                 macro->buf[macro->buf_len +1] = '\0';
3420
3421                 ident->sym_define = macro;
3422                 break;
3423         }
3424         case TOK_ERROR:
3425         {
3426                 char *end;
3427                 int len;
3428                 /* Find the end of the line */
3429                 for(end = file->pos; *end != '\n'; end++)
3430                         ;
3431                 len = (end - file->pos);
3432                 if (state->if_value >= 0) {
3433                         error(state, 0, "%*.*s", len, len, file->pos);
3434                 }
3435                 file->pos = end;
3436                 break;
3437         }
3438         case TOK_WARNING:
3439         {
3440                 char *end;
3441                 int len;
3442                 /* Find the end of the line */
3443                 for(end = file->pos; *end != '\n'; end++)
3444                         ;
3445                 len = (end - file->pos);
3446                 if (state->if_value >= 0) {
3447                         warning(state, 0, "%*.*s", len, len, file->pos);
3448                 }
3449                 file->pos = end;
3450                 break;
3451         }
3452         case TOK_INCLUDE:
3453         {
3454                 char *name;
3455                 char *ptr;
3456                 int local;
3457                 local = 0;
3458                 name = 0;
3459                 next_token(state, index);
3460                 if (tk->tok == TOK_LIT_STRING) {
3461                         const char *token;
3462                         int name_len;
3463                         name = xmalloc(tk->str_len, "include");
3464                         token = tk->val.str +1;
3465                         name_len = tk->str_len -2;
3466                         if (*token == '"') {
3467                                 token++;
3468                                 name_len--;
3469                         }
3470                         memcpy(name, token, name_len);
3471                         name[name_len] = '\0';
3472                         local = 1;
3473                 }
3474                 else if (tk->tok == TOK_LESS) {
3475                         char *start, *end;
3476                         start = file->pos;
3477                         for(end = start; *end != '\n'; end++) {
3478                                 if (*end == '>') {
3479                                         break;
3480                                 }
3481                         }
3482                         if (*end == '\n') {
3483                                 error(state, 0, "Unterminated included directive");
3484                         }
3485                         name = xmalloc(end - start + 1, "include");
3486                         memcpy(name, start, end - start);
3487                         name[end - start] = '\0';
3488                         file->pos = end +1;
3489                         local = 0;
3490                 }
3491                 else {
3492                         error(state, 0, "Invalid include directive");
3493                 }
3494                 /* Error if there are any characters after the include */
3495                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3496                         switch(*ptr) {
3497                         case ' ':
3498                         case '\t':
3499                         case '\v':
3500                                 break;
3501                         default:
3502                                 error(state, 0, "garbage after include directive");
3503                         }
3504                 }
3505                 if (state->if_value >= 0) {
3506                         compile_file(state, name, local);
3507                 }
3508                 xfree(name);
3509                 next_token(state, index);
3510                 return;
3511         }
3512         default:
3513                 /* Ignore # without a following ident */
3514                 if (tk->tok == TOK_IDENT) {
3515                         error(state, 0, "Invalid preprocessor directive: %s", 
3516                                 tk->ident->name);
3517                 }
3518                 break;
3519         }
3520         /* Consume the rest of the macro line */
3521         do {
3522                 tok = mpeek(state, index);
3523                 meat(state, index, tok);
3524         } while(tok != TOK_EOF);
3525         return;
3526 }
3527
3528 static void token(struct compile_state *state, int index)
3529 {
3530         struct file_state *file;
3531         struct token *tk;
3532         int rescan;
3533
3534         tk = &state->token[index];
3535         next_token(state, index);
3536         do {
3537                 rescan = 0;
3538                 file = state->file;
3539                 if (tk->tok == TOK_EOF && file->prev) {
3540                         state->file = file->prev;
3541                         /* file->basename is used keep it */
3542                         xfree(file->dirname);
3543                         xfree(file->buf);
3544                         xfree(file);
3545                         next_token(state, index);
3546                         rescan = 1;
3547                 }
3548                 else if (tk->tok == TOK_MACRO) {
3549                         preprocess(state, index);
3550                         rescan = 1;
3551                 }
3552                 else if (tk->ident && tk->ident->sym_define) {
3553                         compile_macro(state, tk);
3554                         next_token(state, index);
3555                         rescan = 1;
3556                 }
3557                 else if (state->if_value < 0) {
3558                         next_token(state, index);
3559                         rescan = 1;
3560                 }
3561         } while(rescan);
3562 }
3563
3564 static int peek(struct compile_state *state)
3565 {
3566         if (state->token[1].tok == -1) {
3567                 token(state, 1);
3568         }
3569         return state->token[1].tok;
3570 }
3571
3572 static int peek2(struct compile_state *state)
3573 {
3574         if (state->token[1].tok == -1) {
3575                 token(state, 1);
3576         }
3577         if (state->token[2].tok == -1) {
3578                 token(state, 2);
3579         }
3580         return state->token[2].tok;
3581 }
3582
3583 static void eat(struct compile_state *state, int tok)
3584 {
3585         int next_tok;
3586         int i;
3587         next_tok = peek(state);
3588         if (next_tok != tok) {
3589                 const char *name1, *name2;
3590                 name1 = tokens[next_tok];
3591                 name2 = "";
3592                 if (next_tok == TOK_IDENT) {
3593                         name2 = state->token[1].ident->name;
3594                 }
3595                 error(state, 0, "\tfound %s %s expected %s",
3596                         name1, name2 ,tokens[tok]);
3597         }
3598         /* Free the old token value */
3599         if (state->token[0].str_len) {
3600                 xfree((void *)(state->token[0].val.str));
3601         }
3602         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3603                 state->token[i] = state->token[i + 1];
3604         }
3605         memset(&state->token[i], 0, sizeof(state->token[i]));
3606         state->token[i].tok = -1;
3607 }
3608
3609 #warning "FIXME do not hardcode the include paths"
3610 static char *include_paths[] = {
3611         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3612         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3613         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3614         0
3615 };
3616
3617 static void compile_file(struct compile_state *state, const char *filename, int local)
3618 {
3619         char cwd[4096];
3620         const char *subdir, *base;
3621         int subdir_len;
3622         struct file_state *file;
3623         char *basename;
3624         file = xmalloc(sizeof(*file), "file_state");
3625
3626         base = strrchr(filename, '/');
3627         subdir = filename;
3628         if (base != 0) {
3629                 subdir_len = base - filename;
3630                 base++;
3631         }
3632         else {
3633                 base = filename;
3634                 subdir_len = 0;
3635         }
3636         basename = xmalloc(strlen(base) +1, "basename");
3637         strcpy(basename, base);
3638         file->basename = basename;
3639
3640         if (getcwd(cwd, sizeof(cwd)) == 0) {
3641                 die("cwd buffer to small");
3642         }
3643         
3644         if (subdir[0] == '/') {
3645                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3646                 memcpy(file->dirname, subdir, subdir_len);
3647                 file->dirname[subdir_len] = '\0';
3648         }
3649         else {
3650                 char *dir;
3651                 int dirlen;
3652                 char **path;
3653                 /* Find the appropriate directory... */
3654                 dir = 0;
3655                 if (!state->file && exists(cwd, filename)) {
3656                         dir = cwd;
3657                 }
3658                 if (local && state->file && exists(state->file->dirname, filename)) {
3659                         dir = state->file->dirname;
3660                 }
3661                 for(path = include_paths; !dir && *path; path++) {
3662                         if (exists(*path, filename)) {
3663                                 dir = *path;
3664                         }
3665                 }
3666                 if (!dir) {
3667                         error(state, 0, "Cannot find `%s'\n", filename);
3668                 }
3669                 dirlen = strlen(dir);
3670                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3671                 memcpy(file->dirname, dir, dirlen);
3672                 file->dirname[dirlen] = '/';
3673                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3674                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3675         }
3676         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3677         xchdir(cwd);
3678
3679         file->pos = file->buf;
3680         file->line_start = file->pos;
3681         file->line = 1;
3682
3683         file->report_line = 1;
3684         file->report_name = file->basename;
3685         file->report_dir  = file->dirname;
3686
3687         file->prev = state->file;
3688         state->file = file;
3689         
3690         process_trigraphs(state);
3691         splice_lines(state);
3692 }
3693
3694 /* Type helper functions */
3695
3696 static struct type *new_type(
3697         unsigned int type, struct type *left, struct type *right)
3698 {
3699         struct type *result;
3700         result = xmalloc(sizeof(*result), "type");
3701         result->type = type;
3702         result->left = left;
3703         result->right = right;
3704         result->field_ident = 0;
3705         result->type_ident = 0;
3706         return result;
3707 }
3708
3709 static struct type *clone_type(unsigned int specifiers, struct type *old)
3710 {
3711         struct type *result;
3712         result = xmalloc(sizeof(*result), "type");
3713         memcpy(result, old, sizeof(*result));
3714         result->type &= TYPE_MASK;
3715         result->type |= specifiers;
3716         return result;
3717 }
3718
3719 #define SIZEOF_SHORT 2
3720 #define SIZEOF_INT   4
3721 #define SIZEOF_LONG  (sizeof(long_t))
3722
3723 #define ALIGNOF_SHORT 2
3724 #define ALIGNOF_INT   4
3725 #define ALIGNOF_LONG  (sizeof(long_t))
3726
3727 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3728 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3729 static inline ulong_t mask_uint(ulong_t x)
3730 {
3731         if (SIZEOF_INT < SIZEOF_LONG) {
3732                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3733                 x &= mask;
3734         }
3735         return x;
3736 }
3737 #define MASK_UINT(X)      (mask_uint(X))
3738 #define MASK_ULONG(X)    (X)
3739
3740 static struct type void_type   = { .type  = TYPE_VOID };
3741 static struct type char_type   = { .type  = TYPE_CHAR };
3742 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3743 static struct type short_type  = { .type  = TYPE_SHORT };
3744 static struct type ushort_type = { .type  = TYPE_USHORT };
3745 static struct type int_type    = { .type  = TYPE_INT };
3746 static struct type uint_type   = { .type  = TYPE_UINT };
3747 static struct type long_type   = { .type  = TYPE_LONG };
3748 static struct type ulong_type  = { .type  = TYPE_ULONG };
3749
3750 static struct triple *variable(struct compile_state *state, struct type *type)
3751 {
3752         struct triple *result;
3753         if ((type->type & STOR_MASK) != STOR_PERM) {
3754                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3755                         result = triple(state, OP_ADECL, type, 0, 0);
3756                 } else {
3757                         struct type *field;
3758                         struct triple **vector;
3759                         ulong_t index;
3760                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3761                         vector = &result->param[0];
3762
3763                         field = type->left;
3764                         index = 0;
3765                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3766                                 vector[index] = variable(state, field->left);
3767                                 field = field->right;
3768                                 index++;
3769                         }
3770                         vector[index] = variable(state, field);
3771                 }
3772         }
3773         else {
3774                 result = triple(state, OP_SDECL, type, 0, 0);
3775         }
3776         return result;
3777 }
3778
3779 static void stor_of(FILE *fp, struct type *type)
3780 {
3781         switch(type->type & STOR_MASK) {
3782         case STOR_AUTO:
3783                 fprintf(fp, "auto ");
3784                 break;
3785         case STOR_STATIC:
3786                 fprintf(fp, "static ");
3787                 break;
3788         case STOR_EXTERN:
3789                 fprintf(fp, "extern ");
3790                 break;
3791         case STOR_REGISTER:
3792                 fprintf(fp, "register ");
3793                 break;
3794         case STOR_TYPEDEF:
3795                 fprintf(fp, "typedef ");
3796                 break;
3797         case STOR_INLINE:
3798                 fprintf(fp, "inline ");
3799                 break;
3800         }
3801 }
3802 static void qual_of(FILE *fp, struct type *type)
3803 {
3804         if (type->type & QUAL_CONST) {
3805                 fprintf(fp, " const");
3806         }
3807         if (type->type & QUAL_VOLATILE) {
3808                 fprintf(fp, " volatile");
3809         }
3810         if (type->type & QUAL_RESTRICT) {
3811                 fprintf(fp, " restrict");
3812         }
3813 }
3814
3815 static void name_of(FILE *fp, struct type *type)
3816 {
3817         stor_of(fp, type);
3818         switch(type->type & TYPE_MASK) {
3819         case TYPE_VOID:
3820                 fprintf(fp, "void");
3821                 qual_of(fp, type);
3822                 break;
3823         case TYPE_CHAR:
3824                 fprintf(fp, "signed char");
3825                 qual_of(fp, type);
3826                 break;
3827         case TYPE_UCHAR:
3828                 fprintf(fp, "unsigned char");
3829                 qual_of(fp, type);
3830                 break;
3831         case TYPE_SHORT:
3832                 fprintf(fp, "signed short");
3833                 qual_of(fp, type);
3834                 break;
3835         case TYPE_USHORT:
3836                 fprintf(fp, "unsigned short");
3837                 qual_of(fp, type);
3838                 break;
3839         case TYPE_INT:
3840                 fprintf(fp, "signed int");
3841                 qual_of(fp, type);
3842                 break;
3843         case TYPE_UINT:
3844                 fprintf(fp, "unsigned int");
3845                 qual_of(fp, type);
3846                 break;
3847         case TYPE_LONG:
3848                 fprintf(fp, "signed long");
3849                 qual_of(fp, type);
3850                 break;
3851         case TYPE_ULONG:
3852                 fprintf(fp, "unsigned long");
3853                 qual_of(fp, type);
3854                 break;
3855         case TYPE_POINTER:
3856                 name_of(fp, type->left);
3857                 fprintf(fp, " * ");
3858                 qual_of(fp, type);
3859                 break;
3860         case TYPE_PRODUCT:
3861         case TYPE_OVERLAP:
3862                 name_of(fp, type->left);
3863                 fprintf(fp, ", ");
3864                 name_of(fp, type->right);
3865                 break;
3866         case TYPE_ENUM:
3867                 fprintf(fp, "enum %s", type->type_ident->name);
3868                 qual_of(fp, type);
3869                 break;
3870         case TYPE_STRUCT:
3871                 fprintf(fp, "struct %s", type->type_ident->name);
3872                 qual_of(fp, type);
3873                 break;
3874         case TYPE_FUNCTION:
3875         {
3876                 name_of(fp, type->left);
3877                 fprintf(fp, " (*)(");
3878                 name_of(fp, type->right);
3879                 fprintf(fp, ")");
3880                 break;
3881         }
3882         case TYPE_ARRAY:
3883                 name_of(fp, type->left);
3884                 fprintf(fp, " [%ld]", type->elements);
3885                 break;
3886         default:
3887                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3888                 break;
3889         }
3890 }
3891
3892 static size_t align_of(struct compile_state *state, struct type *type)
3893 {
3894         size_t align;
3895         align = 0;
3896         switch(type->type & TYPE_MASK) {
3897         case TYPE_VOID:
3898                 align = 1;
3899                 break;
3900         case TYPE_CHAR:
3901         case TYPE_UCHAR:
3902                 align = 1;
3903                 break;
3904         case TYPE_SHORT:
3905         case TYPE_USHORT:
3906                 align = ALIGNOF_SHORT;
3907                 break;
3908         case TYPE_INT:
3909         case TYPE_UINT:
3910         case TYPE_ENUM:
3911                 align = ALIGNOF_INT;
3912                 break;
3913         case TYPE_LONG:
3914         case TYPE_ULONG:
3915         case TYPE_POINTER:
3916                 align = ALIGNOF_LONG;
3917                 break;
3918         case TYPE_PRODUCT:
3919         case TYPE_OVERLAP:
3920         {
3921                 size_t left_align, right_align;
3922                 left_align  = align_of(state, type->left);
3923                 right_align = align_of(state, type->right);
3924                 align = (left_align >= right_align) ? left_align : right_align;
3925                 break;
3926         }
3927         case TYPE_ARRAY:
3928                 align = align_of(state, type->left);
3929                 break;
3930         case TYPE_STRUCT:
3931                 align = align_of(state, type->left);
3932                 break;
3933         default:
3934                 error(state, 0, "alignof not yet defined for type\n");
3935                 break;
3936         }
3937         return align;
3938 }
3939
3940 static size_t needed_padding(size_t offset, size_t align)
3941 {
3942         size_t padding;
3943         padding = 0;
3944         if (offset % align) {
3945                 padding = align - (offset % align);
3946         }
3947         return padding;
3948 }
3949 static size_t size_of(struct compile_state *state, struct type *type)
3950 {
3951         size_t size;
3952         size = 0;
3953         switch(type->type & TYPE_MASK) {
3954         case TYPE_VOID:
3955                 size = 0;
3956                 break;
3957         case TYPE_CHAR:
3958         case TYPE_UCHAR:
3959                 size = 1;
3960                 break;
3961         case TYPE_SHORT:
3962         case TYPE_USHORT:
3963                 size = SIZEOF_SHORT;
3964                 break;
3965         case TYPE_INT:
3966         case TYPE_UINT:
3967         case TYPE_ENUM:
3968                 size = SIZEOF_INT;
3969                 break;
3970         case TYPE_LONG:
3971         case TYPE_ULONG:
3972         case TYPE_POINTER:
3973                 size = SIZEOF_LONG;
3974                 break;
3975         case TYPE_PRODUCT:
3976         {
3977                 size_t align, pad;
3978                 size = 0;
3979                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3980                         align = align_of(state, type->left);
3981                         pad = needed_padding(size, align);
3982                         size = size + pad + size_of(state, type->left);
3983                         type = type->right;
3984                 }
3985                 align = align_of(state, type);
3986                 pad = needed_padding(size, align);
3987                 size = size + pad + sizeof(type);
3988                 break;
3989         }
3990         case TYPE_OVERLAP:
3991         {
3992                 size_t size_left, size_right;
3993                 size_left = size_of(state, type->left);
3994                 size_right = size_of(state, type->right);
3995                 size = (size_left >= size_right)? size_left : size_right;
3996                 break;
3997         }
3998         case TYPE_ARRAY:
3999                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4000                         internal_error(state, 0, "Invalid array type");
4001                 } else {
4002                         size = size_of(state, type->left) * type->elements;
4003                 }
4004                 break;
4005         case TYPE_STRUCT:
4006                 size = size_of(state, type->left);
4007                 break;
4008         default:
4009                 internal_error(state, 0, "sizeof not yet defined for type\n");
4010                 break;
4011         }
4012         return size;
4013 }
4014
4015 static size_t field_offset(struct compile_state *state, 
4016         struct type *type, struct hash_entry *field)
4017 {
4018         struct type *member;
4019         size_t size, align;
4020         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4021                 internal_error(state, 0, "field_offset only works on structures");
4022         }
4023         size = 0;
4024         member = type->left;
4025         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4026                 align = align_of(state, member->left);
4027                 size += needed_padding(size, align);
4028                 if (member->left->field_ident == field) {
4029                         member = member->left;
4030                         break;
4031                 }
4032                 size += size_of(state, member->left);
4033                 member = member->right;
4034         }
4035         align = align_of(state, member);
4036         size += needed_padding(size, align);
4037         if (member->field_ident != field) {
4038                 error(state, 0, "member %s not present", field->name);
4039         }
4040         return size;
4041 }
4042
4043 static struct type *field_type(struct compile_state *state, 
4044         struct type *type, struct hash_entry *field)
4045 {
4046         struct type *member;
4047         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4048                 internal_error(state, 0, "field_type only works on structures");
4049         }
4050         member = type->left;
4051         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4052                 if (member->left->field_ident == field) {
4053                         member = member->left;
4054                         break;
4055                 }
4056                 member = member->right;
4057         }
4058         if (member->field_ident != field) {
4059                 error(state, 0, "member %s not present", field->name);
4060         }
4061         return member;
4062 }
4063
4064 static struct type *next_field(struct compile_state *state,
4065         struct type *type, struct type *prev_member) 
4066 {
4067         struct type *member;
4068         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4069                 internal_error(state, 0, "next_field only works on structures");
4070         }
4071         member = type->left;
4072         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4073                 if (!prev_member) {
4074                         member = member->left;
4075                         break;
4076                 }
4077                 if (member->left == prev_member) {
4078                         prev_member = 0;
4079                 }
4080                 member = member->right;
4081         }
4082         if (member == prev_member) {
4083                 prev_member = 0;
4084         }
4085         if (prev_member) {
4086                 internal_error(state, 0, "prev_member %s not present", 
4087                         prev_member->field_ident->name);
4088         }
4089         return member;
4090 }
4091
4092 static struct triple *struct_field(struct compile_state *state,
4093         struct triple *decl, struct hash_entry *field)
4094 {
4095         struct triple **vector;
4096         struct type *type;
4097         ulong_t index;
4098         type = decl->type;
4099         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4100                 return decl;
4101         }
4102         if (decl->op != OP_VAL_VEC) {
4103                 internal_error(state, 0, "Invalid struct variable");
4104         }
4105         if (!field) {
4106                 internal_error(state, 0, "Missing structure field");
4107         }
4108         type = type->left;
4109         vector = &RHS(decl, 0);
4110         index = 0;
4111         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4112                 if (type->left->field_ident == field) {
4113                         type = type->left;
4114                         break;
4115                 }
4116                 index += 1;
4117                 type = type->right;
4118         }
4119         if (type->field_ident != field) {
4120                 internal_error(state, 0, "field %s not found?", field->name);
4121         }
4122         return vector[index];
4123 }
4124
4125 static void arrays_complete(struct compile_state *state, struct type *type)
4126 {
4127         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4128                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4129                         error(state, 0, "array size not specified");
4130                 }
4131                 arrays_complete(state, type->left);
4132         }
4133 }
4134
4135 static unsigned int do_integral_promotion(unsigned int type)
4136 {
4137         type &= TYPE_MASK;
4138         if (TYPE_INTEGER(type) && 
4139                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4140                 type = TYPE_INT;
4141         }
4142         return type;
4143 }
4144
4145 static unsigned int do_arithmetic_conversion(
4146         unsigned int left, unsigned int right)
4147 {
4148         left &= TYPE_MASK;
4149         right &= TYPE_MASK;
4150         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4151                 return TYPE_LDOUBLE;
4152         }
4153         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4154                 return TYPE_DOUBLE;
4155         }
4156         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4157                 return TYPE_FLOAT;
4158         }
4159         left = do_integral_promotion(left);
4160         right = do_integral_promotion(right);
4161         /* If both operands have the same size done */
4162         if (left == right) {
4163                 return left;
4164         }
4165         /* If both operands have the same signedness pick the larger */
4166         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4167                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4168         }
4169         /* If the signed type can hold everything use it */
4170         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4171                 return left;
4172         }
4173         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4174                 return right;
4175         }
4176         /* Convert to the unsigned type with the same rank as the signed type */
4177         else if (TYPE_SIGNED(left)) {
4178                 return TYPE_MKUNSIGNED(left);
4179         }
4180         else {
4181                 return TYPE_MKUNSIGNED(right);
4182         }
4183 }
4184
4185 /* see if two types are the same except for qualifiers */
4186 static int equiv_types(struct type *left, struct type *right)
4187 {
4188         unsigned int type;
4189         /* Error if the basic types do not match */
4190         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4191                 return 0;
4192         }
4193         type = left->type & TYPE_MASK;
4194         /* if the basic types match and it is an arithmetic type we are done */
4195         if (TYPE_ARITHMETIC(type)) {
4196                 return 1;
4197         }
4198         /* If it is a pointer type recurse and keep testing */
4199         if (type == TYPE_POINTER) {
4200                 return equiv_types(left->left, right->left);
4201         }
4202         else if (type == TYPE_ARRAY) {
4203                 return (left->elements == right->elements) &&
4204                         equiv_types(left->left, right->left);
4205         }
4206         /* test for struct/union equality */
4207         else if (type == TYPE_STRUCT) {
4208                 return left->type_ident == right->type_ident;
4209         }
4210         /* Test for equivalent functions */
4211         else if (type == TYPE_FUNCTION) {
4212                 return equiv_types(left->left, right->left) &&
4213                         equiv_types(left->right, right->right);
4214         }
4215         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4216         else if (type == TYPE_PRODUCT) {
4217                 return equiv_types(left->left, right->left) &&
4218                         equiv_types(left->right, right->right);
4219         }
4220         /* We should see TYPE_OVERLAP */
4221         else {
4222                 return 0;
4223         }
4224 }
4225
4226 static int equiv_ptrs(struct type *left, struct type *right)
4227 {
4228         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4229                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4230                 return 0;
4231         }
4232         return equiv_types(left->left, right->left);
4233 }
4234
4235 static struct type *compatible_types(struct type *left, struct type *right)
4236 {
4237         struct type *result;
4238         unsigned int type, qual_type;
4239         /* Error if the basic types do not match */
4240         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4241                 return 0;
4242         }
4243         type = left->type & TYPE_MASK;
4244         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4245         result = 0;
4246         /* if the basic types match and it is an arithmetic type we are done */
4247         if (TYPE_ARITHMETIC(type)) {
4248                 result = new_type(qual_type, 0, 0);
4249         }
4250         /* If it is a pointer type recurse and keep testing */
4251         else if (type == TYPE_POINTER) {
4252                 result = compatible_types(left->left, right->left);
4253                 if (result) {
4254                         result = new_type(qual_type, result, 0);
4255                 }
4256         }
4257         /* test for struct/union equality */
4258         else if (type == TYPE_STRUCT) {
4259                 if (left->type_ident == right->type_ident) {
4260                         result = left;
4261                 }
4262         }
4263         /* Test for equivalent functions */
4264         else if (type == TYPE_FUNCTION) {
4265                 struct type *lf, *rf;
4266                 lf = compatible_types(left->left, right->left);
4267                 rf = compatible_types(left->right, right->right);
4268                 if (lf && rf) {
4269                         result = new_type(qual_type, lf, rf);
4270                 }
4271         }
4272         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4273         else if (type == TYPE_PRODUCT) {
4274                 struct type *lf, *rf;
4275                 lf = compatible_types(left->left, right->left);
4276                 rf = compatible_types(left->right, right->right);
4277                 if (lf && rf) {
4278                         result = new_type(qual_type, lf, rf);
4279                 }
4280         }
4281         else {
4282                 /* Nothing else is compatible */
4283         }
4284         return result;
4285 }
4286
4287 static struct type *compatible_ptrs(struct type *left, struct type *right)
4288 {
4289         struct type *result;
4290         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4291                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4292                 return 0;
4293         }
4294         result = compatible_types(left->left, right->left);
4295         if (result) {
4296                 unsigned int qual_type;
4297                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4298                 result = new_type(qual_type, result, 0);
4299         }
4300         return result;
4301         
4302 }
4303 static struct triple *integral_promotion(
4304         struct compile_state *state, struct triple *def)
4305 {
4306         struct type *type;
4307         type = def->type;
4308         /* As all operations are carried out in registers
4309          * the values are converted on load I just convert
4310          * logical type of the operand.
4311          */
4312         if (TYPE_INTEGER(type->type)) {
4313                 unsigned int int_type;
4314                 int_type = type->type & ~TYPE_MASK;
4315                 int_type |= do_integral_promotion(type->type);
4316                 if (int_type != type->type) {
4317                         def->type = new_type(int_type, 0, 0);
4318                 }
4319         }
4320         return def;
4321 }
4322
4323
4324 static void arithmetic(struct compile_state *state, struct triple *def)
4325 {
4326         if (!TYPE_ARITHMETIC(def->type->type)) {
4327                 error(state, 0, "arithmetic type expexted");
4328         }
4329 }
4330
4331 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4332 {
4333         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4334                 error(state, def, "pointer or arithmetic type expected");
4335         }
4336 }
4337
4338 static int is_integral(struct triple *ins)
4339 {
4340         return TYPE_INTEGER(ins->type->type);
4341 }
4342
4343 static void integral(struct compile_state *state, struct triple *def)
4344 {
4345         if (!is_integral(def)) {
4346                 error(state, 0, "integral type expected");
4347         }
4348 }
4349
4350
4351 static void bool(struct compile_state *state, struct triple *def)
4352 {
4353         if (!TYPE_ARITHMETIC(def->type->type) &&
4354                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4355                 error(state, 0, "arithmetic or pointer type expected");
4356         }
4357 }
4358
4359 static int is_signed(struct type *type)
4360 {
4361         return !!TYPE_SIGNED(type->type);
4362 }
4363
4364 /* Is this value located in a register otherwise it must be in memory */
4365 static int is_in_reg(struct compile_state *state, struct triple *def)
4366 {
4367         int in_reg;
4368         if (def->op == OP_ADECL) {
4369                 in_reg = 1;
4370         }
4371         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4372                 in_reg = 0;
4373         }
4374         else if (def->op == OP_VAL_VEC) {
4375                 in_reg = is_in_reg(state, RHS(def, 0));
4376         }
4377         else if (def->op == OP_DOT) {
4378                 in_reg = is_in_reg(state, RHS(def, 0));
4379         }
4380         else {
4381                 internal_error(state, 0, "unknown expr storage location");
4382                 in_reg = -1;
4383         }
4384         return in_reg;
4385 }
4386
4387 /* Is this a stable variable location otherwise it must be a temporary */
4388 static int is_stable(struct compile_state *state, struct triple *def)
4389 {
4390         int ret;
4391         ret = 0;
4392         if (!def) {
4393                 return 0;
4394         }
4395         if ((def->op == OP_ADECL) || 
4396                 (def->op == OP_SDECL) || 
4397                 (def->op == OP_DEREF) ||
4398                 (def->op == OP_BLOBCONST)) {
4399                 ret = 1;
4400         }
4401         else if (def->op == OP_DOT) {
4402                 ret = is_stable(state, RHS(def, 0));
4403         }
4404         else if (def->op == OP_VAL_VEC) {
4405                 struct triple **vector;
4406                 ulong_t i;
4407                 ret = 1;
4408                 vector = &RHS(def, 0);
4409                 for(i = 0; i < def->type->elements; i++) {
4410                         if (!is_stable(state, vector[i])) {
4411                                 ret = 0;
4412                                 break;
4413                         }
4414                 }
4415         }
4416         return ret;
4417 }
4418
4419 static int is_lvalue(struct compile_state *state, struct triple *def)
4420 {
4421         int ret;
4422         ret = 1;
4423         if (!def) {
4424                 return 0;
4425         }
4426         if (!is_stable(state, def)) {
4427                 return 0;
4428         }
4429         if (def->op == OP_DOT) {
4430                 ret = is_lvalue(state, RHS(def, 0));
4431         }
4432         return ret;
4433 }
4434
4435 static void clvalue(struct compile_state *state, struct triple *def)
4436 {
4437         if (!def) {
4438                 internal_error(state, def, "nothing where lvalue expected?");
4439         }
4440         if (!is_lvalue(state, def)) { 
4441                 error(state, def, "lvalue expected");
4442         }
4443 }
4444 static void lvalue(struct compile_state *state, struct triple *def)
4445 {
4446         clvalue(state, def);
4447         if (def->type->type & QUAL_CONST) {
4448                 error(state, def, "modifable lvalue expected");
4449         }
4450 }
4451
4452 static int is_pointer(struct triple *def)
4453 {
4454         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4455 }
4456
4457 static void pointer(struct compile_state *state, struct triple *def)
4458 {
4459         if (!is_pointer(def)) {
4460                 error(state, def, "pointer expected");
4461         }
4462 }
4463
4464 static struct triple *int_const(
4465         struct compile_state *state, struct type *type, ulong_t value)
4466 {
4467         struct triple *result;
4468         switch(type->type & TYPE_MASK) {
4469         case TYPE_CHAR:
4470         case TYPE_INT:   case TYPE_UINT:
4471         case TYPE_LONG:  case TYPE_ULONG:
4472                 break;
4473         default:
4474                 internal_error(state, 0, "constant for unkown type");
4475         }
4476         result = triple(state, OP_INTCONST, type, 0, 0);
4477         result->u.cval = value;
4478         return result;
4479 }
4480
4481
4482 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4483         struct triple *expr, struct type *type, ulong_t offset)
4484 {
4485         struct triple *result;
4486         clvalue(state, expr);
4487
4488         type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4489
4490         result = 0;
4491         if (expr->op == OP_ADECL) {
4492                 error(state, expr, "address of auto variables not supported");
4493         }
4494         else if (expr->op == OP_SDECL) {
4495                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4496                 MISC(result, 0) = expr;
4497                 result->u.cval = offset;
4498         }
4499         else if (expr->op == OP_DEREF) {
4500                 result = triple(state, OP_ADD, type,
4501                         RHS(expr, 0),
4502                         int_const(state, &ulong_type, offset));
4503         }
4504         return result;
4505 }
4506
4507 static struct triple *mk_addr_expr(
4508         struct compile_state *state, struct triple *expr, ulong_t offset)
4509 {
4510         return do_mk_addr_expr(state, expr, expr->type, offset);
4511 }
4512
4513 static struct triple *mk_deref_expr(
4514         struct compile_state *state, struct triple *expr)
4515 {
4516         struct type *base_type;
4517         pointer(state, expr);
4518         base_type = expr->type->left;
4519         return triple(state, OP_DEREF, base_type, expr, 0);
4520 }
4521
4522 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4523 {
4524         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4525                 struct type *type;
4526                 struct triple *addrconst;
4527                 type = new_type(
4528                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4529                         def->type->left, 0);
4530                 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4531                 MISC(addrconst, 0) = def;
4532                 def = addrconst;
4533         }
4534         return def;
4535 }
4536
4537 static struct triple *deref_field(
4538         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4539 {
4540         struct triple *result;
4541         struct type *type, *member;
4542         if (!field) {
4543                 internal_error(state, 0, "No field passed to deref_field");
4544         }
4545         result = 0;
4546         type = expr->type;
4547         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4548                 error(state, 0, "request for member %s in something not a struct or union",
4549                         field->name);
4550         }
4551         member = field_type(state, type, field);
4552         if ((type->type & STOR_MASK) == STOR_PERM) {
4553                 /* Do the pointer arithmetic to get a deref the field */
4554                 ulong_t offset;
4555                 offset = field_offset(state, type, field);
4556                 result = do_mk_addr_expr(state, expr, member, offset);
4557                 result = mk_deref_expr(state, result);
4558         }
4559         else {
4560                 /* Find the variable for the field I want. */
4561                 result = triple(state, OP_DOT, member, expr, 0);
4562                 result->u.field = field;
4563         }
4564         return result;
4565 }
4566
4567 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4568 {
4569         int op;
4570         if  (!def) {
4571                 return 0;
4572         }
4573         if (!is_stable(state, def)) {
4574                 return def;
4575         }
4576         /* Tranform an array to a pointer to the first element */
4577         
4578 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4579         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4580                 return array_to_pointer(state, def);
4581         }
4582         if (is_in_reg(state, def)) {
4583                 op = OP_READ;
4584         } else {
4585                 op = OP_LOAD;
4586         }
4587         return triple(state, op, def->type, def, 0);
4588 }
4589
4590 static void write_compatible(struct compile_state *state,
4591         struct type *dest, struct type *rval)
4592 {
4593         int compatible = 0;
4594         /* Both operands have arithmetic type */
4595         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4596                 compatible = 1;
4597         }
4598         /* One operand is a pointer and the other is a pointer to void */
4599         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4600                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4601                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4602                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4603                 compatible = 1;
4604         }
4605         /* If both types are the same without qualifiers we are good */
4606         else if (equiv_ptrs(dest, rval)) {
4607                 compatible = 1;
4608         }
4609         /* test for struct/union equality  */
4610         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4611                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4612                 (dest->type_ident == rval->type_ident)) {
4613                 compatible = 1;
4614         }
4615         if (!compatible) {
4616                 error(state, 0, "Incompatible types in assignment");
4617         }
4618 }
4619
4620 static struct triple *write_expr(
4621         struct compile_state *state, struct triple *dest, struct triple *rval)
4622 {
4623         struct triple *def;
4624         int op;
4625
4626         def = 0;
4627         if (!rval) {
4628                 internal_error(state, 0, "missing rval");
4629         }
4630
4631         if (rval->op == OP_LIST) {
4632                 internal_error(state, 0, "expression of type OP_LIST?");
4633         }
4634         if (!is_lvalue(state, dest)) {
4635                 internal_error(state, 0, "writing to a non lvalue?");
4636         }
4637         if (dest->type->type & QUAL_CONST) {
4638                 internal_error(state, 0, "modifable lvalue expexted");
4639         }
4640
4641         write_compatible(state, dest->type, rval->type);
4642
4643         /* Now figure out which assignment operator to use */
4644         op = -1;
4645         if (is_in_reg(state, dest)) {
4646                 op = OP_WRITE;
4647         } else {
4648                 op = OP_STORE;
4649         }
4650         def = triple(state, op, dest->type, dest, rval);
4651         return def;
4652 }
4653
4654 static struct triple *init_expr(
4655         struct compile_state *state, struct triple *dest, struct triple *rval)
4656 {
4657         struct triple *def;
4658
4659         def = 0;
4660         if (!rval) {
4661                 internal_error(state, 0, "missing rval");
4662         }
4663         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4664                 rval = read_expr(state, rval);
4665                 def = write_expr(state, dest, rval);
4666         }
4667         else {
4668                 /* Fill in the array size if necessary */
4669                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4670                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4671                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4672                                 dest->type->elements = rval->type->elements;
4673                         }
4674                 }
4675                 if (!equiv_types(dest->type, rval->type)) {
4676                         error(state, 0, "Incompatible types in inializer");
4677                 }
4678                 MISC(dest, 0) = rval;
4679                 insert_triple(state, dest, rval);
4680                 rval->id |= TRIPLE_FLAG_FLATTENED;
4681                 use_triple(MISC(dest, 0), dest);
4682         }
4683         return def;
4684 }
4685
4686 struct type *arithmetic_result(
4687         struct compile_state *state, struct triple *left, struct triple *right)
4688 {
4689         struct type *type;
4690         /* Sanity checks to ensure I am working with arithmetic types */
4691         arithmetic(state, left);
4692         arithmetic(state, right);
4693         type = new_type(
4694                 do_arithmetic_conversion(
4695                         left->type->type, 
4696                         right->type->type), 0, 0);
4697         return type;
4698 }
4699
4700 struct type *ptr_arithmetic_result(
4701         struct compile_state *state, struct triple *left, struct triple *right)
4702 {
4703         struct type *type;
4704         /* Sanity checks to ensure I am working with the proper types */
4705         ptr_arithmetic(state, left);
4706         arithmetic(state, right);
4707         if (TYPE_ARITHMETIC(left->type->type) && 
4708                 TYPE_ARITHMETIC(right->type->type)) {
4709                 type = arithmetic_result(state, left, right);
4710         }
4711         else if (TYPE_PTR(left->type->type)) {
4712                 type = left->type;
4713         }
4714         else {
4715                 internal_error(state, 0, "huh?");
4716                 type = 0;
4717         }
4718         return type;
4719 }
4720
4721
4722 /* boolean helper function */
4723
4724 static struct triple *ltrue_expr(struct compile_state *state, 
4725         struct triple *expr)
4726 {
4727         switch(expr->op) {
4728         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4729         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4730         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4731                 /* If the expression is already boolean do nothing */
4732                 break;
4733         default:
4734                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4735                 break;
4736         }
4737         return expr;
4738 }
4739
4740 static struct triple *lfalse_expr(struct compile_state *state, 
4741         struct triple *expr)
4742 {
4743         return triple(state, OP_LFALSE, &int_type, expr, 0);
4744 }
4745
4746 static struct triple *cond_expr(
4747         struct compile_state *state, 
4748         struct triple *test, struct triple *left, struct triple *right)
4749 {
4750         struct triple *def;
4751         struct type *result_type;
4752         unsigned int left_type, right_type;
4753         bool(state, test);
4754         left_type = left->type->type;
4755         right_type = right->type->type;
4756         result_type = 0;
4757         /* Both operands have arithmetic type */
4758         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4759                 result_type = arithmetic_result(state, left, right);
4760         }
4761         /* Both operands have void type */
4762         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4763                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4764                 result_type = &void_type;
4765         }
4766         /* pointers to the same type... */
4767         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4768                 ;
4769         }
4770         /* Both operands are pointers and left is a pointer to void */
4771         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4772                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4773                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4774                 result_type = right->type;
4775         }
4776         /* Both operands are pointers and right is a pointer to void */
4777         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4778                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4779                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4780                 result_type = left->type;
4781         }
4782         if (!result_type) {
4783                 error(state, 0, "Incompatible types in conditional expression");
4784         }
4785         /* Cleanup and invert the test */
4786         test = lfalse_expr(state, read_expr(state, test));
4787         def = new_triple(state, OP_COND, result_type, 0, 3);
4788         def->param[0] = test;
4789         def->param[1] = left;
4790         def->param[2] = right;
4791         return def;
4792 }
4793
4794
4795 static int expr_depth(struct compile_state *state, struct triple *ins)
4796 {
4797         int count;
4798         count = 0;
4799         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4800                 count = 0;
4801         }
4802         else if (ins->op == OP_DEREF) {
4803                 count = expr_depth(state, RHS(ins, 0)) - 1;
4804         }
4805         else if (ins->op == OP_VAL) {
4806                 count = expr_depth(state, RHS(ins, 0)) - 1;
4807         }
4808         else if (ins->op == OP_COMMA) {
4809                 int ldepth, rdepth;
4810                 ldepth = expr_depth(state, RHS(ins, 0));
4811                 rdepth = expr_depth(state, RHS(ins, 1));
4812                 count = (ldepth >= rdepth)? ldepth : rdepth;
4813         }
4814         else if (ins->op == OP_CALL) {
4815                 /* Don't figure the depth of a call just guess it is huge */
4816                 count = 1000;
4817         }
4818         else {
4819                 struct triple **expr;
4820                 expr = triple_rhs(state, ins, 0);
4821                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4822                         if (*expr) {
4823                                 int depth;
4824                                 depth = expr_depth(state, *expr);
4825                                 if (depth > count) {
4826                                         count = depth;
4827                                 }
4828                         }
4829                 }
4830         }
4831         return count + 1;
4832 }
4833
4834 static struct triple *flatten(
4835         struct compile_state *state, struct triple *first, struct triple *ptr);
4836
4837 static struct triple *flatten_generic(
4838         struct compile_state *state, struct triple *first, struct triple *ptr)
4839 {
4840         struct rhs_vector {
4841                 int depth;
4842                 struct triple **ins;
4843         } vector[MAX_RHS];
4844         int i, rhs, lhs;
4845         /* Only operations with just a rhs should come here */
4846         rhs = TRIPLE_RHS(ptr->sizes);
4847         lhs = TRIPLE_LHS(ptr->sizes);
4848         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4849                 internal_error(state, ptr, "unexpected args for: %d %s",
4850                         ptr->op, tops(ptr->op));
4851         }
4852         /* Find the depth of the rhs elements */
4853         for(i = 0; i < rhs; i++) {
4854                 vector[i].ins = &RHS(ptr, i);
4855                 vector[i].depth = expr_depth(state, *vector[i].ins);
4856         }
4857         /* Selection sort the rhs */
4858         for(i = 0; i < rhs; i++) {
4859                 int j, max = i;
4860                 for(j = i + 1; j < rhs; j++ ) {
4861                         if (vector[j].depth > vector[max].depth) {
4862                                 max = j;
4863                         }
4864                 }
4865                 if (max != i) {
4866                         struct rhs_vector tmp;
4867                         tmp = vector[i];
4868                         vector[i] = vector[max];
4869                         vector[max] = tmp;
4870                 }
4871         }
4872         /* Now flatten the rhs elements */
4873         for(i = 0; i < rhs; i++) {
4874                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4875                 use_triple(*vector[i].ins, ptr);
4876         }
4877         
4878         /* Now flatten the lhs elements */
4879         for(i = 0; i < lhs; i++) {
4880                 struct triple **ins = &LHS(ptr, i);
4881                 *ins = flatten(state, first, *ins);
4882                 use_triple(*ins, ptr);
4883         }
4884         return ptr;
4885 }
4886
4887 static struct triple *flatten_land(
4888         struct compile_state *state, struct triple *first, struct triple *ptr)
4889 {
4890         struct triple *left, *right;
4891         struct triple *val, *test, *jmp, *label1, *end;
4892
4893         /* Find the triples */
4894         left = RHS(ptr, 0);
4895         right = RHS(ptr, 1);
4896
4897         /* Generate the needed triples */
4898         end = label(state);
4899
4900         /* Thread the triples together */
4901         val          = flatten(state, first, variable(state, ptr->type));
4902         left         = flatten(state, first, write_expr(state, val, left));
4903         test         = flatten(state, first, 
4904                 lfalse_expr(state, read_expr(state, val)));
4905         jmp          = flatten(state, first, branch(state, end, test));
4906         label1       = flatten(state, first, label(state));
4907         right        = flatten(state, first, write_expr(state, val, right));
4908         TARG(jmp, 0) = flatten(state, first, end); 
4909         
4910         /* Now give the caller something to chew on */
4911         return read_expr(state, val);
4912 }
4913
4914 static struct triple *flatten_lor(
4915         struct compile_state *state, struct triple *first, struct triple *ptr)
4916 {
4917         struct triple *left, *right;
4918         struct triple *val, *jmp, *label1, *end;
4919
4920         /* Find the triples */
4921         left = RHS(ptr, 0);
4922         right = RHS(ptr, 1);
4923
4924         /* Generate the needed triples */
4925         end = label(state);
4926
4927         /* Thread the triples together */
4928         val          = flatten(state, first, variable(state, ptr->type));
4929         left         = flatten(state, first, write_expr(state, val, left));
4930         jmp          = flatten(state, first, branch(state, end, left));
4931         label1       = flatten(state, first, label(state));
4932         right        = flatten(state, first, write_expr(state, val, right));
4933         TARG(jmp, 0) = flatten(state, first, end);
4934        
4935         
4936         /* Now give the caller something to chew on */
4937         return read_expr(state, val);
4938 }
4939
4940 static struct triple *flatten_cond(
4941         struct compile_state *state, struct triple *first, struct triple *ptr)
4942 {
4943         struct triple *test, *left, *right;
4944         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4945
4946         /* Find the triples */
4947         test = RHS(ptr, 0);
4948         left = RHS(ptr, 1);
4949         right = RHS(ptr, 2);
4950
4951         /* Generate the needed triples */
4952         end = label(state);
4953         middle = label(state);
4954
4955         /* Thread the triples together */
4956         val           = flatten(state, first, variable(state, ptr->type));
4957         test          = flatten(state, first, test);
4958         jmp1          = flatten(state, first, branch(state, middle, test));
4959         label1        = flatten(state, first, label(state));
4960         left          = flatten(state, first, left);
4961         mv1           = flatten(state, first, write_expr(state, val, left));
4962         jmp2          = flatten(state, first, branch(state, end, 0));
4963         TARG(jmp1, 0) = flatten(state, first, middle);
4964         right         = flatten(state, first, right);
4965         mv2           = flatten(state, first, write_expr(state, val, right));
4966         TARG(jmp2, 0) = flatten(state, first, end);
4967         
4968         /* Now give the caller something to chew on */
4969         return read_expr(state, val);
4970 }
4971
4972 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
4973         struct occurance *base_occurance)
4974 {
4975         struct triple *nfunc;
4976         struct triple *nfirst, *ofirst;
4977         struct triple *new, *old;
4978
4979 #if 0
4980         fprintf(stdout, "\n");
4981         loc(stdout, state, 0);
4982         fprintf(stdout, "\n__________ copy_func _________\n");
4983         print_triple(state, ofunc);
4984         fprintf(stdout, "__________ copy_func _________ done\n\n");
4985 #endif
4986
4987         /* Make a new copy of the old function */
4988         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4989         nfirst = 0;
4990         ofirst = old = RHS(ofunc, 0);
4991         do {
4992                 struct triple *new;
4993                 struct occurance *occurance;
4994                 int old_lhs, old_rhs;
4995                 old_lhs = TRIPLE_LHS(old->sizes);
4996                 old_rhs = TRIPLE_RHS(old->sizes);
4997                 occurance = inline_occurance(state, base_occurance, old->occurance);
4998                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4999                         occurance);
5000                 if (!triple_stores_block(state, new)) {
5001                         memcpy(&new->u, &old->u, sizeof(new->u));
5002                 }
5003                 if (!nfirst) {
5004                         RHS(nfunc, 0) = nfirst = new;
5005                 }
5006                 else {
5007                         insert_triple(state, nfirst, new);
5008                 }
5009                 new->id |= TRIPLE_FLAG_FLATTENED;
5010                 
5011                 /* During the copy remember new as user of old */
5012                 use_triple(old, new);
5013
5014                 /* Populate the return type if present */
5015                 if (old == MISC(ofunc, 0)) {
5016                         MISC(nfunc, 0) = new;
5017                 }
5018                 old = old->next;
5019         } while(old != ofirst);
5020
5021         /* Make a second pass to fix up any unresolved references */
5022         old = ofirst;
5023         new = nfirst;
5024         do {
5025                 struct triple **oexpr, **nexpr;
5026                 int count, i;
5027                 /* Lookup where the copy is, to join pointers */
5028                 count = TRIPLE_SIZE(old->sizes);
5029                 for(i = 0; i < count; i++) {
5030                         oexpr = &old->param[i];
5031                         nexpr = &new->param[i];
5032                         if (!*nexpr && *oexpr && (*oexpr)->use) {
5033                                 *nexpr = (*oexpr)->use->member;
5034                                 if (*nexpr == old) {
5035                                         internal_error(state, 0, "new == old?");
5036                                 }
5037                                 use_triple(*nexpr, new);
5038                         }
5039                         if (!*nexpr && *oexpr) {
5040                                 internal_error(state, 0, "Could not copy %d\n", i);
5041                         }
5042                 }
5043                 old = old->next;
5044                 new = new->next;
5045         } while((old != ofirst) && (new != nfirst));
5046         
5047         /* Make a third pass to cleanup the extra useses */
5048         old = ofirst;
5049         new = nfirst;
5050         do {
5051                 unuse_triple(old, new);
5052                 old = old->next;
5053                 new = new->next;
5054         } while ((old != ofirst) && (new != nfirst));
5055         return nfunc;
5056 }
5057
5058 static struct triple *flatten_call(
5059         struct compile_state *state, struct triple *first, struct triple *ptr)
5060 {
5061         /* Inline the function call */
5062         struct type *ptype;
5063         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5064         struct triple *end, *nend;
5065         int pvals, i;
5066
5067         /* Find the triples */
5068         ofunc = MISC(ptr, 0);
5069         if (ofunc->op != OP_LIST) {
5070                 internal_error(state, 0, "improper function");
5071         }
5072         nfunc = copy_func(state, ofunc, ptr->occurance);
5073         nfirst = RHS(nfunc, 0)->next;
5074         /* Prepend the parameter reading into the new function list */
5075         ptype = nfunc->type->right;
5076         param = RHS(nfunc, 0)->next;
5077         pvals = TRIPLE_RHS(ptr->sizes);
5078         for(i = 0; i < pvals; i++) {
5079                 struct type *atype;
5080                 struct triple *arg;
5081                 atype = ptype;
5082                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5083                         atype = ptype->left;
5084                 }
5085                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5086                         param = param->next;
5087                 }
5088                 arg = RHS(ptr, i);
5089                 flatten(state, nfirst, write_expr(state, param, arg));
5090                 ptype = ptype->right;
5091                 param = param->next;
5092         }
5093         result = 0;
5094         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5095                 result = read_expr(state, MISC(nfunc,0));
5096         }
5097 #if 0
5098         fprintf(stdout, "\n");
5099         loc(stdout, state, 0);
5100         fprintf(stdout, "\n__________ flatten_call _________\n");
5101         print_triple(state, nfunc);
5102         fprintf(stdout, "__________ flatten_call _________ done\n\n");
5103 #endif
5104
5105         /* Get rid of the extra triples */
5106         nfirst = RHS(nfunc, 0)->next;
5107         free_triple(state, RHS(nfunc, 0));
5108         RHS(nfunc, 0) = 0;
5109         free_triple(state, nfunc);
5110
5111         /* Append the new function list onto the return list */
5112         end = first->prev;
5113         nend = nfirst->prev;
5114         end->next    = nfirst;
5115         nfirst->prev = end;
5116         nend->next   = first;
5117         first->prev  = nend;
5118
5119         return result;
5120 }
5121
5122 static struct triple *flatten(
5123         struct compile_state *state, struct triple *first, struct triple *ptr)
5124 {
5125         struct triple *orig_ptr;
5126         if (!ptr)
5127                 return 0;
5128         do {
5129                 orig_ptr = ptr;
5130                 /* Only flatten triples once */
5131                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5132                         return ptr;
5133                 }
5134                 switch(ptr->op) {
5135                 case OP_WRITE:
5136                 case OP_STORE:
5137                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5138                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5139                         use_triple(LHS(ptr, 0), ptr);
5140                         use_triple(RHS(ptr, 0), ptr);
5141                         break;
5142                 case OP_COMMA:
5143                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5144                         ptr = RHS(ptr, 1);
5145                         break;
5146                 case OP_VAL:
5147                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5148                         return MISC(ptr, 0);
5149                         break;
5150                 case OP_LAND:
5151                         ptr = flatten_land(state, first, ptr);
5152                         break;
5153                 case OP_LOR:
5154                         ptr = flatten_lor(state, first, ptr);
5155                         break;
5156                 case OP_COND:
5157                         ptr = flatten_cond(state, first, ptr);
5158                         break;
5159                 case OP_CALL:
5160                         ptr = flatten_call(state, first, ptr);
5161                         break;
5162                 case OP_READ:
5163                 case OP_LOAD:
5164                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5165                         use_triple(RHS(ptr, 0), ptr);
5166                         break;
5167                 case OP_BRANCH:
5168                         use_triple(TARG(ptr, 0), ptr);
5169                         if (TRIPLE_RHS(ptr->sizes)) {
5170                                 use_triple(RHS(ptr, 0), ptr);
5171                                 if (ptr->next != ptr) {
5172                                         use_triple(ptr->next, ptr);
5173                                 }
5174                         }
5175                         break;
5176                 case OP_BLOBCONST:
5177                         insert_triple(state, first, ptr);
5178                         ptr->id |= TRIPLE_FLAG_FLATTENED;
5179                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5180                         use_triple(MISC(ptr, 0), ptr);
5181                         break;
5182                 case OP_DEREF:
5183                         /* Since OP_DEREF is just a marker delete it when I flatten it */
5184                         ptr = RHS(ptr, 0);
5185                         RHS(orig_ptr, 0) = 0;
5186                         free_triple(state, orig_ptr);
5187                         break;
5188                 case OP_DOT:
5189                 {
5190                         struct triple *base;
5191                         base = RHS(ptr, 0);
5192                         if (base->op == OP_DEREF) {
5193                                 struct triple *left;
5194                                 ulong_t offset;
5195                                 offset = field_offset(state, base->type, ptr->u.field);
5196                                 left = RHS(base, 0);
5197                                 ptr = triple(state, OP_ADD, left->type, 
5198                                         read_expr(state, left),
5199                                         int_const(state, &ulong_type, offset));
5200                                 free_triple(state, base);
5201                         }
5202                         else if (base->op == OP_VAL_VEC) {
5203                                 base = flatten(state, first, base);
5204                                 ptr = struct_field(state, base, ptr->u.field);
5205                         }
5206                         break;
5207                 }
5208                 case OP_PIECE:
5209                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5210                         use_triple(MISC(ptr, 0), ptr);
5211                         use_triple(ptr, MISC(ptr, 0));
5212                         break;
5213                 case OP_ADDRCONST:
5214                 case OP_SDECL:
5215                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5216                         use_triple(MISC(ptr, 0), ptr);
5217                         break;
5218                 case OP_ADECL:
5219                         break;
5220                 default:
5221                         /* Flatten the easy cases we don't override */
5222                         ptr = flatten_generic(state, first, ptr);
5223                         break;
5224                 }
5225         } while(ptr && (ptr != orig_ptr));
5226         if (ptr) {
5227                 insert_triple(state, first, ptr);
5228                 ptr->id |= TRIPLE_FLAG_FLATTENED;
5229         }
5230         return ptr;
5231 }
5232
5233 static void release_expr(struct compile_state *state, struct triple *expr)
5234 {
5235         struct triple *head;
5236         head = label(state);
5237         flatten(state, head, expr);
5238         while(head->next != head) {
5239                 release_triple(state, head->next);
5240         }
5241         free_triple(state, head);
5242 }
5243
5244 static int replace_rhs_use(struct compile_state *state,
5245         struct triple *orig, struct triple *new, struct triple *use)
5246 {
5247         struct triple **expr;
5248         int found;
5249         found = 0;
5250         expr = triple_rhs(state, use, 0);
5251         for(;expr; expr = triple_rhs(state, use, expr)) {
5252                 if (*expr == orig) {
5253                         *expr = new;
5254                         found = 1;
5255                 }
5256         }
5257         if (found) {
5258                 unuse_triple(orig, use);
5259                 use_triple(new, use);
5260         }
5261         return found;
5262 }
5263
5264 static int replace_lhs_use(struct compile_state *state,
5265         struct triple *orig, struct triple *new, struct triple *use)
5266 {
5267         struct triple **expr;
5268         int found;
5269         found = 0;
5270         expr = triple_lhs(state, use, 0);
5271         for(;expr; expr = triple_lhs(state, use, expr)) {
5272                 if (*expr == orig) {
5273                         *expr = new;
5274                         found = 1;
5275                 }
5276         }
5277         if (found) {
5278                 unuse_triple(orig, use);
5279                 use_triple(new, use);
5280         }
5281         return found;
5282 }
5283
5284 static void propogate_use(struct compile_state *state,
5285         struct triple *orig, struct triple *new)
5286 {
5287         struct triple_set *user, *next;
5288         for(user = orig->use; user; user = next) {
5289                 struct triple *use;
5290                 int found;
5291                 next = user->next;
5292                 use = user->member;
5293                 found = 0;
5294                 found |= replace_rhs_use(state, orig, new, use);
5295                 found |= replace_lhs_use(state, orig, new, use);
5296                 if (!found) {
5297                         internal_error(state, use, "use without use");
5298                 }
5299         }
5300         if (orig->use) {
5301                 internal_error(state, orig, "used after propogate_use");
5302         }
5303 }
5304
5305 /*
5306  * Code generators
5307  * ===========================
5308  */
5309
5310 static struct triple *mk_add_expr(
5311         struct compile_state *state, struct triple *left, struct triple *right)
5312 {
5313         struct type *result_type;
5314         /* Put pointer operands on the left */
5315         if (is_pointer(right)) {
5316                 struct triple *tmp;
5317                 tmp = left;
5318                 left = right;
5319                 right = tmp;
5320         }
5321         left  = read_expr(state, left);
5322         right = read_expr(state, right);
5323         result_type = ptr_arithmetic_result(state, left, right);
5324         if (is_pointer(left)) {
5325                 right = triple(state, 
5326                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5327                         &ulong_type, 
5328                         right, 
5329                         int_const(state, &ulong_type, 
5330                                 size_of(state, left->type->left)));
5331         }
5332         return triple(state, OP_ADD, result_type, left, right);
5333 }
5334
5335 static struct triple *mk_sub_expr(
5336         struct compile_state *state, struct triple *left, struct triple *right)
5337 {
5338         struct type *result_type;
5339         result_type = ptr_arithmetic_result(state, left, right);
5340         left  = read_expr(state, left);
5341         right = read_expr(state, right);
5342         if (is_pointer(left)) {
5343                 right = triple(state, 
5344                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5345                         &ulong_type, 
5346                         right, 
5347                         int_const(state, &ulong_type, 
5348                                 size_of(state, left->type->left)));
5349         }
5350         return triple(state, OP_SUB, result_type, left, right);
5351 }
5352
5353 static struct triple *mk_pre_inc_expr(
5354         struct compile_state *state, struct triple *def)
5355 {
5356         struct triple *val;
5357         lvalue(state, def);
5358         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5359         return triple(state, OP_VAL, def->type,
5360                 write_expr(state, def, val),
5361                 val);
5362 }
5363
5364 static struct triple *mk_pre_dec_expr(
5365         struct compile_state *state, struct triple *def)
5366 {
5367         struct triple *val;
5368         lvalue(state, def);
5369         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5370         return triple(state, OP_VAL, def->type,
5371                 write_expr(state, def, val),
5372                 val);
5373 }
5374
5375 static struct triple *mk_post_inc_expr(
5376         struct compile_state *state, struct triple *def)
5377 {
5378         struct triple *val;
5379         lvalue(state, def);
5380         val = read_expr(state, def);
5381         return triple(state, OP_VAL, def->type,
5382                 write_expr(state, def,
5383                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5384                 , val);
5385 }
5386
5387 static struct triple *mk_post_dec_expr(
5388         struct compile_state *state, struct triple *def)
5389 {
5390         struct triple *val;
5391         lvalue(state, def);
5392         val = read_expr(state, def);
5393         return triple(state, OP_VAL, def->type, 
5394                 write_expr(state, def,
5395                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5396                 , val);
5397 }
5398
5399 static struct triple *mk_subscript_expr(
5400         struct compile_state *state, struct triple *left, struct triple *right)
5401 {
5402         left  = read_expr(state, left);
5403         right = read_expr(state, right);
5404         if (!is_pointer(left) && !is_pointer(right)) {
5405                 error(state, left, "subscripted value is not a pointer");
5406         }
5407         return mk_deref_expr(state, mk_add_expr(state, left, right));
5408 }
5409
5410 /*
5411  * Compile time evaluation
5412  * ===========================
5413  */
5414 static int is_const(struct triple *ins)
5415 {
5416         return IS_CONST_OP(ins->op);
5417 }
5418
5419 static int constants_equal(struct compile_state *state, 
5420         struct triple *left, struct triple *right)
5421 {
5422         int equal;
5423         if (!is_const(left) || !is_const(right)) {
5424                 equal = 0;
5425         }
5426         else if (left->op != right->op) {
5427                 equal = 0;
5428         }
5429         else if (!equiv_types(left->type, right->type)) {
5430                 equal = 0;
5431         }
5432         else {
5433                 equal = 0;
5434                 switch(left->op) {
5435                 case OP_INTCONST:
5436                         if (left->u.cval == right->u.cval) {
5437                                 equal = 1;
5438                         }
5439                         break;
5440                 case OP_BLOBCONST:
5441                 {
5442                         size_t lsize, rsize;
5443                         lsize = size_of(state, left->type);
5444                         rsize = size_of(state, right->type);
5445                         if (lsize != rsize) {
5446                                 break;
5447                         }
5448                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5449                                 equal = 1;
5450                         }
5451                         break;
5452                 }
5453                 case OP_ADDRCONST:
5454                         if ((MISC(left, 0) == MISC(right, 0)) &&
5455                                 (left->u.cval == right->u.cval)) {
5456                                 equal = 1;
5457                         }
5458                         break;
5459                 default:
5460                         internal_error(state, left, "uknown constant type");
5461                         break;
5462                 }
5463         }
5464         return equal;
5465 }
5466
5467 static int is_zero(struct triple *ins)
5468 {
5469         return is_const(ins) && (ins->u.cval == 0);
5470 }
5471
5472 static int is_one(struct triple *ins)
5473 {
5474         return is_const(ins) && (ins->u.cval == 1);
5475 }
5476
5477 static long_t bsr(ulong_t value)
5478 {
5479         int i;
5480         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5481                 ulong_t mask;
5482                 mask = 1;
5483                 mask <<= i;
5484                 if (value & mask) {
5485                         return i;
5486                 }
5487         }
5488         return -1;
5489 }
5490
5491 static long_t bsf(ulong_t value)
5492 {
5493         int i;
5494         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5495                 ulong_t mask;
5496                 mask = 1;
5497                 mask <<= 1;
5498                 if (value & mask) {
5499                         return i;
5500                 }
5501         }
5502         return -1;
5503 }
5504
5505 static long_t log2(ulong_t value)
5506 {
5507         return bsr(value);
5508 }
5509
5510 static long_t tlog2(struct triple *ins)
5511 {
5512         return log2(ins->u.cval);
5513 }
5514
5515 static int is_pow2(struct triple *ins)
5516 {
5517         ulong_t value, mask;
5518         long_t log;
5519         if (!is_const(ins)) {
5520                 return 0;
5521         }
5522         value = ins->u.cval;
5523         log = log2(value);
5524         if (log == -1) {
5525                 return 0;
5526         }
5527         mask = 1;
5528         mask <<= log;
5529         return  ((value & mask) == value);
5530 }
5531
5532 static ulong_t read_const(struct compile_state *state,
5533         struct triple *ins, struct triple **expr)
5534 {
5535         struct triple *rhs;
5536         rhs = *expr;
5537         switch(rhs->type->type &TYPE_MASK) {
5538         case TYPE_CHAR:   
5539         case TYPE_SHORT:
5540         case TYPE_INT:
5541         case TYPE_LONG:
5542         case TYPE_UCHAR:   
5543         case TYPE_USHORT:  
5544         case TYPE_UINT:
5545         case TYPE_ULONG:
5546         case TYPE_POINTER:
5547                 break;
5548         default:
5549                 internal_error(state, rhs, "bad type to read_const\n");
5550                 break;
5551         }
5552         return rhs->u.cval;
5553 }
5554
5555 static long_t read_sconst(struct triple *ins, struct triple **expr)
5556 {
5557         struct triple *rhs;
5558         rhs = *expr;
5559         return (long_t)(rhs->u.cval);
5560 }
5561
5562 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5563 {
5564         struct triple **expr;
5565         expr = triple_rhs(state, ins, 0);
5566         for(;expr;expr = triple_rhs(state, ins, expr)) {
5567                 if (*expr) {
5568                         unuse_triple(*expr, ins);
5569                         *expr = 0;
5570                 }
5571         }
5572 }
5573
5574 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5575 {
5576         struct triple **expr;
5577         expr = triple_lhs(state, ins, 0);
5578         for(;expr;expr = triple_lhs(state, ins, expr)) {
5579                 unuse_triple(*expr, ins);
5580                 *expr = 0;
5581         }
5582 }
5583
5584 static void check_lhs(struct compile_state *state, struct triple *ins)
5585 {
5586         struct triple **expr;
5587         expr = triple_lhs(state, ins, 0);
5588         for(;expr;expr = triple_lhs(state, ins, expr)) {
5589                 internal_error(state, ins, "unexpected lhs");
5590         }
5591         
5592 }
5593 static void check_targ(struct compile_state *state, struct triple *ins)
5594 {
5595         struct triple **expr;
5596         expr = triple_targ(state, ins, 0);
5597         for(;expr;expr = triple_targ(state, ins, expr)) {
5598                 internal_error(state, ins, "unexpected targ");
5599         }
5600 }
5601
5602 static void wipe_ins(struct compile_state *state, struct triple *ins)
5603 {
5604         /* Becareful which instructions you replace the wiped
5605          * instruction with, as there are not enough slots
5606          * in all instructions to hold all others.
5607          */
5608         check_targ(state, ins);
5609         unuse_rhs(state, ins);
5610         unuse_lhs(state, ins);
5611 }
5612
5613 static void mkcopy(struct compile_state *state, 
5614         struct triple *ins, struct triple *rhs)
5615 {
5616         wipe_ins(state, ins);
5617         ins->op = OP_COPY;
5618         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5619         RHS(ins, 0) = rhs;
5620         use_triple(RHS(ins, 0), ins);
5621 }
5622
5623 static void mkconst(struct compile_state *state, 
5624         struct triple *ins, ulong_t value)
5625 {
5626         if (!is_integral(ins) && !is_pointer(ins)) {
5627                 internal_error(state, ins, "unknown type to make constant\n");
5628         }
5629         wipe_ins(state, ins);
5630         ins->op = OP_INTCONST;
5631         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5632         ins->u.cval = value;
5633 }
5634
5635 static void mkaddr_const(struct compile_state *state,
5636         struct triple *ins, struct triple *sdecl, ulong_t value)
5637 {
5638         wipe_ins(state, ins);
5639         ins->op = OP_ADDRCONST;
5640         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5641         MISC(ins, 0) = sdecl;
5642         ins->u.cval = value;
5643         use_triple(sdecl, ins);
5644 }
5645
5646 /* Transform multicomponent variables into simple register variables */
5647 static void flatten_structures(struct compile_state *state)
5648 {
5649         struct triple *ins, *first;
5650         first = RHS(state->main_function, 0);
5651         ins = first;
5652         /* Pass one expand structure values into valvecs.
5653          */
5654         ins = first;
5655         do {
5656                 struct triple *next;
5657                 next = ins->next;
5658                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5659                         if (ins->op == OP_VAL_VEC) {
5660                                 /* Do nothing */
5661                         }
5662                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5663                                 struct triple *def, **vector;
5664                                 struct type *tptr;
5665                                 int op;
5666                                 ulong_t i;
5667
5668                                 op = ins->op;
5669                                 def = RHS(ins, 0);
5670                                 get_occurance(ins->occurance);
5671                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5672                                         ins->occurance);
5673
5674                                 vector = &RHS(next, 0);
5675                                 tptr = next->type->left;
5676                                 for(i = 0; i < next->type->elements; i++) {
5677                                         struct triple *sfield;
5678                                         struct type *mtype;
5679                                         mtype = tptr;
5680                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5681                                                 mtype = mtype->left;
5682                                         }
5683                                         sfield = deref_field(state, def, mtype->field_ident);
5684                                         
5685                                         vector[i] = triple(
5686                                                 state, op, mtype, sfield, 0);
5687                                         put_occurance(vector[i]->occurance);
5688                                         get_occurance(next->occurance);
5689                                         vector[i]->occurance = next->occurance;
5690                                         tptr = tptr->right;
5691                                 }
5692                                 propogate_use(state, ins, next);
5693                                 flatten(state, ins, next);
5694                                 free_triple(state, ins);
5695                         }
5696                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5697                                 struct triple *src, *dst, **vector;
5698                                 struct type *tptr;
5699                                 int op;
5700                                 ulong_t i;
5701
5702                                 op = ins->op;
5703                                 src = RHS(ins, 0);
5704                                 dst = LHS(ins, 0);
5705                                 get_occurance(ins->occurance);
5706                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5707                                         ins->occurance);
5708                                 
5709                                 vector = &RHS(next, 0);
5710                                 tptr = next->type->left;
5711                                 for(i = 0; i < ins->type->elements; i++) {
5712                                         struct triple *dfield, *sfield;
5713                                         struct type *mtype;
5714                                         mtype = tptr;
5715                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5716                                                 mtype = mtype->left;
5717                                         }
5718                                         sfield = deref_field(state, src, mtype->field_ident);
5719                                         dfield = deref_field(state, dst, mtype->field_ident);
5720                                         vector[i] = triple(
5721                                                 state, op, mtype, dfield, sfield);
5722                                         put_occurance(vector[i]->occurance);
5723                                         get_occurance(next->occurance);
5724                                         vector[i]->occurance = next->occurance;
5725                                         tptr = tptr->right;
5726                                 }
5727                                 propogate_use(state, ins, next);
5728                                 flatten(state, ins, next);
5729                                 free_triple(state, ins);
5730                         }
5731                 }
5732                 ins = next;
5733         } while(ins != first);
5734         /* Pass two flatten the valvecs.
5735          */
5736         ins = first;
5737         do {
5738                 struct triple *next;
5739                 next = ins->next;
5740                 if (ins->op == OP_VAL_VEC) {
5741                         release_triple(state, ins);
5742                 } 
5743                 ins = next;
5744         } while(ins != first);
5745         /* Pass three verify the state and set ->id to 0.
5746          */
5747         ins = first;
5748         do {
5749                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5750                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5751                         internal_error(state, ins, "STRUCT_TYPE remains?");
5752                 }
5753                 if (ins->op == OP_DOT) {
5754                         internal_error(state, ins, "OP_DOT remains?");
5755                 }
5756                 if (ins->op == OP_VAL_VEC) {
5757                         internal_error(state, ins, "OP_VAL_VEC remains?");
5758                 }
5759                 ins = ins->next;
5760         } while(ins != first);
5761 }
5762
5763 /* For those operations that cannot be simplified */
5764 static void simplify_noop(struct compile_state *state, struct triple *ins)
5765 {
5766         return;
5767 }
5768
5769 static void simplify_smul(struct compile_state *state, struct triple *ins)
5770 {
5771         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5772                 struct triple *tmp;
5773                 tmp = RHS(ins, 0);
5774                 RHS(ins, 0) = RHS(ins, 1);
5775                 RHS(ins, 1) = tmp;
5776         }
5777         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5778                 long_t left, right;
5779                 left  = read_sconst(ins, &RHS(ins, 0));
5780                 right = read_sconst(ins, &RHS(ins, 1));
5781                 mkconst(state, ins, left * right);
5782         }
5783         else if (is_zero(RHS(ins, 1))) {
5784                 mkconst(state, ins, 0);
5785         }
5786         else if (is_one(RHS(ins, 1))) {
5787                 mkcopy(state, ins, RHS(ins, 0));
5788         }
5789         else if (is_pow2(RHS(ins, 1))) {
5790                 struct triple *val;
5791                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5792                 ins->op = OP_SL;
5793                 insert_triple(state, ins, val);
5794                 unuse_triple(RHS(ins, 1), ins);
5795                 use_triple(val, ins);
5796                 RHS(ins, 1) = val;
5797         }
5798 }
5799
5800 static void simplify_umul(struct compile_state *state, struct triple *ins)
5801 {
5802         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5803                 struct triple *tmp;
5804                 tmp = RHS(ins, 0);
5805                 RHS(ins, 0) = RHS(ins, 1);
5806                 RHS(ins, 1) = tmp;
5807         }
5808         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5809                 ulong_t left, right;
5810                 left  = read_const(state, ins, &RHS(ins, 0));
5811                 right = read_const(state, ins, &RHS(ins, 1));
5812                 mkconst(state, ins, left * right);
5813         }
5814         else if (is_zero(RHS(ins, 1))) {
5815                 mkconst(state, ins, 0);
5816         }
5817         else if (is_one(RHS(ins, 1))) {
5818                 mkcopy(state, ins, RHS(ins, 0));
5819         }
5820         else if (is_pow2(RHS(ins, 1))) {
5821                 struct triple *val;
5822                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5823                 ins->op = OP_SL;
5824                 insert_triple(state, ins, val);
5825                 unuse_triple(RHS(ins, 1), ins);
5826                 use_triple(val, ins);
5827                 RHS(ins, 1) = val;
5828         }
5829 }
5830
5831 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5832 {
5833         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5834                 long_t left, right;
5835                 left  = read_sconst(ins, &RHS(ins, 0));
5836                 right = read_sconst(ins, &RHS(ins, 1));
5837                 mkconst(state, ins, left / right);
5838         }
5839         else if (is_zero(RHS(ins, 0))) {
5840                 mkconst(state, ins, 0);
5841         }
5842         else if (is_zero(RHS(ins, 1))) {
5843                 error(state, ins, "division by zero");
5844         }
5845         else if (is_one(RHS(ins, 1))) {
5846                 mkcopy(state, ins, RHS(ins, 0));
5847         }
5848         else if (is_pow2(RHS(ins, 1))) {
5849                 struct triple *val;
5850                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5851                 ins->op = OP_SSR;
5852                 insert_triple(state, ins, val);
5853                 unuse_triple(RHS(ins, 1), ins);
5854                 use_triple(val, ins);
5855                 RHS(ins, 1) = val;
5856         }
5857 }
5858
5859 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5860 {
5861         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5862                 ulong_t left, right;
5863                 left  = read_const(state, ins, &RHS(ins, 0));
5864                 right = read_const(state, ins, &RHS(ins, 1));
5865                 mkconst(state, ins, left / right);
5866         }
5867         else if (is_zero(RHS(ins, 0))) {
5868                 mkconst(state, ins, 0);
5869         }
5870         else if (is_zero(RHS(ins, 1))) {
5871                 error(state, ins, "division by zero");
5872         }
5873         else if (is_one(RHS(ins, 1))) {
5874                 mkcopy(state, ins, RHS(ins, 0));
5875         }
5876         else if (is_pow2(RHS(ins, 1))) {
5877                 struct triple *val;
5878                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5879                 ins->op = OP_USR;
5880                 insert_triple(state, ins, val);
5881                 unuse_triple(RHS(ins, 1), ins);
5882                 use_triple(val, ins);
5883                 RHS(ins, 1) = val;
5884         }
5885 }
5886
5887 static void simplify_smod(struct compile_state *state, struct triple *ins)
5888 {
5889         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5890                 long_t left, right;
5891                 left  = read_const(state, ins, &RHS(ins, 0));
5892                 right = read_const(state, ins, &RHS(ins, 1));
5893                 mkconst(state, ins, left % right);
5894         }
5895         else if (is_zero(RHS(ins, 0))) {
5896                 mkconst(state, ins, 0);
5897         }
5898         else if (is_zero(RHS(ins, 1))) {
5899                 error(state, ins, "division by zero");
5900         }
5901         else if (is_one(RHS(ins, 1))) {
5902                 mkconst(state, ins, 0);
5903         }
5904         else if (is_pow2(RHS(ins, 1))) {
5905                 struct triple *val;
5906                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5907                 ins->op = OP_AND;
5908                 insert_triple(state, ins, val);
5909                 unuse_triple(RHS(ins, 1), ins);
5910                 use_triple(val, ins);
5911                 RHS(ins, 1) = val;
5912         }
5913 }
5914 static void simplify_umod(struct compile_state *state, struct triple *ins)
5915 {
5916         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5917                 ulong_t left, right;
5918                 left  = read_const(state, ins, &RHS(ins, 0));
5919                 right = read_const(state, ins, &RHS(ins, 1));
5920                 mkconst(state, ins, left % right);
5921         }
5922         else if (is_zero(RHS(ins, 0))) {
5923                 mkconst(state, ins, 0);
5924         }
5925         else if (is_zero(RHS(ins, 1))) {
5926                 error(state, ins, "division by zero");
5927         }
5928         else if (is_one(RHS(ins, 1))) {
5929                 mkconst(state, ins, 0);
5930         }
5931         else if (is_pow2(RHS(ins, 1))) {
5932                 struct triple *val;
5933                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5934                 ins->op = OP_AND;
5935                 insert_triple(state, ins, val);
5936                 unuse_triple(RHS(ins, 1), ins);
5937                 use_triple(val, ins);
5938                 RHS(ins, 1) = val;
5939         }
5940 }
5941
5942 static void simplify_add(struct compile_state *state, struct triple *ins)
5943 {
5944         /* start with the pointer on the left */
5945         if (is_pointer(RHS(ins, 1))) {
5946                 struct triple *tmp;
5947                 tmp = RHS(ins, 0);
5948                 RHS(ins, 0) = RHS(ins, 1);
5949                 RHS(ins, 1) = tmp;
5950         }
5951         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5952                 if (!is_pointer(RHS(ins, 0))) {
5953                         ulong_t left, right;
5954                         left  = read_const(state, ins, &RHS(ins, 0));
5955                         right = read_const(state, ins, &RHS(ins, 1));
5956                         mkconst(state, ins, left + right);
5957                 }
5958                 else /* op == OP_ADDRCONST */ {
5959                         struct triple *sdecl;
5960                         ulong_t left, right;
5961                         sdecl = MISC(RHS(ins, 0), 0);
5962                         left  = RHS(ins, 0)->u.cval;
5963                         right = RHS(ins, 1)->u.cval;
5964                         mkaddr_const(state, ins, sdecl, left + right);
5965                 }
5966         }
5967         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5968                 struct triple *tmp;
5969                 tmp = RHS(ins, 1);
5970                 RHS(ins, 1) = RHS(ins, 0);
5971                 RHS(ins, 0) = tmp;
5972         }
5973 }
5974
5975 static void simplify_sub(struct compile_state *state, struct triple *ins)
5976 {
5977         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5978                 if (!is_pointer(RHS(ins, 0))) {
5979                         ulong_t left, right;
5980                         left  = read_const(state, ins, &RHS(ins, 0));
5981                         right = read_const(state, ins, &RHS(ins, 1));
5982                         mkconst(state, ins, left - right);
5983                 }
5984                 else /* op == OP_ADDRCONST */ {
5985                         struct triple *sdecl;
5986                         ulong_t left, right;
5987                         sdecl = MISC(RHS(ins, 0), 0);
5988                         left  = RHS(ins, 0)->u.cval;
5989                         right = RHS(ins, 1)->u.cval;
5990                         mkaddr_const(state, ins, sdecl, left - right);
5991                 }
5992         }
5993 }
5994
5995 static void simplify_sl(struct compile_state *state, struct triple *ins)
5996 {
5997         if (is_const(RHS(ins, 1))) {
5998                 ulong_t right;
5999                 right = read_const(state, ins, &RHS(ins, 1));
6000                 if (right >= (size_of(state, ins->type)*8)) {
6001                         warning(state, ins, "left shift count >= width of type");
6002                 }
6003         }
6004         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6005                 ulong_t left, right;
6006                 left  = read_const(state, ins, &RHS(ins, 0));
6007                 right = read_const(state, ins, &RHS(ins, 1));
6008                 mkconst(state, ins,  left << right);
6009         }
6010 }
6011
6012 static void simplify_usr(struct compile_state *state, struct triple *ins)
6013 {
6014         if (is_const(RHS(ins, 1))) {
6015                 ulong_t right;
6016                 right = read_const(state, ins, &RHS(ins, 1));
6017                 if (right >= (size_of(state, ins->type)*8)) {
6018                         warning(state, ins, "right shift count >= width of type");
6019                 }
6020         }
6021         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6022                 ulong_t left, right;
6023                 left  = read_const(state, ins, &RHS(ins, 0));
6024                 right = read_const(state, ins, &RHS(ins, 1));
6025                 mkconst(state, ins, left >> right);
6026         }
6027 }
6028
6029 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6030 {
6031         if (is_const(RHS(ins, 1))) {
6032                 ulong_t right;
6033                 right = read_const(state, ins, &RHS(ins, 1));
6034                 if (right >= (size_of(state, ins->type)*8)) {
6035                         warning(state, ins, "right shift count >= width of type");
6036                 }
6037         }
6038         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6039                 long_t left, right;
6040                 left  = read_sconst(ins, &RHS(ins, 0));
6041                 right = read_sconst(ins, &RHS(ins, 1));
6042                 mkconst(state, ins, left >> right);
6043         }
6044 }
6045
6046 static void simplify_and(struct compile_state *state, struct triple *ins)
6047 {
6048         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6049                 ulong_t left, right;
6050                 left  = read_const(state, ins, &RHS(ins, 0));
6051                 right = read_const(state, ins, &RHS(ins, 1));
6052                 mkconst(state, ins, left & right);
6053         }
6054 }
6055
6056 static void simplify_or(struct compile_state *state, struct triple *ins)
6057 {
6058         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6059                 ulong_t left, right;
6060                 left  = read_const(state, ins, &RHS(ins, 0));
6061                 right = read_const(state, ins, &RHS(ins, 1));
6062                 mkconst(state, ins, left | right);
6063         }
6064 }
6065
6066 static void simplify_xor(struct compile_state *state, struct triple *ins)
6067 {
6068         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6069                 ulong_t left, right;
6070                 left  = read_const(state, ins, &RHS(ins, 0));
6071                 right = read_const(state, ins, &RHS(ins, 1));
6072                 mkconst(state, ins, left ^ right);
6073         }
6074 }
6075
6076 static void simplify_pos(struct compile_state *state, struct triple *ins)
6077 {
6078         if (is_const(RHS(ins, 0))) {
6079                 mkconst(state, ins, RHS(ins, 0)->u.cval);
6080         }
6081         else {
6082                 mkcopy(state, ins, RHS(ins, 0));
6083         }
6084 }
6085
6086 static void simplify_neg(struct compile_state *state, struct triple *ins)
6087 {
6088         if (is_const(RHS(ins, 0))) {
6089                 ulong_t left;
6090                 left = read_const(state, ins, &RHS(ins, 0));
6091                 mkconst(state, ins, -left);
6092         }
6093         else if (RHS(ins, 0)->op == OP_NEG) {
6094                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6095         }
6096 }
6097
6098 static void simplify_invert(struct compile_state *state, struct triple *ins)
6099 {
6100         if (is_const(RHS(ins, 0))) {
6101                 ulong_t left;
6102                 left = read_const(state, ins, &RHS(ins, 0));
6103                 mkconst(state, ins, ~left);
6104         }
6105 }
6106
6107 static void simplify_eq(struct compile_state *state, struct triple *ins)
6108 {
6109         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6110                 ulong_t left, right;
6111                 left  = read_const(state, ins, &RHS(ins, 0));
6112                 right = read_const(state, ins, &RHS(ins, 1));
6113                 mkconst(state, ins, left == right);
6114         }
6115         else if (RHS(ins, 0) == RHS(ins, 1)) {
6116                 mkconst(state, ins, 1);
6117         }
6118 }
6119
6120 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6121 {
6122         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6123                 ulong_t left, right;
6124                 left  = read_const(state, ins, &RHS(ins, 0));
6125                 right = read_const(state, ins, &RHS(ins, 1));
6126                 mkconst(state, ins, left != right);
6127         }
6128         else if (RHS(ins, 0) == RHS(ins, 1)) {
6129                 mkconst(state, ins, 0);
6130         }
6131 }
6132
6133 static void simplify_sless(struct compile_state *state, struct triple *ins)
6134 {
6135         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6136                 long_t left, right;
6137                 left  = read_sconst(ins, &RHS(ins, 0));
6138                 right = read_sconst(ins, &RHS(ins, 1));
6139                 mkconst(state, ins, left < right);
6140         }
6141         else if (RHS(ins, 0) == RHS(ins, 1)) {
6142                 mkconst(state, ins, 0);
6143         }
6144 }
6145
6146 static void simplify_uless(struct compile_state *state, struct triple *ins)
6147 {
6148         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6149                 ulong_t left, right;
6150                 left  = read_const(state, ins, &RHS(ins, 0));
6151                 right = read_const(state, ins, &RHS(ins, 1));
6152                 mkconst(state, ins, left < right);
6153         }
6154         else if (is_zero(RHS(ins, 0))) {
6155                 mkconst(state, ins, 1);
6156         }
6157         else if (RHS(ins, 0) == RHS(ins, 1)) {
6158                 mkconst(state, ins, 0);
6159         }
6160 }
6161
6162 static void simplify_smore(struct compile_state *state, struct triple *ins)
6163 {
6164         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6165                 long_t left, right;
6166                 left  = read_sconst(ins, &RHS(ins, 0));
6167                 right = read_sconst(ins, &RHS(ins, 1));
6168                 mkconst(state, ins, left > right);
6169         }
6170         else if (RHS(ins, 0) == RHS(ins, 1)) {
6171                 mkconst(state, ins, 0);
6172         }
6173 }
6174
6175 static void simplify_umore(struct compile_state *state, struct triple *ins)
6176 {
6177         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6178                 ulong_t left, right;
6179                 left  = read_const(state, ins, &RHS(ins, 0));
6180                 right = read_const(state, ins, &RHS(ins, 1));
6181                 mkconst(state, ins, left > right);
6182         }
6183         else if (is_zero(RHS(ins, 1))) {
6184                 mkconst(state, ins, 1);
6185         }
6186         else if (RHS(ins, 0) == RHS(ins, 1)) {
6187                 mkconst(state, ins, 0);
6188         }
6189 }
6190
6191
6192 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6193 {
6194         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6195                 long_t left, right;
6196                 left  = read_sconst(ins, &RHS(ins, 0));
6197                 right = read_sconst(ins, &RHS(ins, 1));
6198                 mkconst(state, ins, left <= right);
6199         }
6200         else if (RHS(ins, 0) == RHS(ins, 1)) {
6201                 mkconst(state, ins, 1);
6202         }
6203 }
6204
6205 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6206 {
6207         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6208                 ulong_t left, right;
6209                 left  = read_const(state, ins, &RHS(ins, 0));
6210                 right = read_const(state, ins, &RHS(ins, 1));
6211                 mkconst(state, ins, left <= right);
6212         }
6213         else if (is_zero(RHS(ins, 0))) {
6214                 mkconst(state, ins, 1);
6215         }
6216         else if (RHS(ins, 0) == RHS(ins, 1)) {
6217                 mkconst(state, ins, 1);
6218         }
6219 }
6220
6221 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6222 {
6223         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6224                 long_t left, right;
6225                 left  = read_sconst(ins, &RHS(ins, 0));
6226                 right = read_sconst(ins, &RHS(ins, 1));
6227                 mkconst(state, ins, left >= right);
6228         }
6229         else if (RHS(ins, 0) == RHS(ins, 1)) {
6230                 mkconst(state, ins, 1);
6231         }
6232 }
6233
6234 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6235 {
6236         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6237                 ulong_t left, right;
6238                 left  = read_const(state, ins, &RHS(ins, 0));
6239                 right = read_const(state, ins, &RHS(ins, 1));
6240                 mkconst(state, ins, left >= right);
6241         }
6242         else if (is_zero(RHS(ins, 1))) {
6243                 mkconst(state, ins, 1);
6244         }
6245         else if (RHS(ins, 0) == RHS(ins, 1)) {
6246                 mkconst(state, ins, 1);
6247         }
6248 }
6249
6250 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6251 {
6252         if (is_const(RHS(ins, 0))) {
6253                 ulong_t left;
6254                 left = read_const(state, ins, &RHS(ins, 0));
6255                 mkconst(state, ins, left == 0);
6256         }
6257         /* Otherwise if I am the only user... */
6258         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6259                 int need_copy = 1;
6260                 /* Invert a boolean operation */
6261                 switch(RHS(ins, 0)->op) {
6262                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
6263                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
6264                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
6265                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
6266                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
6267                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
6268                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
6269                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
6270                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
6271                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
6272                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
6273                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6274                 default:
6275                         need_copy = 0;
6276                         break;
6277                 }
6278                 if (need_copy) {
6279                         mkcopy(state, ins, RHS(ins, 0));
6280                 }
6281         }
6282 }
6283
6284 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6285 {
6286         if (is_const(RHS(ins, 0))) {
6287                 ulong_t left;
6288                 left = read_const(state, ins, &RHS(ins, 0));
6289                 mkconst(state, ins, left != 0);
6290         }
6291         else switch(RHS(ins, 0)->op) {
6292         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6293         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6294         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6295                 mkcopy(state, ins, RHS(ins, 0));
6296         }
6297
6298 }
6299
6300 static void simplify_copy(struct compile_state *state, struct triple *ins)
6301 {
6302         if (is_const(RHS(ins, 0))) {
6303                 switch(RHS(ins, 0)->op) {
6304                 case OP_INTCONST:
6305                 {
6306                         ulong_t left;
6307                         left = read_const(state, ins, &RHS(ins, 0));
6308                         mkconst(state, ins, left);
6309                         break;
6310                 }
6311                 case OP_ADDRCONST:
6312                 {
6313                         struct triple *sdecl;
6314                         ulong_t offset;
6315                         sdecl  = MISC(RHS(ins, 0), 0);
6316                         offset = RHS(ins, 0)->u.cval;
6317                         mkaddr_const(state, ins, sdecl, offset);
6318                         break;
6319                 }
6320                 default:
6321                         internal_error(state, ins, "uknown constant");
6322                         break;
6323                 }
6324         }
6325 }
6326
6327 static void simplify_branch(struct compile_state *state, struct triple *ins)
6328 {
6329         struct block *block;
6330         if (ins->op != OP_BRANCH) {
6331                 internal_error(state, ins, "not branch");
6332         }
6333         if (ins->use != 0) {
6334                 internal_error(state, ins, "branch use");
6335         }
6336 #warning "FIXME implement simplify branch."
6337         /* The challenge here with simplify branch is that I need to 
6338          * make modifications to the control flow graph as well
6339          * as to the branch instruction itself.
6340          */
6341         block = ins->u.block;
6342         
6343         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6344                 struct triple *targ;
6345                 ulong_t value;
6346                 value = read_const(state, ins, &RHS(ins, 0));
6347                 unuse_triple(RHS(ins, 0), ins);
6348                 targ = TARG(ins, 0);
6349                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6350                 if (value) {
6351                         unuse_triple(ins->next, ins);
6352                         TARG(ins, 0) = targ;
6353                 }
6354                 else {
6355                         unuse_triple(targ, ins);
6356                         TARG(ins, 0) = ins->next;
6357                 }
6358 #warning "FIXME handle the case of making a branch unconditional"
6359         }
6360         if (TARG(ins, 0) == ins->next) {
6361                 unuse_triple(ins->next, ins);
6362                 if (TRIPLE_RHS(ins->sizes)) {
6363                         unuse_triple(RHS(ins, 0), ins);
6364                         unuse_triple(ins->next, ins);
6365                 }
6366                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6367                 ins->op = OP_NOOP;
6368                 if (ins->use) {
6369                         internal_error(state, ins, "noop use != 0");
6370                 }
6371 #warning "FIXME handle the case of killing a branch"
6372         }
6373 }
6374
6375 static void simplify_phi(struct compile_state *state, struct triple *ins)
6376 {
6377         struct triple **expr;
6378         ulong_t value;
6379         expr = triple_rhs(state, ins, 0);
6380         if (!*expr || !is_const(*expr)) {
6381                 return;
6382         }
6383         value = read_const(state, ins, expr);
6384         for(;expr;expr = triple_rhs(state, ins, expr)) {
6385                 if (!*expr || !is_const(*expr)) {
6386                         return;
6387                 }
6388                 if (value != read_const(state, ins, expr)) {
6389                         return;
6390                 }
6391         }
6392         mkconst(state, ins, value);
6393 }
6394
6395
6396 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6397 {
6398         if (is_const(RHS(ins, 0))) {
6399                 ulong_t left;
6400                 left = read_const(state, ins, &RHS(ins, 0));
6401                 mkconst(state, ins, bsf(left));
6402         }
6403 }
6404
6405 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6406 {
6407         if (is_const(RHS(ins, 0))) {
6408                 ulong_t left;
6409                 left = read_const(state, ins, &RHS(ins, 0));
6410                 mkconst(state, ins, bsr(left));
6411         }
6412 }
6413
6414
6415 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6416 static const simplify_t table_simplify[] = {
6417 #if 0
6418 #define simplify_smul     simplify_noop
6419 #define simplify_umul     simplify_noop
6420 #define simplify_sdiv     simplify_noop
6421 #define simplify_udiv     simplify_noop
6422 #define simplify_smod     simplify_noop
6423 #define simplify_umod     simplify_noop
6424 #endif
6425 #if 0
6426 #define simplify_add      simplify_noop
6427 #define simplify_sub      simplify_noop
6428 #endif
6429 #if 0
6430 #define simplify_sl       simplify_noop
6431 #define simplify_usr      simplify_noop
6432 #define simplify_ssr      simplify_noop
6433 #endif
6434 #if 0
6435 #define simplify_and      simplify_noop
6436 #define simplify_xor      simplify_noop
6437 #define simplify_or       simplify_noop
6438 #endif
6439 #if 0
6440 #define simplify_pos      simplify_noop
6441 #define simplify_neg      simplify_noop
6442 #define simplify_invert   simplify_noop
6443 #endif
6444
6445 #if 0
6446 #define simplify_eq       simplify_noop
6447 #define simplify_noteq    simplify_noop
6448 #endif
6449 #if 0
6450 #define simplify_sless    simplify_noop
6451 #define simplify_uless    simplify_noop
6452 #define simplify_smore    simplify_noop
6453 #define simplify_umore    simplify_noop
6454 #endif
6455 #if 0
6456 #define simplify_slesseq  simplify_noop
6457 #define simplify_ulesseq  simplify_noop
6458 #define simplify_smoreeq  simplify_noop
6459 #define simplify_umoreeq  simplify_noop
6460 #endif
6461 #if 0
6462 #define simplify_lfalse   simplify_noop
6463 #endif
6464 #if 0
6465 #define simplify_ltrue    simplify_noop
6466 #endif
6467
6468 #if 0
6469 #define simplify_copy     simplify_noop
6470 #endif
6471
6472 #if 0
6473 #define simplify_branch   simplify_noop
6474 #endif
6475
6476 #if 0
6477 #define simplify_phi      simplify_noop
6478 #endif
6479
6480 #if 0
6481 #define simplify_bsf      simplify_noop
6482 #define simplify_bsr      simplify_noop
6483 #endif
6484
6485 [OP_SMUL       ] = simplify_smul,
6486 [OP_UMUL       ] = simplify_umul,
6487 [OP_SDIV       ] = simplify_sdiv,
6488 [OP_UDIV       ] = simplify_udiv,
6489 [OP_SMOD       ] = simplify_smod,
6490 [OP_UMOD       ] = simplify_umod,
6491 [OP_ADD        ] = simplify_add,
6492 [OP_SUB        ] = simplify_sub,
6493 [OP_SL         ] = simplify_sl,
6494 [OP_USR        ] = simplify_usr,
6495 [OP_SSR        ] = simplify_ssr,
6496 [OP_AND        ] = simplify_and,
6497 [OP_XOR        ] = simplify_xor,
6498 [OP_OR         ] = simplify_or,
6499 [OP_POS        ] = simplify_pos,
6500 [OP_NEG        ] = simplify_neg,
6501 [OP_INVERT     ] = simplify_invert,
6502
6503 [OP_EQ         ] = simplify_eq,
6504 [OP_NOTEQ      ] = simplify_noteq,
6505 [OP_SLESS      ] = simplify_sless,
6506 [OP_ULESS      ] = simplify_uless,
6507 [OP_SMORE      ] = simplify_smore,
6508 [OP_UMORE      ] = simplify_umore,
6509 [OP_SLESSEQ    ] = simplify_slesseq,
6510 [OP_ULESSEQ    ] = simplify_ulesseq,
6511 [OP_SMOREEQ    ] = simplify_smoreeq,
6512 [OP_UMOREEQ    ] = simplify_umoreeq,
6513 [OP_LFALSE     ] = simplify_lfalse,
6514 [OP_LTRUE      ] = simplify_ltrue,
6515
6516 [OP_LOAD       ] = simplify_noop,
6517 [OP_STORE      ] = simplify_noop,
6518
6519 [OP_NOOP       ] = simplify_noop,
6520
6521 [OP_INTCONST   ] = simplify_noop,
6522 [OP_BLOBCONST  ] = simplify_noop,
6523 [OP_ADDRCONST  ] = simplify_noop,
6524
6525 [OP_WRITE      ] = simplify_noop,
6526 [OP_READ       ] = simplify_noop,
6527 [OP_COPY       ] = simplify_copy,
6528 [OP_PIECE      ] = simplify_noop,
6529 [OP_ASM        ] = simplify_noop,
6530
6531 [OP_DOT        ] = simplify_noop,
6532 [OP_VAL_VEC    ] = simplify_noop,
6533
6534 [OP_LIST       ] = simplify_noop,
6535 [OP_BRANCH     ] = simplify_branch,
6536 [OP_LABEL      ] = simplify_noop,
6537 [OP_ADECL      ] = simplify_noop,
6538 [OP_SDECL      ] = simplify_noop,
6539 [OP_PHI        ] = simplify_phi,
6540
6541 [OP_INB        ] = simplify_noop,
6542 [OP_INW        ] = simplify_noop,
6543 [OP_INL        ] = simplify_noop,
6544 [OP_OUTB       ] = simplify_noop,
6545 [OP_OUTW       ] = simplify_noop,
6546 [OP_OUTL       ] = simplify_noop,
6547 [OP_BSF        ] = simplify_bsf,
6548 [OP_BSR        ] = simplify_bsr,
6549 [OP_RDMSR      ] = simplify_noop,
6550 [OP_WRMSR      ] = simplify_noop,                    
6551 [OP_HLT        ] = simplify_noop,
6552 };
6553
6554 static void simplify(struct compile_state *state, struct triple *ins)
6555 {
6556         int op;
6557         simplify_t do_simplify;
6558         do {
6559                 op = ins->op;
6560                 do_simplify = 0;
6561                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6562                         do_simplify = 0;
6563                 }
6564                 else {
6565                         do_simplify = table_simplify[op];
6566                 }
6567                 if (!do_simplify) {
6568                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6569                                 op, tops(op));
6570                         return;
6571                 }
6572                 do_simplify(state, ins);
6573         } while(ins->op != op);
6574 }
6575
6576 static void simplify_all(struct compile_state *state)
6577 {
6578         struct triple *ins, *first;
6579         first = RHS(state->main_function, 0);
6580         ins = first;
6581         do {
6582                 simplify(state, ins);
6583                 ins = ins->next;
6584         } while(ins != first);
6585 }
6586
6587 /*
6588  * Builtins....
6589  * ============================
6590  */
6591
6592 static void register_builtin_function(struct compile_state *state,
6593         const char *name, int op, struct type *rtype, ...)
6594 {
6595         struct type *ftype, *atype, *param, **next;
6596         struct triple *def, *arg, *result, *work, *last, *first;
6597         struct hash_entry *ident;
6598         struct file_state file;
6599         int parameters;
6600         int name_len;
6601         va_list args;
6602         int i;
6603
6604         /* Dummy file state to get debug handling right */
6605         memset(&file, 0, sizeof(file));
6606         file.basename = "<built-in>";
6607         file.line = 1;
6608         file.report_line = 1;
6609         file.report_name = file.basename;
6610         file.prev = state->file;
6611         state->file = &file;
6612         state->function = name;
6613
6614         /* Find the Parameter count */
6615         valid_op(state, op);
6616         parameters = table_ops[op].rhs;
6617         if (parameters < 0 ) {
6618                 internal_error(state, 0, "Invalid builtin parameter count");
6619         }
6620
6621         /* Find the function type */
6622         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6623         next = &ftype->right;
6624         va_start(args, rtype);
6625         for(i = 0; i < parameters; i++) {
6626                 atype = va_arg(args, struct type *);
6627                 if (!*next) {
6628                         *next = atype;
6629                 } else {
6630                         *next = new_type(TYPE_PRODUCT, *next, atype);
6631                         next = &((*next)->right);
6632                 }
6633         }
6634         if (!*next) {
6635                 *next = &void_type;
6636         }
6637         va_end(args);
6638
6639         /* Generate the needed triples */
6640         def = triple(state, OP_LIST, ftype, 0, 0);
6641         first = label(state);
6642         RHS(def, 0) = first;
6643
6644         /* Now string them together */
6645         param = ftype->right;
6646         for(i = 0; i < parameters; i++) {
6647                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6648                         atype = param->left;
6649                 } else {
6650                         atype = param;
6651                 }
6652                 arg = flatten(state, first, variable(state, atype));
6653                 param = param->right;
6654         }
6655         result = 0;
6656         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6657                 result = flatten(state, first, variable(state, rtype));
6658         }
6659         MISC(def, 0) = result;
6660         work = new_triple(state, op, rtype, -1, parameters);
6661         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6662                 RHS(work, i) = read_expr(state, arg);
6663         }
6664         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6665                 struct triple *val;
6666                 /* Populate the LHS with the target registers */
6667                 work = flatten(state, first, work);
6668                 work->type = &void_type;
6669                 param = rtype->left;
6670                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6671                         internal_error(state, 0, "Invalid result type");
6672                 }
6673                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6674                 for(i = 0; i < rtype->elements; i++) {
6675                         struct triple *piece;
6676                         atype = param;
6677                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6678                                 atype = param->left;
6679                         }
6680                         if (!TYPE_ARITHMETIC(atype->type) &&
6681                                 !TYPE_PTR(atype->type)) {
6682                                 internal_error(state, 0, "Invalid lhs type");
6683                         }
6684                         piece = triple(state, OP_PIECE, atype, work, 0);
6685                         piece->u.cval = i;
6686                         LHS(work, i) = piece;
6687                         RHS(val, i) = piece;
6688                 }
6689                 work = val;
6690         }
6691         if (result) {
6692                 work = write_expr(state, result, work);
6693         }
6694         work = flatten(state, first, work);
6695         last = flatten(state, first, label(state));
6696         name_len = strlen(name);
6697         ident = lookup(state, name, name_len);
6698         symbol(state, ident, &ident->sym_ident, def, ftype);
6699         
6700         state->file = file.prev;
6701         state->function = 0;
6702 #if 0
6703         fprintf(stdout, "\n");
6704         loc(stdout, state, 0);
6705         fprintf(stdout, "\n__________ builtin_function _________\n");
6706         print_triple(state, def);
6707         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6708 #endif
6709 }
6710
6711 static struct type *partial_struct(struct compile_state *state,
6712         const char *field_name, struct type *type, struct type *rest)
6713 {
6714         struct hash_entry *field_ident;
6715         struct type *result;
6716         int field_name_len;
6717
6718         field_name_len = strlen(field_name);
6719         field_ident = lookup(state, field_name, field_name_len);
6720
6721         result = clone_type(0, type);
6722         result->field_ident = field_ident;
6723
6724         if (rest) {
6725                 result = new_type(TYPE_PRODUCT, result, rest);
6726         }
6727         return result;
6728 }
6729
6730 static struct type *register_builtin_type(struct compile_state *state,
6731         const char *name, struct type *type)
6732 {
6733         struct hash_entry *ident;
6734         int name_len;
6735
6736         name_len = strlen(name);
6737         ident = lookup(state, name, name_len);
6738         
6739         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6740                 ulong_t elements = 0;
6741                 struct type *field;
6742                 type = new_type(TYPE_STRUCT, type, 0);
6743                 field = type->left;
6744                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6745                         elements++;
6746                         field = field->right;
6747                 }
6748                 elements++;
6749                 symbol(state, ident, &ident->sym_struct, 0, type);
6750                 type->type_ident = ident;
6751                 type->elements = elements;
6752         }
6753         symbol(state, ident, &ident->sym_ident, 0, type);
6754         ident->tok = TOK_TYPE_NAME;
6755         return type;
6756 }
6757
6758
6759 static void register_builtins(struct compile_state *state)
6760 {
6761         struct type *msr_type;
6762
6763         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6764                 &ushort_type);
6765         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6766                 &ushort_type);
6767         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6768                 &ushort_type);
6769
6770         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6771                 &uchar_type, &ushort_type);
6772         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6773                 &ushort_type, &ushort_type);
6774         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6775                 &uint_type, &ushort_type);
6776         
6777         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6778                 &int_type);
6779         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6780                 &int_type);
6781
6782         msr_type = register_builtin_type(state, "__builtin_msr_t",
6783                 partial_struct(state, "lo", &ulong_type,
6784                 partial_struct(state, "hi", &ulong_type, 0)));
6785
6786         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6787                 &ulong_type);
6788         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6789                 &ulong_type, &ulong_type, &ulong_type);
6790         
6791         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6792                 &void_type);
6793 }
6794
6795 static struct type *declarator(
6796         struct compile_state *state, struct type *type, 
6797         struct hash_entry **ident, int need_ident);
6798 static void decl(struct compile_state *state, struct triple *first);
6799 static struct type *specifier_qualifier_list(struct compile_state *state);
6800 static int isdecl_specifier(int tok);
6801 static struct type *decl_specifiers(struct compile_state *state);
6802 static int istype(int tok);
6803 static struct triple *expr(struct compile_state *state);
6804 static struct triple *assignment_expr(struct compile_state *state);
6805 static struct type *type_name(struct compile_state *state);
6806 static void statement(struct compile_state *state, struct triple *fist);
6807
6808 static struct triple *call_expr(
6809         struct compile_state *state, struct triple *func)
6810 {
6811         struct triple *def;
6812         struct type *param, *type;
6813         ulong_t pvals, index;
6814
6815         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6816                 error(state, 0, "Called object is not a function");
6817         }
6818         if (func->op != OP_LIST) {
6819                 internal_error(state, 0, "improper function");
6820         }
6821         eat(state, TOK_LPAREN);
6822         /* Find the return type without any specifiers */
6823         type = clone_type(0, func->type->left);
6824         def = new_triple(state, OP_CALL, func->type, -1, -1);
6825         def->type = type;
6826
6827         pvals = TRIPLE_RHS(def->sizes);
6828         MISC(def, 0) = func;
6829
6830         param = func->type->right;
6831         for(index = 0; index < pvals; index++) {
6832                 struct triple *val;
6833                 struct type *arg_type;
6834                 val = read_expr(state, assignment_expr(state));
6835                 arg_type = param;
6836                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6837                         arg_type = param->left;
6838                 }
6839                 write_compatible(state, arg_type, val->type);
6840                 RHS(def, index) = val;
6841                 if (index != (pvals - 1)) {
6842                         eat(state, TOK_COMMA);
6843                         param = param->right;
6844                 }
6845         }
6846         eat(state, TOK_RPAREN);
6847         return def;
6848 }
6849
6850
6851 static struct triple *character_constant(struct compile_state *state)
6852 {
6853         struct triple *def;
6854         struct token *tk;
6855         const signed char *str, *end;
6856         int c;
6857         int str_len;
6858         eat(state, TOK_LIT_CHAR);
6859         tk = &state->token[0];
6860         str = tk->val.str + 1;
6861         str_len = tk->str_len - 2;
6862         if (str_len <= 0) {
6863                 error(state, 0, "empty character constant");
6864         }
6865         end = str + str_len;
6866         c = char_value(state, &str, end);
6867         if (str != end) {
6868                 error(state, 0, "multibyte character constant not supported");
6869         }
6870         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6871         return def;
6872 }
6873
6874 static struct triple *string_constant(struct compile_state *state)
6875 {
6876         struct triple *def;
6877         struct token *tk;
6878         struct type *type;
6879         const signed char *str, *end;
6880         signed char *buf, *ptr;
6881         int str_len;
6882
6883         buf = 0;
6884         type = new_type(TYPE_ARRAY, &char_type, 0);
6885         type->elements = 0;
6886         /* The while loop handles string concatenation */
6887         do {
6888                 eat(state, TOK_LIT_STRING);
6889                 tk = &state->token[0];
6890                 str = tk->val.str + 1;
6891                 str_len = tk->str_len - 2;
6892                 if (str_len < 0) {
6893                         error(state, 0, "negative string constant length");
6894                 }
6895                 end = str + str_len;
6896                 ptr = buf;
6897                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6898                 memcpy(buf, ptr, type->elements);
6899                 ptr = buf + type->elements;
6900                 do {
6901                         *ptr++ = char_value(state, &str, end);
6902                 } while(str < end);
6903                 type->elements = ptr - buf;
6904         } while(peek(state) == TOK_LIT_STRING);
6905         *ptr = '\0';
6906         type->elements += 1;
6907         def = triple(state, OP_BLOBCONST, type, 0, 0);
6908         def->u.blob = buf;
6909         return def;
6910 }
6911
6912
6913 static struct triple *integer_constant(struct compile_state *state)
6914 {
6915         struct triple *def;
6916         unsigned long val;
6917         struct token *tk;
6918         char *end;
6919         int u, l, decimal;
6920         struct type *type;
6921
6922         eat(state, TOK_LIT_INT);
6923         tk = &state->token[0];
6924         errno = 0;
6925         decimal = (tk->val.str[0] != '0');
6926         val = strtoul(tk->val.str, &end, 0);
6927         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6928                 error(state, 0, "Integer constant to large");
6929         }
6930         u = l = 0;
6931         if ((*end == 'u') || (*end == 'U')) {
6932                 u = 1;
6933                         end++;
6934         }
6935         if ((*end == 'l') || (*end == 'L')) {
6936                 l = 1;
6937                 end++;
6938         }
6939         if ((*end == 'u') || (*end == 'U')) {
6940                 u = 1;
6941                 end++;
6942         }
6943         if (*end) {
6944                 error(state, 0, "Junk at end of integer constant");
6945         }
6946         if (u && l)  {
6947                 type = &ulong_type;
6948         }
6949         else if (l) {
6950                 type = &long_type;
6951                 if (!decimal && (val > LONG_MAX)) {
6952                         type = &ulong_type;
6953                 }
6954         }
6955         else if (u) {
6956                 type = &uint_type;
6957                 if (val > UINT_MAX) {
6958                         type = &ulong_type;
6959                 }
6960         }
6961         else {
6962                 type = &int_type;
6963                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6964                         type = &uint_type;
6965                 }
6966                 else if (!decimal && (val > LONG_MAX)) {
6967                         type = &ulong_type;
6968                 }
6969                 else if (val > INT_MAX) {
6970                         type = &long_type;
6971                 }
6972         }
6973         def = int_const(state, type, val);
6974         return def;
6975 }
6976
6977 static struct triple *primary_expr(struct compile_state *state)
6978 {
6979         struct triple *def;
6980         int tok;
6981         tok = peek(state);
6982         switch(tok) {
6983         case TOK_IDENT:
6984         {
6985                 struct hash_entry *ident;
6986                 /* Here ident is either:
6987                  * a varable name
6988                  * a function name
6989                  * an enumeration constant.
6990                  */
6991                 eat(state, TOK_IDENT);
6992                 ident = state->token[0].ident;
6993                 if (!ident->sym_ident) {
6994                         error(state, 0, "%s undeclared", ident->name);
6995                 }
6996                 def = ident->sym_ident->def;
6997                 break;
6998         }
6999         case TOK_ENUM_CONST:
7000                 /* Here ident is an enumeration constant */
7001                 eat(state, TOK_ENUM_CONST);
7002                 def = 0;
7003                 FINISHME();
7004                 break;
7005         case TOK_LPAREN:
7006                 eat(state, TOK_LPAREN);
7007                 def = expr(state);
7008                 eat(state, TOK_RPAREN);
7009                 break;
7010         case TOK_LIT_INT:
7011                 def = integer_constant(state);
7012                 break;
7013         case TOK_LIT_FLOAT:
7014                 eat(state, TOK_LIT_FLOAT);
7015                 error(state, 0, "Floating point constants not supported");
7016                 def = 0;
7017                 FINISHME();
7018                 break;
7019         case TOK_LIT_CHAR:
7020                 def = character_constant(state);
7021                 break;
7022         case TOK_LIT_STRING:
7023                 def = string_constant(state);
7024                 break;
7025         default:
7026                 def = 0;
7027                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7028         }
7029         return def;
7030 }
7031
7032 static struct triple *postfix_expr(struct compile_state *state)
7033 {
7034         struct triple *def;
7035         int postfix;
7036         def = primary_expr(state);
7037         do {
7038                 struct triple *left;
7039                 int tok;
7040                 postfix = 1;
7041                 left = def;
7042                 switch((tok = peek(state))) {
7043                 case TOK_LBRACKET:
7044                         eat(state, TOK_LBRACKET);
7045                         def = mk_subscript_expr(state, left, expr(state));
7046                         eat(state, TOK_RBRACKET);
7047                         break;
7048                 case TOK_LPAREN:
7049                         def = call_expr(state, def);
7050                         break;
7051                 case TOK_DOT:
7052                 {
7053                         struct hash_entry *field;
7054                         eat(state, TOK_DOT);
7055                         eat(state, TOK_IDENT);
7056                         field = state->token[0].ident;
7057                         def = deref_field(state, def, field);
7058                         break;
7059                 }
7060                 case TOK_ARROW:
7061                 {
7062                         struct hash_entry *field;
7063                         eat(state, TOK_ARROW);
7064                         eat(state, TOK_IDENT);
7065                         field = state->token[0].ident;
7066                         def = mk_deref_expr(state, read_expr(state, def));
7067                         def = deref_field(state, def, field);
7068                         break;
7069                 }
7070                 case TOK_PLUSPLUS:
7071                         eat(state, TOK_PLUSPLUS);
7072                         def = mk_post_inc_expr(state, left);
7073                         break;
7074                 case TOK_MINUSMINUS:
7075                         eat(state, TOK_MINUSMINUS);
7076                         def = mk_post_dec_expr(state, left);
7077                         break;
7078                 default:
7079                         postfix = 0;
7080                         break;
7081                 }
7082         } while(postfix);
7083         return def;
7084 }
7085
7086 static struct triple *cast_expr(struct compile_state *state);
7087
7088 static struct triple *unary_expr(struct compile_state *state)
7089 {
7090         struct triple *def, *right;
7091         int tok;
7092         switch((tok = peek(state))) {
7093         case TOK_PLUSPLUS:
7094                 eat(state, TOK_PLUSPLUS);
7095                 def = mk_pre_inc_expr(state, unary_expr(state));
7096                 break;
7097         case TOK_MINUSMINUS:
7098                 eat(state, TOK_MINUSMINUS);
7099                 def = mk_pre_dec_expr(state, unary_expr(state));
7100                 break;
7101         case TOK_AND:
7102                 eat(state, TOK_AND);
7103                 def = mk_addr_expr(state, cast_expr(state), 0);
7104                 break;
7105         case TOK_STAR:
7106                 eat(state, TOK_STAR);
7107                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7108                 break;
7109         case TOK_PLUS:
7110                 eat(state, TOK_PLUS);
7111                 right = read_expr(state, cast_expr(state));
7112                 arithmetic(state, right);
7113                 def = integral_promotion(state, right);
7114                 break;
7115         case TOK_MINUS:
7116                 eat(state, TOK_MINUS);
7117                 right = read_expr(state, cast_expr(state));
7118                 arithmetic(state, right);
7119                 def = integral_promotion(state, right);
7120                 def = triple(state, OP_NEG, def->type, def, 0);
7121                 break;
7122         case TOK_TILDE:
7123                 eat(state, TOK_TILDE);
7124                 right = read_expr(state, cast_expr(state));
7125                 integral(state, right);
7126                 def = integral_promotion(state, right);
7127                 def = triple(state, OP_INVERT, def->type, def, 0);
7128                 break;
7129         case TOK_BANG:
7130                 eat(state, TOK_BANG);
7131                 right = read_expr(state, cast_expr(state));
7132                 bool(state, right);
7133                 def = lfalse_expr(state, right);
7134                 break;
7135         case TOK_SIZEOF:
7136         {
7137                 struct type *type;
7138                 int tok1, tok2;
7139                 eat(state, TOK_SIZEOF);
7140                 tok1 = peek(state);
7141                 tok2 = peek2(state);
7142                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7143                         eat(state, TOK_LPAREN);
7144                         type = type_name(state);
7145                         eat(state, TOK_RPAREN);
7146                 }
7147                 else {
7148                         struct triple *expr;
7149                         expr = unary_expr(state);
7150                         type = expr->type;
7151                         release_expr(state, expr);
7152                 }
7153                 def = int_const(state, &ulong_type, size_of(state, type));
7154                 break;
7155         }
7156         case TOK_ALIGNOF:
7157         {
7158                 struct type *type;
7159                 int tok1, tok2;
7160                 eat(state, TOK_ALIGNOF);
7161                 tok1 = peek(state);
7162                 tok2 = peek2(state);
7163                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7164                         eat(state, TOK_LPAREN);
7165                         type = type_name(state);
7166                         eat(state, TOK_RPAREN);
7167                 }
7168                 else {
7169                         struct triple *expr;
7170                         expr = unary_expr(state);
7171                         type = expr->type;
7172                         release_expr(state, expr);
7173                 }
7174                 def = int_const(state, &ulong_type, align_of(state, type));
7175                 break;
7176         }
7177         default:
7178                 def = postfix_expr(state);
7179                 break;
7180         }
7181         return def;
7182 }
7183
7184 static struct triple *cast_expr(struct compile_state *state)
7185 {
7186         struct triple *def;
7187         int tok1, tok2;
7188         tok1 = peek(state);
7189         tok2 = peek2(state);
7190         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7191                 struct type *type;
7192                 eat(state, TOK_LPAREN);
7193                 type = type_name(state);
7194                 eat(state, TOK_RPAREN);
7195                 def = read_expr(state, cast_expr(state));
7196                 def = triple(state, OP_COPY, type, def, 0);
7197         }
7198         else {
7199                 def = unary_expr(state);
7200         }
7201         return def;
7202 }
7203
7204 static struct triple *mult_expr(struct compile_state *state)
7205 {
7206         struct triple *def;
7207         int done;
7208         def = cast_expr(state);
7209         do {
7210                 struct triple *left, *right;
7211                 struct type *result_type;
7212                 int tok, op, sign;
7213                 done = 0;
7214                 switch(tok = (peek(state))) {
7215                 case TOK_STAR:
7216                 case TOK_DIV:
7217                 case TOK_MOD:
7218                         left = read_expr(state, def);
7219                         arithmetic(state, left);
7220
7221                         eat(state, tok);
7222
7223                         right = read_expr(state, cast_expr(state));
7224                         arithmetic(state, right);
7225
7226                         result_type = arithmetic_result(state, left, right);
7227                         sign = is_signed(result_type);
7228                         op = -1;
7229                         switch(tok) {
7230                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7231                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
7232                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
7233                         }
7234                         def = triple(state, op, result_type, left, right);
7235                         break;
7236                 default:
7237                         done = 1;
7238                         break;
7239                 }
7240         } while(!done);
7241         return def;
7242 }
7243
7244 static struct triple *add_expr(struct compile_state *state)
7245 {
7246         struct triple *def;
7247         int done;
7248         def = mult_expr(state);
7249         do {
7250                 done = 0;
7251                 switch( peek(state)) {
7252                 case TOK_PLUS:
7253                         eat(state, TOK_PLUS);
7254                         def = mk_add_expr(state, def, mult_expr(state));
7255                         break;
7256                 case TOK_MINUS:
7257                         eat(state, TOK_MINUS);
7258                         def = mk_sub_expr(state, def, mult_expr(state));
7259                         break;
7260                 default:
7261                         done = 1;
7262                         break;
7263                 }
7264         } while(!done);
7265         return def;
7266 }
7267
7268 static struct triple *shift_expr(struct compile_state *state)
7269 {
7270         struct triple *def;
7271         int done;
7272         def = add_expr(state);
7273         do {
7274                 struct triple *left, *right;
7275                 int tok, op;
7276                 done = 0;
7277                 switch((tok = peek(state))) {
7278                 case TOK_SL:
7279                 case TOK_SR:
7280                         left = read_expr(state, def);
7281                         integral(state, left);
7282                         left = integral_promotion(state, left);
7283
7284                         eat(state, tok);
7285
7286                         right = read_expr(state, add_expr(state));
7287                         integral(state, right);
7288                         right = integral_promotion(state, right);
7289                         
7290                         op = (tok == TOK_SL)? OP_SL : 
7291                                 is_signed(left->type)? OP_SSR: OP_USR;
7292
7293                         def = triple(state, op, left->type, left, right);
7294                         break;
7295                 default:
7296                         done = 1;
7297                         break;
7298                 }
7299         } while(!done);
7300         return def;
7301 }
7302
7303 static struct triple *relational_expr(struct compile_state *state)
7304 {
7305 #warning "Extend relational exprs to work on more than arithmetic types"
7306         struct triple *def;
7307         int done;
7308         def = shift_expr(state);
7309         do {
7310                 struct triple *left, *right;
7311                 struct type *arg_type;
7312                 int tok, op, sign;
7313                 done = 0;
7314                 switch((tok = peek(state))) {
7315                 case TOK_LESS:
7316                 case TOK_MORE:
7317                 case TOK_LESSEQ:
7318                 case TOK_MOREEQ:
7319                         left = read_expr(state, def);
7320                         arithmetic(state, left);
7321
7322                         eat(state, tok);
7323
7324                         right = read_expr(state, shift_expr(state));
7325                         arithmetic(state, right);
7326
7327                         arg_type = arithmetic_result(state, left, right);
7328                         sign = is_signed(arg_type);
7329                         op = -1;
7330                         switch(tok) {
7331                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7332                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7333                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7334                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7335                         }
7336                         def = triple(state, op, &int_type, left, right);
7337                         break;
7338                 default:
7339                         done = 1;
7340                         break;
7341                 }
7342         } while(!done);
7343         return def;
7344 }
7345
7346 static struct triple *equality_expr(struct compile_state *state)
7347 {
7348 #warning "Extend equality exprs to work on more than arithmetic types"
7349         struct triple *def;
7350         int done;
7351         def = relational_expr(state);
7352         do {
7353                 struct triple *left, *right;
7354                 int tok, op;
7355                 done = 0;
7356                 switch((tok = peek(state))) {
7357                 case TOK_EQEQ:
7358                 case TOK_NOTEQ:
7359                         left = read_expr(state, def);
7360                         arithmetic(state, left);
7361                         eat(state, tok);
7362                         right = read_expr(state, relational_expr(state));
7363                         arithmetic(state, right);
7364                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7365                         def = triple(state, op, &int_type, left, right);
7366                         break;
7367                 default:
7368                         done = 1;
7369                         break;
7370                 }
7371         } while(!done);
7372         return def;
7373 }
7374
7375 static struct triple *and_expr(struct compile_state *state)
7376 {
7377         struct triple *def;
7378         def = equality_expr(state);
7379         while(peek(state) == TOK_AND) {
7380                 struct triple *left, *right;
7381                 struct type *result_type;
7382                 left = read_expr(state, def);
7383                 integral(state, left);
7384                 eat(state, TOK_AND);
7385                 right = read_expr(state, equality_expr(state));
7386                 integral(state, right);
7387                 result_type = arithmetic_result(state, left, right);
7388                 def = triple(state, OP_AND, result_type, left, right);
7389         }
7390         return def;
7391 }
7392
7393 static struct triple *xor_expr(struct compile_state *state)
7394 {
7395         struct triple *def;
7396         def = and_expr(state);
7397         while(peek(state) == TOK_XOR) {
7398                 struct triple *left, *right;
7399                 struct type *result_type;
7400                 left = read_expr(state, def);
7401                 integral(state, left);
7402                 eat(state, TOK_XOR);
7403                 right = read_expr(state, and_expr(state));
7404                 integral(state, right);
7405                 result_type = arithmetic_result(state, left, right);
7406                 def = triple(state, OP_XOR, result_type, left, right);
7407         }
7408         return def;
7409 }
7410
7411 static struct triple *or_expr(struct compile_state *state)
7412 {
7413         struct triple *def;
7414         def = xor_expr(state);
7415         while(peek(state) == TOK_OR) {
7416                 struct triple *left, *right;
7417                 struct type *result_type;
7418                 left = read_expr(state, def);
7419                 integral(state, left);
7420                 eat(state, TOK_OR);
7421                 right = read_expr(state, xor_expr(state));
7422                 integral(state, right);
7423                 result_type = arithmetic_result(state, left, right);
7424                 def = triple(state, OP_OR, result_type, left, right);
7425         }
7426         return def;
7427 }
7428
7429 static struct triple *land_expr(struct compile_state *state)
7430 {
7431         struct triple *def;
7432         def = or_expr(state);
7433         while(peek(state) == TOK_LOGAND) {
7434                 struct triple *left, *right;
7435                 left = read_expr(state, def);
7436                 bool(state, left);
7437                 eat(state, TOK_LOGAND);
7438                 right = read_expr(state, or_expr(state));
7439                 bool(state, right);
7440
7441                 def = triple(state, OP_LAND, &int_type,
7442                         ltrue_expr(state, left),
7443                         ltrue_expr(state, right));
7444         }
7445         return def;
7446 }
7447
7448 static struct triple *lor_expr(struct compile_state *state)
7449 {
7450         struct triple *def;
7451         def = land_expr(state);
7452         while(peek(state) == TOK_LOGOR) {
7453                 struct triple *left, *right;
7454                 left = read_expr(state, def);
7455                 bool(state, left);
7456                 eat(state, TOK_LOGOR);
7457                 right = read_expr(state, land_expr(state));
7458                 bool(state, right);
7459                 
7460                 def = triple(state, OP_LOR, &int_type,
7461                         ltrue_expr(state, left),
7462                         ltrue_expr(state, right));
7463         }
7464         return def;
7465 }
7466
7467 static struct triple *conditional_expr(struct compile_state *state)
7468 {
7469         struct triple *def;
7470         def = lor_expr(state);
7471         if (peek(state) == TOK_QUEST) {
7472                 struct triple *test, *left, *right;
7473                 bool(state, def);
7474                 test = ltrue_expr(state, read_expr(state, def));
7475                 eat(state, TOK_QUEST);
7476                 left = read_expr(state, expr(state));
7477                 eat(state, TOK_COLON);
7478                 right = read_expr(state, conditional_expr(state));
7479
7480                 def = cond_expr(state, test, left, right);
7481         }
7482         return def;
7483 }
7484
7485 static struct triple *eval_const_expr(
7486         struct compile_state *state, struct triple *expr)
7487 {
7488         struct triple *def;
7489         if (is_const(expr)) {
7490                 def = expr;
7491         } 
7492         else {
7493                 /* If we don't start out as a constant simplify into one */
7494                 struct triple *head, *ptr;
7495                 head = label(state); /* dummy initial triple */
7496                 flatten(state, head, expr);
7497                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7498                         simplify(state, ptr);
7499                 }
7500                 /* Remove the constant value the tail of the list */
7501                 def = head->prev;
7502                 def->prev->next = def->next;
7503                 def->next->prev = def->prev;
7504                 def->next = def->prev = def;
7505                 if (!is_const(def)) {
7506                         error(state, 0, "Not a constant expression");
7507                 }
7508                 /* Free the intermediate expressions */
7509                 while(head->next != head) {
7510                         release_triple(state, head->next);
7511                 }
7512                 free_triple(state, head);
7513         }
7514         return def;
7515 }
7516
7517 static struct triple *constant_expr(struct compile_state *state)
7518 {
7519         return eval_const_expr(state, conditional_expr(state));
7520 }
7521
7522 static struct triple *assignment_expr(struct compile_state *state)
7523 {
7524         struct triple *def, *left, *right;
7525         int tok, op, sign;
7526         /* The C grammer in K&R shows assignment expressions
7527          * only taking unary expressions as input on their
7528          * left hand side.  But specifies the precedence of
7529          * assignemnt as the lowest operator except for comma.
7530          *
7531          * Allowing conditional expressions on the left hand side
7532          * of an assignement results in a grammar that accepts
7533          * a larger set of statements than standard C.   As long
7534          * as the subset of the grammar that is standard C behaves
7535          * correctly this should cause no problems.
7536          * 
7537          * For the extra token strings accepted by the grammar
7538          * none of them should produce a valid lvalue, so they
7539          * should not produce functioning programs.
7540          *
7541          * GCC has this bug as well, so surprises should be minimal.
7542          */
7543         def = conditional_expr(state);
7544         left = def;
7545         switch((tok = peek(state))) {
7546         case TOK_EQ:
7547                 lvalue(state, left);
7548                 eat(state, TOK_EQ);
7549                 def = write_expr(state, left, 
7550                         read_expr(state, assignment_expr(state)));
7551                 break;
7552         case TOK_TIMESEQ:
7553         case TOK_DIVEQ:
7554         case TOK_MODEQ:
7555                 lvalue(state, left);
7556                 arithmetic(state, left);
7557                 eat(state, tok);
7558                 right = read_expr(state, assignment_expr(state));
7559                 arithmetic(state, right);
7560
7561                 sign = is_signed(left->type);
7562                 op = -1;
7563                 switch(tok) {
7564                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7565                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7566                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7567                 }
7568                 def = write_expr(state, left,
7569                         triple(state, op, left->type, 
7570                                 read_expr(state, left), right));
7571                 break;
7572         case TOK_PLUSEQ:
7573                 lvalue(state, left);
7574                 eat(state, TOK_PLUSEQ);
7575                 def = write_expr(state, left,
7576                         mk_add_expr(state, left, assignment_expr(state)));
7577                 break;
7578         case TOK_MINUSEQ:
7579                 lvalue(state, left);
7580                 eat(state, TOK_MINUSEQ);
7581                 def = write_expr(state, left,
7582                         mk_sub_expr(state, left, assignment_expr(state)));
7583                 break;
7584         case TOK_SLEQ:
7585         case TOK_SREQ:
7586         case TOK_ANDEQ:
7587         case TOK_XOREQ:
7588         case TOK_OREQ:
7589                 lvalue(state, left);
7590                 integral(state, left);
7591                 eat(state, tok);
7592                 right = read_expr(state, assignment_expr(state));
7593                 integral(state, right);
7594                 right = integral_promotion(state, right);
7595                 sign = is_signed(left->type);
7596                 op = -1;
7597                 switch(tok) {
7598                 case TOK_SLEQ:  op = OP_SL; break;
7599                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7600                 case TOK_ANDEQ: op = OP_AND; break;
7601                 case TOK_XOREQ: op = OP_XOR; break;
7602                 case TOK_OREQ:  op = OP_OR; break;
7603                 }
7604                 def = write_expr(state, left,
7605                         triple(state, op, left->type, 
7606                                 read_expr(state, left), right));
7607                 break;
7608         }
7609         return def;
7610 }
7611
7612 static struct triple *expr(struct compile_state *state)
7613 {
7614         struct triple *def;
7615         def = assignment_expr(state);
7616         while(peek(state) == TOK_COMMA) {
7617                 struct triple *left, *right;
7618                 left = def;
7619                 eat(state, TOK_COMMA);
7620                 right = assignment_expr(state);
7621                 def = triple(state, OP_COMMA, right->type, left, right);
7622         }
7623         return def;
7624 }
7625
7626 static void expr_statement(struct compile_state *state, struct triple *first)
7627 {
7628         if (peek(state) != TOK_SEMI) {
7629                 flatten(state, first, expr(state));
7630         }
7631         eat(state, TOK_SEMI);
7632 }
7633
7634 static void if_statement(struct compile_state *state, struct triple *first)
7635 {
7636         struct triple *test, *jmp1, *jmp2, *middle, *end;
7637
7638         jmp1 = jmp2 = middle = 0;
7639         eat(state, TOK_IF);
7640         eat(state, TOK_LPAREN);
7641         test = expr(state);
7642         bool(state, test);
7643         /* Cleanup and invert the test */
7644         test = lfalse_expr(state, read_expr(state, test));
7645         eat(state, TOK_RPAREN);
7646         /* Generate the needed pieces */
7647         middle = label(state);
7648         jmp1 = branch(state, middle, test);
7649         /* Thread the pieces together */
7650         flatten(state, first, test);
7651         flatten(state, first, jmp1);
7652         flatten(state, first, label(state));
7653         statement(state, first);
7654         if (peek(state) == TOK_ELSE) {
7655                 eat(state, TOK_ELSE);
7656                 /* Generate the rest of the pieces */
7657                 end = label(state);
7658                 jmp2 = branch(state, end, 0);
7659                 /* Thread them together */
7660                 flatten(state, first, jmp2);
7661                 flatten(state, first, middle);
7662                 statement(state, first);
7663                 flatten(state, first, end);
7664         }
7665         else {
7666                 flatten(state, first, middle);
7667         }
7668 }
7669
7670 static void for_statement(struct compile_state *state, struct triple *first)
7671 {
7672         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7673         struct triple *label1, *label2, *label3;
7674         struct hash_entry *ident;
7675
7676         eat(state, TOK_FOR);
7677         eat(state, TOK_LPAREN);
7678         head = test = tail = jmp1 = jmp2 = 0;
7679         if (peek(state) != TOK_SEMI) {
7680                 head = expr(state);
7681         } 
7682         eat(state, TOK_SEMI);
7683         if (peek(state) != TOK_SEMI) {
7684                 test = expr(state);
7685                 bool(state, test);
7686                 test = ltrue_expr(state, read_expr(state, test));
7687         }
7688         eat(state, TOK_SEMI);
7689         if (peek(state) != TOK_RPAREN) {
7690                 tail = expr(state);
7691         }
7692         eat(state, TOK_RPAREN);
7693         /* Generate the needed pieces */
7694         label1 = label(state);
7695         label2 = label(state);
7696         label3 = label(state);
7697         if (test) {
7698                 jmp1 = branch(state, label3, 0);
7699                 jmp2 = branch(state, label1, test);
7700         }
7701         else {
7702                 jmp2 = branch(state, label1, 0);
7703         }
7704         end = label(state);
7705         /* Remember where break and continue go */
7706         start_scope(state);
7707         ident = state->i_break;
7708         symbol(state, ident, &ident->sym_ident, end, end->type);
7709         ident = state->i_continue;
7710         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7711         /* Now include the body */
7712         flatten(state, first, head);
7713         flatten(state, first, jmp1);
7714         flatten(state, first, label1);
7715         statement(state, first);
7716         flatten(state, first, label2);
7717         flatten(state, first, tail);
7718         flatten(state, first, label3);
7719         flatten(state, first, test);
7720         flatten(state, first, jmp2);
7721         flatten(state, first, end);
7722         /* Cleanup the break/continue scope */
7723         end_scope(state);
7724 }
7725
7726 static void while_statement(struct compile_state *state, struct triple *first)
7727 {
7728         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7729         struct hash_entry *ident;
7730         eat(state, TOK_WHILE);
7731         eat(state, TOK_LPAREN);
7732         test = expr(state);
7733         bool(state, test);
7734         test = ltrue_expr(state, read_expr(state, test));
7735         eat(state, TOK_RPAREN);
7736         /* Generate the needed pieces */
7737         label1 = label(state);
7738         label2 = label(state);
7739         jmp1 = branch(state, label2, 0);
7740         jmp2 = branch(state, label1, test);
7741         end = label(state);
7742         /* Remember where break and continue go */
7743         start_scope(state);
7744         ident = state->i_break;
7745         symbol(state, ident, &ident->sym_ident, end, end->type);
7746         ident = state->i_continue;
7747         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7748         /* Thread them together */
7749         flatten(state, first, jmp1);
7750         flatten(state, first, label1);
7751         statement(state, first);
7752         flatten(state, first, label2);
7753         flatten(state, first, test);
7754         flatten(state, first, jmp2);
7755         flatten(state, first, end);
7756         /* Cleanup the break/continue scope */
7757         end_scope(state);
7758 }
7759
7760 static void do_statement(struct compile_state *state, struct triple *first)
7761 {
7762         struct triple *label1, *label2, *test, *end;
7763         struct hash_entry *ident;
7764         eat(state, TOK_DO);
7765         /* Generate the needed pieces */
7766         label1 = label(state);
7767         label2 = label(state);
7768         end = label(state);
7769         /* Remember where break and continue go */
7770         start_scope(state);
7771         ident = state->i_break;
7772         symbol(state, ident, &ident->sym_ident, end, end->type);
7773         ident = state->i_continue;
7774         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7775         /* Now include the body */
7776         flatten(state, first, label1);
7777         statement(state, first);
7778         /* Cleanup the break/continue scope */
7779         end_scope(state);
7780         /* Eat the rest of the loop */
7781         eat(state, TOK_WHILE);
7782         eat(state, TOK_LPAREN);
7783         test = read_expr(state, expr(state));
7784         bool(state, test);
7785         eat(state, TOK_RPAREN);
7786         eat(state, TOK_SEMI);
7787         /* Thread the pieces together */
7788         test = ltrue_expr(state, test);
7789         flatten(state, first, label2);
7790         flatten(state, first, test);
7791         flatten(state, first, branch(state, label1, test));
7792         flatten(state, first, end);
7793 }
7794
7795
7796 static void return_statement(struct compile_state *state, struct triple *first)
7797 {
7798         struct triple *jmp, *mv, *dest, *var, *val;
7799         int last;
7800         eat(state, TOK_RETURN);
7801
7802 #warning "FIXME implement a more general excess branch elimination"
7803         val = 0;
7804         /* If we have a return value do some more work */
7805         if (peek(state) != TOK_SEMI) {
7806                 val = read_expr(state, expr(state));
7807         }
7808         eat(state, TOK_SEMI);
7809
7810         /* See if this last statement in a function */
7811         last = ((peek(state) == TOK_RBRACE) && 
7812                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7813
7814         /* Find the return variable */
7815         var = MISC(state->main_function, 0);
7816         /* Find the return destination */
7817         dest = RHS(state->main_function, 0)->prev;
7818         mv = jmp = 0;
7819         /* If needed generate a jump instruction */
7820         if (!last) {
7821                 jmp = branch(state, dest, 0);
7822         }
7823         /* If needed generate an assignment instruction */
7824         if (val) {
7825                 mv = write_expr(state, var, val);
7826         }
7827         /* Now put the code together */
7828         if (mv) {
7829                 flatten(state, first, mv);
7830                 flatten(state, first, jmp);
7831         }
7832         else if (jmp) {
7833                 flatten(state, first, jmp);
7834         }
7835 }
7836
7837 static void break_statement(struct compile_state *state, struct triple *first)
7838 {
7839         struct triple *dest;
7840         eat(state, TOK_BREAK);
7841         eat(state, TOK_SEMI);
7842         if (!state->i_break->sym_ident) {
7843                 error(state, 0, "break statement not within loop or switch");
7844         }
7845         dest = state->i_break->sym_ident->def;
7846         flatten(state, first, branch(state, dest, 0));
7847 }
7848
7849 static void continue_statement(struct compile_state *state, struct triple *first)
7850 {
7851         struct triple *dest;
7852         eat(state, TOK_CONTINUE);
7853         eat(state, TOK_SEMI);
7854         if (!state->i_continue->sym_ident) {
7855                 error(state, 0, "continue statement outside of a loop");
7856         }
7857         dest = state->i_continue->sym_ident->def;
7858         flatten(state, first, branch(state, dest, 0));
7859 }
7860
7861 static void goto_statement(struct compile_state *state, struct triple *first)
7862 {
7863         struct hash_entry *ident;
7864         eat(state, TOK_GOTO);
7865         eat(state, TOK_IDENT);
7866         ident = state->token[0].ident;
7867         if (!ident->sym_label) {
7868                 /* If this is a forward branch allocate the label now,
7869                  * it will be flattend in the appropriate location later.
7870                  */
7871                 struct triple *ins;
7872                 ins = label(state);
7873                 label_symbol(state, ident, ins);
7874         }
7875         eat(state, TOK_SEMI);
7876
7877         flatten(state, first, branch(state, ident->sym_label->def, 0));
7878 }
7879
7880 static void labeled_statement(struct compile_state *state, struct triple *first)
7881 {
7882         struct triple *ins;
7883         struct hash_entry *ident;
7884         eat(state, TOK_IDENT);
7885
7886         ident = state->token[0].ident;
7887         if (ident->sym_label && ident->sym_label->def) {
7888                 ins = ident->sym_label->def;
7889                 put_occurance(ins->occurance);
7890                 ins->occurance = new_occurance(state);
7891         }
7892         else {
7893                 ins = label(state);
7894                 label_symbol(state, ident, ins);
7895         }
7896         if (ins->id & TRIPLE_FLAG_FLATTENED) {
7897                 error(state, 0, "label %s already defined", ident->name);
7898         }
7899         flatten(state, first, ins);
7900
7901         eat(state, TOK_COLON);
7902         statement(state, first);
7903 }
7904
7905 static void switch_statement(struct compile_state *state, struct triple *first)
7906 {
7907         FINISHME();
7908         eat(state, TOK_SWITCH);
7909         eat(state, TOK_LPAREN);
7910         expr(state);
7911         eat(state, TOK_RPAREN);
7912         statement(state, first);
7913         error(state, 0, "switch statements are not implemented");
7914         FINISHME();
7915 }
7916
7917 static void case_statement(struct compile_state *state, struct triple *first)
7918 {
7919         FINISHME();
7920         eat(state, TOK_CASE);
7921         constant_expr(state);
7922         eat(state, TOK_COLON);
7923         statement(state, first);
7924         error(state, 0, "case statements are not implemented");
7925         FINISHME();
7926 }
7927
7928 static void default_statement(struct compile_state *state, struct triple *first)
7929 {
7930         FINISHME();
7931         eat(state, TOK_DEFAULT);
7932         eat(state, TOK_COLON);
7933         statement(state, first);
7934         error(state, 0, "default statements are not implemented");
7935         FINISHME();
7936 }
7937
7938 static void asm_statement(struct compile_state *state, struct triple *first)
7939 {
7940         struct asm_info *info;
7941         struct {
7942                 struct triple *constraint;
7943                 struct triple *expr;
7944         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7945         struct triple *def, *asm_str;
7946         int out, in, clobbers, more, colons, i;
7947
7948         eat(state, TOK_ASM);
7949         /* For now ignore the qualifiers */
7950         switch(peek(state)) {
7951         case TOK_CONST:
7952                 eat(state, TOK_CONST);
7953                 break;
7954         case TOK_VOLATILE:
7955                 eat(state, TOK_VOLATILE);
7956                 break;
7957         }
7958         eat(state, TOK_LPAREN);
7959         asm_str = string_constant(state);
7960
7961         colons = 0;
7962         out = in = clobbers = 0;
7963         /* Outputs */
7964         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7965                 eat(state, TOK_COLON);
7966                 colons++;
7967                 more = (peek(state) == TOK_LIT_STRING);
7968                 while(more) {
7969                         struct triple *var;
7970                         struct triple *constraint;
7971                         char *str;
7972                         more = 0;
7973                         if (out > MAX_LHS) {
7974                                 error(state, 0, "Maximum output count exceeded.");
7975                         }
7976                         constraint = string_constant(state);
7977                         str = constraint->u.blob;
7978                         if (str[0] != '=') {
7979                                 error(state, 0, "Output constraint does not start with =");
7980                         }
7981                         constraint->u.blob = str + 1;
7982                         eat(state, TOK_LPAREN);
7983                         var = conditional_expr(state);
7984                         eat(state, TOK_RPAREN);
7985
7986                         lvalue(state, var);
7987                         out_param[out].constraint = constraint;
7988                         out_param[out].expr       = var;
7989                         if (peek(state) == TOK_COMMA) {
7990                                 eat(state, TOK_COMMA);
7991                                 more = 1;
7992                         }
7993                         out++;
7994                 }
7995         }
7996         /* Inputs */
7997         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7998                 eat(state, TOK_COLON);
7999                 colons++;
8000                 more = (peek(state) == TOK_LIT_STRING);
8001                 while(more) {
8002                         struct triple *val;
8003                         struct triple *constraint;
8004                         char *str;
8005                         more = 0;
8006                         if (in > MAX_RHS) {
8007                                 error(state, 0, "Maximum input count exceeded.");
8008                         }
8009                         constraint = string_constant(state);
8010                         str = constraint->u.blob;
8011                         if (digitp(str[0] && str[1] == '\0')) {
8012                                 int val;
8013                                 val = digval(str[0]);
8014                                 if ((val < 0) || (val >= out)) {
8015                                         error(state, 0, "Invalid input constraint %d", val);
8016                                 }
8017                         }
8018                         eat(state, TOK_LPAREN);
8019                         val = conditional_expr(state);
8020                         eat(state, TOK_RPAREN);
8021
8022                         in_param[in].constraint = constraint;
8023                         in_param[in].expr       = val;
8024                         if (peek(state) == TOK_COMMA) {
8025                                 eat(state, TOK_COMMA);
8026                                 more = 1;
8027                         }
8028                         in++;
8029                 }
8030         }
8031
8032         /* Clobber */
8033         if ((colons == 2) && (peek(state) == TOK_COLON)) {
8034                 eat(state, TOK_COLON);
8035                 colons++;
8036                 more = (peek(state) == TOK_LIT_STRING);
8037                 while(more) {
8038                         struct triple *clobber;
8039                         more = 0;
8040                         if ((clobbers + out) > MAX_LHS) {
8041                                 error(state, 0, "Maximum clobber limit exceeded.");
8042                         }
8043                         clobber = string_constant(state);
8044                         eat(state, TOK_RPAREN);
8045
8046                         clob_param[clobbers].constraint = clobber;
8047                         if (peek(state) == TOK_COMMA) {
8048                                 eat(state, TOK_COMMA);
8049                                 more = 1;
8050                         }
8051                         clobbers++;
8052                 }
8053         }
8054         eat(state, TOK_RPAREN);
8055         eat(state, TOK_SEMI);
8056
8057
8058         info = xcmalloc(sizeof(*info), "asm_info");
8059         info->str = asm_str->u.blob;
8060         free_triple(state, asm_str);
8061
8062         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8063         def->u.ainfo = info;
8064
8065         /* Find the register constraints */
8066         for(i = 0; i < out; i++) {
8067                 struct triple *constraint;
8068                 constraint = out_param[i].constraint;
8069                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
8070                         out_param[i].expr->type, constraint->u.blob);
8071                 free_triple(state, constraint);
8072         }
8073         for(; i - out < clobbers; i++) {
8074                 struct triple *constraint;
8075                 constraint = clob_param[i - out].constraint;
8076                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8077                 free_triple(state, constraint);
8078         }
8079         for(i = 0; i < in; i++) {
8080                 struct triple *constraint;
8081                 const char *str;
8082                 constraint = in_param[i].constraint;
8083                 str = constraint->u.blob;
8084                 if (digitp(str[0]) && str[1] == '\0') {
8085                         struct reg_info cinfo;
8086                         int val;
8087                         val = digval(str[0]);
8088                         cinfo.reg = info->tmpl.lhs[val].reg;
8089                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8090                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
8091                         if (cinfo.reg == REG_UNSET) {
8092                                 cinfo.reg = REG_VIRT0 + val;
8093                         }
8094                         if (cinfo.regcm == 0) {
8095                                 error(state, 0, "No registers for %d", val);
8096                         }
8097                         info->tmpl.lhs[val] = cinfo;
8098                         info->tmpl.rhs[i]   = cinfo;
8099                                 
8100                 } else {
8101                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
8102                                 in_param[i].expr->type, str);
8103                 }
8104                 free_triple(state, constraint);
8105         }
8106
8107         /* Now build the helper expressions */
8108         for(i = 0; i < in; i++) {
8109                 RHS(def, i) = read_expr(state,in_param[i].expr);
8110         }
8111         flatten(state, first, def);
8112         for(i = 0; i < out; i++) {
8113                 struct triple *piece;
8114                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8115                 piece->u.cval = i;
8116                 LHS(def, i) = piece;
8117                 flatten(state, first,
8118                         write_expr(state, out_param[i].expr, piece));
8119         }
8120         for(; i - out < clobbers; i++) {
8121                 struct triple *piece;
8122                 piece = triple(state, OP_PIECE, &void_type, def, 0);
8123                 piece->u.cval = i;
8124                 LHS(def, i) = piece;
8125                 flatten(state, first, piece);
8126         }
8127 }
8128
8129
8130 static int isdecl(int tok)
8131 {
8132         switch(tok) {
8133         case TOK_AUTO:
8134         case TOK_REGISTER:
8135         case TOK_STATIC:
8136         case TOK_EXTERN:
8137         case TOK_TYPEDEF:
8138         case TOK_CONST:
8139         case TOK_RESTRICT:
8140         case TOK_VOLATILE:
8141         case TOK_VOID:
8142         case TOK_CHAR:
8143         case TOK_SHORT:
8144         case TOK_INT:
8145         case TOK_LONG:
8146         case TOK_FLOAT:
8147         case TOK_DOUBLE:
8148         case TOK_SIGNED:
8149         case TOK_UNSIGNED:
8150         case TOK_STRUCT:
8151         case TOK_UNION:
8152         case TOK_ENUM:
8153         case TOK_TYPE_NAME: /* typedef name */
8154                 return 1;
8155         default:
8156                 return 0;
8157         }
8158 }
8159
8160 static void compound_statement(struct compile_state *state, struct triple *first)
8161 {
8162         eat(state, TOK_LBRACE);
8163         start_scope(state);
8164
8165         /* statement-list opt */
8166         while (peek(state) != TOK_RBRACE) {
8167                 statement(state, first);
8168         }
8169         end_scope(state);
8170         eat(state, TOK_RBRACE);
8171 }
8172
8173 static void statement(struct compile_state *state, struct triple *first)
8174 {
8175         int tok;
8176         tok = peek(state);
8177         if (tok == TOK_LBRACE) {
8178                 compound_statement(state, first);
8179         }
8180         else if (tok == TOK_IF) {
8181                 if_statement(state, first); 
8182         }
8183         else if (tok == TOK_FOR) {
8184                 for_statement(state, first);
8185         }
8186         else if (tok == TOK_WHILE) {
8187                 while_statement(state, first);
8188         }
8189         else if (tok == TOK_DO) {
8190                 do_statement(state, first);
8191         }
8192         else if (tok == TOK_RETURN) {
8193                 return_statement(state, first);
8194         }
8195         else if (tok == TOK_BREAK) {
8196                 break_statement(state, first);
8197         }
8198         else if (tok == TOK_CONTINUE) {
8199                 continue_statement(state, first);
8200         }
8201         else if (tok == TOK_GOTO) {
8202                 goto_statement(state, first);
8203         }
8204         else if (tok == TOK_SWITCH) {
8205                 switch_statement(state, first);
8206         }
8207         else if (tok == TOK_ASM) {
8208                 asm_statement(state, first);
8209         }
8210         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8211                 labeled_statement(state, first); 
8212         }
8213         else if (tok == TOK_CASE) {
8214                 case_statement(state, first);
8215         }
8216         else if (tok == TOK_DEFAULT) {
8217                 default_statement(state, first);
8218         }
8219         else if (isdecl(tok)) {
8220                 /* This handles C99 intermixing of statements and decls */
8221                 decl(state, first);
8222         }
8223         else {
8224                 expr_statement(state, first);
8225         }
8226 }
8227
8228 static struct type *param_decl(struct compile_state *state)
8229 {
8230         struct type *type;
8231         struct hash_entry *ident;
8232         /* Cheat so the declarator will know we are not global */
8233         start_scope(state); 
8234         ident = 0;
8235         type = decl_specifiers(state);
8236         type = declarator(state, type, &ident, 0);
8237         type->field_ident = ident;
8238         end_scope(state);
8239         return type;
8240 }
8241
8242 static struct type *param_type_list(struct compile_state *state, struct type *type)
8243 {
8244         struct type *ftype, **next;
8245         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8246         next = &ftype->right;
8247         while(peek(state) == TOK_COMMA) {
8248                 eat(state, TOK_COMMA);
8249                 if (peek(state) == TOK_DOTS) {
8250                         eat(state, TOK_DOTS);
8251                         error(state, 0, "variadic functions not supported");
8252                 }
8253                 else {
8254                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8255                         next = &((*next)->right);
8256                 }
8257         }
8258         return ftype;
8259 }
8260
8261
8262 static struct type *type_name(struct compile_state *state)
8263 {
8264         struct type *type;
8265         type = specifier_qualifier_list(state);
8266         /* abstract-declarator (may consume no tokens) */
8267         type = declarator(state, type, 0, 0);
8268         return type;
8269 }
8270
8271 static struct type *direct_declarator(
8272         struct compile_state *state, struct type *type, 
8273         struct hash_entry **ident, int need_ident)
8274 {
8275         struct type *outer;
8276         int op;
8277         outer = 0;
8278         arrays_complete(state, type);
8279         switch(peek(state)) {
8280         case TOK_IDENT:
8281                 eat(state, TOK_IDENT);
8282                 if (!ident) {
8283                         error(state, 0, "Unexpected identifier found");
8284                 }
8285                 /* The name of what we are declaring */
8286                 *ident = state->token[0].ident;
8287                 break;
8288         case TOK_LPAREN:
8289                 eat(state, TOK_LPAREN);
8290                 outer = declarator(state, type, ident, need_ident);
8291                 eat(state, TOK_RPAREN);
8292                 break;
8293         default:
8294                 if (need_ident) {
8295                         error(state, 0, "Identifier expected");
8296                 }
8297                 break;
8298         }
8299         do {
8300                 op = 1;
8301                 arrays_complete(state, type);
8302                 switch(peek(state)) {
8303                 case TOK_LPAREN:
8304                         eat(state, TOK_LPAREN);
8305                         type = param_type_list(state, type);
8306                         eat(state, TOK_RPAREN);
8307                         break;
8308                 case TOK_LBRACKET:
8309                 {
8310                         unsigned int qualifiers;
8311                         struct triple *value;
8312                         value = 0;
8313                         eat(state, TOK_LBRACKET);
8314                         if (peek(state) != TOK_RBRACKET) {
8315                                 value = constant_expr(state);
8316                                 integral(state, value);
8317                         }
8318                         eat(state, TOK_RBRACKET);
8319
8320                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8321                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8322                         if (value) {
8323                                 type->elements = value->u.cval;
8324                                 free_triple(state, value);
8325                         } else {
8326                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8327                                 op = 0;
8328                         }
8329                 }
8330                         break;
8331                 default:
8332                         op = 0;
8333                         break;
8334                 }
8335         } while(op);
8336         if (outer) {
8337                 struct type *inner;
8338                 arrays_complete(state, type);
8339                 FINISHME();
8340                 for(inner = outer; inner->left; inner = inner->left)
8341                         ;
8342                 inner->left = type;
8343                 type = outer;
8344         }
8345         return type;
8346 }
8347
8348 static struct type *declarator(
8349         struct compile_state *state, struct type *type, 
8350         struct hash_entry **ident, int need_ident)
8351 {
8352         while(peek(state) == TOK_STAR) {
8353                 eat(state, TOK_STAR);
8354                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8355         }
8356         type = direct_declarator(state, type, ident, need_ident);
8357         return type;
8358 }
8359
8360
8361 static struct type *typedef_name(
8362         struct compile_state *state, unsigned int specifiers)
8363 {
8364         struct hash_entry *ident;
8365         struct type *type;
8366         eat(state, TOK_TYPE_NAME);
8367         ident = state->token[0].ident;
8368         type = ident->sym_ident->type;
8369         specifiers |= type->type & QUAL_MASK;
8370         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8371                 (type->type & (STOR_MASK | QUAL_MASK))) {
8372                 type = clone_type(specifiers, type);
8373         }
8374         return type;
8375 }
8376
8377 static struct type *enum_specifier(
8378         struct compile_state *state, unsigned int specifiers)
8379 {
8380         int tok;
8381         struct type *type;
8382         type = 0;
8383         FINISHME();
8384         eat(state, TOK_ENUM);
8385         tok = peek(state);
8386         if (tok == TOK_IDENT) {
8387                 eat(state, TOK_IDENT);
8388         }
8389         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8390                 eat(state, TOK_LBRACE);
8391                 do {
8392                         eat(state, TOK_IDENT);
8393                         if (peek(state) == TOK_EQ) {
8394                                 eat(state, TOK_EQ);
8395                                 constant_expr(state);
8396                         }
8397                         if (peek(state) == TOK_COMMA) {
8398                                 eat(state, TOK_COMMA);
8399                         }
8400                 } while(peek(state) != TOK_RBRACE);
8401                 eat(state, TOK_RBRACE);
8402         }
8403         FINISHME();
8404         return type;
8405 }
8406
8407 #if 0
8408 static struct type *struct_declarator(
8409         struct compile_state *state, struct type *type, struct hash_entry **ident)
8410 {
8411         int tok;
8412 #warning "struct_declarator is complicated because of bitfields, kill them?"
8413         tok = peek(state);
8414         if (tok != TOK_COLON) {
8415                 type = declarator(state, type, ident, 1);
8416         }
8417         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8418                 eat(state, TOK_COLON);
8419                 constant_expr(state);
8420         }
8421         FINISHME();
8422         return type;
8423 }
8424 #endif
8425
8426 static struct type *struct_or_union_specifier(
8427         struct compile_state *state, unsigned int spec)
8428 {
8429         struct type *struct_type;
8430         struct hash_entry *ident;
8431         unsigned int type_join;
8432         int tok;
8433         struct_type = 0;
8434         ident = 0;
8435         switch(peek(state)) {
8436         case TOK_STRUCT:
8437                 eat(state, TOK_STRUCT);
8438                 type_join = TYPE_PRODUCT;
8439                 break;
8440         case TOK_UNION:
8441                 eat(state, TOK_UNION);
8442                 type_join = TYPE_OVERLAP;
8443                 error(state, 0, "unions not yet supported\n");
8444                 break;
8445         default:
8446                 eat(state, TOK_STRUCT);
8447                 type_join = TYPE_PRODUCT;
8448                 break;
8449         }
8450         tok = peek(state);
8451         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8452                 eat(state, tok);
8453                 ident = state->token[0].ident;
8454         }
8455         if (!ident || (peek(state) == TOK_LBRACE)) {
8456                 ulong_t elements;
8457                 struct type **next;
8458                 elements = 0;
8459                 eat(state, TOK_LBRACE);
8460                 next = &struct_type;
8461                 do {
8462                         struct type *base_type;
8463                         int done;
8464                         base_type = specifier_qualifier_list(state);
8465                         do {
8466                                 struct type *type;
8467                                 struct hash_entry *fident;
8468                                 done = 1;
8469                                 type = declarator(state, base_type, &fident, 1);
8470                                 elements++;
8471                                 if (peek(state) == TOK_COMMA) {
8472                                         done = 0;
8473                                         eat(state, TOK_COMMA);
8474                                 }
8475                                 type = clone_type(0, type);
8476                                 type->field_ident = fident;
8477                                 if (*next) {
8478                                         *next = new_type(type_join, *next, type);
8479                                         next = &((*next)->right);
8480                                 } else {
8481                                         *next = type;
8482                                 }
8483                         } while(!done);
8484                         eat(state, TOK_SEMI);
8485                 } while(peek(state) != TOK_RBRACE);
8486                 eat(state, TOK_RBRACE);
8487                 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8488                 struct_type->type_ident = ident;
8489                 struct_type->elements = elements;
8490                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8491         }
8492         if (ident && ident->sym_struct) {
8493                 struct_type = clone_type(spec,  ident->sym_struct->type);
8494         }
8495         else if (ident && !ident->sym_struct) {
8496                 error(state, 0, "struct %s undeclared", ident->name);
8497         }
8498         return struct_type;
8499 }
8500
8501 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8502 {
8503         unsigned int specifiers;
8504         switch(peek(state)) {
8505         case TOK_AUTO:
8506                 eat(state, TOK_AUTO);
8507                 specifiers = STOR_AUTO;
8508                 break;
8509         case TOK_REGISTER:
8510                 eat(state, TOK_REGISTER);
8511                 specifiers = STOR_REGISTER;
8512                 break;
8513         case TOK_STATIC:
8514                 eat(state, TOK_STATIC);
8515                 specifiers = STOR_STATIC;
8516                 break;
8517         case TOK_EXTERN:
8518                 eat(state, TOK_EXTERN);
8519                 specifiers = STOR_EXTERN;
8520                 break;
8521         case TOK_TYPEDEF:
8522                 eat(state, TOK_TYPEDEF);
8523                 specifiers = STOR_TYPEDEF;
8524                 break;
8525         default:
8526                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8527                         specifiers = STOR_STATIC;
8528                 }
8529                 else {
8530                         specifiers = STOR_AUTO;
8531                 }
8532         }
8533         return specifiers;
8534 }
8535
8536 static unsigned int function_specifier_opt(struct compile_state *state)
8537 {
8538         /* Ignore the inline keyword */
8539         unsigned int specifiers;
8540         specifiers = 0;
8541         switch(peek(state)) {
8542         case TOK_INLINE:
8543                 eat(state, TOK_INLINE);
8544                 specifiers = STOR_INLINE;
8545         }
8546         return specifiers;
8547 }
8548
8549 static unsigned int type_qualifiers(struct compile_state *state)
8550 {
8551         unsigned int specifiers;
8552         int done;
8553         done = 0;
8554         specifiers = QUAL_NONE;
8555         do {
8556                 switch(peek(state)) {
8557                 case TOK_CONST:
8558                         eat(state, TOK_CONST);
8559                         specifiers = QUAL_CONST;
8560                         break;
8561                 case TOK_VOLATILE:
8562                         eat(state, TOK_VOLATILE);
8563                         specifiers = QUAL_VOLATILE;
8564                         break;
8565                 case TOK_RESTRICT:
8566                         eat(state, TOK_RESTRICT);
8567                         specifiers = QUAL_RESTRICT;
8568                         break;
8569                 default:
8570                         done = 1;
8571                         break;
8572                 }
8573         } while(!done);
8574         return specifiers;
8575 }
8576
8577 static struct type *type_specifier(
8578         struct compile_state *state, unsigned int spec)
8579 {
8580         struct type *type;
8581         type = 0;
8582         switch(peek(state)) {
8583         case TOK_VOID:
8584                 eat(state, TOK_VOID);
8585                 type = new_type(TYPE_VOID | spec, 0, 0);
8586                 break;
8587         case TOK_CHAR:
8588                 eat(state, TOK_CHAR);
8589                 type = new_type(TYPE_CHAR | spec, 0, 0);
8590                 break;
8591         case TOK_SHORT:
8592                 eat(state, TOK_SHORT);
8593                 if (peek(state) == TOK_INT) {
8594                         eat(state, TOK_INT);
8595                 }
8596                 type = new_type(TYPE_SHORT | spec, 0, 0);
8597                 break;
8598         case TOK_INT:
8599                 eat(state, TOK_INT);
8600                 type = new_type(TYPE_INT | spec, 0, 0);
8601                 break;
8602         case TOK_LONG:
8603                 eat(state, TOK_LONG);
8604                 switch(peek(state)) {
8605                 case TOK_LONG:
8606                         eat(state, TOK_LONG);
8607                         error(state, 0, "long long not supported");
8608                         break;
8609                 case TOK_DOUBLE:
8610                         eat(state, TOK_DOUBLE);
8611                         error(state, 0, "long double not supported");
8612                         break;
8613                 case TOK_INT:
8614                         eat(state, TOK_INT);
8615                         type = new_type(TYPE_LONG | spec, 0, 0);
8616                         break;
8617                 default:
8618                         type = new_type(TYPE_LONG | spec, 0, 0);
8619                         break;
8620                 }
8621                 break;
8622         case TOK_FLOAT:
8623                 eat(state, TOK_FLOAT);
8624                 error(state, 0, "type float not supported");
8625                 break;
8626         case TOK_DOUBLE:
8627                 eat(state, TOK_DOUBLE);
8628                 error(state, 0, "type double not supported");
8629                 break;
8630         case TOK_SIGNED:
8631                 eat(state, TOK_SIGNED);
8632                 switch(peek(state)) {
8633                 case TOK_LONG:
8634                         eat(state, TOK_LONG);
8635                         switch(peek(state)) {
8636                         case TOK_LONG:
8637                                 eat(state, TOK_LONG);
8638                                 error(state, 0, "type long long not supported");
8639                                 break;
8640                         case TOK_INT:
8641                                 eat(state, TOK_INT);
8642                                 type = new_type(TYPE_LONG | spec, 0, 0);
8643                                 break;
8644                         default:
8645                                 type = new_type(TYPE_LONG | spec, 0, 0);
8646                                 break;
8647                         }
8648                         break;
8649                 case TOK_INT:
8650                         eat(state, TOK_INT);
8651                         type = new_type(TYPE_INT | spec, 0, 0);
8652                         break;
8653                 case TOK_SHORT:
8654                         eat(state, TOK_SHORT);
8655                         type = new_type(TYPE_SHORT | spec, 0, 0);
8656                         break;
8657                 case TOK_CHAR:
8658                         eat(state, TOK_CHAR);
8659                         type = new_type(TYPE_CHAR | spec, 0, 0);
8660                         break;
8661                 default:
8662                         type = new_type(TYPE_INT | spec, 0, 0);
8663                         break;
8664                 }
8665                 break;
8666         case TOK_UNSIGNED:
8667                 eat(state, TOK_UNSIGNED);
8668                 switch(peek(state)) {
8669                 case TOK_LONG:
8670                         eat(state, TOK_LONG);
8671                         switch(peek(state)) {
8672                         case TOK_LONG:
8673                                 eat(state, TOK_LONG);
8674                                 error(state, 0, "unsigned long long not supported");
8675                                 break;
8676                         case TOK_INT:
8677                                 eat(state, TOK_INT);
8678                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8679                                 break;
8680                         default:
8681                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8682                                 break;
8683                         }
8684                         break;
8685                 case TOK_INT:
8686                         eat(state, TOK_INT);
8687                         type = new_type(TYPE_UINT | spec, 0, 0);
8688                         break;
8689                 case TOK_SHORT:
8690                         eat(state, TOK_SHORT);
8691                         type = new_type(TYPE_USHORT | spec, 0, 0);
8692                         break;
8693                 case TOK_CHAR:
8694                         eat(state, TOK_CHAR);
8695                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8696                         break;
8697                 default:
8698                         type = new_type(TYPE_UINT | spec, 0, 0);
8699                         break;
8700                 }
8701                 break;
8702                 /* struct or union specifier */
8703         case TOK_STRUCT:
8704         case TOK_UNION:
8705                 type = struct_or_union_specifier(state, spec);
8706                 break;
8707                 /* enum-spefifier */
8708         case TOK_ENUM:
8709                 type = enum_specifier(state, spec);
8710                 break;
8711                 /* typedef name */
8712         case TOK_TYPE_NAME:
8713                 type = typedef_name(state, spec);
8714                 break;
8715         default:
8716                 error(state, 0, "bad type specifier %s", 
8717                         tokens[peek(state)]);
8718                 break;
8719         }
8720         return type;
8721 }
8722
8723 static int istype(int tok)
8724 {
8725         switch(tok) {
8726         case TOK_CONST:
8727         case TOK_RESTRICT:
8728         case TOK_VOLATILE:
8729         case TOK_VOID:
8730         case TOK_CHAR:
8731         case TOK_SHORT:
8732         case TOK_INT:
8733         case TOK_LONG:
8734         case TOK_FLOAT:
8735         case TOK_DOUBLE:
8736         case TOK_SIGNED:
8737         case TOK_UNSIGNED:
8738         case TOK_STRUCT:
8739         case TOK_UNION:
8740         case TOK_ENUM:
8741         case TOK_TYPE_NAME:
8742                 return 1;
8743         default:
8744                 return 0;
8745         }
8746 }
8747
8748
8749 static struct type *specifier_qualifier_list(struct compile_state *state)
8750 {
8751         struct type *type;
8752         unsigned int specifiers = 0;
8753
8754         /* type qualifiers */
8755         specifiers |= type_qualifiers(state);
8756
8757         /* type specifier */
8758         type = type_specifier(state, specifiers);
8759
8760         return type;
8761 }
8762
8763 static int isdecl_specifier(int tok)
8764 {
8765         switch(tok) {
8766                 /* storage class specifier */
8767         case TOK_AUTO:
8768         case TOK_REGISTER:
8769         case TOK_STATIC:
8770         case TOK_EXTERN:
8771         case TOK_TYPEDEF:
8772                 /* type qualifier */
8773         case TOK_CONST:
8774         case TOK_RESTRICT:
8775         case TOK_VOLATILE:
8776                 /* type specifiers */
8777         case TOK_VOID:
8778         case TOK_CHAR:
8779         case TOK_SHORT:
8780         case TOK_INT:
8781         case TOK_LONG:
8782         case TOK_FLOAT:
8783         case TOK_DOUBLE:
8784         case TOK_SIGNED:
8785         case TOK_UNSIGNED:
8786                 /* struct or union specifier */
8787         case TOK_STRUCT:
8788         case TOK_UNION:
8789                 /* enum-spefifier */
8790         case TOK_ENUM:
8791                 /* typedef name */
8792         case TOK_TYPE_NAME:
8793                 /* function specifiers */
8794         case TOK_INLINE:
8795                 return 1;
8796         default:
8797                 return 0;
8798         }
8799 }
8800
8801 static struct type *decl_specifiers(struct compile_state *state)
8802 {
8803         struct type *type;
8804         unsigned int specifiers;
8805         /* I am overly restrictive in the arragement of specifiers supported.
8806          * C is overly flexible in this department it makes interpreting
8807          * the parse tree difficult.
8808          */
8809         specifiers = 0;
8810
8811         /* storage class specifier */
8812         specifiers |= storage_class_specifier_opt(state);
8813
8814         /* function-specifier */
8815         specifiers |= function_specifier_opt(state);
8816
8817         /* type qualifier */
8818         specifiers |= type_qualifiers(state);
8819
8820         /* type specifier */
8821         type = type_specifier(state, specifiers);
8822         return type;
8823 }
8824
8825 struct field_info {
8826         struct type *type;
8827         size_t offset;
8828 };
8829
8830 static struct field_info designator(struct compile_state *state, struct type *type)
8831 {
8832         int tok;
8833         struct field_info info;
8834         info.offset = ~0U;
8835         info.type = 0;
8836         do {
8837                 switch(peek(state)) {
8838                 case TOK_LBRACKET:
8839                 {
8840                         struct triple *value;
8841                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8842                                 error(state, 0, "Array designator not in array initializer");
8843                         }
8844                         eat(state, TOK_LBRACKET);
8845                         value = constant_expr(state);
8846                         eat(state, TOK_RBRACKET);
8847
8848                         info.type = type->left;
8849                         info.offset = value->u.cval * size_of(state, info.type);
8850                         break;
8851                 }
8852                 case TOK_DOT:
8853                 {
8854                         struct hash_entry *field;
8855                         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8856                                 error(state, 0, "Struct designator not in struct initializer");
8857                         }
8858                         eat(state, TOK_DOT);
8859                         eat(state, TOK_IDENT);
8860                         field = state->token[0].ident;
8861                         info.offset = field_offset(state, type, field);
8862                         info.type   = field_type(state, type, field);
8863                         break;
8864                 }
8865                 default:
8866                         error(state, 0, "Invalid designator");
8867                 }
8868                 tok = peek(state);
8869         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8870         eat(state, TOK_EQ);
8871         return info;
8872 }
8873
8874 static struct triple *initializer(
8875         struct compile_state *state, struct type *type)
8876 {
8877         struct triple *result;
8878         if (peek(state) != TOK_LBRACE) {
8879                 result = assignment_expr(state);
8880         }
8881         else {
8882                 int comma;
8883                 size_t max_offset;
8884                 struct field_info info;
8885                 void *buf;
8886                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8887                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8888                         internal_error(state, 0, "unknown initializer type");
8889                 }
8890                 info.offset = 0;
8891                 info.type = type->left;
8892                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8893                         info.type = next_field(state, type, 0);
8894                 }
8895                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8896                         max_offset = 0;
8897                 } else {
8898                         max_offset = size_of(state, type);
8899                 }
8900                 buf = xcmalloc(max_offset, "initializer");
8901                 eat(state, TOK_LBRACE);
8902                 do {
8903                         struct triple *value;
8904                         struct type *value_type;
8905                         size_t value_size;
8906                         void *dest;
8907                         int tok;
8908                         comma = 0;
8909                         tok = peek(state);
8910                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8911                                 info = designator(state, type);
8912                         }
8913                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8914                                 (info.offset >= max_offset)) {
8915                                 error(state, 0, "element beyond bounds");
8916                         }
8917                         value_type = info.type;
8918                         value = eval_const_expr(state, initializer(state, value_type));
8919                         value_size = size_of(state, value_type);
8920                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8921                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8922                                 (max_offset <= info.offset)) {
8923                                 void *old_buf;
8924                                 size_t old_size;
8925                                 old_buf = buf;
8926                                 old_size = max_offset;
8927                                 max_offset = info.offset + value_size;
8928                                 buf = xmalloc(max_offset, "initializer");
8929                                 memcpy(buf, old_buf, old_size);
8930                                 xfree(old_buf);
8931                         }
8932                         dest = ((char *)buf) + info.offset;
8933                         if (value->op == OP_BLOBCONST) {
8934                                 memcpy(dest, value->u.blob, value_size);
8935                         }
8936                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8937                                 *((uint8_t *)dest) = value->u.cval & 0xff;
8938                         }
8939                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8940                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
8941                         }
8942                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8943                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8944                         }
8945                         else {
8946                                 internal_error(state, 0, "unhandled constant initializer");
8947                         }
8948                         free_triple(state, value);
8949                         if (peek(state) == TOK_COMMA) {
8950                                 eat(state, TOK_COMMA);
8951                                 comma = 1;
8952                         }
8953                         info.offset += value_size;
8954                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8955                                 info.type = next_field(state, type, info.type);
8956                                 info.offset = field_offset(state, type, 
8957                                         info.type->field_ident);
8958                         }
8959                 } while(comma && (peek(state) != TOK_RBRACE));
8960                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8961                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8962                         type->elements = max_offset / size_of(state, type->left);
8963                 }
8964                 eat(state, TOK_RBRACE);
8965                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8966                 result->u.blob = buf;
8967         }
8968         return result;
8969 }
8970
8971 static void resolve_branches(struct compile_state *state)
8972 {
8973         /* Make a second pass and finish anything outstanding
8974          * with respect to branches.  The only outstanding item
8975          * is to see if there are goto to labels that have not
8976          * been defined and to error about them.
8977          */
8978         int i;
8979         for(i = 0; i < HASH_TABLE_SIZE; i++) {
8980                 struct hash_entry *entry;
8981                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8982                         struct triple *ins;
8983                         if (!entry->sym_label) {
8984                                 continue;
8985                         }
8986                         ins = entry->sym_label->def;
8987                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8988                                 error(state, ins, "label `%s' used but not defined",
8989                                         entry->name);
8990                         }
8991                 }
8992         }
8993 }
8994
8995 static struct triple *function_definition(
8996         struct compile_state *state, struct type *type)
8997 {
8998         struct triple *def, *tmp, *first, *end;
8999         struct hash_entry *ident;
9000         struct type *param;
9001         int i;
9002         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9003                 error(state, 0, "Invalid function header");
9004         }
9005
9006         /* Verify the function type */
9007         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
9008                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9009                 (type->right->field_ident == 0)) {
9010                 error(state, 0, "Invalid function parameters");
9011         }
9012         param = type->right;
9013         i = 0;
9014         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9015                 i++;
9016                 if (!param->left->field_ident) {
9017                         error(state, 0, "No identifier for parameter %d\n", i);
9018                 }
9019                 param = param->right;
9020         }
9021         i++;
9022         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9023                 error(state, 0, "No identifier for paramter %d\n", i);
9024         }
9025         
9026         /* Get a list of statements for this function. */
9027         def = triple(state, OP_LIST, type, 0, 0);
9028
9029         /* Start a new scope for the passed parameters */
9030         start_scope(state);
9031
9032         /* Put a label at the very start of a function */
9033         first = label(state);
9034         RHS(def, 0) = first;
9035
9036         /* Put a label at the very end of a function */
9037         end = label(state);
9038         flatten(state, first, end);
9039
9040         /* Walk through the parameters and create symbol table entries
9041          * for them.
9042          */
9043         param = type->right;
9044         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9045                 ident = param->left->field_ident;
9046                 tmp = variable(state, param->left);
9047                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9048                 flatten(state, end, tmp);
9049                 param = param->right;
9050         }
9051         if ((param->type & TYPE_MASK) != TYPE_VOID) {
9052                 /* And don't forget the last parameter */
9053                 ident = param->field_ident;
9054                 tmp = variable(state, param);
9055                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9056                 flatten(state, end, tmp);
9057         }
9058         /* Add a variable for the return value */
9059         MISC(def, 0) = 0;
9060         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9061                 /* Remove all type qualifiers from the return type */
9062                 tmp = variable(state, clone_type(0, type->left));
9063                 flatten(state, end, tmp);
9064                 /* Remember where the return value is */
9065                 MISC(def, 0) = tmp;
9066         }
9067
9068         /* Remember which function I am compiling.
9069          * Also assume the last defined function is the main function.
9070          */
9071         state->main_function = def;
9072
9073         /* Now get the actual function definition */
9074         compound_statement(state, end);
9075
9076         /* Finish anything unfinished with branches */
9077         resolve_branches(state);
9078
9079         /* Remove the parameter scope */
9080         end_scope(state);
9081
9082 #if 0
9083         fprintf(stdout, "\n");
9084         loc(stdout, state, 0);
9085         fprintf(stdout, "\n__________ function_definition _________\n");
9086         print_triple(state, def);
9087         fprintf(stdout, "__________ function_definition _________ done\n\n");
9088 #endif
9089
9090         return def;
9091 }
9092
9093 static struct triple *do_decl(struct compile_state *state, 
9094         struct type *type, struct hash_entry *ident)
9095 {
9096         struct triple *def;
9097         def = 0;
9098         /* Clean up the storage types used */
9099         switch (type->type & STOR_MASK) {
9100         case STOR_AUTO:
9101         case STOR_STATIC:
9102                 /* These are the good types I am aiming for */
9103                 break;
9104         case STOR_REGISTER:
9105                 type->type &= ~STOR_MASK;
9106                 type->type |= STOR_AUTO;
9107                 break;
9108         case STOR_EXTERN:
9109                 type->type &= ~STOR_MASK;
9110                 type->type |= STOR_STATIC;
9111                 break;
9112         case STOR_TYPEDEF:
9113                 if (!ident) {
9114                         error(state, 0, "typedef without name");
9115                 }
9116                 symbol(state, ident, &ident->sym_ident, 0, type);
9117                 ident->tok = TOK_TYPE_NAME;
9118                 return 0;
9119                 break;
9120         default:
9121                 internal_error(state, 0, "Undefined storage class");
9122         }
9123         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9124                 error(state, 0, "Function prototypes not supported");
9125         }
9126         if (ident && 
9127                 ((type->type & STOR_MASK) == STOR_STATIC) &&
9128                 ((type->type & QUAL_CONST) == 0)) {
9129                 error(state, 0, "non const static variables not supported");
9130         }
9131         if (ident) {
9132                 def = variable(state, type);
9133                 symbol(state, ident, &ident->sym_ident, def, type);
9134         }
9135         return def;
9136 }
9137
9138 static void decl(struct compile_state *state, struct triple *first)
9139 {
9140         struct type *base_type, *type;
9141         struct hash_entry *ident;
9142         struct triple *def;
9143         int global;
9144         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9145         base_type = decl_specifiers(state);
9146         ident = 0;
9147         type = declarator(state, base_type, &ident, 0);
9148         if (global && ident && (peek(state) == TOK_LBRACE)) {
9149                 /* function */
9150                 state->function = ident->name;
9151                 def = function_definition(state, type);
9152                 symbol(state, ident, &ident->sym_ident, def, type);
9153                 state->function = 0;
9154         }
9155         else {
9156                 int done;
9157                 flatten(state, first, do_decl(state, type, ident));
9158                 /* type or variable definition */
9159                 do {
9160                         done = 1;
9161                         if (peek(state) == TOK_EQ) {
9162                                 if (!ident) {
9163                                         error(state, 0, "cannot assign to a type");
9164                                 }
9165                                 eat(state, TOK_EQ);
9166                                 flatten(state, first,
9167                                         init_expr(state, 
9168                                                 ident->sym_ident->def, 
9169                                                 initializer(state, type)));
9170                         }
9171                         arrays_complete(state, type);
9172                         if (peek(state) == TOK_COMMA) {
9173                                 eat(state, TOK_COMMA);
9174                                 ident = 0;
9175                                 type = declarator(state, base_type, &ident, 0);
9176                                 flatten(state, first, do_decl(state, type, ident));
9177                                 done = 0;
9178                         }
9179                 } while(!done);
9180                 eat(state, TOK_SEMI);
9181         }
9182 }
9183
9184 static void decls(struct compile_state *state)
9185 {
9186         struct triple *list;
9187         int tok;
9188         list = label(state);
9189         while(1) {
9190                 tok = peek(state);
9191                 if (tok == TOK_EOF) {
9192                         return;
9193                 }
9194                 if (tok == TOK_SPACE) {
9195                         eat(state, TOK_SPACE);
9196                 }
9197                 decl(state, list);
9198                 if (list->next != list) {
9199                         error(state, 0, "global variables not supported");
9200                 }
9201         }
9202 }
9203
9204 /*
9205  * Data structurs for optimation.
9206  */
9207
9208 static void do_use_block(
9209         struct block *used, struct block_set **head, struct block *user, 
9210         int front)
9211 {
9212         struct block_set **ptr, *new;
9213         if (!used)
9214                 return;
9215         if (!user)
9216                 return;
9217         ptr = head;
9218         while(*ptr) {
9219                 if ((*ptr)->member == user) {
9220                         return;
9221                 }
9222                 ptr = &(*ptr)->next;
9223         }
9224         new = xcmalloc(sizeof(*new), "block_set");
9225         new->member = user;
9226         if (front) {
9227                 new->next = *head;
9228                 *head = new;
9229         }
9230         else {
9231                 new->next = 0;
9232                 *ptr = new;
9233         }
9234 }
9235 static void do_unuse_block(
9236         struct block *used, struct block_set **head, struct block *unuser)
9237 {
9238         struct block_set *use, **ptr;
9239         ptr = head;
9240         while(*ptr) {
9241                 use = *ptr;
9242                 if (use->member == unuser) {
9243                         *ptr = use->next;
9244                         memset(use, -1, sizeof(*use));
9245                         xfree(use);
9246                 }
9247                 else {
9248                         ptr = &use->next;
9249                 }
9250         }
9251 }
9252
9253 static void use_block(struct block *used, struct block *user)
9254 {
9255         /* Append new to the head of the list, print_block
9256          * depends on this.
9257          */
9258         do_use_block(used, &used->use, user, 1); 
9259         used->users++;
9260 }
9261 static void unuse_block(struct block *used, struct block *unuser)
9262 {
9263         do_unuse_block(used, &used->use, unuser); 
9264         used->users--;
9265 }
9266
9267 static void idom_block(struct block *idom, struct block *user)
9268 {
9269         do_use_block(idom, &idom->idominates, user, 0);
9270 }
9271
9272 static void unidom_block(struct block *idom, struct block *unuser)
9273 {
9274         do_unuse_block(idom, &idom->idominates, unuser);
9275 }
9276
9277 static void domf_block(struct block *block, struct block *domf)
9278 {
9279         do_use_block(block, &block->domfrontier, domf, 0);
9280 }
9281
9282 static void undomf_block(struct block *block, struct block *undomf)
9283 {
9284         do_unuse_block(block, &block->domfrontier, undomf);
9285 }
9286
9287 static void ipdom_block(struct block *ipdom, struct block *user)
9288 {
9289         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9290 }
9291
9292 static void unipdom_block(struct block *ipdom, struct block *unuser)
9293 {
9294         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9295 }
9296
9297 static void ipdomf_block(struct block *block, struct block *ipdomf)
9298 {
9299         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9300 }
9301
9302 static void unipdomf_block(struct block *block, struct block *unipdomf)
9303 {
9304         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9305 }
9306
9307
9308
9309 static int do_walk_triple(struct compile_state *state,
9310         struct triple *ptr, int depth,
9311         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
9312 {
9313         int result;
9314         result = cb(state, ptr, depth);
9315         if ((result == 0) && (ptr->op == OP_LIST)) {
9316                 struct triple *list;
9317                 list = ptr;
9318                 ptr = RHS(list, 0);
9319                 do {
9320                         result = do_walk_triple(state, ptr, depth + 1, cb);
9321                         if (ptr->next->prev != ptr) {
9322                                 internal_error(state, ptr->next, "bad prev");
9323                         }
9324                         ptr = ptr->next;
9325                         
9326                 } while((result == 0) && (ptr != RHS(list, 0)));
9327         }
9328         return result;
9329 }
9330
9331 static int walk_triple(
9332         struct compile_state *state, 
9333         struct triple *ptr, 
9334         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9335 {
9336         return do_walk_triple(state, ptr, 0, cb);
9337 }
9338
9339 static void do_print_prefix(int depth)
9340 {
9341         int i;
9342         for(i = 0; i < depth; i++) {
9343                 printf("  ");
9344         }
9345 }
9346
9347 #define PRINT_LIST 1
9348 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9349 {
9350         int op;
9351         op = ins->op;
9352         if (op == OP_LIST) {
9353 #if !PRINT_LIST
9354                 return 0;
9355 #endif
9356         }
9357         if ((op == OP_LABEL) && (ins->use)) {
9358                 printf("\n%p:\n", ins);
9359         }
9360         do_print_prefix(depth);
9361         display_triple(stdout, ins);
9362
9363         if ((ins->op == OP_BRANCH) && ins->use) {
9364                 internal_error(state, ins, "branch used?");
9365         }
9366 #if 0
9367         {
9368                 struct triple_set *user;
9369                 for(user = ins->use; user; user = user->next) {
9370                         printf("use: %p\n", user->member);
9371                 }
9372         }
9373 #endif
9374         if (triple_is_branch(state, ins)) {
9375                 printf("\n");
9376         }
9377         return 0;
9378 }
9379
9380 static void print_triple(struct compile_state *state, struct triple *ins)
9381 {
9382         walk_triple(state, ins, do_print_triple);
9383 }
9384
9385 static void print_triples(struct compile_state *state)
9386 {
9387         print_triple(state, state->main_function);
9388 }
9389
9390 struct cf_block {
9391         struct block *block;
9392 };
9393 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9394 {
9395         if (!block || (cf[block->vertex].block == block)) {
9396                 return;
9397         }
9398         cf[block->vertex].block = block;
9399         find_cf_blocks(cf, block->left);
9400         find_cf_blocks(cf, block->right);
9401 }
9402
9403 static void print_control_flow(struct compile_state *state)
9404 {
9405         struct cf_block *cf;
9406         int i;
9407         printf("\ncontrol flow\n");
9408         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9409         find_cf_blocks(cf, state->first_block);
9410
9411         for(i = 1; i <= state->last_vertex; i++) {
9412                 struct block *block;
9413                 block = cf[i].block;
9414                 if (!block)
9415                         continue;
9416                 printf("(%p) %d:", block, block->vertex);
9417                 if (block->left) {
9418                         printf(" %d", block->left->vertex);
9419                 }
9420                 if (block->right && (block->right != block->left)) {
9421                         printf(" %d", block->right->vertex);
9422                 }
9423                 printf("\n");
9424         }
9425
9426         xfree(cf);
9427 }
9428
9429
9430 static struct block *basic_block(struct compile_state *state,
9431         struct triple *first)
9432 {
9433         struct block *block;
9434         struct triple *ptr;
9435         int op;
9436         if (first->op != OP_LABEL) {
9437                 internal_error(state, 0, "block does not start with a label");
9438         }
9439         /* See if this basic block has already been setup */
9440         if (first->u.block != 0) {
9441                 return first->u.block;
9442         }
9443         /* Allocate another basic block structure */
9444         state->last_vertex += 1;
9445         block = xcmalloc(sizeof(*block), "block");
9446         block->first = block->last = first;
9447         block->vertex = state->last_vertex;
9448         ptr = first;
9449         do {
9450                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9451                         break;
9452                 }
9453                 block->last = ptr;
9454                 /* If ptr->u is not used remember where the baic block is */
9455                 if (triple_stores_block(state, ptr)) {
9456                         ptr->u.block = block;
9457                 }
9458                 if (ptr->op == OP_BRANCH) {
9459                         break;
9460                 }
9461                 ptr = ptr->next;
9462         } while (ptr != RHS(state->main_function, 0));
9463         if (ptr == RHS(state->main_function, 0))
9464                 return block;
9465         op = ptr->op;
9466         if (op == OP_LABEL) {
9467                 block->left = basic_block(state, ptr);
9468                 block->right = 0;
9469                 use_block(block->left, block);
9470         }
9471         else if (op == OP_BRANCH) {
9472                 block->left = 0;
9473                 /* Trace the branch target */
9474                 block->right = basic_block(state, TARG(ptr, 0));
9475                 use_block(block->right, block);
9476                 /* If there is a test trace the branch as well */
9477                 if (TRIPLE_RHS(ptr->sizes)) {
9478                         block->left = basic_block(state, ptr->next);
9479                         use_block(block->left, block);
9480                 }
9481         }
9482         else {
9483                 internal_error(state, 0, "Bad basic block split");
9484         }
9485         return block;
9486 }
9487
9488
9489 static void walk_blocks(struct compile_state *state,
9490         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9491         void *arg)
9492 {
9493         struct triple *ptr, *first;
9494         struct block *last_block;
9495         last_block = 0;
9496         first = RHS(state->main_function, 0);
9497         ptr = first;
9498         do {
9499                 struct block *block;
9500                 if (ptr->op == OP_LABEL) {
9501                         block = ptr->u.block;
9502                         if (block && (block != last_block)) {
9503                                 cb(state, block, arg);
9504                         }
9505                         last_block = block;
9506                 }
9507                 ptr = ptr->next;
9508         } while(ptr != first);
9509 }
9510
9511 static void print_block(
9512         struct compile_state *state, struct block *block, void *arg)
9513 {
9514         struct triple *ptr;
9515         FILE *fp = arg;
9516
9517         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9518                 block, 
9519                 block->vertex,
9520                 block->left, 
9521                 block->left && block->left->use?block->left->use->member : 0,
9522                 block->right, 
9523                 block->right && block->right->use?block->right->use->member : 0);
9524         if (block->first->op == OP_LABEL) {
9525                 fprintf(fp, "%p:\n", block->first);
9526         }
9527         for(ptr = block->first; ; ptr = ptr->next) {
9528                 struct triple_set *user;
9529                 int op = ptr->op;
9530                 
9531                 if (triple_stores_block(state, ptr)) {
9532                         if (ptr->u.block != block) {
9533                                 internal_error(state, ptr, 
9534                                         "Wrong block pointer: %p\n",
9535                                         ptr->u.block);
9536                         }
9537                 }
9538                 if (op == OP_ADECL) {
9539                         for(user = ptr->use; user; user = user->next) {
9540                                 if (!user->member->u.block) {
9541                                         internal_error(state, user->member, 
9542                                                 "Use %p not in a block?\n",
9543                                                 user->member);
9544                                 }
9545                         }
9546                 }
9547                 display_triple(fp, ptr);
9548
9549 #if 0
9550                 for(user = ptr->use; user; user = user->next) {
9551                         fprintf(fp, "use: %p\n", user->member);
9552                 }
9553 #endif
9554
9555                 /* Sanity checks... */
9556                 valid_ins(state, ptr);
9557                 for(user = ptr->use; user; user = user->next) {
9558                         struct triple *use;
9559                         use = user->member;
9560                         valid_ins(state, use);
9561                         if (triple_stores_block(state, user->member) &&
9562                                 !user->member->u.block) {
9563                                 internal_error(state, user->member,
9564                                         "Use %p not in a block?",
9565                                         user->member);
9566                         }
9567                 }
9568
9569                 if (ptr == block->last)
9570                         break;
9571         }
9572         fprintf(fp,"\n");
9573 }
9574
9575
9576 static void print_blocks(struct compile_state *state, FILE *fp)
9577 {
9578         fprintf(fp, "--------------- blocks ---------------\n");
9579         walk_blocks(state, print_block, fp);
9580 }
9581
9582 static void prune_nonblock_triples(struct compile_state *state)
9583 {
9584         struct block *block;
9585         struct triple *first, *ins, *next;
9586         /* Delete the triples not in a basic block */
9587         first = RHS(state->main_function, 0);
9588         block = 0;
9589         ins = first;
9590         do {
9591                 next = ins->next;
9592                 if (ins->op == OP_LABEL) {
9593                         block = ins->u.block;
9594                 }
9595                 if (!block) {
9596                         release_triple(state, ins);
9597                 }
9598                 ins = next;
9599         } while(ins != first);
9600 }
9601
9602 static void setup_basic_blocks(struct compile_state *state)
9603 {
9604         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9605                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9606                 internal_error(state, 0, "ins will not store block?");
9607         }
9608         /* Find the basic blocks */
9609         state->last_vertex = 0;
9610         state->first_block = basic_block(state, RHS(state->main_function,0));
9611         /* Delete the triples not in a basic block */
9612         prune_nonblock_triples(state);
9613         /* Find the last basic block */
9614         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9615         if (!state->last_block) {
9616                 internal_error(state, 0, "end not used?");
9617         }
9618         /* Insert an extra unused edge from start to the end 
9619          * This helps with reverse control flow calculations.
9620          */
9621         use_block(state->first_block, state->last_block);
9622         /* If we are debugging print what I have just done */
9623         if (state->debug & DEBUG_BASIC_BLOCKS) {
9624                 print_blocks(state, stdout);
9625                 print_control_flow(state);
9626         }
9627 }
9628
9629 static void free_basic_block(struct compile_state *state, struct block *block)
9630 {
9631         struct block_set *entry, *next;
9632         struct block *child;
9633         if (!block) {
9634                 return;
9635         }
9636         if (block->vertex == -1) {
9637                 return;
9638         }
9639         block->vertex = -1;
9640         if (block->left) {
9641                 unuse_block(block->left, block);
9642         }
9643         if (block->right) {
9644                 unuse_block(block->right, block);
9645         }
9646         if (block->idom) {
9647                 unidom_block(block->idom, block);
9648         }
9649         block->idom = 0;
9650         if (block->ipdom) {
9651                 unipdom_block(block->ipdom, block);
9652         }
9653         block->ipdom = 0;
9654         for(entry = block->use; entry; entry = next) {
9655                 next = entry->next;
9656                 child = entry->member;
9657                 unuse_block(block, child);
9658                 if (child->left == block) {
9659                         child->left = 0;
9660                 }
9661                 if (child->right == block) {
9662                         child->right = 0;
9663                 }
9664         }
9665         for(entry = block->idominates; entry; entry = next) {
9666                 next = entry->next;
9667                 child = entry->member;
9668                 unidom_block(block, child);
9669                 child->idom = 0;
9670         }
9671         for(entry = block->domfrontier; entry; entry = next) {
9672                 next = entry->next;
9673                 child = entry->member;
9674                 undomf_block(block, child);
9675         }
9676         for(entry = block->ipdominates; entry; entry = next) {
9677                 next = entry->next;
9678                 child = entry->member;
9679                 unipdom_block(block, child);
9680                 child->ipdom = 0;
9681         }
9682         for(entry = block->ipdomfrontier; entry; entry = next) {
9683                 next = entry->next;
9684                 child = entry->member;
9685                 unipdomf_block(block, child);
9686         }
9687         if (block->users != 0) {
9688                 internal_error(state, 0, "block still has users");
9689         }
9690         free_basic_block(state, block->left);
9691         block->left = 0;
9692         free_basic_block(state, block->right);
9693         block->right = 0;
9694         memset(block, -1, sizeof(*block));
9695         xfree(block);
9696 }
9697
9698 static void free_basic_blocks(struct compile_state *state)
9699 {
9700         struct triple *first, *ins;
9701         free_basic_block(state, state->first_block);
9702         state->last_vertex = 0;
9703         state->first_block = state->last_block = 0;
9704         first = RHS(state->main_function, 0);
9705         ins = first;
9706         do {
9707                 if (triple_stores_block(state, ins)) {
9708                         ins->u.block = 0;
9709                 }
9710                 ins = ins->next;
9711         } while(ins != first);
9712         
9713 }
9714
9715 struct sdom_block {
9716         struct block *block;
9717         struct sdom_block *sdominates;
9718         struct sdom_block *sdom_next;
9719         struct sdom_block *sdom;
9720         struct sdom_block *label;
9721         struct sdom_block *parent;
9722         struct sdom_block *ancestor;
9723         int vertex;
9724 };
9725
9726
9727 static void unsdom_block(struct sdom_block *block)
9728 {
9729         struct sdom_block **ptr;
9730         if (!block->sdom_next) {
9731                 return;
9732         }
9733         ptr = &block->sdom->sdominates;
9734         while(*ptr) {
9735                 if ((*ptr) == block) {
9736                         *ptr = block->sdom_next;
9737                         return;
9738                 }
9739                 ptr = &(*ptr)->sdom_next;
9740         }
9741 }
9742
9743 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9744 {
9745         unsdom_block(block);
9746         block->sdom = sdom;
9747         block->sdom_next = sdom->sdominates;
9748         sdom->sdominates = block;
9749 }
9750
9751
9752
9753 static int initialize_sdblock(struct sdom_block *sd,
9754         struct block *parent, struct block *block, int vertex)
9755 {
9756         if (!block || (sd[block->vertex].block == block)) {
9757                 return vertex;
9758         }
9759         vertex += 1;
9760         /* Renumber the blocks in a convinient fashion */
9761         block->vertex = vertex;
9762         sd[vertex].block    = block;
9763         sd[vertex].sdom     = &sd[vertex];
9764         sd[vertex].label    = &sd[vertex];
9765         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9766         sd[vertex].ancestor = 0;
9767         sd[vertex].vertex   = vertex;
9768         vertex = initialize_sdblock(sd, block, block->left, vertex);
9769         vertex = initialize_sdblock(sd, block, block->right, vertex);
9770         return vertex;
9771 }
9772
9773 static int initialize_sdpblock(struct sdom_block *sd,
9774         struct block *parent, struct block *block, int vertex)
9775 {
9776         struct block_set *user;
9777         if (!block || (sd[block->vertex].block == block)) {
9778                 return vertex;
9779         }
9780         vertex += 1;
9781         /* Renumber the blocks in a convinient fashion */
9782         block->vertex = vertex;
9783         sd[vertex].block    = block;
9784         sd[vertex].sdom     = &sd[vertex];
9785         sd[vertex].label    = &sd[vertex];
9786         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9787         sd[vertex].ancestor = 0;
9788         sd[vertex].vertex   = vertex;
9789         for(user = block->use; user; user = user->next) {
9790                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9791         }
9792         return vertex;
9793 }
9794
9795 static void compress_ancestors(struct sdom_block *v)
9796 {
9797         /* This procedure assumes ancestor(v) != 0 */
9798         /* if (ancestor(ancestor(v)) != 0) {
9799          *      compress(ancestor(ancestor(v)));
9800          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9801          *              label(v) = label(ancestor(v));
9802          *      }
9803          *      ancestor(v) = ancestor(ancestor(v));
9804          * }
9805          */
9806         if (!v->ancestor) {
9807                 return;
9808         }
9809         if (v->ancestor->ancestor) {
9810                 compress_ancestors(v->ancestor->ancestor);
9811                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9812                         v->label = v->ancestor->label;
9813                 }
9814                 v->ancestor = v->ancestor->ancestor;
9815         }
9816 }
9817
9818 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9819 {
9820         int i;
9821         /* // step 2 
9822          *  for each v <= pred(w) {
9823          *      u = EVAL(v);
9824          *      if (semi[u] < semi[w] { 
9825          *              semi[w] = semi[u]; 
9826          *      } 
9827          * }
9828          * add w to bucket(vertex(semi[w]));
9829          * LINK(parent(w), w);
9830          *
9831          * // step 3
9832          * for each v <= bucket(parent(w)) {
9833          *      delete v from bucket(parent(w));
9834          *      u = EVAL(v);
9835          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9836          * }
9837          */
9838         for(i = state->last_vertex; i >= 2; i--) {
9839                 struct sdom_block *v, *parent, *next;
9840                 struct block_set *user;
9841                 struct block *block;
9842                 block = sd[i].block;
9843                 parent = sd[i].parent;
9844                 /* Step 2 */
9845                 for(user = block->use; user; user = user->next) {
9846                         struct sdom_block *v, *u;
9847                         v = &sd[user->member->vertex];
9848                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9849                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9850                                 sd[i].sdom = u->sdom;
9851                         }
9852                 }
9853                 sdom_block(sd[i].sdom, &sd[i]);
9854                 sd[i].ancestor = parent;
9855                 /* Step 3 */
9856                 for(v = parent->sdominates; v; v = next) {
9857                         struct sdom_block *u;
9858                         next = v->sdom_next;
9859                         unsdom_block(v);
9860                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9861                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9862                                 u->block : parent->block;
9863                 }
9864         }
9865 }
9866
9867 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9868 {
9869         int i;
9870         /* // step 2 
9871          *  for each v <= pred(w) {
9872          *      u = EVAL(v);
9873          *      if (semi[u] < semi[w] { 
9874          *              semi[w] = semi[u]; 
9875          *      } 
9876          * }
9877          * add w to bucket(vertex(semi[w]));
9878          * LINK(parent(w), w);
9879          *
9880          * // step 3
9881          * for each v <= bucket(parent(w)) {
9882          *      delete v from bucket(parent(w));
9883          *      u = EVAL(v);
9884          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9885          * }
9886          */
9887         for(i = state->last_vertex; i >= 2; i--) {
9888                 struct sdom_block *u, *v, *parent, *next;
9889                 struct block *block;
9890                 block = sd[i].block;
9891                 parent = sd[i].parent;
9892                 /* Step 2 */
9893                 if (block->left) {
9894                         v = &sd[block->left->vertex];
9895                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9896                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9897                                 sd[i].sdom = u->sdom;
9898                         }
9899                 }
9900                 if (block->right && (block->right != block->left)) {
9901                         v = &sd[block->right->vertex];
9902                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9903                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9904                                 sd[i].sdom = u->sdom;
9905                         }
9906                 }
9907                 sdom_block(sd[i].sdom, &sd[i]);
9908                 sd[i].ancestor = parent;
9909                 /* Step 3 */
9910                 for(v = parent->sdominates; v; v = next) {
9911                         struct sdom_block *u;
9912                         next = v->sdom_next;
9913                         unsdom_block(v);
9914                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9915                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9916                                 u->block : parent->block;
9917                 }
9918         }
9919 }
9920
9921 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9922 {
9923         int i;
9924         for(i = 2; i <= state->last_vertex; i++) {
9925                 struct block *block;
9926                 block = sd[i].block;
9927                 if (block->idom->vertex != sd[i].sdom->vertex) {
9928                         block->idom = block->idom->idom;
9929                 }
9930                 idom_block(block->idom, block);
9931         }
9932         sd[1].block->idom = 0;
9933 }
9934
9935 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9936 {
9937         int i;
9938         for(i = 2; i <= state->last_vertex; i++) {
9939                 struct block *block;
9940                 block = sd[i].block;
9941                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9942                         block->ipdom = block->ipdom->ipdom;
9943                 }
9944                 ipdom_block(block->ipdom, block);
9945         }
9946         sd[1].block->ipdom = 0;
9947 }
9948
9949         /* Theorem 1:
9950          *   Every vertex of a flowgraph G = (V, E, r) except r has
9951          *   a unique immediate dominator.  
9952          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9953          *   rooted at r, called the dominator tree of G, such that 
9954          *   v dominates w if and only if v is a proper ancestor of w in
9955          *   the dominator tree.
9956          */
9957         /* Lemma 1:  
9958          *   If v and w are vertices of G such that v <= w,
9959          *   than any path from v to w must contain a common ancestor
9960          *   of v and w in T.
9961          */
9962         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9963         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9964         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9965         /* Theorem 2:
9966          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9967          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9968          */
9969         /* Theorem 3:
9970          *   Let w != r and let u be a vertex for which sdom(u) is 
9971          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9972          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9973          */
9974         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9975          *           Then v -> idom(w) or idom(w) -> idom(v)
9976          */
9977
9978 static void find_immediate_dominators(struct compile_state *state)
9979 {
9980         struct sdom_block *sd;
9981         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9982          *           vi > w for (1 <= i <= k - 1}
9983          */
9984         /* Theorem 4:
9985          *   For any vertex w != r.
9986          *   sdom(w) = min(
9987          *                 {v|(v,w) <= E  and v < w } U 
9988          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9989          */
9990         /* Corollary 1:
9991          *   Let w != r and let u be a vertex for which sdom(u) is 
9992          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9993          *   Then:
9994          *                   { sdom(w) if sdom(w) = sdom(u),
9995          *        idom(w) = {
9996          *                   { idom(u) otherwise
9997          */
9998         /* The algorithm consists of the following 4 steps.
9999          * Step 1.  Carry out a depth-first search of the problem graph.  
10000          *    Number the vertices from 1 to N as they are reached during
10001          *    the search.  Initialize the variables used in succeeding steps.
10002          * Step 2.  Compute the semidominators of all vertices by applying
10003          *    theorem 4.   Carry out the computation vertex by vertex in
10004          *    decreasing order by number.
10005          * Step 3.  Implicitly define the immediate dominator of each vertex
10006          *    by applying Corollary 1.
10007          * Step 4.  Explicitly define the immediate dominator of each vertex,
10008          *    carrying out the computation vertex by vertex in increasing order
10009          *    by number.
10010          */
10011         /* Step 1 initialize the basic block information */
10012         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10013         initialize_sdblock(sd, 0, state->first_block, 0);
10014 #if 0
10015         sd[1].size  = 0;
10016         sd[1].label = 0;
10017         sd[1].sdom  = 0;
10018 #endif
10019         /* Step 2 compute the semidominators */
10020         /* Step 3 implicitly define the immediate dominator of each vertex */
10021         compute_sdom(state, sd);
10022         /* Step 4 explicitly define the immediate dominator of each vertex */
10023         compute_idom(state, sd);
10024         xfree(sd);
10025 }
10026
10027 static void find_post_dominators(struct compile_state *state)
10028 {
10029         struct sdom_block *sd;
10030         /* Step 1 initialize the basic block information */
10031         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10032
10033         initialize_sdpblock(sd, 0, state->last_block, 0);
10034
10035         /* Step 2 compute the semidominators */
10036         /* Step 3 implicitly define the immediate dominator of each vertex */
10037         compute_spdom(state, sd);
10038         /* Step 4 explicitly define the immediate dominator of each vertex */
10039         compute_ipdom(state, sd);
10040         xfree(sd);
10041 }
10042
10043
10044
10045 static void find_block_domf(struct compile_state *state, struct block *block)
10046 {
10047         struct block *child;
10048         struct block_set *user;
10049         if (block->domfrontier != 0) {
10050                 internal_error(state, block->first, "domfrontier present?");
10051         }
10052         for(user = block->idominates; user; user = user->next) {
10053                 child = user->member;
10054                 if (child->idom != block) {
10055                         internal_error(state, block->first, "bad idom");
10056                 }
10057                 find_block_domf(state, child);
10058         }
10059         if (block->left && block->left->idom != block) {
10060                 domf_block(block, block->left);
10061         }
10062         if (block->right && block->right->idom != block) {
10063                 domf_block(block, block->right);
10064         }
10065         for(user = block->idominates; user; user = user->next) {
10066                 struct block_set *frontier;
10067                 child = user->member;
10068                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10069                         if (frontier->member->idom != block) {
10070                                 domf_block(block, frontier->member);
10071                         }
10072                 }
10073         }
10074 }
10075
10076 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10077 {
10078         struct block *child;
10079         struct block_set *user;
10080         if (block->ipdomfrontier != 0) {
10081                 internal_error(state, block->first, "ipdomfrontier present?");
10082         }
10083         for(user = block->ipdominates; user; user = user->next) {
10084                 child = user->member;
10085                 if (child->ipdom != block) {
10086                         internal_error(state, block->first, "bad ipdom");
10087                 }
10088                 find_block_ipdomf(state, child);
10089         }
10090         if (block->left && block->left->ipdom != block) {
10091                 ipdomf_block(block, block->left);
10092         }
10093         if (block->right && block->right->ipdom != block) {
10094                 ipdomf_block(block, block->right);
10095         }
10096         for(user = block->idominates; user; user = user->next) {
10097                 struct block_set *frontier;
10098                 child = user->member;
10099                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10100                         if (frontier->member->ipdom != block) {
10101                                 ipdomf_block(block, frontier->member);
10102                         }
10103                 }
10104         }
10105 }
10106
10107 static void print_dominated(
10108         struct compile_state *state, struct block *block, void *arg)
10109 {
10110         struct block_set *user;
10111         FILE *fp = arg;
10112
10113         fprintf(fp, "%d:", block->vertex);
10114         for(user = block->idominates; user; user = user->next) {
10115                 fprintf(fp, " %d", user->member->vertex);
10116                 if (user->member->idom != block) {
10117                         internal_error(state, user->member->first, "bad idom");
10118                 }
10119         }
10120         fprintf(fp,"\n");
10121 }
10122
10123 static void print_dominators(struct compile_state *state, FILE *fp)
10124 {
10125         fprintf(fp, "\ndominates\n");
10126         walk_blocks(state, print_dominated, fp);
10127 }
10128
10129
10130 static int print_frontiers(
10131         struct compile_state *state, struct block *block, int vertex)
10132 {
10133         struct block_set *user;
10134
10135         if (!block || (block->vertex != vertex + 1)) {
10136                 return vertex;
10137         }
10138         vertex += 1;
10139
10140         printf("%d:", block->vertex);
10141         for(user = block->domfrontier; user; user = user->next) {
10142                 printf(" %d", user->member->vertex);
10143         }
10144         printf("\n");
10145
10146         vertex = print_frontiers(state, block->left, vertex);
10147         vertex = print_frontiers(state, block->right, vertex);
10148         return vertex;
10149 }
10150 static void print_dominance_frontiers(struct compile_state *state)
10151 {
10152         printf("\ndominance frontiers\n");
10153         print_frontiers(state, state->first_block, 0);
10154         
10155 }
10156
10157 static void analyze_idominators(struct compile_state *state)
10158 {
10159         /* Find the immediate dominators */
10160         find_immediate_dominators(state);
10161         /* Find the dominance frontiers */
10162         find_block_domf(state, state->first_block);
10163         /* If debuging print the print what I have just found */
10164         if (state->debug & DEBUG_FDOMINATORS) {
10165                 print_dominators(state, stdout);
10166                 print_dominance_frontiers(state);
10167                 print_control_flow(state);
10168         }
10169 }
10170
10171
10172
10173 static void print_ipdominated(
10174         struct compile_state *state, struct block *block, void *arg)
10175 {
10176         struct block_set *user;
10177         FILE *fp = arg;
10178
10179         fprintf(fp, "%d:", block->vertex);
10180         for(user = block->ipdominates; user; user = user->next) {
10181                 fprintf(fp, " %d", user->member->vertex);
10182                 if (user->member->ipdom != block) {
10183                         internal_error(state, user->member->first, "bad ipdom");
10184                 }
10185         }
10186         fprintf(fp, "\n");
10187 }
10188
10189 static void print_ipdominators(struct compile_state *state, FILE *fp)
10190 {
10191         fprintf(fp, "\nipdominates\n");
10192         walk_blocks(state, print_ipdominated, fp);
10193 }
10194
10195 static int print_pfrontiers(
10196         struct compile_state *state, struct block *block, int vertex)
10197 {
10198         struct block_set *user;
10199
10200         if (!block || (block->vertex != vertex + 1)) {
10201                 return vertex;
10202         }
10203         vertex += 1;
10204
10205         printf("%d:", block->vertex);
10206         for(user = block->ipdomfrontier; user; user = user->next) {
10207                 printf(" %d", user->member->vertex);
10208         }
10209         printf("\n");
10210         for(user = block->use; user; user = user->next) {
10211                 vertex = print_pfrontiers(state, user->member, vertex);
10212         }
10213         return vertex;
10214 }
10215 static void print_ipdominance_frontiers(struct compile_state *state)
10216 {
10217         printf("\nipdominance frontiers\n");
10218         print_pfrontiers(state, state->last_block, 0);
10219         
10220 }
10221
10222 static void analyze_ipdominators(struct compile_state *state)
10223 {
10224         /* Find the post dominators */
10225         find_post_dominators(state);
10226         /* Find the control dependencies (post dominance frontiers) */
10227         find_block_ipdomf(state, state->last_block);
10228         /* If debuging print the print what I have just found */
10229         if (state->debug & DEBUG_RDOMINATORS) {
10230                 print_ipdominators(state, stdout);
10231                 print_ipdominance_frontiers(state);
10232                 print_control_flow(state);
10233         }
10234 }
10235
10236 static int bdominates(struct compile_state *state,
10237         struct block *dom, struct block *sub)
10238 {
10239         while(sub && (sub != dom)) {
10240                 sub = sub->idom;
10241         }
10242         return sub == dom;
10243 }
10244
10245 static int tdominates(struct compile_state *state,
10246         struct triple *dom, struct triple *sub)
10247 {
10248         struct block *bdom, *bsub;
10249         int result;
10250         bdom = block_of_triple(state, dom);
10251         bsub = block_of_triple(state, sub);
10252         if (bdom != bsub) {
10253                 result = bdominates(state, bdom, bsub);
10254         } 
10255         else {
10256                 struct triple *ins;
10257                 ins = sub;
10258                 while((ins != bsub->first) && (ins != dom)) {
10259                         ins = ins->prev;
10260                 }
10261                 result = (ins == dom);
10262         }
10263         return result;
10264 }
10265
10266 static void insert_phi_operations(struct compile_state *state)
10267 {
10268         size_t size;
10269         struct triple *first;
10270         int *has_already, *work;
10271         struct block *work_list, **work_list_tail;
10272         int iter;
10273         struct triple *var, *vnext;
10274
10275         size = sizeof(int) * (state->last_vertex + 1);
10276         has_already = xcmalloc(size, "has_already");
10277         work =        xcmalloc(size, "work");
10278         iter = 0;
10279
10280         first = RHS(state->main_function, 0);
10281         for(var = first->next; var != first ; var = vnext) {
10282                 struct block *block;
10283                 struct triple_set *user, *unext;
10284                 vnext = var->next;
10285                 if ((var->op != OP_ADECL) || !var->use) {
10286                         continue;
10287                 }
10288                 iter += 1;
10289                 work_list = 0;
10290                 work_list_tail = &work_list;
10291                 for(user = var->use; user; user = unext) {
10292                         unext = user->next;
10293                         if (user->member->op == OP_READ) {
10294                                 continue;
10295                         }
10296                         if (user->member->op != OP_WRITE) {
10297                                 internal_error(state, user->member, 
10298                                         "bad variable access");
10299                         }
10300                         block = user->member->u.block;
10301                         if (!block) {
10302                                 warning(state, user->member, "dead code");
10303                                 release_triple(state, user->member);
10304                                 continue;
10305                         }
10306                         if (work[block->vertex] >= iter) {
10307                                 continue;
10308                         }
10309                         work[block->vertex] = iter;
10310                         *work_list_tail = block;
10311                         block->work_next = 0;
10312                         work_list_tail = &block->work_next;
10313                 }
10314                 for(block = work_list; block; block = block->work_next) {
10315                         struct block_set *df;
10316                         for(df = block->domfrontier; df; df = df->next) {
10317                                 struct triple *phi;
10318                                 struct block *front;
10319                                 int in_edges;
10320                                 front = df->member;
10321
10322                                 if (has_already[front->vertex] >= iter) {
10323                                         continue;
10324                                 }
10325                                 /* Count how many edges flow into this block */
10326                                 in_edges = front->users;
10327                                 /* Insert a phi function for this variable */
10328                                 get_occurance(front->first->occurance);
10329                                 phi = alloc_triple(
10330                                         state, OP_PHI, var->type, -1, in_edges, 
10331                                         front->first->occurance);
10332                                 phi->u.block = front;
10333                                 MISC(phi, 0) = var;
10334                                 use_triple(var, phi);
10335                                 /* Insert the phi functions immediately after the label */
10336                                 insert_triple(state, front->first->next, phi);
10337                                 if (front->first == front->last) {
10338                                         front->last = front->first->next;
10339                                 }
10340                                 has_already[front->vertex] = iter;
10341
10342                                 /* If necessary plan to visit the basic block */
10343                                 if (work[front->vertex] >= iter) {
10344                                         continue;
10345                                 }
10346                                 work[front->vertex] = iter;
10347                                 *work_list_tail = front;
10348                                 front->work_next = 0;
10349                                 work_list_tail = &front->work_next;
10350                         }
10351                 }
10352         }
10353         xfree(has_already);
10354         xfree(work);
10355 }
10356
10357 /*
10358  * C(V)
10359  * S(V)
10360  */
10361 static void fixup_block_phi_variables(
10362         struct compile_state *state, struct block *parent, struct block *block)
10363 {
10364         struct block_set *set;
10365         struct triple *ptr;
10366         int edge;
10367         if (!parent || !block)
10368                 return;
10369         /* Find the edge I am coming in on */
10370         edge = 0;
10371         for(set = block->use; set; set = set->next, edge++) {
10372                 if (set->member == parent) {
10373                         break;
10374                 }
10375         }
10376         if (!set) {
10377                 internal_error(state, 0, "phi input is not on a control predecessor");
10378         }
10379         for(ptr = block->first; ; ptr = ptr->next) {
10380                 if (ptr->op == OP_PHI) {
10381                         struct triple *var, *val, **slot;
10382                         var = MISC(ptr, 0);
10383                         if (!var) {
10384                                 internal_error(state, ptr, "no var???");
10385                         }
10386                         /* Find the current value of the variable */
10387                         val = var->use->member;
10388                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10389                                 internal_error(state, val, "bad value in phi");
10390                         }
10391                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10392                                 internal_error(state, ptr, "edges > phi rhs");
10393                         }
10394                         slot = &RHS(ptr, edge);
10395                         if ((*slot != 0) && (*slot != val)) {
10396                                 internal_error(state, ptr, "phi already bound on this edge");
10397                         }
10398                         *slot = val;
10399                         use_triple(val, ptr);
10400                 }
10401                 if (ptr == block->last) {
10402                         break;
10403                 }
10404         }
10405 }
10406
10407
10408 static void rename_block_variables(
10409         struct compile_state *state, struct block *block)
10410 {
10411         struct block_set *user;
10412         struct triple *ptr, *next, *last;
10413         int done;
10414         if (!block)
10415                 return;
10416         last = block->first;
10417         done = 0;
10418         for(ptr = block->first; !done; ptr = next) {
10419                 next = ptr->next;
10420                 if (ptr == block->last) {
10421                         done = 1;
10422                 }
10423                 /* RHS(A) */
10424                 if (ptr->op == OP_READ) {
10425                         struct triple *var, *val;
10426                         var = RHS(ptr, 0);
10427                         unuse_triple(var, ptr);
10428                         if (!var->use) {
10429                                 error(state, ptr, "variable used without being set");
10430                         }
10431                         /* Find the current value of the variable */
10432                         val = var->use->member;
10433                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10434                                 internal_error(state, val, "bad value in read");
10435                         }
10436                         propogate_use(state, ptr, val);
10437                         release_triple(state, ptr);
10438                         continue;
10439                 }
10440                 /* LHS(A) */
10441                 if (ptr->op == OP_WRITE) {
10442                         struct triple *var, *val, *tval;
10443                         var = LHS(ptr, 0);
10444                         tval = val = RHS(ptr, 0);
10445                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10446                                 internal_error(state, val, "bad value in write");
10447                         }
10448                         /* Insert a copy if the types differ */
10449                         if (!equiv_types(ptr->type, val->type)) {
10450                                 if (val->op == OP_INTCONST) {
10451                                         tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10452                                         tval->u.cval = val->u.cval;
10453                                 }
10454                                 else {
10455                                         tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10456                                         use_triple(val, tval);
10457                                 }
10458                                 unuse_triple(val, ptr);
10459                                 RHS(ptr, 0) = tval;
10460                                 use_triple(tval, ptr);
10461                         }
10462                         propogate_use(state, ptr, tval);
10463                         unuse_triple(var, ptr);
10464                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10465                         push_triple(var, tval);
10466                 }
10467                 if (ptr->op == OP_PHI) {
10468                         struct triple *var;
10469                         var = MISC(ptr, 0);
10470                         /* Push OP_PHI onto a stack of variable uses */
10471                         push_triple(var, ptr);
10472                 }
10473                 last = ptr;
10474         }
10475         block->last = last;
10476
10477         /* Fixup PHI functions in the cf successors */
10478         fixup_block_phi_variables(state, block, block->left);
10479         fixup_block_phi_variables(state, block, block->right);
10480         /* rename variables in the dominated nodes */
10481         for(user = block->idominates; user; user = user->next) {
10482                 rename_block_variables(state, user->member);
10483         }
10484         /* pop the renamed variable stack */
10485         last = block->first;
10486         done = 0;
10487         for(ptr = block->first; !done ; ptr = next) {
10488                 next = ptr->next;
10489                 if (ptr == block->last) {
10490                         done = 1;
10491                 }
10492                 if (ptr->op == OP_WRITE) {
10493                         struct triple *var;
10494                         var = LHS(ptr, 0);
10495                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10496                         pop_triple(var, RHS(ptr, 0));
10497                         release_triple(state, ptr);
10498                         continue;
10499                 }
10500                 if (ptr->op == OP_PHI) {
10501                         struct triple *var;
10502                         var = MISC(ptr, 0);
10503                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10504                         pop_triple(var, ptr);
10505                 }
10506                 last = ptr;
10507         }
10508         block->last = last;
10509 }
10510
10511 static void prune_block_variables(struct compile_state *state,
10512         struct block *block)
10513 {
10514         struct block_set *user;
10515         struct triple *next, *last, *ptr;
10516         int done;
10517         last = block->first;
10518         done = 0;
10519         for(ptr = block->first; !done; ptr = next) {
10520                 next = ptr->next;
10521                 if (ptr == block->last) {
10522                         done = 1;
10523                 }
10524                 if (ptr->op == OP_ADECL) {
10525                         struct triple_set *user, *next;
10526                         for(user = ptr->use; user; user = next) {
10527                                 struct triple *use;
10528                                 next = user->next;
10529                                 use = user->member;
10530                                 if (use->op != OP_PHI) {
10531                                         internal_error(state, use, "decl still used");
10532                                 }
10533                                 if (MISC(use, 0) != ptr) {
10534                                         internal_error(state, use, "bad phi use of decl");
10535                                 }
10536                                 unuse_triple(ptr, use);
10537                                 MISC(use, 0) = 0;
10538                         }
10539                         release_triple(state, ptr);
10540                         continue;
10541                 }
10542                 last = ptr;
10543         }
10544         block->last = last;
10545         for(user = block->idominates; user; user = user->next) {
10546                 prune_block_variables(state, user->member);
10547         }
10548 }
10549
10550 static void transform_to_ssa_form(struct compile_state *state)
10551 {
10552         insert_phi_operations(state);
10553 #if 0
10554         printf("@%s:%d\n", __FILE__, __LINE__);
10555         print_blocks(state, stdout);
10556 #endif
10557         rename_block_variables(state, state->first_block);
10558         prune_block_variables(state, state->first_block);
10559 }
10560
10561
10562 static void clear_vertex(
10563         struct compile_state *state, struct block *block, void *arg)
10564 {
10565         block->vertex = 0;
10566 }
10567
10568 static void mark_live_block(
10569         struct compile_state *state, struct block *block, int *next_vertex)
10570 {
10571         /* See if this is a block that has not been marked */
10572         if (block->vertex != 0) {
10573                 return;
10574         }
10575         block->vertex = *next_vertex;
10576         *next_vertex += 1;
10577         if (triple_is_branch(state, block->last)) {
10578                 struct triple **targ;
10579                 targ = triple_targ(state, block->last, 0);
10580                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10581                         if (!*targ) {
10582                                 continue;
10583                         }
10584                         if (!triple_stores_block(state, *targ)) {
10585                                 internal_error(state, 0, "bad targ");
10586                         }
10587                         mark_live_block(state, (*targ)->u.block, next_vertex);
10588                 }
10589         }
10590         else if (block->last->next != RHS(state->main_function, 0)) {
10591                 struct triple *ins;
10592                 ins = block->last->next;
10593                 if (!triple_stores_block(state, ins)) {
10594                         internal_error(state, 0, "bad block start");
10595                 }
10596                 mark_live_block(state, ins->u.block, next_vertex);
10597         }
10598 }
10599
10600 static void transform_from_ssa_form(struct compile_state *state)
10601 {
10602         /* To get out of ssa form we insert moves on the incoming
10603          * edges to blocks containting phi functions.
10604          */
10605         struct triple *first;
10606         struct triple *phi, *next;
10607         int next_vertex;
10608
10609         /* Walk the control flow to see which blocks remain alive */
10610         walk_blocks(state, clear_vertex, 0);
10611         next_vertex = 1;
10612         mark_live_block(state, state->first_block, &next_vertex);
10613
10614         /* Walk all of the operations to find the phi functions */
10615         first = RHS(state->main_function, 0);
10616         for(phi = first->next; phi != first ; phi = next) {
10617                 struct block_set *set;
10618                 struct block *block;
10619                 struct triple **slot;
10620                 struct triple *var, *read;
10621                 struct triple_set *use, *use_next;
10622                 int edge, used;
10623                 next = phi->next;
10624                 if (phi->op != OP_PHI) {
10625                         continue;
10626                 }
10627                 block = phi->u.block;
10628                 slot  = &RHS(phi, 0);
10629
10630                 /* Forget uses from code in dead blocks */
10631                 for(use = phi->use; use; use = use_next) {
10632                         struct block *ublock;
10633                         struct triple **expr;
10634                         use_next = use->next;
10635                         ublock = block_of_triple(state, use->member);
10636                         if ((use->member == phi) || (ublock->vertex != 0)) {
10637                                 continue;
10638                         }
10639                         expr = triple_rhs(state, use->member, 0);
10640                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10641                                 if (*expr == phi) {
10642                                         *expr = 0;
10643                                 }
10644                         }
10645                         unuse_triple(phi, use->member);
10646                 }
10647
10648                 /* A variable to replace the phi function */
10649                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10650                 /* A read of the single value that is set into the variable */
10651                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10652                 use_triple(var, read);
10653
10654                 /* Replaces uses of the phi with variable reads */
10655                 propogate_use(state, phi, read);
10656
10657                 /* Walk all of the incoming edges/blocks and insert moves.
10658                  */
10659                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10660                         struct block *eblock;
10661                         struct triple *move;
10662                         struct triple *val;
10663                         eblock = set->member;
10664                         val = slot[edge];
10665                         slot[edge] = 0;
10666                         unuse_triple(val, phi);
10667
10668                         if (!val || (val == &zero_triple) ||
10669                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10670                                 (val == phi) || (val == read)) {
10671                                 continue;
10672                         }
10673                         
10674                         move = post_triple(state, 
10675                                 val, OP_WRITE, phi->type, var, val);
10676                         use_triple(val, move);
10677                         use_triple(var, move);
10678                 }               
10679                 /* See if there are any writers of var */
10680                 used = 0;
10681                 for(use = var->use; use; use = use->next) {
10682                         struct triple **expr;
10683                         expr = triple_lhs(state, use->member, 0);
10684                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10685                                 if (*expr == var) {
10686                                         used = 1;
10687                                 }
10688                         }
10689                 }
10690                 /* If var is not used free it */
10691                 if (!used) {
10692                         unuse_triple(var, read);
10693                         free_triple(state, read);
10694                         free_triple(state, var);
10695                 }
10696
10697                 /* Release the phi function */
10698                 release_triple(state, phi);
10699         }
10700         
10701 }
10702
10703
10704 /* 
10705  * Register conflict resolution
10706  * =========================================================
10707  */
10708
10709 static struct reg_info find_def_color(
10710         struct compile_state *state, struct triple *def)
10711 {
10712         struct triple_set *set;
10713         struct reg_info info;
10714         info.reg = REG_UNSET;
10715         info.regcm = 0;
10716         if (!triple_is_def(state, def)) {
10717                 return info;
10718         }
10719         info = arch_reg_lhs(state, def, 0);
10720         if (info.reg >= MAX_REGISTERS) {
10721                 info.reg = REG_UNSET;
10722         }
10723         for(set = def->use; set; set = set->next) {
10724                 struct reg_info tinfo;
10725                 int i;
10726                 i = find_rhs_use(state, set->member, def);
10727                 if (i < 0) {
10728                         continue;
10729                 }
10730                 tinfo = arch_reg_rhs(state, set->member, i);
10731                 if (tinfo.reg >= MAX_REGISTERS) {
10732                         tinfo.reg = REG_UNSET;
10733                 }
10734                 if ((tinfo.reg != REG_UNSET) && 
10735                         (info.reg != REG_UNSET) &&
10736                         (tinfo.reg != info.reg)) {
10737                         internal_error(state, def, "register conflict");
10738                 }
10739                 if ((info.regcm & tinfo.regcm) == 0) {
10740                         internal_error(state, def, "regcm conflict %x & %x == 0",
10741                                 info.regcm, tinfo.regcm);
10742                 }
10743                 if (info.reg == REG_UNSET) {
10744                         info.reg = tinfo.reg;
10745                 }
10746                 info.regcm &= tinfo.regcm;
10747         }
10748         if (info.reg >= MAX_REGISTERS) {
10749                 internal_error(state, def, "register out of range");
10750         }
10751         return info;
10752 }
10753
10754 static struct reg_info find_lhs_pre_color(
10755         struct compile_state *state, struct triple *ins, int index)
10756 {
10757         struct reg_info info;
10758         int zlhs, zrhs, i;
10759         zrhs = TRIPLE_RHS(ins->sizes);
10760         zlhs = TRIPLE_LHS(ins->sizes);
10761         if (!zlhs && triple_is_def(state, ins)) {
10762                 zlhs = 1;
10763         }
10764         if (index >= zlhs) {
10765                 internal_error(state, ins, "Bad lhs %d", index);
10766         }
10767         info = arch_reg_lhs(state, ins, index);
10768         for(i = 0; i < zrhs; i++) {
10769                 struct reg_info rinfo;
10770                 rinfo = arch_reg_rhs(state, ins, i);
10771                 if ((info.reg == rinfo.reg) &&
10772                         (rinfo.reg >= MAX_REGISTERS)) {
10773                         struct reg_info tinfo;
10774                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10775                         info.reg = tinfo.reg;
10776                         info.regcm &= tinfo.regcm;
10777                         break;
10778                 }
10779         }
10780         if (info.reg >= MAX_REGISTERS) {
10781                 info.reg = REG_UNSET;
10782         }
10783         return info;
10784 }
10785
10786 static struct reg_info find_rhs_post_color(
10787         struct compile_state *state, struct triple *ins, int index);
10788
10789 static struct reg_info find_lhs_post_color(
10790         struct compile_state *state, struct triple *ins, int index)
10791 {
10792         struct triple_set *set;
10793         struct reg_info info;
10794         struct triple *lhs;
10795 #if 0
10796         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10797                 ins, index);
10798 #endif
10799         if ((index == 0) && triple_is_def(state, ins)) {
10800                 lhs = ins;
10801         }
10802         else if (index < TRIPLE_LHS(ins->sizes)) {
10803                 lhs = LHS(ins, index);
10804         }
10805         else {
10806                 internal_error(state, ins, "Bad lhs %d", index);
10807                 lhs = 0;
10808         }
10809         info = arch_reg_lhs(state, ins, index);
10810         if (info.reg >= MAX_REGISTERS) {
10811                 info.reg = REG_UNSET;
10812         }
10813         for(set = lhs->use; set; set = set->next) {
10814                 struct reg_info rinfo;
10815                 struct triple *user;
10816                 int zrhs, i;
10817                 user = set->member;
10818                 zrhs = TRIPLE_RHS(user->sizes);
10819                 for(i = 0; i < zrhs; i++) {
10820                         if (RHS(user, i) != lhs) {
10821                                 continue;
10822                         }
10823                         rinfo = find_rhs_post_color(state, user, i);
10824                         if ((info.reg != REG_UNSET) &&
10825                                 (rinfo.reg != REG_UNSET) &&
10826                                 (info.reg != rinfo.reg)) {
10827                                 internal_error(state, ins, "register conflict");
10828                         }
10829                         if ((info.regcm & rinfo.regcm) == 0) {
10830                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10831                                         info.regcm, rinfo.regcm);
10832                         }
10833                         if (info.reg == REG_UNSET) {
10834                                 info.reg = rinfo.reg;
10835                         }
10836                         info.regcm &= rinfo.regcm;
10837                 }
10838         }
10839 #if 0
10840         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10841                 ins, index, info.reg, info.regcm);
10842 #endif
10843         return info;
10844 }
10845
10846 static struct reg_info find_rhs_post_color(
10847         struct compile_state *state, struct triple *ins, int index)
10848 {
10849         struct reg_info info, rinfo;
10850         int zlhs, i;
10851 #if 0
10852         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10853                 ins, index);
10854 #endif
10855         rinfo = arch_reg_rhs(state, ins, index);
10856         zlhs = TRIPLE_LHS(ins->sizes);
10857         if (!zlhs && triple_is_def(state, ins)) {
10858                 zlhs = 1;
10859         }
10860         info = rinfo;
10861         if (info.reg >= MAX_REGISTERS) {
10862                 info.reg = REG_UNSET;
10863         }
10864         for(i = 0; i < zlhs; i++) {
10865                 struct reg_info linfo;
10866                 linfo = arch_reg_lhs(state, ins, i);
10867                 if ((linfo.reg == rinfo.reg) &&
10868                         (linfo.reg >= MAX_REGISTERS)) {
10869                         struct reg_info tinfo;
10870                         tinfo = find_lhs_post_color(state, ins, i);
10871                         if (tinfo.reg >= MAX_REGISTERS) {
10872                                 tinfo.reg = REG_UNSET;
10873                         }
10874                         info.regcm &= linfo.reg;
10875                         info.regcm &= tinfo.regcm;
10876                         if (info.reg != REG_UNSET) {
10877                                 internal_error(state, ins, "register conflict");
10878                         }
10879                         if (info.regcm == 0) {
10880                                 internal_error(state, ins, "regcm conflict");
10881                         }
10882                         info.reg = tinfo.reg;
10883                 }
10884         }
10885 #if 0
10886         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10887                 ins, index, info.reg, info.regcm);
10888 #endif
10889         return info;
10890 }
10891
10892 static struct reg_info find_lhs_color(
10893         struct compile_state *state, struct triple *ins, int index)
10894 {
10895         struct reg_info pre, post, info;
10896 #if 0
10897         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10898                 ins, index);
10899 #endif
10900         pre = find_lhs_pre_color(state, ins, index);
10901         post = find_lhs_post_color(state, ins, index);
10902         if ((pre.reg != post.reg) &&
10903                 (pre.reg != REG_UNSET) &&
10904                 (post.reg != REG_UNSET)) {
10905                 internal_error(state, ins, "register conflict");
10906         }
10907         info.regcm = pre.regcm & post.regcm;
10908         info.reg = pre.reg;
10909         if (info.reg == REG_UNSET) {
10910                 info.reg = post.reg;
10911         }
10912 #if 0
10913         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10914                 ins, index, info.reg, info.regcm);
10915 #endif
10916         return info;
10917 }
10918
10919 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10920 {
10921         struct triple_set *entry, *next;
10922         struct triple *out;
10923         struct reg_info info, rinfo;
10924
10925         info = arch_reg_lhs(state, ins, 0);
10926         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10927         use_triple(RHS(out, 0), out);
10928         /* Get the users of ins to use out instead */
10929         for(entry = ins->use; entry; entry = next) {
10930                 int i;
10931                 next = entry->next;
10932                 if (entry->member == out) {
10933                         continue;
10934                 }
10935                 i = find_rhs_use(state, entry->member, ins);
10936                 if (i < 0) {
10937                         continue;
10938                 }
10939                 rinfo = arch_reg_rhs(state, entry->member, i);
10940                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10941                         continue;
10942                 }
10943                 replace_rhs_use(state, ins, out, entry->member);
10944         }
10945         transform_to_arch_instruction(state, out);
10946         return out;
10947 }
10948
10949 static struct triple *typed_pre_copy(
10950         struct compile_state *state, struct type *type, struct triple *ins, int index)
10951 {
10952         /* Carefully insert enough operations so that I can
10953          * enter any operation with a GPR32.
10954          */
10955         struct triple *in;
10956         struct triple **expr;
10957         unsigned classes;
10958         struct reg_info info;
10959         if (ins->op == OP_PHI) {
10960                 internal_error(state, ins, "pre_copy on a phi?");
10961         }
10962         classes = arch_type_to_regcm(state, type);
10963         info = arch_reg_rhs(state, ins, index);
10964         expr = &RHS(ins, index);
10965         if ((info.regcm & classes) == 0) {
10966                 internal_error(state, ins, "pre_copy with no register classes");
10967         }
10968         in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
10969         unuse_triple(*expr, ins);
10970         *expr = in;
10971         use_triple(RHS(in, 0), in);
10972         use_triple(in, ins);
10973         transform_to_arch_instruction(state, in);
10974         return in;
10975         
10976 }
10977 static struct triple *pre_copy(
10978         struct compile_state *state, struct triple *ins, int index)
10979 {
10980         return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
10981 }
10982
10983
10984 static void insert_copies_to_phi(struct compile_state *state)
10985 {
10986         /* To get out of ssa form we insert moves on the incoming
10987          * edges to blocks containting phi functions.
10988          */
10989         struct triple *first;
10990         struct triple *phi;
10991
10992         /* Walk all of the operations to find the phi functions */
10993         first = RHS(state->main_function, 0);
10994         for(phi = first->next; phi != first ; phi = phi->next) {
10995                 struct block_set *set;
10996                 struct block *block;
10997                 struct triple **slot, *copy;
10998                 int edge;
10999                 if (phi->op != OP_PHI) {
11000                         continue;
11001                 }
11002                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11003                 block = phi->u.block;
11004                 slot  = &RHS(phi, 0);
11005                 /* Phi's that feed into mandatory live range joins
11006                  * cause nasty complications.  Insert a copy of
11007                  * the phi value so I never have to deal with
11008                  * that in the rest of the code.
11009                  */
11010                 copy = post_copy(state, phi);
11011                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11012                 /* Walk all of the incoming edges/blocks and insert moves.
11013                  */
11014                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11015                         struct block *eblock;
11016                         struct triple *move;
11017                         struct triple *val;
11018                         struct triple *ptr;
11019                         eblock = set->member;
11020                         val = slot[edge];
11021
11022                         if (val == phi) {
11023                                 continue;
11024                         }
11025
11026                         get_occurance(val->occurance);
11027                         move = build_triple(state, OP_COPY, phi->type, val, 0,
11028                                 val->occurance);
11029                         move->u.block = eblock;
11030                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
11031                         use_triple(val, move);
11032                         
11033                         slot[edge] = move;
11034                         unuse_triple(val, phi);
11035                         use_triple(move, phi);
11036
11037                         /* Walk through the block backwards to find
11038                          * an appropriate location for the OP_COPY.
11039                          */
11040                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11041                                 struct triple **expr;
11042                                 if ((ptr == phi) || (ptr == val)) {
11043                                         goto out;
11044                                 }
11045                                 expr = triple_rhs(state, ptr, 0);
11046                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11047                                         if ((*expr) == phi) {
11048                                                 goto out;
11049                                         }
11050                                 }
11051                         }
11052                 out:
11053                         if (triple_is_branch(state, ptr)) {
11054                                 internal_error(state, ptr,
11055                                         "Could not insert write to phi");
11056                         }
11057                         insert_triple(state, ptr->next, move);
11058                         if (eblock->last == ptr) {
11059                                 eblock->last = move;
11060                         }
11061                         transform_to_arch_instruction(state, move);
11062                 }
11063         }
11064 }
11065
11066 struct triple_reg_set {
11067         struct triple_reg_set *next;
11068         struct triple *member;
11069         struct triple *new;
11070 };
11071
11072 struct reg_block {
11073         struct block *block;
11074         struct triple_reg_set *in;
11075         struct triple_reg_set *out;
11076         int vertex;
11077 };
11078
11079 static int do_triple_set(struct triple_reg_set **head, 
11080         struct triple *member, struct triple *new_member)
11081 {
11082         struct triple_reg_set **ptr, *new;
11083         if (!member)
11084                 return 0;
11085         ptr = head;
11086         while(*ptr) {
11087                 if ((*ptr)->member == member) {
11088                         return 0;
11089                 }
11090                 ptr = &(*ptr)->next;
11091         }
11092         new = xcmalloc(sizeof(*new), "triple_set");
11093         new->member = member;
11094         new->new    = new_member;
11095         new->next   = *head;
11096         *head       = new;
11097         return 1;
11098 }
11099
11100 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11101 {
11102         struct triple_reg_set *entry, **ptr;
11103         ptr = head;
11104         while(*ptr) {
11105                 entry = *ptr;
11106                 if (entry->member == member) {
11107                         *ptr = entry->next;
11108                         xfree(entry);
11109                         return;
11110                 }
11111                 else {
11112                         ptr = &entry->next;
11113                 }
11114         }
11115 }
11116
11117 static int in_triple(struct reg_block *rb, struct triple *in)
11118 {
11119         return do_triple_set(&rb->in, in, 0);
11120 }
11121 static void unin_triple(struct reg_block *rb, struct triple *unin)
11122 {
11123         do_triple_unset(&rb->in, unin);
11124 }
11125
11126 static int out_triple(struct reg_block *rb, struct triple *out)
11127 {
11128         return do_triple_set(&rb->out, out, 0);
11129 }
11130 static void unout_triple(struct reg_block *rb, struct triple *unout)
11131 {
11132         do_triple_unset(&rb->out, unout);
11133 }
11134
11135 static int initialize_regblock(struct reg_block *blocks,
11136         struct block *block, int vertex)
11137 {
11138         struct block_set *user;
11139         if (!block || (blocks[block->vertex].block == block)) {
11140                 return vertex;
11141         }
11142         vertex += 1;
11143         /* Renumber the blocks in a convinient fashion */
11144         block->vertex = vertex;
11145         blocks[vertex].block    = block;
11146         blocks[vertex].vertex   = vertex;
11147         for(user = block->use; user; user = user->next) {
11148                 vertex = initialize_regblock(blocks, user->member, vertex);
11149         }
11150         return vertex;
11151 }
11152
11153 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11154         struct reg_block *rb, struct block *suc)
11155 {
11156         /* Read the conditional input set of a successor block
11157          * (i.e. the input to the phi nodes) and place it in the
11158          * current blocks output set.
11159          */
11160         struct block_set *set;
11161         struct triple *ptr;
11162         int edge;
11163         int done, change;
11164         change = 0;
11165         /* Find the edge I am coming in on */
11166         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11167                 if (set->member == rb->block) {
11168                         break;
11169                 }
11170         }
11171         if (!set) {
11172                 internal_error(state, 0, "Not coming on a control edge?");
11173         }
11174         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11175                 struct triple **slot, *expr, *ptr2;
11176                 int out_change, done2;
11177                 done = (ptr == suc->last);
11178                 if (ptr->op != OP_PHI) {
11179                         continue;
11180                 }
11181                 slot = &RHS(ptr, 0);
11182                 expr = slot[edge];
11183                 out_change = out_triple(rb, expr);
11184                 if (!out_change) {
11185                         continue;
11186                 }
11187                 /* If we don't define the variable also plast it
11188                  * in the current blocks input set.
11189                  */
11190                 ptr2 = rb->block->first;
11191                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11192                         if (ptr2 == expr) {
11193                                 break;
11194                         }
11195                         done2 = (ptr2 == rb->block->last);
11196                 }
11197                 if (!done2) {
11198                         continue;
11199                 }
11200                 change |= in_triple(rb, expr);
11201         }
11202         return change;
11203 }
11204
11205 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11206         struct reg_block *rb, struct block *suc)
11207 {
11208         struct triple_reg_set *in_set;
11209         int change;
11210         change = 0;
11211         /* Read the input set of a successor block
11212          * and place it in the current blocks output set.
11213          */
11214         in_set = blocks[suc->vertex].in;
11215         for(; in_set; in_set = in_set->next) {
11216                 int out_change, done;
11217                 struct triple *first, *last, *ptr;
11218                 out_change = out_triple(rb, in_set->member);
11219                 if (!out_change) {
11220                         continue;
11221                 }
11222                 /* If we don't define the variable also place it
11223                  * in the current blocks input set.
11224                  */
11225                 first = rb->block->first;
11226                 last = rb->block->last;
11227                 done = 0;
11228                 for(ptr = first; !done; ptr = ptr->next) {
11229                         if (ptr == in_set->member) {
11230                                 break;
11231                         }
11232                         done = (ptr == last);
11233                 }
11234                 if (!done) {
11235                         continue;
11236                 }
11237                 change |= in_triple(rb, in_set->member);
11238         }
11239         change |= phi_in(state, blocks, rb, suc);
11240         return change;
11241 }
11242
11243
11244 static int use_in(struct compile_state *state, struct reg_block *rb)
11245 {
11246         /* Find the variables we use but don't define and add
11247          * it to the current blocks input set.
11248          */
11249 #warning "FIXME is this O(N^2) algorithm bad?"
11250         struct block *block;
11251         struct triple *ptr;
11252         int done;
11253         int change;
11254         block = rb->block;
11255         change = 0;
11256         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11257                 struct triple **expr;
11258                 done = (ptr == block->first);
11259                 /* The variable a phi function uses depends on the
11260                  * control flow, and is handled in phi_in, not
11261                  * here.
11262                  */
11263                 if (ptr->op == OP_PHI) {
11264                         continue;
11265                 }
11266                 expr = triple_rhs(state, ptr, 0);
11267                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11268                         struct triple *rhs, *test;
11269                         int tdone;
11270                         rhs = *expr;
11271                         if (!rhs) {
11272                                 continue;
11273                         }
11274                         /* See if rhs is defined in this block */
11275                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11276                                 tdone = (test == block->first);
11277                                 if (test == rhs) {
11278                                         rhs = 0;
11279                                         break;
11280                                 }
11281                         }
11282                         /* If I still have a valid rhs add it to in */
11283                         change |= in_triple(rb, rhs);
11284                 }
11285         }
11286         return change;
11287 }
11288
11289 static struct reg_block *compute_variable_lifetimes(
11290         struct compile_state *state)
11291 {
11292         struct reg_block *blocks;
11293         int change;
11294         blocks = xcmalloc(
11295                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11296         initialize_regblock(blocks, state->last_block, 0);
11297         do {
11298                 int i;
11299                 change = 0;
11300                 for(i = 1; i <= state->last_vertex; i++) {
11301                         struct reg_block *rb;
11302                         rb = &blocks[i];
11303                         /* Add the left successor's input set to in */
11304                         if (rb->block->left) {
11305                                 change |= reg_in(state, blocks, rb, rb->block->left);
11306                         }
11307                         /* Add the right successor's input set to in */
11308                         if ((rb->block->right) && 
11309                                 (rb->block->right != rb->block->left)) {
11310                                 change |= reg_in(state, blocks, rb, rb->block->right);
11311                         }
11312                         /* Add use to in... */
11313                         change |= use_in(state, rb);
11314                 }
11315         } while(change);
11316         return blocks;
11317 }
11318
11319 static void free_variable_lifetimes(
11320         struct compile_state *state, struct reg_block *blocks)
11321 {
11322         int i;
11323         /* free in_set && out_set on each block */
11324         for(i = 1; i <= state->last_vertex; i++) {
11325                 struct triple_reg_set *entry, *next;
11326                 struct reg_block *rb;
11327                 rb = &blocks[i];
11328                 for(entry = rb->in; entry ; entry = next) {
11329                         next = entry->next;
11330                         do_triple_unset(&rb->in, entry->member);
11331                 }
11332                 for(entry = rb->out; entry; entry = next) {
11333                         next = entry->next;
11334                         do_triple_unset(&rb->out, entry->member);
11335                 }
11336         }
11337         xfree(blocks);
11338
11339 }
11340
11341 typedef void (*wvl_cb_t)(
11342         struct compile_state *state, 
11343         struct reg_block *blocks, struct triple_reg_set *live, 
11344         struct reg_block *rb, struct triple *ins, void *arg);
11345
11346 static void walk_variable_lifetimes(struct compile_state *state,
11347         struct reg_block *blocks, wvl_cb_t cb, void *arg)
11348 {
11349         int i;
11350         
11351         for(i = 1; i <= state->last_vertex; i++) {
11352                 struct triple_reg_set *live;
11353                 struct triple_reg_set *entry, *next;
11354                 struct triple *ptr, *prev;
11355                 struct reg_block *rb;
11356                 struct block *block;
11357                 int done;
11358
11359                 /* Get the blocks */
11360                 rb = &blocks[i];
11361                 block = rb->block;
11362
11363                 /* Copy out into live */
11364                 live = 0;
11365                 for(entry = rb->out; entry; entry = next) {
11366                         next = entry->next;
11367                         do_triple_set(&live, entry->member, entry->new);
11368                 }
11369                 /* Walk through the basic block calculating live */
11370                 for(done = 0, ptr = block->last; !done; ptr = prev) {
11371                         struct triple **expr;
11372
11373                         prev = ptr->prev;
11374                         done = (ptr == block->first);
11375
11376                         /* Ensure the current definition is in live */
11377                         if (triple_is_def(state, ptr)) {
11378                                 do_triple_set(&live, ptr, 0);
11379                         }
11380
11381                         /* Inform the callback function of what is
11382                          * going on.
11383                          */
11384                          cb(state, blocks, live, rb, ptr, arg);
11385                         
11386                         /* Remove the current definition from live */
11387                         do_triple_unset(&live, ptr);
11388
11389                         /* Add the current uses to live.
11390                          *
11391                          * It is safe to skip phi functions because they do
11392                          * not have any block local uses, and the block
11393                          * output sets already properly account for what
11394                          * control flow depedent uses phi functions do have.
11395                          */
11396                         if (ptr->op == OP_PHI) {
11397                                 continue;
11398                         }
11399                         expr = triple_rhs(state, ptr, 0);
11400                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
11401                                 /* If the triple is not a definition skip it. */
11402                                 if (!*expr || !triple_is_def(state, *expr)) {
11403                                         continue;
11404                                 }
11405                                 do_triple_set(&live, *expr, 0);
11406                         }
11407                 }
11408                 /* Free live */
11409                 for(entry = live; entry; entry = next) {
11410                         next = entry->next;
11411                         do_triple_unset(&live, entry->member);
11412                 }
11413         }
11414 }
11415
11416 static int count_triples(struct compile_state *state)
11417 {
11418         struct triple *first, *ins;
11419         int triples = 0;
11420         first = RHS(state->main_function, 0);
11421         ins = first;
11422         do {
11423                 triples++;
11424                 ins = ins->next;
11425         } while (ins != first);
11426         return triples;
11427 }
11428 struct dead_triple {
11429         struct triple *triple;
11430         struct dead_triple *work_next;
11431         struct block *block;
11432         int color;
11433         int flags;
11434 #define TRIPLE_FLAG_ALIVE 1
11435 };
11436
11437
11438 static void awaken(
11439         struct compile_state *state,
11440         struct dead_triple *dtriple, struct triple **expr,
11441         struct dead_triple ***work_list_tail)
11442 {
11443         struct triple *triple;
11444         struct dead_triple *dt;
11445         if (!expr) {
11446                 return;
11447         }
11448         triple = *expr;
11449         if (!triple) {
11450                 return;
11451         }
11452         if (triple->id <= 0)  {
11453                 internal_error(state, triple, "bad triple id: %d",
11454                         triple->id);
11455         }
11456         if (triple->op == OP_NOOP) {
11457                 internal_warning(state, triple, "awakening noop?");
11458                 return;
11459         }
11460         dt = &dtriple[triple->id];
11461         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11462                 dt->flags |= TRIPLE_FLAG_ALIVE;
11463                 if (!dt->work_next) {
11464                         **work_list_tail = dt;
11465                         *work_list_tail = &dt->work_next;
11466                 }
11467         }
11468 }
11469
11470 static void eliminate_inefectual_code(struct compile_state *state)
11471 {
11472         struct block *block;
11473         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11474         int triples, i;
11475         struct triple *first, *ins;
11476
11477         /* Setup the work list */
11478         work_list = 0;
11479         work_list_tail = &work_list;
11480
11481         first = RHS(state->main_function, 0);
11482
11483         /* Count how many triples I have */
11484         triples = count_triples(state);
11485
11486         /* Now put then in an array and mark all of the triples dead */
11487         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11488         
11489         ins = first;
11490         i = 1;
11491         block = 0;
11492         do {
11493                 if (ins->op == OP_LABEL) {
11494                         block = ins->u.block;
11495                 }
11496                 dtriple[i].triple = ins;
11497                 dtriple[i].block  = block;
11498                 dtriple[i].flags  = 0;
11499                 dtriple[i].color  = ins->id;
11500                 ins->id = i;
11501                 /* See if it is an operation we always keep */
11502 #warning "FIXME handle the case of killing a branch instruction"
11503                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11504                         awaken(state, dtriple, &ins, &work_list_tail);
11505                 }
11506                 i++;
11507                 ins = ins->next;
11508         } while(ins != first);
11509         while(work_list) {
11510                 struct dead_triple *dt;
11511                 struct block_set *user;
11512                 struct triple **expr;
11513                 dt = work_list;
11514                 work_list = dt->work_next;
11515                 if (!work_list) {
11516                         work_list_tail = &work_list;
11517                 }
11518                 /* Wake up the data depencencies of this triple */
11519                 expr = 0;
11520                 do {
11521                         expr = triple_rhs(state, dt->triple, expr);
11522                         awaken(state, dtriple, expr, &work_list_tail);
11523                 } while(expr);
11524                 do {
11525                         expr = triple_lhs(state, dt->triple, expr);
11526                         awaken(state, dtriple, expr, &work_list_tail);
11527                 } while(expr);
11528                 do {
11529                         expr = triple_misc(state, dt->triple, expr);
11530                         awaken(state, dtriple, expr, &work_list_tail);
11531                 } while(expr);
11532                 /* Wake up the forward control dependencies */
11533                 do {
11534                         expr = triple_targ(state, dt->triple, expr);
11535                         awaken(state, dtriple, expr, &work_list_tail);
11536                 } while(expr);
11537                 /* Wake up the reverse control dependencies of this triple */
11538                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11539                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11540                 }
11541         }
11542         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11543                 if ((dt->triple->op == OP_NOOP) && 
11544                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11545                         internal_error(state, dt->triple, "noop effective?");
11546                 }
11547                 dt->triple->id = dt->color;     /* Restore the color */
11548                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11549 #warning "FIXME handle the case of killing a basic block"
11550                         if (dt->block->first == dt->triple) {
11551                                 continue;
11552                         }
11553                         if (dt->block->last == dt->triple) {
11554                                 dt->block->last = dt->triple->prev;
11555                         }
11556                         release_triple(state, dt->triple);
11557                 }
11558         }
11559         xfree(dtriple);
11560 }
11561
11562
11563 static void insert_mandatory_copies(struct compile_state *state)
11564 {
11565         struct triple *ins, *first;
11566
11567         /* The object is with a minimum of inserted copies,
11568          * to resolve in fundamental register conflicts between
11569          * register value producers and consumers.
11570          * Theoretically we may be greater than minimal when we
11571          * are inserting copies before instructions but that
11572          * case should be rare.
11573          */
11574         first = RHS(state->main_function, 0);
11575         ins = first;
11576         do {
11577                 struct triple_set *entry, *next;
11578                 struct triple *tmp;
11579                 struct reg_info info;
11580                 unsigned reg, regcm;
11581                 int do_post_copy, do_pre_copy;
11582                 tmp = 0;
11583                 if (!triple_is_def(state, ins)) {
11584                         goto next;
11585                 }
11586                 /* Find the architecture specific color information */
11587                 info = arch_reg_lhs(state, ins, 0);
11588                 if (info.reg >= MAX_REGISTERS) {
11589                         info.reg = REG_UNSET;
11590                 }
11591                 
11592                 reg = REG_UNSET;
11593                 regcm = arch_type_to_regcm(state, ins->type);
11594                 do_post_copy = do_pre_copy = 0;
11595
11596                 /* Walk through the uses of ins and check for conflicts */
11597                 for(entry = ins->use; entry; entry = next) {
11598                         struct reg_info rinfo;
11599                         int i;
11600                         next = entry->next;
11601                         i = find_rhs_use(state, entry->member, ins);
11602                         if (i < 0) {
11603                                 continue;
11604                         }
11605                         
11606                         /* Find the users color requirements */
11607                         rinfo = arch_reg_rhs(state, entry->member, i);
11608                         if (rinfo.reg >= MAX_REGISTERS) {
11609                                 rinfo.reg = REG_UNSET;
11610                         }
11611                         
11612                         /* See if I need a pre_copy */
11613                         if (rinfo.reg != REG_UNSET) {
11614                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11615                                         do_pre_copy = 1;
11616                                 }
11617                                 reg = rinfo.reg;
11618                         }
11619                         regcm &= rinfo.regcm;
11620                         regcm = arch_regcm_normalize(state, regcm);
11621                         if (regcm == 0) {
11622                                 do_pre_copy = 1;
11623                         }
11624                         /* Always use pre_copies for constants.
11625                          * They do not take up any registers until a
11626                          * copy places them in one.
11627                          */
11628                         if ((info.reg == REG_UNNEEDED) && 
11629                                 (rinfo.reg != REG_UNNEEDED)) {
11630                                 do_pre_copy = 1;
11631                         }
11632                 }
11633                 do_post_copy =
11634                         !do_pre_copy &&
11635                         (((info.reg != REG_UNSET) && 
11636                                 (reg != REG_UNSET) &&
11637                                 (info.reg != reg)) ||
11638                         ((info.regcm & regcm) == 0));
11639
11640                 reg = info.reg;
11641                 regcm = info.regcm;
11642                 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11643                 for(entry = ins->use; entry; entry = next) {
11644                         struct reg_info rinfo;
11645                         int i;
11646                         next = entry->next;
11647                         i = find_rhs_use(state, entry->member, ins);
11648                         if (i < 0) {
11649                                 continue;
11650                         }
11651                         
11652                         /* Find the users color requirements */
11653                         rinfo = arch_reg_rhs(state, entry->member, i);
11654                         if (rinfo.reg >= MAX_REGISTERS) {
11655                                 rinfo.reg = REG_UNSET;
11656                         }
11657
11658                         /* Now see if it is time to do the pre_copy */
11659                         if (rinfo.reg != REG_UNSET) {
11660                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11661                                         ((regcm & rinfo.regcm) == 0) ||
11662                                         /* Don't let a mandatory coalesce sneak
11663                                          * into a operation that is marked to prevent
11664                                          * coalescing.
11665                                          */
11666                                         ((reg != REG_UNNEEDED) &&
11667                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11668                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11669                                         ) {
11670                                         if (do_pre_copy) {
11671                                                 struct triple *user;
11672                                                 user = entry->member;
11673                                                 if (RHS(user, i) != ins) {
11674                                                         internal_error(state, user, "bad rhs");
11675                                                 }
11676                                                 tmp = pre_copy(state, user, i);
11677                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11678                                                 continue;
11679                                         } else {
11680                                                 do_post_copy = 1;
11681                                         }
11682                                 }
11683                                 reg = rinfo.reg;
11684                         }
11685                         if ((regcm & rinfo.regcm) == 0) {
11686                                 if (do_pre_copy) {
11687                                         struct triple *user;
11688                                         user = entry->member;
11689                                         if (RHS(user, i) != ins) {
11690                                                 internal_error(state, user, "bad rhs");
11691                                         }
11692                                         tmp = pre_copy(state, user, i);
11693                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11694                                         continue;
11695                                 } else {
11696                                         do_post_copy = 1;
11697                                 }
11698                         }
11699                         regcm &= rinfo.regcm;
11700                         
11701                 }
11702                 if (do_post_copy) {
11703                         struct reg_info pre, post;
11704                         tmp = post_copy(state, ins);
11705                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11706                         pre = arch_reg_lhs(state, ins, 0);
11707                         post = arch_reg_lhs(state, tmp, 0);
11708                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11709                                 internal_error(state, tmp, "useless copy");
11710                         }
11711                 }
11712         next:
11713                 ins = ins->next;
11714         } while(ins != first);
11715 }
11716
11717
11718 struct live_range_edge;
11719 struct live_range_def;
11720 struct live_range {
11721         struct live_range_edge *edges;
11722         struct live_range_def *defs;
11723 /* Note. The list pointed to by defs is kept in order.
11724  * That is baring splits in the flow control
11725  * defs dominates defs->next wich dominates defs->next->next
11726  * etc.
11727  */
11728         unsigned color;
11729         unsigned classes;
11730         unsigned degree;
11731         unsigned length;
11732         struct live_range *group_next, **group_prev;
11733 };
11734
11735 struct live_range_edge {
11736         struct live_range_edge *next;
11737         struct live_range *node;
11738 };
11739
11740 struct live_range_def {
11741         struct live_range_def *next;
11742         struct live_range_def *prev;
11743         struct live_range *lr;
11744         struct triple *def;
11745         unsigned orig_id;
11746 };
11747
11748 #define LRE_HASH_SIZE 2048
11749 struct lre_hash {
11750         struct lre_hash *next;
11751         struct live_range *left;
11752         struct live_range *right;
11753 };
11754
11755
11756 struct reg_state {
11757         struct lre_hash *hash[LRE_HASH_SIZE];
11758         struct reg_block *blocks;
11759         struct live_range_def *lrd;
11760         struct live_range *lr;
11761         struct live_range *low, **low_tail;
11762         struct live_range *high, **high_tail;
11763         unsigned defs;
11764         unsigned ranges;
11765         int passes, max_passes;
11766 #define MAX_ALLOCATION_PASSES 100
11767 };
11768
11769
11770
11771 struct print_interference_block_info {
11772         struct reg_state *rstate;
11773         FILE *fp;
11774         int need_edges;
11775 };
11776 static void print_interference_block(
11777         struct compile_state *state, struct block *block, void *arg)
11778
11779 {
11780         struct print_interference_block_info *info = arg;
11781         struct reg_state *rstate = info->rstate;
11782         FILE *fp = info->fp;
11783         struct reg_block *rb;
11784         struct triple *ptr;
11785         int phi_present;
11786         int done;
11787         rb = &rstate->blocks[block->vertex];
11788
11789         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
11790                 block, 
11791                 block->vertex,
11792                 block->left, 
11793                 block->left && block->left->use?block->left->use->member : 0,
11794                 block->right, 
11795                 block->right && block->right->use?block->right->use->member : 0);
11796         if (rb->in) {
11797                 struct triple_reg_set *in_set;
11798                 fprintf(fp, "        in:");
11799                 for(in_set = rb->in; in_set; in_set = in_set->next) {
11800                         fprintf(fp, " %-10p", in_set->member);
11801                 }
11802                 fprintf(fp, "\n");
11803         }
11804         phi_present = 0;
11805         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11806                 done = (ptr == block->last);
11807                 if (ptr->op == OP_PHI) {
11808                         phi_present = 1;
11809                         break;
11810                 }
11811         }
11812         if (phi_present) {
11813                 int edge;
11814                 for(edge = 0; edge < block->users; edge++) {
11815                         fprintf(fp, "     in(%d):", edge);
11816                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11817                                 struct triple **slot;
11818                                 done = (ptr == block->last);
11819                                 if (ptr->op != OP_PHI) {
11820                                         continue;
11821                                 }
11822                                 slot = &RHS(ptr, 0);
11823                                 fprintf(fp, " %-10p", slot[edge]);
11824                         }
11825                         fprintf(fp, "\n");
11826                 }
11827         }
11828         if (block->first->op == OP_LABEL) {
11829                 fprintf(fp, "%p:\n", block->first);
11830         }
11831         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11832                 struct triple_set *user;
11833                 struct live_range *lr;
11834                 unsigned id;
11835                 int op;
11836                 op = ptr->op;
11837                 done = (ptr == block->last);
11838                 lr = rstate->lrd[ptr->id].lr;
11839                 
11840                 if (triple_stores_block(state, ptr)) {
11841                         if (ptr->u.block != block) {
11842                                 internal_error(state, ptr, 
11843                                         "Wrong block pointer: %p",
11844                                         ptr->u.block);
11845                         }
11846                 }
11847                 if (op == OP_ADECL) {
11848                         for(user = ptr->use; user; user = user->next) {
11849                                 if (!user->member->u.block) {
11850                                         internal_error(state, user->member, 
11851                                                 "Use %p not in a block?",
11852                                                 user->member);
11853                                 }
11854                                 
11855                         }
11856                 }
11857                 id = ptr->id;
11858                 ptr->id = rstate->lrd[id].orig_id;
11859                 SET_REG(ptr->id, lr->color);
11860                 display_triple(fp, ptr);
11861                 ptr->id = id;
11862
11863                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
11864                         internal_error(state, ptr, "lr has no defs!");
11865                 }
11866                 if (info->need_edges) {
11867                         if (lr->defs) {
11868                                 struct live_range_def *lrd;
11869                                 fprintf(fp, "       range:");
11870                                 lrd = lr->defs;
11871                                 do {
11872                                         fprintf(fp, " %-10p", lrd->def);
11873                                         lrd = lrd->next;
11874                                 } while(lrd != lr->defs);
11875                                 fprintf(fp, "\n");
11876                         }
11877                         if (lr->edges > 0) {
11878                                 struct live_range_edge *edge;
11879                                 fprintf(fp, "       edges:");
11880                                 for(edge = lr->edges; edge; edge = edge->next) {
11881                                         struct live_range_def *lrd;
11882                                         lrd = edge->node->defs;
11883                                         do {
11884                                                 fprintf(fp, " %-10p", lrd->def);
11885                                                 lrd = lrd->next;
11886                                         } while(lrd != edge->node->defs);
11887                                         fprintf(fp, "|");
11888                                 }
11889                                 fprintf(fp, "\n");
11890                         }
11891                 }
11892                 /* Do a bunch of sanity checks */
11893                 valid_ins(state, ptr);
11894                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
11895                         internal_error(state, ptr, "Invalid triple id: %d",
11896                                 ptr->id);
11897                 }
11898                 for(user = ptr->use; user; user = user->next) {
11899                         struct triple *use;
11900                         struct live_range *ulr;
11901                         use = user->member;
11902                         valid_ins(state, use);
11903                         if ((use->id < 0) || (use->id > rstate->defs)) {
11904                                 internal_error(state, use, "Invalid triple id: %d",
11905                                         use->id);
11906                         }
11907                         ulr = rstate->lrd[user->member->id].lr;
11908                         if (triple_stores_block(state, user->member) &&
11909                                 !user->member->u.block) {
11910                                 internal_error(state, user->member,
11911                                         "Use %p not in a block?",
11912                                         user->member);
11913                         }
11914                 }
11915         }
11916         if (rb->out) {
11917                 struct triple_reg_set *out_set;
11918                 fprintf(fp, "       out:");
11919                 for(out_set = rb->out; out_set; out_set = out_set->next) {
11920                         fprintf(fp, " %-10p", out_set->member);
11921                 }
11922                 fprintf(fp, "\n");
11923         }
11924         fprintf(fp, "\n");
11925 }
11926
11927 static void print_interference_blocks(
11928         struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
11929 {
11930         struct print_interference_block_info info;
11931         info.rstate = rstate;
11932         info.fp = fp;
11933         info.need_edges = need_edges;
11934         fprintf(fp, "\nlive variables by block\n");
11935         walk_blocks(state, print_interference_block, &info);
11936
11937 }
11938
11939 static unsigned regc_max_size(struct compile_state *state, int classes)
11940 {
11941         unsigned max_size;
11942         int i;
11943         max_size = 0;
11944         for(i = 0; i < MAX_REGC; i++) {
11945                 if (classes & (1 << i)) {
11946                         unsigned size;
11947                         size = arch_regc_size(state, i);
11948                         if (size > max_size) {
11949                                 max_size = size;
11950                         }
11951                 }
11952         }
11953         return max_size;
11954 }
11955
11956 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11957 {
11958         unsigned equivs[MAX_REG_EQUIVS];
11959         int i;
11960         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11961                 internal_error(state, 0, "invalid register");
11962         }
11963         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11964                 internal_error(state, 0, "invalid register");
11965         }
11966         arch_reg_equivs(state, equivs, reg1);
11967         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11968                 if (equivs[i] == reg2) {
11969                         return 1;
11970                 }
11971         }
11972         return 0;
11973 }
11974
11975 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11976 {
11977         unsigned equivs[MAX_REG_EQUIVS];
11978         int i;
11979         if (reg == REG_UNNEEDED) {
11980                 return;
11981         }
11982         arch_reg_equivs(state, equivs, reg);
11983         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11984                 used[equivs[i]] = 1;
11985         }
11986         return;
11987 }
11988
11989 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11990 {
11991         unsigned equivs[MAX_REG_EQUIVS];
11992         int i;
11993         if (reg == REG_UNNEEDED) {
11994                 return;
11995         }
11996         arch_reg_equivs(state, equivs, reg);
11997         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11998                 used[equivs[i]] += 1;
11999         }
12000         return;
12001 }
12002
12003 static unsigned int hash_live_edge(
12004         struct live_range *left, struct live_range *right)
12005 {
12006         unsigned int hash, val;
12007         unsigned long lval, rval;
12008         lval = ((unsigned long)left)/sizeof(struct live_range);
12009         rval = ((unsigned long)right)/sizeof(struct live_range);
12010         hash = 0;
12011         while(lval) {
12012                 val = lval & 0xff;
12013                 lval >>= 8;
12014                 hash = (hash *263) + val;
12015         }
12016         while(rval) {
12017                 val = rval & 0xff;
12018                 rval >>= 8;
12019                 hash = (hash *263) + val;
12020         }
12021         hash = hash & (LRE_HASH_SIZE - 1);
12022         return hash;
12023 }
12024
12025 static struct lre_hash **lre_probe(struct reg_state *rstate,
12026         struct live_range *left, struct live_range *right)
12027 {
12028         struct lre_hash **ptr;
12029         unsigned int index;
12030         /* Ensure left <= right */
12031         if (left > right) {
12032                 struct live_range *tmp;
12033                 tmp = left;
12034                 left = right;
12035                 right = tmp;
12036         }
12037         index = hash_live_edge(left, right);
12038         
12039         ptr = &rstate->hash[index];
12040         while(*ptr) {
12041                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12042                         break;
12043                 }
12044                 ptr = &(*ptr)->next;
12045         }
12046         return ptr;
12047 }
12048
12049 static int interfere(struct reg_state *rstate,
12050         struct live_range *left, struct live_range *right)
12051 {
12052         struct lre_hash **ptr;
12053         ptr = lre_probe(rstate, left, right);
12054         return ptr && *ptr;
12055 }
12056
12057 static void add_live_edge(struct reg_state *rstate, 
12058         struct live_range *left, struct live_range *right)
12059 {
12060         /* FIXME the memory allocation overhead is noticeable here... */
12061         struct lre_hash **ptr, *new_hash;
12062         struct live_range_edge *edge;
12063
12064         if (left == right) {
12065                 return;
12066         }
12067         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12068                 return;
12069         }
12070         /* Ensure left <= right */
12071         if (left > right) {
12072                 struct live_range *tmp;
12073                 tmp = left;
12074                 left = right;
12075                 right = tmp;
12076         }
12077         ptr = lre_probe(rstate, left, right);
12078         if (*ptr) {
12079                 return;
12080         }
12081 #if 0
12082         fprintf(stderr, "new_live_edge(%p, %p)\n",
12083                 left, right);
12084 #endif
12085         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12086         new_hash->next  = *ptr;
12087         new_hash->left  = left;
12088         new_hash->right = right;
12089         *ptr = new_hash;
12090
12091         edge = xmalloc(sizeof(*edge), "live_range_edge");
12092         edge->next   = left->edges;
12093         edge->node   = right;
12094         left->edges  = edge;
12095         left->degree += 1;
12096         
12097         edge = xmalloc(sizeof(*edge), "live_range_edge");
12098         edge->next    = right->edges;
12099         edge->node    = left;
12100         right->edges  = edge;
12101         right->degree += 1;
12102 }
12103
12104 static void remove_live_edge(struct reg_state *rstate,
12105         struct live_range *left, struct live_range *right)
12106 {
12107         struct live_range_edge *edge, **ptr;
12108         struct lre_hash **hptr, *entry;
12109         hptr = lre_probe(rstate, left, right);
12110         if (!hptr || !*hptr) {
12111                 return;
12112         }
12113         entry = *hptr;
12114         *hptr = entry->next;
12115         xfree(entry);
12116
12117         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12118                 edge = *ptr;
12119                 if (edge->node == right) {
12120                         *ptr = edge->next;
12121                         memset(edge, 0, sizeof(*edge));
12122                         xfree(edge);
12123                         right->degree--;
12124                         break;
12125                 }
12126         }
12127         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12128                 edge = *ptr;
12129                 if (edge->node == left) {
12130                         *ptr = edge->next;
12131                         memset(edge, 0, sizeof(*edge));
12132                         xfree(edge);
12133                         left->degree--;
12134                         break;
12135                 }
12136         }
12137 }
12138
12139 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12140 {
12141         struct live_range_edge *edge, *next;
12142         for(edge = range->edges; edge; edge = next) {
12143                 next = edge->next;
12144                 remove_live_edge(rstate, range, edge->node);
12145         }
12146 }
12147
12148 static void transfer_live_edges(struct reg_state *rstate, 
12149         struct live_range *dest, struct live_range *src)
12150 {
12151         struct live_range_edge *edge, *next;
12152         for(edge = src->edges; edge; edge = next) {
12153                 struct live_range *other;
12154                 next = edge->next;
12155                 other = edge->node;
12156                 remove_live_edge(rstate, src, other);
12157                 add_live_edge(rstate, dest, other);
12158         }
12159 }
12160
12161
12162 /* Interference graph...
12163  * 
12164  * new(n) --- Return a graph with n nodes but no edges.
12165  * add(g,x,y) --- Return a graph including g with an between x and y
12166  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12167  *                x and y in the graph g
12168  * degree(g, x) --- Return the degree of the node x in the graph g
12169  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12170  *
12171  * Implement with a hash table && a set of adjcency vectors.
12172  * The hash table supports constant time implementations of add and interfere.
12173  * The adjacency vectors support an efficient implementation of neighbors.
12174  */
12175
12176 /* 
12177  *     +---------------------------------------------------+
12178  *     |         +--------------+                          |
12179  *     v         v              |                          |
12180  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
12181  *
12182  * -- In simplify implment optimistic coloring... (No backtracking)
12183  * -- Implement Rematerialization it is the only form of spilling we can perform
12184  *    Essentially this means dropping a constant from a register because
12185  *    we can regenerate it later.
12186  *
12187  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12188  *     coalesce at phi points...
12189  * --- Bias coloring if at all possible do the coalesing a compile time.
12190  *
12191  *
12192  */
12193
12194 static void different_colored(
12195         struct compile_state *state, struct reg_state *rstate, 
12196         struct triple *parent, struct triple *ins)
12197 {
12198         struct live_range *lr;
12199         struct triple **expr;
12200         lr = rstate->lrd[ins->id].lr;
12201         expr = triple_rhs(state, ins, 0);
12202         for(;expr; expr = triple_rhs(state, ins, expr)) {
12203                 struct live_range *lr2;
12204                 if (!*expr || (*expr == parent) || (*expr == ins)) {
12205                         continue;
12206                 }
12207                 lr2 = rstate->lrd[(*expr)->id].lr;
12208                 if (lr->color == lr2->color) {
12209                         internal_error(state, ins, "live range too big");
12210                 }
12211         }
12212 }
12213
12214
12215 static struct live_range *coalesce_ranges(
12216         struct compile_state *state, struct reg_state *rstate,
12217         struct live_range *lr1, struct live_range *lr2)
12218 {
12219         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12220         unsigned color;
12221         unsigned classes;
12222         if (lr1 == lr2) {
12223                 return lr1;
12224         }
12225         if (!lr1->defs || !lr2->defs) {
12226                 internal_error(state, 0,
12227                         "cannot coalese dead live ranges");
12228         }
12229         if ((lr1->color == REG_UNNEEDED) ||
12230                 (lr2->color == REG_UNNEEDED)) {
12231                 internal_error(state, 0, 
12232                         "cannot coalesce live ranges without a possible color");
12233         }
12234         if ((lr1->color != lr2->color) &&
12235                 (lr1->color != REG_UNSET) &&
12236                 (lr2->color != REG_UNSET)) {
12237                 internal_error(state, lr1->defs->def, 
12238                         "cannot coalesce live ranges of different colors");
12239         }
12240         color = lr1->color;
12241         if (color == REG_UNSET) {
12242                 color = lr2->color;
12243         }
12244         classes = lr1->classes & lr2->classes;
12245         if (!classes) {
12246                 internal_error(state, lr1->defs->def,
12247                         "cannot coalesce live ranges with dissimilar register classes");
12248         }
12249 #if DEBUG_COALESCING
12250         fprintf(stderr, "coalescing:");
12251         lrd = lr1->defs;
12252         do {
12253                 fprintf(stderr, " %p", lrd->def);
12254                 lrd = lrd->next;
12255         } while(lrd != lr1->defs);
12256         fprintf(stderr, " |");
12257         lrd = lr2->defs;
12258         do {
12259                 fprintf(stderr, " %p", lrd->def);
12260                 lrd = lrd->next;
12261         } while(lrd != lr2->defs);
12262         fprintf(stderr, "\n");
12263 #endif
12264         /* If there is a clear dominate live range put it in lr1,
12265          * For purposes of this test phi functions are
12266          * considered dominated by the definitions that feed into
12267          * them. 
12268          */
12269         if ((lr1->defs->prev->def->op == OP_PHI) ||
12270                 ((lr2->defs->prev->def->op != OP_PHI) &&
12271                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12272                 struct live_range *tmp;
12273                 tmp = lr1;
12274                 lr1 = lr2;
12275                 lr2 = tmp;
12276         }
12277 #if 0
12278         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12279                 fprintf(stderr, "lr1 post\n");
12280         }
12281         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12282                 fprintf(stderr, "lr1 pre\n");
12283         }
12284         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12285                 fprintf(stderr, "lr2 post\n");
12286         }
12287         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12288                 fprintf(stderr, "lr2 pre\n");
12289         }
12290 #endif
12291 #if 0
12292         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12293                 lr1->defs->def,
12294                 lr1->color,
12295                 lr2->defs->def,
12296                 lr2->color);
12297 #endif
12298         
12299         /* Append lr2 onto lr1 */
12300 #warning "FIXME should this be a merge instead of a splice?"
12301         /* This FIXME item applies to the correctness of live_range_end 
12302          * and to the necessity of making multiple passes of coalesce_live_ranges.
12303          * A failure to find some coalesce opportunities in coaleace_live_ranges
12304          * does not impact the correct of the compiler just the efficiency with
12305          * which registers are allocated.
12306          */
12307         head = lr1->defs;
12308         mid1 = lr1->defs->prev;
12309         mid2 = lr2->defs;
12310         end  = lr2->defs->prev;
12311         
12312         head->prev = end;
12313         end->next  = head;
12314
12315         mid1->next = mid2;
12316         mid2->prev = mid1;
12317
12318         /* Fixup the live range in the added live range defs */
12319         lrd = head;
12320         do {
12321                 lrd->lr = lr1;
12322                 lrd = lrd->next;
12323         } while(lrd != head);
12324
12325         /* Mark lr2 as free. */
12326         lr2->defs = 0;
12327         lr2->color = REG_UNNEEDED;
12328         lr2->classes = 0;
12329
12330         if (!lr1->defs) {
12331                 internal_error(state, 0, "lr1->defs == 0 ?");
12332         }
12333
12334         lr1->color   = color;
12335         lr1->classes = classes;
12336
12337         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12338         transfer_live_edges(rstate, lr1, lr2);
12339
12340         return lr1;
12341 }
12342
12343 static struct live_range_def *live_range_head(
12344         struct compile_state *state, struct live_range *lr,
12345         struct live_range_def *last)
12346 {
12347         struct live_range_def *result;
12348         result = 0;
12349         if (last == 0) {
12350                 result = lr->defs;
12351         }
12352         else if (!tdominates(state, lr->defs->def, last->next->def)) {
12353                 result = last->next;
12354         }
12355         return result;
12356 }
12357
12358 static struct live_range_def *live_range_end(
12359         struct compile_state *state, struct live_range *lr,
12360         struct live_range_def *last)
12361 {
12362         struct live_range_def *result;
12363         result = 0;
12364         if (last == 0) {
12365                 result = lr->defs->prev;
12366         }
12367         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12368                 result = last->prev;
12369         }
12370         return result;
12371 }
12372
12373
12374 static void initialize_live_ranges(
12375         struct compile_state *state, struct reg_state *rstate)
12376 {
12377         struct triple *ins, *first;
12378         size_t count, size;
12379         int i, j;
12380
12381         first = RHS(state->main_function, 0);
12382         /* First count how many instructions I have.
12383          */
12384         count = count_triples(state);
12385         /* Potentially I need one live range definitions for each
12386          * instruction.
12387          */
12388         rstate->defs = count;
12389         /* Potentially I need one live range for each instruction
12390          * plus an extra for the dummy live range.
12391          */
12392         rstate->ranges = count + 1;
12393         size = sizeof(rstate->lrd[0]) * rstate->defs;
12394         rstate->lrd = xcmalloc(size, "live_range_def");
12395         size = sizeof(rstate->lr[0]) * rstate->ranges;
12396         rstate->lr  = xcmalloc(size, "live_range");
12397
12398         /* Setup the dummy live range */
12399         rstate->lr[0].classes = 0;
12400         rstate->lr[0].color = REG_UNSET;
12401         rstate->lr[0].defs = 0;
12402         i = j = 0;
12403         ins = first;
12404         do {
12405                 /* If the triple is a variable give it a live range */
12406                 if (triple_is_def(state, ins)) {
12407                         struct reg_info info;
12408                         /* Find the architecture specific color information */
12409                         info = find_def_color(state, ins);
12410                         i++;
12411                         rstate->lr[i].defs    = &rstate->lrd[j];
12412                         rstate->lr[i].color   = info.reg;
12413                         rstate->lr[i].classes = info.regcm;
12414                         rstate->lr[i].degree  = 0;
12415                         rstate->lrd[j].lr = &rstate->lr[i];
12416                 } 
12417                 /* Otherwise give the triple the dummy live range. */
12418                 else {
12419                         rstate->lrd[j].lr = &rstate->lr[0];
12420                 }
12421
12422                 /* Initalize the live_range_def */
12423                 rstate->lrd[j].next    = &rstate->lrd[j];
12424                 rstate->lrd[j].prev    = &rstate->lrd[j];
12425                 rstate->lrd[j].def     = ins;
12426                 rstate->lrd[j].orig_id = ins->id;
12427                 ins->id = j;
12428
12429                 j++;
12430                 ins = ins->next;
12431         } while(ins != first);
12432         rstate->ranges = i;
12433
12434         /* Make a second pass to handle achitecture specific register
12435          * constraints.
12436          */
12437         ins = first;
12438         do {
12439                 int zlhs, zrhs, i, j;
12440                 if (ins->id > rstate->defs) {
12441                         internal_error(state, ins, "bad id");
12442                 }
12443                 
12444                 /* Walk through the template of ins and coalesce live ranges */
12445                 zlhs = TRIPLE_LHS(ins->sizes);
12446                 if ((zlhs == 0) && triple_is_def(state, ins)) {
12447                         zlhs = 1;
12448                 }
12449                 zrhs = TRIPLE_RHS(ins->sizes);
12450
12451 #if DEBUG_COALESCING > 1
12452                 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12453                         ins, zlhs, zrhs);
12454                 
12455 #endif          
12456                 for(i = 0; i < zlhs; i++) {
12457                         struct reg_info linfo;
12458                         struct live_range_def *lhs;
12459                         linfo = arch_reg_lhs(state, ins, i);
12460                         if (linfo.reg < MAX_REGISTERS) {
12461                                 continue;
12462                         }
12463                         if (triple_is_def(state, ins)) {
12464                                 lhs = &rstate->lrd[ins->id];
12465                         } else {
12466                                 lhs = &rstate->lrd[LHS(ins, i)->id];
12467                         }
12468 #if DEBUG_COALESCING > 1
12469                         fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12470                                 i, lhs, linfo.reg);
12471                 
12472 #endif          
12473                         for(j = 0; j < zrhs; j++) {
12474                                 struct reg_info rinfo;
12475                                 struct live_range_def *rhs;
12476                                 rinfo = arch_reg_rhs(state, ins, j);
12477                                 if (rinfo.reg < MAX_REGISTERS) {
12478                                         continue;
12479                                 }
12480                                 rhs = &rstate->lrd[RHS(ins, j)->id];
12481 #if DEBUG_COALESCING > 1
12482                                 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12483                                         j, rhs, rinfo.reg);
12484                 
12485 #endif          
12486                                 if (rinfo.reg == linfo.reg) {
12487                                         coalesce_ranges(state, rstate, 
12488                                                 lhs->lr, rhs->lr);
12489                                 }
12490                         }
12491                 }
12492                 ins = ins->next;
12493         } while(ins != first);
12494 }
12495
12496 static void graph_ins(
12497         struct compile_state *state, 
12498         struct reg_block *blocks, struct triple_reg_set *live, 
12499         struct reg_block *rb, struct triple *ins, void *arg)
12500 {
12501         struct reg_state *rstate = arg;
12502         struct live_range *def;
12503         struct triple_reg_set *entry;
12504
12505         /* If the triple is not a definition
12506          * we do not have a definition to add to
12507          * the interference graph.
12508          */
12509         if (!triple_is_def(state, ins)) {
12510                 return;
12511         }
12512         def = rstate->lrd[ins->id].lr;
12513         
12514         /* Create an edge between ins and everything that is
12515          * alive, unless the live_range cannot share
12516          * a physical register with ins.
12517          */
12518         for(entry = live; entry; entry = entry->next) {
12519                 struct live_range *lr;
12520                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12521                         internal_error(state, 0, "bad entry?");
12522                 }
12523                 lr = rstate->lrd[entry->member->id].lr;
12524                 if (def == lr) {
12525                         continue;
12526                 }
12527                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12528                         continue;
12529                 }
12530                 add_live_edge(rstate, def, lr);
12531         }
12532         return;
12533 }
12534
12535 static struct live_range *get_verify_live_range(
12536         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12537 {
12538         struct live_range *lr;
12539         struct live_range_def *lrd;
12540         int ins_found;
12541         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12542                 internal_error(state, ins, "bad ins?");
12543         }
12544         lr = rstate->lrd[ins->id].lr;
12545         ins_found = 0;
12546         lrd = lr->defs;
12547         do {
12548                 if (lrd->def == ins) {
12549                         ins_found = 1;
12550                 }
12551                 lrd = lrd->next;
12552         } while(lrd != lr->defs);
12553         if (!ins_found) {
12554                 internal_error(state, ins, "ins not in live range");
12555         }
12556         return lr;
12557 }
12558
12559 static void verify_graph_ins(
12560         struct compile_state *state, 
12561         struct reg_block *blocks, struct triple_reg_set *live, 
12562         struct reg_block *rb, struct triple *ins, void *arg)
12563 {
12564         struct reg_state *rstate = arg;
12565         struct triple_reg_set *entry1, *entry2;
12566
12567
12568         /* Compare live against edges and make certain the code is working */
12569         for(entry1 = live; entry1; entry1 = entry1->next) {
12570                 struct live_range *lr1;
12571                 lr1 = get_verify_live_range(state, rstate, entry1->member);
12572                 for(entry2 = live; entry2; entry2 = entry2->next) {
12573                         struct live_range *lr2;
12574                         struct live_range_edge *edge2;
12575                         int lr1_found;
12576                         int lr2_degree;
12577                         if (entry2 == entry1) {
12578                                 continue;
12579                         }
12580                         lr2 = get_verify_live_range(state, rstate, entry2->member);
12581                         if (lr1 == lr2) {
12582                                 internal_error(state, entry2->member, 
12583                                         "live range with 2 values simultaneously alive");
12584                         }
12585                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12586                                 continue;
12587                         }
12588                         if (!interfere(rstate, lr1, lr2)) {
12589                                 internal_error(state, entry2->member, 
12590                                         "edges don't interfere?");
12591                         }
12592                                 
12593                         lr1_found = 0;
12594                         lr2_degree = 0;
12595                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12596                                 lr2_degree++;
12597                                 if (edge2->node == lr1) {
12598                                         lr1_found = 1;
12599                                 }
12600                         }
12601                         if (lr2_degree != lr2->degree) {
12602                                 internal_error(state, entry2->member,
12603                                         "computed degree: %d does not match reported degree: %d\n",
12604                                         lr2_degree, lr2->degree);
12605                         }
12606                         if (!lr1_found) {
12607                                 internal_error(state, entry2->member, "missing edge");
12608                         }
12609                 }
12610         }
12611         return;
12612 }
12613
12614
12615 static void print_interference_ins(
12616         struct compile_state *state, 
12617         struct reg_block *blocks, struct triple_reg_set *live, 
12618         struct reg_block *rb, struct triple *ins, void *arg)
12619 {
12620         struct reg_state *rstate = arg;
12621         struct live_range *lr;
12622         unsigned id;
12623
12624         lr = rstate->lrd[ins->id].lr;
12625         id = ins->id;
12626         ins->id = rstate->lrd[id].orig_id;
12627         SET_REG(ins->id, lr->color);
12628         display_triple(stdout, ins);
12629         ins->id = id;
12630
12631         if (lr->defs) {
12632                 struct live_range_def *lrd;
12633                 printf("       range:");
12634                 lrd = lr->defs;
12635                 do {
12636                         printf(" %-10p", lrd->def);
12637                         lrd = lrd->next;
12638                 } while(lrd != lr->defs);
12639                 printf("\n");
12640         }
12641         if (live) {
12642                 struct triple_reg_set *entry;
12643                 printf("        live:");
12644                 for(entry = live; entry; entry = entry->next) {
12645                         printf(" %-10p", entry->member);
12646                 }
12647                 printf("\n");
12648         }
12649         if (lr->edges) {
12650                 struct live_range_edge *entry;
12651                 printf("       edges:");
12652                 for(entry = lr->edges; entry; entry = entry->next) {
12653                         struct live_range_def *lrd;
12654                         lrd = entry->node->defs;
12655                         do {
12656                                 printf(" %-10p", lrd->def);
12657                                 lrd = lrd->next;
12658                         } while(lrd != entry->node->defs);
12659                         printf("|");
12660                 }
12661                 printf("\n");
12662         }
12663         if (triple_is_branch(state, ins)) {
12664                 printf("\n");
12665         }
12666         return;
12667 }
12668
12669 static int coalesce_live_ranges(
12670         struct compile_state *state, struct reg_state *rstate)
12671 {
12672         /* At the point where a value is moved from one
12673          * register to another that value requires two
12674          * registers, thus increasing register pressure.
12675          * Live range coaleescing reduces the register
12676          * pressure by keeping a value in one register
12677          * longer.
12678          *
12679          * In the case of a phi function all paths leading
12680          * into it must be allocated to the same register
12681          * otherwise the phi function may not be removed.
12682          *
12683          * Forcing a value to stay in a single register
12684          * for an extended period of time does have
12685          * limitations when applied to non homogenous
12686          * register pool.  
12687          *
12688          * The two cases I have identified are:
12689          * 1) Two forced register assignments may
12690          *    collide.
12691          * 2) Registers may go unused because they
12692          *    are only good for storing the value
12693          *    and not manipulating it.
12694          *
12695          * Because of this I need to split live ranges,
12696          * even outside of the context of coalesced live
12697          * ranges.  The need to split live ranges does
12698          * impose some constraints on live range coalescing.
12699          *
12700          * - Live ranges may not be coalesced across phi
12701          *   functions.  This creates a 2 headed live
12702          *   range that cannot be sanely split.
12703          *
12704          * - phi functions (coalesced in initialize_live_ranges) 
12705          *   are handled as pre split live ranges so we will
12706          *   never attempt to split them.
12707          */
12708         int coalesced;
12709         int i;
12710
12711         coalesced = 0;
12712         for(i = 0; i <= rstate->ranges; i++) {
12713                 struct live_range *lr1;
12714                 struct live_range_def *lrd1;
12715                 lr1 = &rstate->lr[i];
12716                 if (!lr1->defs) {
12717                         continue;
12718                 }
12719                 lrd1 = live_range_end(state, lr1, 0);
12720                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12721                         struct triple_set *set;
12722                         if (lrd1->def->op != OP_COPY) {
12723                                 continue;
12724                         }
12725                         /* Skip copies that are the result of a live range split. */
12726                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12727                                 continue;
12728                         }
12729                         for(set = lrd1->def->use; set; set = set->next) {
12730                                 struct live_range_def *lrd2;
12731                                 struct live_range *lr2, *res;
12732
12733                                 lrd2 = &rstate->lrd[set->member->id];
12734
12735                                 /* Don't coalesce with instructions
12736                                  * that are the result of a live range
12737                                  * split.
12738                                  */
12739                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12740                                         continue;
12741                                 }
12742                                 lr2 = rstate->lrd[set->member->id].lr;
12743                                 if (lr1 == lr2) {
12744                                         continue;
12745                                 }
12746                                 if ((lr1->color != lr2->color) &&
12747                                         (lr1->color != REG_UNSET) &&
12748                                         (lr2->color != REG_UNSET)) {
12749                                         continue;
12750                                 }
12751                                 if ((lr1->classes & lr2->classes) == 0) {
12752                                         continue;
12753                                 }
12754                                 
12755                                 if (interfere(rstate, lr1, lr2)) {
12756                                         continue;
12757                                 }
12758
12759                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12760                                 coalesced += 1;
12761                                 if (res != lr1) {
12762                                         goto next;
12763                                 }
12764                         }
12765                 }
12766         next:
12767                 ;
12768         }
12769         return coalesced;
12770 }
12771
12772
12773 static void fix_coalesce_conflicts(struct compile_state *state,
12774         struct reg_block *blocks, struct triple_reg_set *live,
12775         struct reg_block *rb, struct triple *ins, void *arg)
12776 {
12777         int *conflicts = arg;
12778         int zlhs, zrhs, i, j;
12779
12780         /* See if we have a mandatory coalesce operation between
12781          * a lhs and a rhs value.  If so and the rhs value is also
12782          * alive then this triple needs to be pre copied.  Otherwise
12783          * we would have two definitions in the same live range simultaneously
12784          * alive.
12785          */
12786         zlhs = TRIPLE_LHS(ins->sizes);
12787         if ((zlhs == 0) && triple_is_def(state, ins)) {
12788                 zlhs = 1;
12789         }
12790         zrhs = TRIPLE_RHS(ins->sizes);
12791         for(i = 0; i < zlhs; i++) {
12792                 struct reg_info linfo;
12793                 linfo = arch_reg_lhs(state, ins, i);
12794                 if (linfo.reg < MAX_REGISTERS) {
12795                         continue;
12796                 }
12797                 for(j = 0; j < zrhs; j++) {
12798                         struct reg_info rinfo;
12799                         struct triple *rhs;
12800                         struct triple_reg_set *set;
12801                         int found;
12802                         found = 0;
12803                         rinfo = arch_reg_rhs(state, ins, j);
12804                         if (rinfo.reg != linfo.reg) {
12805                                 continue;
12806                         }
12807                         rhs = RHS(ins, j);
12808                         for(set = live; set && !found; set = set->next) {
12809                                 if (set->member == rhs) {
12810                                         found = 1;
12811                                 }
12812                         }
12813                         if (found) {
12814                                 struct triple *copy;
12815                                 copy = pre_copy(state, ins, j);
12816                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12817                                 (*conflicts)++;
12818                         }
12819                 }
12820         }
12821         return;
12822 }
12823
12824 static int correct_coalesce_conflicts(
12825         struct compile_state *state, struct reg_block *blocks)
12826 {
12827         int conflicts;
12828         conflicts = 0;
12829         walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
12830         return conflicts;
12831 }
12832
12833 static void replace_set_use(struct compile_state *state,
12834         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12835 {
12836         struct triple_reg_set *set;
12837         for(set = head; set; set = set->next) {
12838                 if (set->member == orig) {
12839                         set->member = new;
12840                 }
12841         }
12842 }
12843
12844 static void replace_block_use(struct compile_state *state, 
12845         struct reg_block *blocks, struct triple *orig, struct triple *new)
12846 {
12847         int i;
12848 #warning "WISHLIST visit just those blocks that need it *"
12849         for(i = 1; i <= state->last_vertex; i++) {
12850                 struct reg_block *rb;
12851                 rb = &blocks[i];
12852                 replace_set_use(state, rb->in, orig, new);
12853                 replace_set_use(state, rb->out, orig, new);
12854         }
12855 }
12856
12857 static void color_instructions(struct compile_state *state)
12858 {
12859         struct triple *ins, *first;
12860         first = RHS(state->main_function, 0);
12861         ins = first;
12862         do {
12863                 if (triple_is_def(state, ins)) {
12864                         struct reg_info info;
12865                         info = find_lhs_color(state, ins, 0);
12866                         if (info.reg >= MAX_REGISTERS) {
12867                                 info.reg = REG_UNSET;
12868                         }
12869                         SET_INFO(ins->id, info);
12870                 }
12871                 ins = ins->next;
12872         } while(ins != first);
12873 }
12874
12875 static struct reg_info read_lhs_color(
12876         struct compile_state *state, struct triple *ins, int index)
12877 {
12878         struct reg_info info;
12879         if ((index == 0) && triple_is_def(state, ins)) {
12880                 info.reg   = ID_REG(ins->id);
12881                 info.regcm = ID_REGCM(ins->id);
12882         }
12883         else if (index < TRIPLE_LHS(ins->sizes)) {
12884                 info = read_lhs_color(state, LHS(ins, index), 0);
12885         }
12886         else {
12887                 internal_error(state, ins, "Bad lhs %d", index);
12888                 info.reg = REG_UNSET;
12889                 info.regcm = 0;
12890         }
12891         return info;
12892 }
12893
12894 static struct triple *resolve_tangle(
12895         struct compile_state *state, struct triple *tangle)
12896 {
12897         struct reg_info info, uinfo;
12898         struct triple_set *set, *next;
12899         struct triple *copy;
12900
12901 #warning "WISHLIST recalculate all affected instructions colors"
12902         info = find_lhs_color(state, tangle, 0);
12903         for(set = tangle->use; set; set = next) {
12904                 struct triple *user;
12905                 int i, zrhs;
12906                 next = set->next;
12907                 user = set->member;
12908                 zrhs = TRIPLE_RHS(user->sizes);
12909                 for(i = 0; i < zrhs; i++) {
12910                         if (RHS(user, i) != tangle) {
12911                                 continue;
12912                         }
12913                         uinfo = find_rhs_post_color(state, user, i);
12914                         if (uinfo.reg == info.reg) {
12915                                 copy = pre_copy(state, user, i);
12916                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12917                                 SET_INFO(copy->id, uinfo);
12918                         }
12919                 }
12920         }
12921         copy = 0;
12922         uinfo = find_lhs_pre_color(state, tangle, 0);
12923         if (uinfo.reg == info.reg) {
12924                 struct reg_info linfo;
12925                 copy = post_copy(state, tangle);
12926                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12927                 linfo = find_lhs_color(state, copy, 0);
12928                 SET_INFO(copy->id, linfo);
12929         }
12930         info = find_lhs_color(state, tangle, 0);
12931         SET_INFO(tangle->id, info);
12932         
12933         return copy;
12934 }
12935
12936
12937 static void fix_tangles(struct compile_state *state,
12938         struct reg_block *blocks, struct triple_reg_set *live,
12939         struct reg_block *rb, struct triple *ins, void *arg)
12940 {
12941         int *tangles = arg;
12942         struct triple *tangle;
12943         do {
12944                 char used[MAX_REGISTERS];
12945                 struct triple_reg_set *set;
12946                 tangle = 0;
12947
12948                 /* Find out which registers have multiple uses at this point */
12949                 memset(used, 0, sizeof(used));
12950                 for(set = live; set; set = set->next) {
12951                         struct reg_info info;
12952                         info = read_lhs_color(state, set->member, 0);
12953                         if (info.reg == REG_UNSET) {
12954                                 continue;
12955                         }
12956                         reg_inc_used(state, used, info.reg);
12957                 }
12958                 
12959                 /* Now find the least dominated definition of a register in
12960                  * conflict I have seen so far.
12961                  */
12962                 for(set = live; set; set = set->next) {
12963                         struct reg_info info;
12964                         info = read_lhs_color(state, set->member, 0);
12965                         if (used[info.reg] < 2) {
12966                                 continue;
12967                         }
12968                         /* Changing copies that feed into phi functions
12969                          * is incorrect.
12970                          */
12971                         if (set->member->use && 
12972                                 (set->member->use->member->op == OP_PHI)) {
12973                                 continue;
12974                         }
12975                         if (!tangle || tdominates(state, set->member, tangle)) {
12976                                 tangle = set->member;
12977                         }
12978                 }
12979                 /* If I have found a tangle resolve it */
12980                 if (tangle) {
12981                         struct triple *post_copy;
12982                         (*tangles)++;
12983                         post_copy = resolve_tangle(state, tangle);
12984                         if (post_copy) {
12985                                 replace_block_use(state, blocks, tangle, post_copy);
12986                         }
12987                         if (post_copy && (tangle != ins)) {
12988                                 replace_set_use(state, live, tangle, post_copy);
12989                         }
12990                 }
12991         } while(tangle);
12992         return;
12993 }
12994
12995 static int correct_tangles(
12996         struct compile_state *state, struct reg_block *blocks)
12997 {
12998         int tangles;
12999         tangles = 0;
13000         color_instructions(state);
13001         walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13002         return tangles;
13003 }
13004
13005
13006 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13007 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13008
13009 struct triple *find_constrained_def(
13010         struct compile_state *state, struct live_range *range, struct triple *constrained)
13011 {
13012         struct live_range_def *lrd;
13013         lrd = range->defs;
13014         do {
13015                 struct reg_info info;
13016                 unsigned regcm;
13017                 int is_constrained;
13018                 regcm = arch_type_to_regcm(state, lrd->def->type);
13019                 info = find_lhs_color(state, lrd->def, 0);
13020                 regcm      = arch_regcm_reg_normalize(state, regcm);
13021                 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13022                 /* If the 2 register class masks are not equal the
13023                  * the current register class is constrained.
13024                  */
13025                 is_constrained = regcm != info.regcm;
13026                 
13027                 /* Of the constrained live ranges deal with the
13028                  * least dominated one first.
13029                  */
13030                 if (is_constrained) {
13031                         if (!constrained || 
13032                                 tdominates(state, lrd->def, constrained))
13033                         {
13034                                 constrained = lrd->def;
13035                         }
13036                 }
13037                 lrd = lrd->next;
13038         } while(lrd != range->defs);
13039         return constrained;
13040 }
13041
13042 static int split_constrained_ranges(
13043         struct compile_state *state, struct reg_state *rstate, 
13044         struct live_range *range)
13045 {
13046         /* Walk through the edges in conflict and our current live
13047          * range, and find definitions that are more severly constrained
13048          * than they type of data they contain require.
13049          * 
13050          * Then pick one of those ranges and relax the constraints.
13051          */
13052         struct live_range_edge *edge;
13053         struct triple *constrained;
13054
13055         constrained = 0;
13056         for(edge = range->edges; edge; edge = edge->next) {
13057                 constrained = find_constrained_def(state, edge->node, constrained);
13058         }
13059         if (!constrained) {
13060                 constrained = find_constrained_def(state, range, constrained);
13061         }
13062 #if DEBUG_RANGE_CONFLICTS
13063         fprintf(stderr, "constrained: %s %p\n",
13064                 tops(constrained->op), constrained);
13065 #endif
13066         if (constrained) {
13067                 ids_from_rstate(state, rstate);
13068                 cleanup_rstate(state, rstate);
13069                 resolve_tangle(state, constrained);
13070         }
13071         return !!constrained;
13072 }
13073         
13074 static int split_ranges(
13075         struct compile_state *state, struct reg_state *rstate,
13076         char *used, struct live_range *range)
13077 {
13078         int split;
13079 #if DEBUG_RANGE_CONFLICTS
13080         fprintf(stderr, "split_ranges %d %s %p\n", 
13081                 rstate->passes, tops(range->defs->def->op), range->defs->def);
13082 #endif
13083         if ((range->color == REG_UNNEEDED) ||
13084                 (rstate->passes >= rstate->max_passes)) {
13085                 return 0;
13086         }
13087         split = split_constrained_ranges(state, rstate, range);
13088
13089         /* Ideally I would split the live range that will not be used
13090          * for the longest period of time in hopes that this will 
13091          * (a) allow me to spill a register or
13092          * (b) allow me to place a value in another register.
13093          *
13094          * So far I don't have a test case for this, the resolving
13095          * of mandatory constraints has solved all of my
13096          * know issues.  So I have choosen not to write any
13097          * code until I cat get a better feel for cases where
13098          * it would be useful to have.
13099          *
13100          */
13101 #warning "WISHLIST implement live range splitting..."
13102         if ((DEBUG_RANGE_CONFLICTS > 1) && 
13103                 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13104                 print_interference_blocks(state, rstate, stderr, 0);
13105                 print_dominators(state, stderr);
13106         }
13107         return split;
13108 }
13109
13110
13111 #if DEBUG_COLOR_GRAPH > 1
13112 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13113 #define cgdebug_flush() fflush(stdout)
13114 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13115 #elif DEBUG_COLOR_GRAPH == 1
13116 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13117 #define cgdebug_flush() fflush(stderr)
13118 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13119 #else
13120 #define cgdebug_printf(...)
13121 #define cgdebug_flush()
13122 #define cgdebug_loc(STATE, TRIPLE)
13123 #endif
13124
13125         
13126 static int select_free_color(struct compile_state *state, 
13127         struct reg_state *rstate, struct live_range *range)
13128 {
13129         struct triple_set *entry;
13130         struct live_range_def *lrd;
13131         struct live_range_def *phi;
13132         struct live_range_edge *edge;
13133         char used[MAX_REGISTERS];
13134         struct triple **expr;
13135
13136         /* Instead of doing just the trivial color select here I try
13137          * a few extra things because a good color selection will help reduce
13138          * copies.
13139          */
13140
13141         /* Find the registers currently in use */
13142         memset(used, 0, sizeof(used));
13143         for(edge = range->edges; edge; edge = edge->next) {
13144                 if (edge->node->color == REG_UNSET) {
13145                         continue;
13146                 }
13147                 reg_fill_used(state, used, edge->node->color);
13148         }
13149 #if DEBUG_COLOR_GRAPH > 1
13150         {
13151                 int i;
13152                 i = 0;
13153                 for(edge = range->edges; edge; edge = edge->next) {
13154                         i++;
13155                 }
13156                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
13157                         tops(range->def->op), i, 
13158                         range->def->filename, range->def->line, range->def->col);
13159                 for(i = 0; i < MAX_REGISTERS; i++) {
13160                         if (used[i]) {
13161                                 cgdebug_printf("used: %s\n",
13162                                         arch_reg_str(i));
13163                         }
13164                 }
13165         }       
13166 #endif
13167
13168 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13169
13170         /* If a color is already assigned see if it will work */
13171         if (range->color != REG_UNSET) {
13172                 struct live_range_def *lrd;
13173                 if (!used[range->color]) {
13174                         return 1;
13175                 }
13176                 for(edge = range->edges; edge; edge = edge->next) {
13177                         if (edge->node->color != range->color) {
13178                                 continue;
13179                         }
13180                         warning(state, edge->node->defs->def, "edge: ");
13181                         lrd = edge->node->defs;
13182                         do {
13183                                 warning(state, lrd->def, " %p %s",
13184                                         lrd->def, tops(lrd->def->op));
13185                                 lrd = lrd->next;
13186                         } while(lrd != edge->node->defs);
13187                 }
13188                 lrd = range->defs;
13189                 warning(state, range->defs->def, "def: ");
13190                 do {
13191                         warning(state, lrd->def, " %p %s",
13192                                 lrd->def, tops(lrd->def->op));
13193                         lrd = lrd->next;
13194                 } while(lrd != range->defs);
13195                 internal_error(state, range->defs->def,
13196                         "live range with already used color %s",
13197                         arch_reg_str(range->color));
13198         }
13199
13200         /* If I feed into an expression reuse it's color.
13201          * This should help remove copies in the case of 2 register instructions
13202          * and phi functions.
13203          */
13204         phi = 0;
13205         lrd = live_range_end(state, range, 0);
13206         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13207                 entry = lrd->def->use;
13208                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13209                         struct live_range_def *insd;
13210                         insd = &rstate->lrd[entry->member->id];
13211                         if (insd->lr->defs == 0) {
13212                                 continue;
13213                         }
13214                         if (!phi && (insd->def->op == OP_PHI) &&
13215                                 !interfere(rstate, range, insd->lr)) {
13216                                 phi = insd;
13217                         }
13218                         if ((insd->lr->color == REG_UNSET) ||
13219                                 ((insd->lr->classes & range->classes) == 0) ||
13220                                 (used[insd->lr->color])) {
13221                                 continue;
13222                         }
13223                         if (interfere(rstate, range, insd->lr)) {
13224                                 continue;
13225                         }
13226                         range->color = insd->lr->color;
13227                 }
13228         }
13229         /* If I feed into a phi function reuse it's color or the color
13230          * of something else that feeds into the phi function.
13231          */
13232         if (phi) {
13233                 if (phi->lr->color != REG_UNSET) {
13234                         if (used[phi->lr->color]) {
13235                                 range->color = phi->lr->color;
13236                         }
13237                 }
13238                 else {
13239                         expr = triple_rhs(state, phi->def, 0);
13240                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13241                                 struct live_range *lr;
13242                                 if (!*expr) {
13243                                         continue;
13244                                 }
13245                                 lr = rstate->lrd[(*expr)->id].lr;
13246                                 if ((lr->color == REG_UNSET) || 
13247                                         ((lr->classes & range->classes) == 0) ||
13248                                         (used[lr->color])) {
13249                                         continue;
13250                                 }
13251                                 if (interfere(rstate, range, lr)) {
13252                                         continue;
13253                                 }
13254                                 range->color = lr->color;
13255                         }
13256                 }
13257         }
13258         /* If I don't interfere with a rhs node reuse it's color */
13259         lrd = live_range_head(state, range, 0);
13260         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13261                 expr = triple_rhs(state, lrd->def, 0);
13262                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13263                         struct live_range *lr;
13264                         if (!*expr) {
13265                                 continue;
13266                         }
13267                         lr = rstate->lrd[(*expr)->id].lr;
13268                         if ((lr->color == -1) || 
13269                                 ((lr->classes & range->classes) == 0) ||
13270                                 (used[lr->color])) {
13271                                 continue;
13272                         }
13273                         if (interfere(rstate, range, lr)) {
13274                                 continue;
13275                         }
13276                         range->color = lr->color;
13277                         break;
13278                 }
13279         }
13280         /* If I have not opportunitically picked a useful color
13281          * pick the first color that is free.
13282          */
13283         if (range->color == REG_UNSET) {
13284                 range->color = 
13285                         arch_select_free_register(state, used, range->classes);
13286         }
13287         if (range->color == REG_UNSET) {
13288                 struct live_range_def *lrd;
13289                 int i;
13290                 if (split_ranges(state, rstate, used, range)) {
13291                         return 0;
13292                 }
13293                 for(edge = range->edges; edge; edge = edge->next) {
13294                         warning(state, edge->node->defs->def, "edge reg %s",
13295                                 arch_reg_str(edge->node->color));
13296                         lrd = edge->node->defs;
13297                         do {
13298                                 warning(state, lrd->def, " %s %p",
13299                                         tops(lrd->def->op), lrd->def);
13300                                 lrd = lrd->next;
13301                         } while(lrd != edge->node->defs);
13302                 }
13303                 warning(state, range->defs->def, "range: ");
13304                 lrd = range->defs;
13305                 do {
13306                         warning(state, lrd->def, " %s %p",
13307                                 tops(lrd->def->op), lrd->def);
13308                         lrd = lrd->next;
13309                 } while(lrd != range->defs);
13310                         
13311                 warning(state, range->defs->def, "classes: %x",
13312                         range->classes);
13313                 for(i = 0; i < MAX_REGISTERS; i++) {
13314                         if (used[i]) {
13315                                 warning(state, range->defs->def, "used: %s",
13316                                         arch_reg_str(i));
13317                         }
13318                 }
13319 #if DEBUG_COLOR_GRAPH < 2
13320                 error(state, range->defs->def, "too few registers");
13321 #else
13322                 internal_error(state, range->defs->def, "too few registers");
13323 #endif
13324         }
13325         range->classes = arch_reg_regcm(state, range->color);
13326         if (range->color == -1) {
13327                 internal_error(state, range->defs->def, "select_free_color did not?");
13328         }
13329         return 1;
13330 }
13331
13332 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13333 {
13334         int colored;
13335         struct live_range_edge *edge;
13336         struct live_range *range;
13337         if (rstate->low) {
13338                 cgdebug_printf("Lo: ");
13339                 range = rstate->low;
13340                 if (*range->group_prev != range) {
13341                         internal_error(state, 0, "lo: *prev != range?");
13342                 }
13343                 *range->group_prev = range->group_next;
13344                 if (range->group_next) {
13345                         range->group_next->group_prev = range->group_prev;
13346                 }
13347                 if (&range->group_next == rstate->low_tail) {
13348                         rstate->low_tail = range->group_prev;
13349                 }
13350                 if (rstate->low == range) {
13351                         internal_error(state, 0, "low: next != prev?");
13352                 }
13353         }
13354         else if (rstate->high) {
13355                 cgdebug_printf("Hi: ");
13356                 range = rstate->high;
13357                 if (*range->group_prev != range) {
13358                         internal_error(state, 0, "hi: *prev != range?");
13359                 }
13360                 *range->group_prev = range->group_next;
13361                 if (range->group_next) {
13362                         range->group_next->group_prev = range->group_prev;
13363                 }
13364                 if (&range->group_next == rstate->high_tail) {
13365                         rstate->high_tail = range->group_prev;
13366                 }
13367                 if (rstate->high == range) {
13368                         internal_error(state, 0, "high: next != prev?");
13369                 }
13370         }
13371         else {
13372                 return 1;
13373         }
13374         cgdebug_printf(" %d\n", range - rstate->lr);
13375         range->group_prev = 0;
13376         for(edge = range->edges; edge; edge = edge->next) {
13377                 struct live_range *node;
13378                 node = edge->node;
13379                 /* Move nodes from the high to the low list */
13380                 if (node->group_prev && (node->color == REG_UNSET) &&
13381                         (node->degree == regc_max_size(state, node->classes))) {
13382                         if (*node->group_prev != node) {
13383                                 internal_error(state, 0, "move: *prev != node?");
13384                         }
13385                         *node->group_prev = node->group_next;
13386                         if (node->group_next) {
13387                                 node->group_next->group_prev = node->group_prev;
13388                         }
13389                         if (&node->group_next == rstate->high_tail) {
13390                                 rstate->high_tail = node->group_prev;
13391                         }
13392                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13393                         node->group_prev  = rstate->low_tail;
13394                         node->group_next  = 0;
13395                         *rstate->low_tail = node;
13396                         rstate->low_tail  = &node->group_next;
13397                         if (*node->group_prev != node) {
13398                                 internal_error(state, 0, "move2: *prev != node?");
13399                         }
13400                 }
13401                 node->degree -= 1;
13402         }
13403         colored = color_graph(state, rstate);
13404         if (colored) {
13405                 cgdebug_printf("Coloring %d @", range - rstate->lr);
13406                 cgdebug_loc(state, range->defs->def);
13407                 cgdebug_flush();
13408                 colored = select_free_color(state, rstate, range);
13409                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13410         }
13411         return colored;
13412 }
13413
13414 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13415 {
13416         struct live_range *lr;
13417         struct live_range_edge *edge;
13418         struct triple *ins, *first;
13419         char used[MAX_REGISTERS];
13420         first = RHS(state->main_function, 0);
13421         ins = first;
13422         do {
13423                 if (triple_is_def(state, ins)) {
13424                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
13425                                 internal_error(state, ins, 
13426                                         "triple without a live range def");
13427                         }
13428                         lr = rstate->lrd[ins->id].lr;
13429                         if (lr->color == REG_UNSET) {
13430                                 internal_error(state, ins,
13431                                         "triple without a color");
13432                         }
13433                         /* Find the registers used by the edges */
13434                         memset(used, 0, sizeof(used));
13435                         for(edge = lr->edges; edge; edge = edge->next) {
13436                                 if (edge->node->color == REG_UNSET) {
13437                                         internal_error(state, 0,
13438                                                 "live range without a color");
13439                         }
13440                                 reg_fill_used(state, used, edge->node->color);
13441                         }
13442                         if (used[lr->color]) {
13443                                 internal_error(state, ins,
13444                                         "triple with already used color");
13445                         }
13446                 }
13447                 ins = ins->next;
13448         } while(ins != first);
13449 }
13450
13451 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13452 {
13453         struct live_range *lr;
13454         struct triple *first, *ins;
13455         first = RHS(state->main_function, 0);
13456         ins = first;
13457         do {
13458                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13459                         internal_error(state, ins, 
13460                                 "triple without a live range");
13461                 }
13462                 lr = rstate->lrd[ins->id].lr;
13463                 SET_REG(ins->id, lr->color);
13464                 ins = ins->next;
13465         } while (ins != first);
13466 }
13467
13468 static struct live_range *merge_sort_lr(
13469         struct live_range *first, struct live_range *last)
13470 {
13471         struct live_range *mid, *join, **join_tail, *pick;
13472         size_t size;
13473         size = (last - first) + 1;
13474         if (size >= 2) {
13475                 mid = first + size/2;
13476                 first = merge_sort_lr(first, mid -1);
13477                 mid   = merge_sort_lr(mid, last);
13478                 
13479                 join = 0;
13480                 join_tail = &join;
13481                 /* merge the two lists */
13482                 while(first && mid) {
13483                         if ((first->degree < mid->degree) ||
13484                                 ((first->degree == mid->degree) &&
13485                                         (first->length < mid->length))) {
13486                                 pick = first;
13487                                 first = first->group_next;
13488                                 if (first) {
13489                                         first->group_prev = 0;
13490                                 }
13491                         }
13492                         else {
13493                                 pick = mid;
13494                                 mid = mid->group_next;
13495                                 if (mid) {
13496                                         mid->group_prev = 0;
13497                                 }
13498                         }
13499                         pick->group_next = 0;
13500                         pick->group_prev = join_tail;
13501                         *join_tail = pick;
13502                         join_tail = &pick->group_next;
13503                 }
13504                 /* Splice the remaining list */
13505                 pick = (first)? first : mid;
13506                 *join_tail = pick;
13507                 if (pick) { 
13508                         pick->group_prev = join_tail;
13509                 }
13510         }
13511         else {
13512                 if (!first->defs) {
13513                         first = 0;
13514                 }
13515                 join = first;
13516         }
13517         return join;
13518 }
13519
13520 static void ids_from_rstate(struct compile_state *state, 
13521         struct reg_state *rstate)
13522 {
13523         struct triple *ins, *first;
13524         if (!rstate->defs) {
13525                 return;
13526         }
13527         /* Display the graph if desired */
13528         if (state->debug & DEBUG_INTERFERENCE) {
13529                 print_blocks(state, stdout);
13530                 print_control_flow(state);
13531         }
13532         first = RHS(state->main_function, 0);
13533         ins = first;
13534         do {
13535                 if (ins->id) {
13536                         struct live_range_def *lrd;
13537                         lrd = &rstate->lrd[ins->id];
13538                         ins->id = lrd->orig_id;
13539                 }
13540                 ins = ins->next;
13541         } while(ins != first);
13542 }
13543
13544 static void cleanup_live_edges(struct reg_state *rstate)
13545 {
13546         int i;
13547         /* Free the edges on each node */
13548         for(i = 1; i <= rstate->ranges; i++) {
13549                 remove_live_edges(rstate, &rstate->lr[i]);
13550         }
13551 }
13552
13553 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13554 {
13555         cleanup_live_edges(rstate);
13556         xfree(rstate->lrd);
13557         xfree(rstate->lr);
13558
13559         /* Free the variable lifetime information */
13560         if (rstate->blocks) {
13561                 free_variable_lifetimes(state, rstate->blocks);
13562         }
13563         rstate->defs = 0;
13564         rstate->ranges = 0;
13565         rstate->lrd = 0;
13566         rstate->lr = 0;
13567         rstate->blocks = 0;
13568 }
13569
13570 static void verify_consistency(struct compile_state *state);
13571 static void allocate_registers(struct compile_state *state)
13572 {
13573         struct reg_state rstate;
13574         int colored;
13575
13576         /* Clear out the reg_state */
13577         memset(&rstate, 0, sizeof(rstate));
13578         rstate.max_passes = MAX_ALLOCATION_PASSES;
13579
13580         do {
13581                 struct live_range **point, **next;
13582                 int conflicts;
13583                 int tangles;
13584                 int coalesced;
13585
13586 #if DEBUG_RANGE_CONFLICTS
13587                 fprintf(stderr, "pass: %d\n", rstate.passes);
13588 #endif
13589
13590                 /* Restore ids */
13591                 ids_from_rstate(state, &rstate);
13592
13593                 /* Cleanup the temporary data structures */
13594                 cleanup_rstate(state, &rstate);
13595
13596                 /* Compute the variable lifetimes */
13597                 rstate.blocks = compute_variable_lifetimes(state);
13598
13599                 /* Fix invalid mandatory live range coalesce conflicts */
13600                 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13601
13602                 /* Fix two simultaneous uses of the same register.
13603                  * In a few pathlogical cases a partial untangle moves
13604                  * the tangle to a part of the graph we won't revisit.
13605                  * So we keep looping until we have no more tangle fixes
13606                  * to apply.
13607                  */
13608                 do {
13609                         tangles = correct_tangles(state, rstate.blocks);
13610                 } while(tangles);
13611
13612                 if (state->debug & DEBUG_INSERTED_COPIES) {
13613                         printf("After resolve_tangles\n");
13614                         print_blocks(state, stdout);
13615                         print_control_flow(state);
13616                 }
13617                 verify_consistency(state);
13618                 
13619                 /* Allocate and initialize the live ranges */
13620                 initialize_live_ranges(state, &rstate);
13621
13622                 /* Note current doing coalescing in a loop appears to 
13623                  * buys me nothing.  The code is left this way in case
13624                  * there is some value in it.  Or if a future bugfix
13625                  *  yields some benefit.
13626                  */
13627                 do {
13628 #if DEBUG_COALESCING
13629                         fprintf(stderr, "coalescing\n");
13630 #endif                  
13631                         /* Remove any previous live edge calculations */
13632                         cleanup_live_edges(&rstate);
13633
13634                         /* Compute the interference graph */
13635                         walk_variable_lifetimes(
13636                                 state, rstate.blocks, graph_ins, &rstate);
13637                         
13638                         /* Display the interference graph if desired */
13639                         if (state->debug & DEBUG_INTERFERENCE) {
13640                                 print_interference_blocks(state, &rstate, stdout, 1);
13641                                 printf("\nlive variables by instruction\n");
13642                                 walk_variable_lifetimes(
13643                                         state, rstate.blocks, 
13644                                         print_interference_ins, &rstate);
13645                         }
13646                         
13647                         coalesced = coalesce_live_ranges(state, &rstate);
13648
13649 #if DEBUG_COALESCING
13650                         fprintf(stderr, "coalesced: %d\n", coalesced);
13651 #endif
13652                 } while(coalesced);
13653
13654 #if DEBUG_CONSISTENCY > 1
13655 # if 0
13656                 fprintf(stderr, "verify_graph_ins...\n");
13657 # endif
13658                 /* Verify the interference graph */
13659                 walk_variable_lifetimes(
13660                         state, rstate.blocks, verify_graph_ins, &rstate);
13661 # if 0
13662                 fprintf(stderr, "verify_graph_ins done\n");
13663 #endif
13664 #endif
13665                         
13666                 /* Build the groups low and high.  But with the nodes
13667                  * first sorted by degree order.
13668                  */
13669                 rstate.low_tail  = &rstate.low;
13670                 rstate.high_tail = &rstate.high;
13671                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13672                 if (rstate.high) {
13673                         rstate.high->group_prev = &rstate.high;
13674                 }
13675                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13676                         ;
13677                 rstate.high_tail = point;
13678                 /* Walk through the high list and move everything that needs
13679                  * to be onto low.
13680                  */
13681                 for(point = &rstate.high; *point; point = next) {
13682                         struct live_range *range;
13683                         next = &(*point)->group_next;
13684                         range = *point;
13685                         
13686                         /* If it has a low degree or it already has a color
13687                          * place the node in low.
13688                          */
13689                         if ((range->degree < regc_max_size(state, range->classes)) ||
13690                                 (range->color != REG_UNSET)) {
13691                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13692                                         range - rstate.lr, range->degree,
13693                                         (range->color != REG_UNSET) ? " (colored)": "");
13694                                 *range->group_prev = range->group_next;
13695                                 if (range->group_next) {
13696                                         range->group_next->group_prev = range->group_prev;
13697                                 }
13698                                 if (&range->group_next == rstate.high_tail) {
13699                                         rstate.high_tail = range->group_prev;
13700                                 }
13701                                 range->group_prev  = rstate.low_tail;
13702                                 range->group_next  = 0;
13703                                 *rstate.low_tail   = range;
13704                                 rstate.low_tail    = &range->group_next;
13705                                 next = point;
13706                         }
13707                         else {
13708                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13709                                         range - rstate.lr, range->degree,
13710                                         (range->color != REG_UNSET) ? " (colored)": "");
13711                         }
13712                 }
13713                 /* Color the live_ranges */
13714                 colored = color_graph(state, &rstate);
13715                 rstate.passes++;
13716         } while (!colored);
13717
13718         /* Verify the graph was properly colored */
13719         verify_colors(state, &rstate);
13720
13721         /* Move the colors from the graph to the triples */
13722         color_triples(state, &rstate);
13723
13724         /* Cleanup the temporary data structures */
13725         cleanup_rstate(state, &rstate);
13726 }
13727
13728 /* Sparce Conditional Constant Propogation
13729  * =========================================
13730  */
13731 struct ssa_edge;
13732 struct flow_block;
13733 struct lattice_node {
13734         unsigned old_id;
13735         struct triple *def;
13736         struct ssa_edge *out;
13737         struct flow_block *fblock;
13738         struct triple *val;
13739         /* lattice high   val && !is_const(val) 
13740          * lattice const  is_const(val)
13741          * lattice low    val == 0
13742          */
13743 };
13744 struct ssa_edge {
13745         struct lattice_node *src;
13746         struct lattice_node *dst;
13747         struct ssa_edge *work_next;
13748         struct ssa_edge *work_prev;
13749         struct ssa_edge *out_next;
13750 };
13751 struct flow_edge {
13752         struct flow_block *src;
13753         struct flow_block *dst;
13754         struct flow_edge *work_next;
13755         struct flow_edge *work_prev;
13756         struct flow_edge *in_next;
13757         struct flow_edge *out_next;
13758         int executable;
13759 };
13760 struct flow_block {
13761         struct block *block;
13762         struct flow_edge *in;
13763         struct flow_edge *out;
13764         struct flow_edge left, right;
13765 };
13766
13767 struct scc_state {
13768         int ins_count;
13769         struct lattice_node *lattice;
13770         struct ssa_edge     *ssa_edges;
13771         struct flow_block   *flow_blocks;
13772         struct flow_edge    *flow_work_list;
13773         struct ssa_edge     *ssa_work_list;
13774 };
13775
13776
13777 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13778         struct flow_edge *fedge)
13779 {
13780         if (!scc->flow_work_list) {
13781                 scc->flow_work_list = fedge;
13782                 fedge->work_next = fedge->work_prev = fedge;
13783         }
13784         else {
13785                 struct flow_edge *ftail;
13786                 ftail = scc->flow_work_list->work_prev;
13787                 fedge->work_next = ftail->work_next;
13788                 fedge->work_prev = ftail;
13789                 fedge->work_next->work_prev = fedge;
13790                 fedge->work_prev->work_next = fedge;
13791         }
13792 }
13793
13794 static struct flow_edge *scc_next_fedge(
13795         struct compile_state *state, struct scc_state *scc)
13796 {
13797         struct flow_edge *fedge;
13798         fedge = scc->flow_work_list;
13799         if (fedge) {
13800                 fedge->work_next->work_prev = fedge->work_prev;
13801                 fedge->work_prev->work_next = fedge->work_next;
13802                 if (fedge->work_next != fedge) {
13803                         scc->flow_work_list = fedge->work_next;
13804                 } else {
13805                         scc->flow_work_list = 0;
13806                 }
13807         }
13808         return fedge;
13809 }
13810
13811 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13812         struct ssa_edge *sedge)
13813 {
13814         if (!scc->ssa_work_list) {
13815                 scc->ssa_work_list = sedge;
13816                 sedge->work_next = sedge->work_prev = sedge;
13817         }
13818         else {
13819                 struct ssa_edge *stail;
13820                 stail = scc->ssa_work_list->work_prev;
13821                 sedge->work_next = stail->work_next;
13822                 sedge->work_prev = stail;
13823                 sedge->work_next->work_prev = sedge;
13824                 sedge->work_prev->work_next = sedge;
13825         }
13826 }
13827
13828 static struct ssa_edge *scc_next_sedge(
13829         struct compile_state *state, struct scc_state *scc)
13830 {
13831         struct ssa_edge *sedge;
13832         sedge = scc->ssa_work_list;
13833         if (sedge) {
13834                 sedge->work_next->work_prev = sedge->work_prev;
13835                 sedge->work_prev->work_next = sedge->work_next;
13836                 if (sedge->work_next != sedge) {
13837                         scc->ssa_work_list = sedge->work_next;
13838                 } else {
13839                         scc->ssa_work_list = 0;
13840                 }
13841         }
13842         return sedge;
13843 }
13844
13845 static void initialize_scc_state(
13846         struct compile_state *state, struct scc_state *scc)
13847 {
13848         int ins_count, ssa_edge_count;
13849         int ins_index, ssa_edge_index, fblock_index;
13850         struct triple *first, *ins;
13851         struct block *block;
13852         struct flow_block *fblock;
13853
13854         memset(scc, 0, sizeof(*scc));
13855
13856         /* Inialize pass zero find out how much memory we need */
13857         first = RHS(state->main_function, 0);
13858         ins = first;
13859         ins_count = ssa_edge_count = 0;
13860         do {
13861                 struct triple_set *edge;
13862                 ins_count += 1;
13863                 for(edge = ins->use; edge; edge = edge->next) {
13864                         ssa_edge_count++;
13865                 }
13866                 ins = ins->next;
13867         } while(ins != first);
13868 #if DEBUG_SCC
13869         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13870                 ins_count, ssa_edge_count, state->last_vertex);
13871 #endif
13872         scc->ins_count   = ins_count;
13873         scc->lattice     = 
13874                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13875         scc->ssa_edges   = 
13876                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13877         scc->flow_blocks = 
13878                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
13879                         "flow_blocks");
13880
13881         /* Initialize pass one collect up the nodes */
13882         fblock = 0;
13883         block = 0;
13884         ins_index = ssa_edge_index = fblock_index = 0;
13885         ins = first;
13886         do {
13887                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13888                         block = ins->u.block;
13889                         if (!block) {
13890                                 internal_error(state, ins, "label without block");
13891                         }
13892                         fblock_index += 1;
13893                         block->vertex = fblock_index;
13894                         fblock = &scc->flow_blocks[fblock_index];
13895                         fblock->block = block;
13896                 }
13897                 {
13898                         struct lattice_node *lnode;
13899                         ins_index += 1;
13900                         lnode = &scc->lattice[ins_index];
13901                         lnode->def = ins;
13902                         lnode->out = 0;
13903                         lnode->fblock = fblock;
13904                         lnode->val = ins; /* LATTICE HIGH */
13905                         lnode->old_id = ins->id;
13906                         ins->id = ins_index;
13907                 }
13908                 ins = ins->next;
13909         } while(ins != first);
13910         /* Initialize pass two collect up the edges */
13911         block = 0;
13912         fblock = 0;
13913         ins = first;
13914         do {
13915                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13916                         struct flow_edge *fedge, **ftail;
13917                         struct block_set *bedge;
13918                         block = ins->u.block;
13919                         fblock = &scc->flow_blocks[block->vertex];
13920                         fblock->in = 0;
13921                         fblock->out = 0;
13922                         ftail = &fblock->out;
13923                         if (block->left) {
13924                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13925                                 if (fblock->left.dst->block != block->left) {
13926                                         internal_error(state, 0, "block mismatch");
13927                                 }
13928                                 fblock->left.out_next = 0;
13929                                 *ftail = &fblock->left;
13930                                 ftail = &fblock->left.out_next;
13931                         }
13932                         if (block->right) {
13933                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13934                                 if (fblock->right.dst->block != block->right) {
13935                                         internal_error(state, 0, "block mismatch");
13936                                 }
13937                                 fblock->right.out_next = 0;
13938                                 *ftail = &fblock->right;
13939                                 ftail = &fblock->right.out_next;
13940                         }
13941                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13942                                 fedge->src = fblock;
13943                                 fedge->work_next = fedge->work_prev = fedge;
13944                                 fedge->executable = 0;
13945                         }
13946                         ftail = &fblock->in;
13947                         for(bedge = block->use; bedge; bedge = bedge->next) {
13948                                 struct block *src_block;
13949                                 struct flow_block *sfblock;
13950                                 struct flow_edge *sfedge;
13951                                 src_block = bedge->member;
13952                                 sfblock = &scc->flow_blocks[src_block->vertex];
13953                                 sfedge = 0;
13954                                 if (src_block->left == block) {
13955                                         sfedge = &sfblock->left;
13956                                 } else {
13957                                         sfedge = &sfblock->right;
13958                                 }
13959                                 *ftail = sfedge;
13960                                 ftail = &sfedge->in_next;
13961                                 sfedge->in_next = 0;
13962                         }
13963                 }
13964                 {
13965                         struct triple_set *edge;
13966                         struct ssa_edge **stail;
13967                         struct lattice_node *lnode;
13968                         lnode = &scc->lattice[ins->id];
13969                         lnode->out = 0;
13970                         stail = &lnode->out;
13971                         for(edge = ins->use; edge; edge = edge->next) {
13972                                 struct ssa_edge *sedge;
13973                                 ssa_edge_index += 1;
13974                                 sedge = &scc->ssa_edges[ssa_edge_index];
13975                                 *stail = sedge;
13976                                 stail = &sedge->out_next;
13977                                 sedge->src = lnode;
13978                                 sedge->dst = &scc->lattice[edge->member->id];
13979                                 sedge->work_next = sedge->work_prev = sedge;
13980                                 sedge->out_next = 0;
13981                         }
13982                 }
13983                 ins = ins->next;
13984         } while(ins != first);
13985         /* Setup a dummy block 0 as a node above the start node */
13986         {
13987                 struct flow_block *fblock, *dst;
13988                 struct flow_edge *fedge;
13989                 fblock = &scc->flow_blocks[0];
13990                 fblock->block = 0;
13991                 fblock->in = 0;
13992                 fblock->out = &fblock->left;
13993                 dst = &scc->flow_blocks[state->first_block->vertex];
13994                 fedge = &fblock->left;
13995                 fedge->src        = fblock;
13996                 fedge->dst        = dst;
13997                 fedge->work_next  = fedge;
13998                 fedge->work_prev  = fedge;
13999                 fedge->in_next    = fedge->dst->in;
14000                 fedge->out_next   = 0;
14001                 fedge->executable = 0;
14002                 fedge->dst->in = fedge;
14003                 
14004                 /* Initialize the work lists */
14005                 scc->flow_work_list = 0;
14006                 scc->ssa_work_list  = 0;
14007                 scc_add_fedge(state, scc, fedge);
14008         }
14009 #if DEBUG_SCC
14010         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14011                 ins_index, ssa_edge_index, fblock_index);
14012 #endif
14013 }
14014
14015         
14016 static void free_scc_state(
14017         struct compile_state *state, struct scc_state *scc)
14018 {
14019         xfree(scc->flow_blocks);
14020         xfree(scc->ssa_edges);
14021         xfree(scc->lattice);
14022         
14023 }
14024
14025 static struct lattice_node *triple_to_lattice(
14026         struct compile_state *state, struct scc_state *scc, struct triple *ins)
14027 {
14028         if (ins->id <= 0) {
14029                 internal_error(state, ins, "bad id");
14030         }
14031         return &scc->lattice[ins->id];
14032 }
14033
14034 static struct triple *preserve_lval(
14035         struct compile_state *state, struct lattice_node *lnode)
14036 {
14037         struct triple *old;
14038         /* Preserve the original value */
14039         if (lnode->val) {
14040                 old = dup_triple(state, lnode->val);
14041                 if (lnode->val != lnode->def) {
14042                         xfree(lnode->val);
14043                 }
14044                 lnode->val = 0;
14045         } else {
14046                 old = 0;
14047         }
14048         return old;
14049 }
14050
14051 static int lval_changed(struct compile_state *state, 
14052         struct triple *old, struct lattice_node *lnode)
14053 {
14054         int changed;
14055         /* See if the lattice value has changed */
14056         changed = 1;
14057         if (!old && !lnode->val) {
14058                 changed = 0;
14059         }
14060         if (changed && lnode->val && !is_const(lnode->val)) {
14061                 changed = 0;
14062         }
14063         if (changed &&
14064                 lnode->val && old &&
14065                 (memcmp(lnode->val->param, old->param,
14066                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14067                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14068                 changed = 0;
14069         }
14070         if (old) {
14071                 xfree(old);
14072         }
14073         return changed;
14074
14075 }
14076
14077 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
14078         struct lattice_node *lnode)
14079 {
14080         struct lattice_node *tmp;
14081         struct triple **slot, *old;
14082         struct flow_edge *fedge;
14083         int index;
14084         if (lnode->def->op != OP_PHI) {
14085                 internal_error(state, lnode->def, "not phi");
14086         }
14087         /* Store the original value */
14088         old = preserve_lval(state, lnode);
14089
14090         /* default to lattice high */
14091         lnode->val = lnode->def;
14092         slot = &RHS(lnode->def, 0);
14093         index = 0;
14094         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14095                 if (!fedge->executable) {
14096                         continue;
14097                 }
14098                 if (!slot[index]) {
14099                         internal_error(state, lnode->def, "no phi value");
14100                 }
14101                 tmp = triple_to_lattice(state, scc, slot[index]);
14102                 /* meet(X, lattice low) = lattice low */
14103                 if (!tmp->val) {
14104                         lnode->val = 0;
14105                 }
14106                 /* meet(X, lattice high) = X */
14107                 else if (!tmp->val) {
14108                         lnode->val = lnode->val;
14109                 }
14110                 /* meet(lattice high, X) = X */
14111                 else if (!is_const(lnode->val)) {
14112                         lnode->val = dup_triple(state, tmp->val);
14113                         lnode->val->type = lnode->def->type;
14114                 }
14115                 /* meet(const, const) = const or lattice low */
14116                 else if (!constants_equal(state, lnode->val, tmp->val)) {
14117                         lnode->val = 0;
14118                 }
14119                 if (!lnode->val) {
14120                         break;
14121                 }
14122         }
14123 #if DEBUG_SCC
14124         fprintf(stderr, "phi: %d -> %s\n",
14125                 lnode->def->id,
14126                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14127 #endif
14128         /* If the lattice value has changed update the work lists. */
14129         if (lval_changed(state, old, lnode)) {
14130                 struct ssa_edge *sedge;
14131                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14132                         scc_add_sedge(state, scc, sedge);
14133                 }
14134         }
14135 }
14136
14137 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14138         struct lattice_node *lnode)
14139 {
14140         int changed;
14141         struct triple *old, *scratch;
14142         struct triple **dexpr, **vexpr;
14143         int count, i;
14144         
14145         /* Store the original value */
14146         old = preserve_lval(state, lnode);
14147
14148         /* Reinitialize the value */
14149         lnode->val = scratch = dup_triple(state, lnode->def);
14150         scratch->id = lnode->old_id;
14151         scratch->next     = scratch;
14152         scratch->prev     = scratch;
14153         scratch->use      = 0;
14154
14155         count = TRIPLE_SIZE(scratch->sizes);
14156         for(i = 0; i < count; i++) {
14157                 dexpr = &lnode->def->param[i];
14158                 vexpr = &scratch->param[i];
14159                 *vexpr = *dexpr;
14160                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14161                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14162                         *dexpr) {
14163                         struct lattice_node *tmp;
14164                         tmp = triple_to_lattice(state, scc, *dexpr);
14165                         *vexpr = (tmp->val)? tmp->val : tmp->def;
14166                 }
14167         }
14168         if (scratch->op == OP_BRANCH) {
14169                 scratch->next = lnode->def->next;
14170         }
14171         /* Recompute the value */
14172 #warning "FIXME see if simplify does anything bad"
14173         /* So far it looks like only the strength reduction
14174          * optimization are things I need to worry about.
14175          */
14176         simplify(state, scratch);
14177         /* Cleanup my value */
14178         if (scratch->use) {
14179                 internal_error(state, lnode->def, "scratch used?");
14180         }
14181         if ((scratch->prev != scratch) ||
14182                 ((scratch->next != scratch) &&
14183                         ((lnode->def->op != OP_BRANCH) ||
14184                                 (scratch->next != lnode->def->next)))) {
14185                 internal_error(state, lnode->def, "scratch in list?");
14186         }
14187         /* undo any uses... */
14188         count = TRIPLE_SIZE(scratch->sizes);
14189         for(i = 0; i < count; i++) {
14190                 vexpr = &scratch->param[i];
14191                 if (*vexpr) {
14192                         unuse_triple(*vexpr, scratch);
14193                 }
14194         }
14195         if (!is_const(scratch)) {
14196                 for(i = 0; i < count; i++) {
14197                         dexpr = &lnode->def->param[i];
14198                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14199                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14200                                 *dexpr) {
14201                                 struct lattice_node *tmp;
14202                                 tmp = triple_to_lattice(state, scc, *dexpr);
14203                                 if (!tmp->val) {
14204                                         lnode->val = 0;
14205                                 }
14206                         }
14207                 }
14208         }
14209         if (lnode->val && 
14210                 (lnode->val->op == lnode->def->op) &&
14211                 (memcmp(lnode->val->param, lnode->def->param, 
14212                         count * sizeof(lnode->val->param[0])) == 0) &&
14213                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14214                 lnode->val = lnode->def;
14215         }
14216         /* Find the cases that are always lattice lo */
14217         if (lnode->val && 
14218                 triple_is_def(state, lnode->val) &&
14219                 !triple_is_pure(state, lnode->val)) {
14220                 lnode->val = 0;
14221         }
14222         if (lnode->val && 
14223                 (lnode->val->op == OP_SDECL) && 
14224                 (lnode->val != lnode->def)) {
14225                 internal_error(state, lnode->def, "bad sdecl");
14226         }
14227         /* See if the lattice value has changed */
14228         changed = lval_changed(state, old, lnode);
14229         if (lnode->val != scratch) {
14230                 xfree(scratch);
14231         }
14232         return changed;
14233 }
14234
14235 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14236         struct lattice_node *lnode)
14237 {
14238         struct lattice_node *cond;
14239 #if DEBUG_SCC
14240         {
14241                 struct flow_edge *fedge;
14242                 fprintf(stderr, "branch: %d (",
14243                         lnode->def->id);
14244                 
14245                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14246                         fprintf(stderr, " %d", fedge->dst->block->vertex);
14247                 }
14248                 fprintf(stderr, " )");
14249                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14250                         fprintf(stderr, " <- %d",
14251                                 RHS(lnode->def, 0)->id);
14252                 }
14253                 fprintf(stderr, "\n");
14254         }
14255 #endif
14256         if (lnode->def->op != OP_BRANCH) {
14257                 internal_error(state, lnode->def, "not branch");
14258         }
14259         /* This only applies to conditional branches */
14260         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14261                 return;
14262         }
14263         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14264         if (cond->val && !is_const(cond->val)) {
14265 #warning "FIXME do I need to do something here?"
14266                 warning(state, cond->def, "condition not constant?");
14267                 return;
14268         }
14269         if (cond->val == 0) {
14270                 scc_add_fedge(state, scc, cond->fblock->out);
14271                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14272         }
14273         else if (cond->val->u.cval) {
14274                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14275                 
14276         } else {
14277                 scc_add_fedge(state, scc, cond->fblock->out);
14278         }
14279
14280 }
14281
14282 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14283         struct lattice_node *lnode)
14284 {
14285         int changed;
14286
14287         changed = compute_lnode_val(state, scc, lnode);
14288 #if DEBUG_SCC
14289         {
14290                 struct triple **expr;
14291                 fprintf(stderr, "expr: %3d %10s (",
14292                         lnode->def->id, tops(lnode->def->op));
14293                 expr = triple_rhs(state, lnode->def, 0);
14294                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14295                         if (*expr) {
14296                                 fprintf(stderr, " %d", (*expr)->id);
14297                         }
14298                 }
14299                 fprintf(stderr, " ) -> %s\n",
14300                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14301         }
14302 #endif
14303         if (lnode->def->op == OP_BRANCH) {
14304                 scc_visit_branch(state, scc, lnode);
14305
14306         }
14307         else if (changed) {
14308                 struct ssa_edge *sedge;
14309                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14310                         scc_add_sedge(state, scc, sedge);
14311                 }
14312         }
14313 }
14314
14315 static void scc_writeback_values(
14316         struct compile_state *state, struct scc_state *scc)
14317 {
14318         struct triple *first, *ins;
14319         first = RHS(state->main_function, 0);
14320         ins = first;
14321         do {
14322                 struct lattice_node *lnode;
14323                 lnode = triple_to_lattice(state, scc, ins);
14324                 /* Restore id */
14325                 ins->id = lnode->old_id;
14326 #if DEBUG_SCC
14327                 if (lnode->val && !is_const(lnode->val)) {
14328                         warning(state, lnode->def, 
14329                                 "lattice node still high?");
14330                 }
14331 #endif
14332                 if (lnode->val && (lnode->val != ins)) {
14333                         /* See if it something I know how to write back */
14334                         switch(lnode->val->op) {
14335                         case OP_INTCONST:
14336                                 mkconst(state, ins, lnode->val->u.cval);
14337                                 break;
14338                         case OP_ADDRCONST:
14339                                 mkaddr_const(state, ins, 
14340                                         MISC(lnode->val, 0), lnode->val->u.cval);
14341                                 break;
14342                         default:
14343                                 /* By default don't copy the changes,
14344                                  * recompute them in place instead.
14345                                  */
14346                                 simplify(state, ins);
14347                                 break;
14348                         }
14349                         if (is_const(lnode->val) &&
14350                                 !constants_equal(state, lnode->val, ins)) {
14351                                 internal_error(state, 0, "constants not equal");
14352                         }
14353                         /* Free the lattice nodes */
14354                         xfree(lnode->val);
14355                         lnode->val = 0;
14356                 }
14357                 ins = ins->next;
14358         } while(ins != first);
14359 }
14360
14361 static void scc_transform(struct compile_state *state)
14362 {
14363         struct scc_state scc;
14364
14365         initialize_scc_state(state, &scc);
14366
14367         while(scc.flow_work_list || scc.ssa_work_list) {
14368                 struct flow_edge *fedge;
14369                 struct ssa_edge *sedge;
14370                 struct flow_edge *fptr;
14371                 while((fedge = scc_next_fedge(state, &scc))) {
14372                         struct block *block;
14373                         struct triple *ptr;
14374                         struct flow_block *fblock;
14375                         int time;
14376                         int done;
14377                         if (fedge->executable) {
14378                                 continue;
14379                         }
14380                         if (!fedge->dst) {
14381                                 internal_error(state, 0, "fedge without dst");
14382                         }
14383                         if (!fedge->src) {
14384                                 internal_error(state, 0, "fedge without src");
14385                         }
14386                         fedge->executable = 1;
14387                         fblock = fedge->dst;
14388                         block = fblock->block;
14389                         time = 0;
14390                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14391                                 if (fptr->executable) {
14392                                         time++;
14393                                 }
14394                         }
14395 #if DEBUG_SCC
14396                         fprintf(stderr, "vertex: %d time: %d\n", 
14397                                 block->vertex, time);
14398                         
14399 #endif
14400                         done = 0;
14401                         for(ptr = block->first; !done; ptr = ptr->next) {
14402                                 struct lattice_node *lnode;
14403                                 done = (ptr == block->last);
14404                                 lnode = &scc.lattice[ptr->id];
14405                                 if (ptr->op == OP_PHI) {
14406                                         scc_visit_phi(state, &scc, lnode);
14407                                 }
14408                                 else if (time == 1) {
14409                                         scc_visit_expr(state, &scc, lnode);
14410                                 }
14411                         }
14412                         if (fblock->out && !fblock->out->out_next) {
14413                                 scc_add_fedge(state, &scc, fblock->out);
14414                         }
14415                 }
14416                 while((sedge = scc_next_sedge(state, &scc))) {
14417                         struct lattice_node *lnode;
14418                         struct flow_block *fblock;
14419                         lnode = sedge->dst;
14420                         fblock = lnode->fblock;
14421 #if DEBUG_SCC
14422                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14423                                 sedge - scc.ssa_edges,
14424                                 sedge->src->def->id,
14425                                 sedge->dst->def->id);
14426 #endif
14427                         if (lnode->def->op == OP_PHI) {
14428                                 scc_visit_phi(state, &scc, lnode);
14429                         }
14430                         else {
14431                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14432                                         if (fptr->executable) {
14433                                                 break;
14434                                         }
14435                                 }
14436                                 if (fptr) {
14437                                         scc_visit_expr(state, &scc, lnode);
14438                                 }
14439                         }
14440                 }
14441         }
14442         
14443         scc_writeback_values(state, &scc);
14444         free_scc_state(state, &scc);
14445 }
14446
14447
14448 static void transform_to_arch_instructions(struct compile_state *state)
14449 {
14450         struct triple *ins, *first;
14451         first = RHS(state->main_function, 0);
14452         ins = first;
14453         do {
14454                 ins = transform_to_arch_instruction(state, ins);
14455         } while(ins != first);
14456 }
14457
14458 #if DEBUG_CONSISTENCY
14459 static void verify_uses(struct compile_state *state)
14460 {
14461         struct triple *first, *ins;
14462         struct triple_set *set;
14463         first = RHS(state->main_function, 0);
14464         ins = first;
14465         do {
14466                 struct triple **expr;
14467                 expr = triple_rhs(state, ins, 0);
14468                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14469                         struct triple *rhs;
14470                         rhs = *expr;
14471                         for(set = rhs?rhs->use:0; set; set = set->next) {
14472                                 if (set->member == ins) {
14473                                         break;
14474                                 }
14475                         }
14476                         if (!set) {
14477                                 internal_error(state, ins, "rhs not used");
14478                         }
14479                 }
14480                 expr = triple_lhs(state, ins, 0);
14481                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14482                         struct triple *lhs;
14483                         lhs = *expr;
14484                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14485                                 if (set->member == ins) {
14486                                         break;
14487                                 }
14488                         }
14489                         if (!set) {
14490                                 internal_error(state, ins, "lhs not used");
14491                         }
14492                 }
14493                 ins = ins->next;
14494         } while(ins != first);
14495         
14496 }
14497 static void verify_blocks_present(struct compile_state *state)
14498 {
14499         struct triple *first, *ins;
14500         if (!state->first_block) {
14501                 return;
14502         }
14503         first = RHS(state->main_function, 0);
14504         ins = first;
14505         do {
14506                 if (triple_stores_block(state, ins)) {
14507                         if (!ins->u.block) {
14508                                 internal_error(state, ins, 
14509                                         "%p not in a block?\n", ins);
14510                         }
14511                 }
14512                 ins = ins->next;
14513         } while(ins != first);
14514         
14515         
14516 }
14517 static void verify_blocks(struct compile_state *state)
14518 {
14519         struct triple *ins;
14520         struct block *block;
14521         block = state->first_block;
14522         if (!block) {
14523                 return;
14524         }
14525         do {
14526                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14527                         if (!triple_stores_block(state, ins)) {
14528                                 continue;
14529                         }
14530                         if (ins->u.block != block) {
14531                                 internal_error(state, ins, "inconsitent block specified");
14532                         }
14533                 }
14534                 if (!triple_stores_block(state, block->last->next)) {
14535                         internal_error(state, block->last->next, 
14536                                 "cannot find next block");
14537                 }
14538                 block = block->last->next->u.block;
14539                 if (!block) {
14540                         internal_error(state, block->last->next,
14541                                 "bad next block");
14542                 }
14543         } while(block != state->first_block);
14544 }
14545
14546 static void verify_domination(struct compile_state *state)
14547 {
14548         struct triple *first, *ins;
14549         struct triple_set *set;
14550         if (!state->first_block) {
14551                 return;
14552         }
14553         
14554         first = RHS(state->main_function, 0);
14555         ins = first;
14556         do {
14557                 for(set = ins->use; set; set = set->next) {
14558                         struct triple **expr;
14559                         if (set->member->op == OP_PHI) {
14560                                 continue;
14561                         }
14562                         /* See if the use is on the righ hand side */
14563                         expr = triple_rhs(state, set->member, 0);
14564                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14565                                 if (*expr == ins) {
14566                                         break;
14567                                 }
14568                         }
14569                         if (expr &&
14570                                 !tdominates(state, ins, set->member)) {
14571                                 internal_error(state, set->member, 
14572                                         "non dominated rhs use?");
14573                         }
14574                 }
14575                 ins = ins->next;
14576         } while(ins != first);
14577 }
14578
14579 static void verify_piece(struct compile_state *state)
14580 {
14581         struct triple *first, *ins;
14582         first = RHS(state->main_function, 0);
14583         ins = first;
14584         do {
14585                 struct triple *ptr;
14586                 int lhs, i;
14587                 lhs = TRIPLE_LHS(ins->sizes);
14588                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14589                         lhs = 0;
14590                 }
14591                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14592                         if (ptr != LHS(ins, i)) {
14593                                 internal_error(state, ins, "malformed lhs on %s",
14594                                         tops(ins->op));
14595                         }
14596                         if (ptr->op != OP_PIECE) {
14597                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14598                                         tops(ptr->op), i, tops(ins->op));
14599                         }
14600                         if (ptr->u.cval != i) {
14601                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14602                                         ptr->u.cval, i);
14603                         }
14604                 }
14605                 ins = ins->next;
14606         } while(ins != first);
14607 }
14608 static void verify_ins_colors(struct compile_state *state)
14609 {
14610         struct triple *first, *ins;
14611         
14612         first = RHS(state->main_function, 0);
14613         ins = first;
14614         do {
14615                 ins = ins->next;
14616         } while(ins != first);
14617 }
14618 static void verify_consistency(struct compile_state *state)
14619 {
14620         verify_uses(state);
14621         verify_blocks_present(state);
14622         verify_blocks(state);
14623         verify_domination(state);
14624         verify_piece(state);
14625         verify_ins_colors(state);
14626 }
14627 #else 
14628 static void verify_consistency(struct compile_state *state) {}
14629 #endif /* DEBUG_USES */
14630
14631 static void optimize(struct compile_state *state)
14632 {
14633         if (state->debug & DEBUG_TRIPLES) {
14634                 print_triples(state);
14635         }
14636         /* Replace structures with simpler data types */
14637         flatten_structures(state);
14638         if (state->debug & DEBUG_TRIPLES) {
14639                 print_triples(state);
14640         }
14641         verify_consistency(state);
14642         /* Analize the intermediate code */
14643         setup_basic_blocks(state);
14644         analyze_idominators(state);
14645         analyze_ipdominators(state);
14646
14647         /* Transform the code to ssa form */
14648         transform_to_ssa_form(state);
14649         verify_consistency(state);
14650         if (state->debug & DEBUG_CODE_ELIMINATION) {
14651                 fprintf(stdout, "After transform_to_ssa_form\n");
14652                 print_blocks(state, stdout);
14653         }
14654         /* Do strength reduction and simple constant optimizations */
14655         if (state->optimize >= 1) {
14656                 simplify_all(state);
14657         }
14658         verify_consistency(state);
14659         /* Propogate constants throughout the code */
14660         if (state->optimize >= 2) {
14661 #warning "FIXME fix scc_transform"
14662                 scc_transform(state);
14663                 transform_from_ssa_form(state);
14664                 free_basic_blocks(state);
14665                 setup_basic_blocks(state);
14666                 analyze_idominators(state);
14667                 analyze_ipdominators(state);
14668                 transform_to_ssa_form(state);
14669         }
14670         verify_consistency(state);
14671 #warning "WISHLIST implement single use constants (least possible register pressure)"
14672 #warning "WISHLIST implement induction variable elimination"
14673         /* Select architecture instructions and an initial partial
14674          * coloring based on architecture constraints.
14675          */
14676         transform_to_arch_instructions(state);
14677         verify_consistency(state);
14678         if (state->debug & DEBUG_ARCH_CODE) {
14679                 printf("After transform_to_arch_instructions\n");
14680                 print_blocks(state, stdout);
14681                 print_control_flow(state);
14682         }
14683         eliminate_inefectual_code(state);
14684         verify_consistency(state);
14685         if (state->debug & DEBUG_CODE_ELIMINATION) {
14686                 printf("After eliminate_inefectual_code\n");
14687                 print_blocks(state, stdout);
14688                 print_control_flow(state);
14689         }
14690         verify_consistency(state);
14691         /* Color all of the variables to see if they will fit in registers */
14692         insert_copies_to_phi(state);
14693         if (state->debug & DEBUG_INSERTED_COPIES) {
14694                 printf("After insert_copies_to_phi\n");
14695                 print_blocks(state, stdout);
14696                 print_control_flow(state);
14697         }
14698         verify_consistency(state);
14699         insert_mandatory_copies(state);
14700         if (state->debug & DEBUG_INSERTED_COPIES) {
14701                 printf("After insert_mandatory_copies\n");
14702                 print_blocks(state, stdout);
14703                 print_control_flow(state);
14704         }
14705         verify_consistency(state);
14706         allocate_registers(state);
14707         verify_consistency(state);
14708         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14709                 print_blocks(state, stdout);
14710         }
14711         if (state->debug & DEBUG_CONTROL_FLOW) {
14712                 print_control_flow(state);
14713         }
14714         /* Remove the optimization information.
14715          * This is more to check for memory consistency than to free memory.
14716          */
14717         free_basic_blocks(state);
14718 }
14719
14720 static void print_op_asm(struct compile_state *state,
14721         struct triple *ins, FILE *fp)
14722 {
14723         struct asm_info *info;
14724         const char *ptr;
14725         unsigned lhs, rhs, i;
14726         info = ins->u.ainfo;
14727         lhs = TRIPLE_LHS(ins->sizes);
14728         rhs = TRIPLE_RHS(ins->sizes);
14729         /* Don't count the clobbers in lhs */
14730         for(i = 0; i < lhs; i++) {
14731                 if (LHS(ins, i)->type == &void_type) {
14732                         break;
14733                 }
14734         }
14735         lhs = i;
14736         fprintf(fp, "#ASM\n");
14737         fputc('\t', fp);
14738         for(ptr = info->str; *ptr; ptr++) {
14739                 char *next;
14740                 unsigned long param;
14741                 struct triple *piece;
14742                 if (*ptr != '%') {
14743                         fputc(*ptr, fp);
14744                         continue;
14745                 }
14746                 ptr++;
14747                 if (*ptr == '%') {
14748                         fputc('%', fp);
14749                         continue;
14750                 }
14751                 param = strtoul(ptr, &next, 10);
14752                 if (ptr == next) {
14753                         error(state, ins, "Invalid asm template");
14754                 }
14755                 if (param >= (lhs + rhs)) {
14756                         error(state, ins, "Invalid param %%%u in asm template",
14757                                 param);
14758                 }
14759                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14760                 fprintf(fp, "%s", 
14761                         arch_reg_str(ID_REG(piece->id)));
14762                 ptr = next -1;
14763         }
14764         fprintf(fp, "\n#NOT ASM\n");
14765 }
14766
14767
14768 /* Only use the low x86 byte registers.  This allows me
14769  * allocate the entire register when a byte register is used.
14770  */
14771 #define X86_4_8BIT_GPRS 1
14772
14773 /* Recognized x86 cpu variants */
14774 #define BAD_CPU      0
14775 #define CPU_I386     1
14776 #define CPU_P3       2
14777 #define CPU_P4       3
14778 #define CPU_K7       4
14779 #define CPU_K8       5
14780
14781 #define CPU_DEFAULT  CPU_I386
14782
14783 /* The x86 register classes */
14784 #define REGC_FLAGS    0
14785 #define REGC_GPR8     1
14786 #define REGC_GPR16    2
14787 #define REGC_GPR32    3
14788 #define REGC_GPR64    4
14789 #define REGC_MMX      5
14790 #define REGC_XMM      6
14791 #define REGC_GPR32_8  7
14792 #define REGC_GPR16_8  8
14793 #define REGC_IMM32    9
14794 #define REGC_IMM16   10
14795 #define REGC_IMM8    11
14796 #define LAST_REGC  REGC_IMM8
14797 #if LAST_REGC >= MAX_REGC
14798 #error "MAX_REGC is to low"
14799 #endif
14800
14801 /* Register class masks */
14802 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14803 #define REGCM_GPR8    (1 << REGC_GPR8)
14804 #define REGCM_GPR16   (1 << REGC_GPR16)
14805 #define REGCM_GPR32   (1 << REGC_GPR32)
14806 #define REGCM_GPR64   (1 << REGC_GPR64)
14807 #define REGCM_MMX     (1 << REGC_MMX)
14808 #define REGCM_XMM     (1 << REGC_XMM)
14809 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14810 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14811 #define REGCM_IMM32   (1 << REGC_IMM32)
14812 #define REGCM_IMM16   (1 << REGC_IMM16)
14813 #define REGCM_IMM8    (1 << REGC_IMM8)
14814 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14815
14816 /* The x86 registers */
14817 #define REG_EFLAGS  2
14818 #define REGC_FLAGS_FIRST REG_EFLAGS
14819 #define REGC_FLAGS_LAST  REG_EFLAGS
14820 #define REG_AL      3
14821 #define REG_BL      4
14822 #define REG_CL      5
14823 #define REG_DL      6
14824 #define REG_AH      7
14825 #define REG_BH      8
14826 #define REG_CH      9
14827 #define REG_DH      10
14828 #define REGC_GPR8_FIRST  REG_AL
14829 #if X86_4_8BIT_GPRS
14830 #define REGC_GPR8_LAST   REG_DL
14831 #else 
14832 #define REGC_GPR8_LAST   REG_DH
14833 #endif
14834 #define REG_AX     11
14835 #define REG_BX     12
14836 #define REG_CX     13
14837 #define REG_DX     14
14838 #define REG_SI     15
14839 #define REG_DI     16
14840 #define REG_BP     17
14841 #define REG_SP     18
14842 #define REGC_GPR16_FIRST REG_AX
14843 #define REGC_GPR16_LAST  REG_SP
14844 #define REG_EAX    19
14845 #define REG_EBX    20
14846 #define REG_ECX    21
14847 #define REG_EDX    22
14848 #define REG_ESI    23
14849 #define REG_EDI    24
14850 #define REG_EBP    25
14851 #define REG_ESP    26
14852 #define REGC_GPR32_FIRST REG_EAX
14853 #define REGC_GPR32_LAST  REG_ESP
14854 #define REG_EDXEAX 27
14855 #define REGC_GPR64_FIRST REG_EDXEAX
14856 #define REGC_GPR64_LAST  REG_EDXEAX
14857 #define REG_MMX0   28
14858 #define REG_MMX1   29
14859 #define REG_MMX2   30
14860 #define REG_MMX3   31
14861 #define REG_MMX4   32
14862 #define REG_MMX5   33
14863 #define REG_MMX6   34
14864 #define REG_MMX7   35
14865 #define REGC_MMX_FIRST REG_MMX0
14866 #define REGC_MMX_LAST  REG_MMX7
14867 #define REG_XMM0   36
14868 #define REG_XMM1   37
14869 #define REG_XMM2   38
14870 #define REG_XMM3   39
14871 #define REG_XMM4   40
14872 #define REG_XMM5   41
14873 #define REG_XMM6   42
14874 #define REG_XMM7   43
14875 #define REGC_XMM_FIRST REG_XMM0
14876 #define REGC_XMM_LAST  REG_XMM7
14877 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14878 #define LAST_REG   REG_XMM7
14879
14880 #define REGC_GPR32_8_FIRST REG_EAX
14881 #define REGC_GPR32_8_LAST  REG_EDX
14882 #define REGC_GPR16_8_FIRST REG_AX
14883 #define REGC_GPR16_8_LAST  REG_DX
14884
14885 #define REGC_IMM8_FIRST    -1
14886 #define REGC_IMM8_LAST     -1
14887 #define REGC_IMM16_FIRST   -2
14888 #define REGC_IMM16_LAST    -1
14889 #define REGC_IMM32_FIRST   -4
14890 #define REGC_IMM32_LAST    -1
14891
14892 #if LAST_REG >= MAX_REGISTERS
14893 #error "MAX_REGISTERS to low"
14894 #endif
14895
14896
14897 static unsigned regc_size[LAST_REGC +1] = {
14898         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
14899         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
14900         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
14901         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
14902         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
14903         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
14904         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
14905         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14906         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14907         [REGC_IMM32]   = 0,
14908         [REGC_IMM16]   = 0,
14909         [REGC_IMM8]    = 0,
14910 };
14911
14912 static const struct {
14913         int first, last;
14914 } regcm_bound[LAST_REGC + 1] = {
14915         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
14916         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
14917         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
14918         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
14919         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
14920         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
14921         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
14922         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14923         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14924         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
14925         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
14926         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
14927 };
14928
14929 static int arch_encode_cpu(const char *cpu)
14930 {
14931         struct cpu {
14932                 const char *name;
14933                 int cpu;
14934         } cpus[] = {
14935                 { "i386", CPU_I386 },
14936                 { "p3",   CPU_P3 },
14937                 { "p4",   CPU_P4 },
14938                 { "k7",   CPU_K7 },
14939                 { "k8",   CPU_K8 },
14940                 {  0,     BAD_CPU }
14941         };
14942         struct cpu *ptr;
14943         for(ptr = cpus; ptr->name; ptr++) {
14944                 if (strcmp(ptr->name, cpu) == 0) {
14945                         break;
14946                 }
14947         }
14948         return ptr->cpu;
14949 }
14950
14951 static unsigned arch_regc_size(struct compile_state *state, int class)
14952 {
14953         if ((class < 0) || (class > LAST_REGC)) {
14954                 return 0;
14955         }
14956         return regc_size[class];
14957 }
14958
14959 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14960 {
14961         /* See if two register classes may have overlapping registers */
14962         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14963                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14964
14965         /* Special case for the immediates */
14966         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14967                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14968                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14969                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
14970                 return 0;
14971         }
14972         return (regcm1 & regcm2) ||
14973                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14974 }
14975
14976 static void arch_reg_equivs(
14977         struct compile_state *state, unsigned *equiv, int reg)
14978 {
14979         if ((reg < 0) || (reg > LAST_REG)) {
14980                 internal_error(state, 0, "invalid register");
14981         }
14982         *equiv++ = reg;
14983         switch(reg) {
14984         case REG_AL:
14985 #if X86_4_8BIT_GPRS
14986                 *equiv++ = REG_AH;
14987 #endif
14988                 *equiv++ = REG_AX;
14989                 *equiv++ = REG_EAX;
14990                 *equiv++ = REG_EDXEAX;
14991                 break;
14992         case REG_AH:
14993 #if X86_4_8BIT_GPRS
14994                 *equiv++ = REG_AL;
14995 #endif
14996                 *equiv++ = REG_AX;
14997                 *equiv++ = REG_EAX;
14998                 *equiv++ = REG_EDXEAX;
14999                 break;
15000         case REG_BL:  
15001 #if X86_4_8BIT_GPRS
15002                 *equiv++ = REG_BH;
15003 #endif
15004                 *equiv++ = REG_BX;
15005                 *equiv++ = REG_EBX;
15006                 break;
15007
15008         case REG_BH:
15009 #if X86_4_8BIT_GPRS
15010                 *equiv++ = REG_BL;
15011 #endif
15012                 *equiv++ = REG_BX;
15013                 *equiv++ = REG_EBX;
15014                 break;
15015         case REG_CL:
15016 #if X86_4_8BIT_GPRS
15017                 *equiv++ = REG_CH;
15018 #endif
15019                 *equiv++ = REG_CX;
15020                 *equiv++ = REG_ECX;
15021                 break;
15022
15023         case REG_CH:
15024 #if X86_4_8BIT_GPRS
15025                 *equiv++ = REG_CL;
15026 #endif
15027                 *equiv++ = REG_CX;
15028                 *equiv++ = REG_ECX;
15029                 break;
15030         case REG_DL:
15031 #if X86_4_8BIT_GPRS
15032                 *equiv++ = REG_DH;
15033 #endif
15034                 *equiv++ = REG_DX;
15035                 *equiv++ = REG_EDX;
15036                 *equiv++ = REG_EDXEAX;
15037                 break;
15038         case REG_DH:
15039 #if X86_4_8BIT_GPRS
15040                 *equiv++ = REG_DL;
15041 #endif
15042                 *equiv++ = REG_DX;
15043                 *equiv++ = REG_EDX;
15044                 *equiv++ = REG_EDXEAX;
15045                 break;
15046         case REG_AX:
15047                 *equiv++ = REG_AL;
15048                 *equiv++ = REG_AH;
15049                 *equiv++ = REG_EAX;
15050                 *equiv++ = REG_EDXEAX;
15051                 break;
15052         case REG_BX:
15053                 *equiv++ = REG_BL;
15054                 *equiv++ = REG_BH;
15055                 *equiv++ = REG_EBX;
15056                 break;
15057         case REG_CX:  
15058                 *equiv++ = REG_CL;
15059                 *equiv++ = REG_CH;
15060                 *equiv++ = REG_ECX;
15061                 break;
15062         case REG_DX:  
15063                 *equiv++ = REG_DL;
15064                 *equiv++ = REG_DH;
15065                 *equiv++ = REG_EDX;
15066                 *equiv++ = REG_EDXEAX;
15067                 break;
15068         case REG_SI:  
15069                 *equiv++ = REG_ESI;
15070                 break;
15071         case REG_DI:
15072                 *equiv++ = REG_EDI;
15073                 break;
15074         case REG_BP:
15075                 *equiv++ = REG_EBP;
15076                 break;
15077         case REG_SP:
15078                 *equiv++ = REG_ESP;
15079                 break;
15080         case REG_EAX:
15081                 *equiv++ = REG_AL;
15082                 *equiv++ = REG_AH;
15083                 *equiv++ = REG_AX;
15084                 *equiv++ = REG_EDXEAX;
15085                 break;
15086         case REG_EBX:
15087                 *equiv++ = REG_BL;
15088                 *equiv++ = REG_BH;
15089                 *equiv++ = REG_BX;
15090                 break;
15091         case REG_ECX:
15092                 *equiv++ = REG_CL;
15093                 *equiv++ = REG_CH;
15094                 *equiv++ = REG_CX;
15095                 break;
15096         case REG_EDX:
15097                 *equiv++ = REG_DL;
15098                 *equiv++ = REG_DH;
15099                 *equiv++ = REG_DX;
15100                 *equiv++ = REG_EDXEAX;
15101                 break;
15102         case REG_ESI: 
15103                 *equiv++ = REG_SI;
15104                 break;
15105         case REG_EDI: 
15106                 *equiv++ = REG_DI;
15107                 break;
15108         case REG_EBP: 
15109                 *equiv++ = REG_BP;
15110                 break;
15111         case REG_ESP: 
15112                 *equiv++ = REG_SP;
15113                 break;
15114         case REG_EDXEAX: 
15115                 *equiv++ = REG_AL;
15116                 *equiv++ = REG_AH;
15117                 *equiv++ = REG_DL;
15118                 *equiv++ = REG_DH;
15119                 *equiv++ = REG_AX;
15120                 *equiv++ = REG_DX;
15121                 *equiv++ = REG_EAX;
15122                 *equiv++ = REG_EDX;
15123                 break;
15124         }
15125         *equiv++ = REG_UNSET; 
15126 }
15127
15128 static unsigned arch_avail_mask(struct compile_state *state)
15129 {
15130         unsigned avail_mask;
15131         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
15132                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15133                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15134         switch(state->cpu) {
15135         case CPU_P3:
15136         case CPU_K7:
15137                 avail_mask |= REGCM_MMX;
15138                 break;
15139         case CPU_P4:
15140         case CPU_K8:
15141                 avail_mask |= REGCM_MMX | REGCM_XMM;
15142                 break;
15143         }
15144 #if 0
15145         /* Don't enable 8 bit values until I can force both operands
15146          * to be 8bits simultaneously.
15147          */
15148         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15149 #endif
15150         return avail_mask;
15151 }
15152
15153 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15154 {
15155         unsigned mask, result;
15156         int class, class2;
15157         result = regcm;
15158         result &= arch_avail_mask(state);
15159
15160         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15161                 if ((result & mask) == 0) {
15162                         continue;
15163                 }
15164                 if (class > LAST_REGC) {
15165                         result &= ~mask;
15166                 }
15167                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15168                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15169                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15170                                 result |= (1 << class2);
15171                         }
15172                 }
15173         }
15174         return result;
15175 }
15176
15177 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15178 {
15179         /* Like arch_regcm_normalize except immediate register classes are excluded */
15180         regcm = arch_regcm_normalize(state, regcm);
15181         /* Remove the immediate register classes */
15182         regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15183         return regcm;
15184         
15185 }
15186
15187 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15188 {
15189         unsigned mask;
15190         int class;
15191         mask = 0;
15192         for(class = 0; class <= LAST_REGC; class++) {
15193                 if ((reg >= regcm_bound[class].first) &&
15194                         (reg <= regcm_bound[class].last)) {
15195                         mask |= (1 << class);
15196                 }
15197         }
15198         if (!mask) {
15199                 internal_error(state, 0, "reg %d not in any class", reg);
15200         }
15201         return mask;
15202 }
15203
15204 static struct reg_info arch_reg_constraint(
15205         struct compile_state *state, struct type *type, const char *constraint)
15206 {
15207         static const struct {
15208                 char class;
15209                 unsigned int mask;
15210                 unsigned int reg;
15211         } constraints[] = {
15212                 { 'r', REGCM_GPR32, REG_UNSET },
15213                 { 'g', REGCM_GPR32, REG_UNSET },
15214                 { 'p', REGCM_GPR32, REG_UNSET },
15215                 { 'q', REGCM_GPR8,  REG_UNSET },
15216                 { 'Q', REGCM_GPR32_8, REG_UNSET },
15217                 { 'x', REGCM_XMM,   REG_UNSET },
15218                 { 'y', REGCM_MMX,   REG_UNSET },
15219                 { 'a', REGCM_GPR32, REG_EAX },
15220                 { 'b', REGCM_GPR32, REG_EBX },
15221                 { 'c', REGCM_GPR32, REG_ECX },
15222                 { 'd', REGCM_GPR32, REG_EDX },
15223                 { 'D', REGCM_GPR32, REG_EDI },
15224                 { 'S', REGCM_GPR32, REG_ESI },
15225                 { '\0', 0, REG_UNSET },
15226         };
15227         unsigned int regcm;
15228         unsigned int mask, reg;
15229         struct reg_info result;
15230         const char *ptr;
15231         regcm = arch_type_to_regcm(state, type);
15232         reg = REG_UNSET;
15233         mask = 0;
15234         for(ptr = constraint; *ptr; ptr++) {
15235                 int i;
15236                 if (*ptr ==  ' ') {
15237                         continue;
15238                 }
15239                 for(i = 0; constraints[i].class != '\0'; i++) {
15240                         if (constraints[i].class == *ptr) {
15241                                 break;
15242                         }
15243                 }
15244                 if (constraints[i].class == '\0') {
15245                         error(state, 0, "invalid register constraint ``%c''", *ptr);
15246                         break;
15247                 }
15248                 if ((constraints[i].mask & regcm) == 0) {
15249                         error(state, 0, "invalid register class %c specified",
15250                                 *ptr);
15251                 }
15252                 mask |= constraints[i].mask;
15253                 if (constraints[i].reg != REG_UNSET) {
15254                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15255                                 error(state, 0, "Only one register may be specified");
15256                         }
15257                         reg = constraints[i].reg;
15258                 }
15259         }
15260         result.reg = reg;
15261         result.regcm = mask;
15262         return result;
15263 }
15264
15265 static struct reg_info arch_reg_clobber(
15266         struct compile_state *state, const char *clobber)
15267 {
15268         struct reg_info result;
15269         if (strcmp(clobber, "memory") == 0) {
15270                 result.reg = REG_UNSET;
15271                 result.regcm = 0;
15272         }
15273         else if (strcmp(clobber, "%eax") == 0) {
15274                 result.reg = REG_EAX;
15275                 result.regcm = REGCM_GPR32;
15276         }
15277         else if (strcmp(clobber, "%ebx") == 0) {
15278                 result.reg = REG_EBX;
15279                 result.regcm = REGCM_GPR32;
15280         }
15281         else if (strcmp(clobber, "%ecx") == 0) {
15282                 result.reg = REG_ECX;
15283                 result.regcm = REGCM_GPR32;
15284         }
15285         else if (strcmp(clobber, "%edx") == 0) {
15286                 result.reg = REG_EDX;
15287                 result.regcm = REGCM_GPR32;
15288         }
15289         else if (strcmp(clobber, "%esi") == 0) {
15290                 result.reg = REG_ESI;
15291                 result.regcm = REGCM_GPR32;
15292         }
15293         else if (strcmp(clobber, "%edi") == 0) {
15294                 result.reg = REG_EDI;
15295                 result.regcm = REGCM_GPR32;
15296         }
15297         else if (strcmp(clobber, "%ebp") == 0) {
15298                 result.reg = REG_EBP;
15299                 result.regcm = REGCM_GPR32;
15300         }
15301         else if (strcmp(clobber, "%esp") == 0) {
15302                 result.reg = REG_ESP;
15303                 result.regcm = REGCM_GPR32;
15304         }
15305         else if (strcmp(clobber, "cc") == 0) {
15306                 result.reg = REG_EFLAGS;
15307                 result.regcm = REGCM_FLAGS;
15308         }
15309         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
15310                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15311                 result.reg = REG_XMM0 + octdigval(clobber[3]);
15312                 result.regcm = REGCM_XMM;
15313         }
15314         else if ((strncmp(clobber, "mmx", 3) == 0) &&
15315                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15316                 result.reg = REG_MMX0 + octdigval(clobber[3]);
15317                 result.regcm = REGCM_MMX;
15318         }
15319         else {
15320                 error(state, 0, "Invalid register clobber");
15321                 result.reg = REG_UNSET;
15322                 result.regcm = 0;
15323         }
15324         return result;
15325 }
15326
15327 static int do_select_reg(struct compile_state *state, 
15328         char *used, int reg, unsigned classes)
15329 {
15330         unsigned mask;
15331         if (used[reg]) {
15332                 return REG_UNSET;
15333         }
15334         mask = arch_reg_regcm(state, reg);
15335         return (classes & mask) ? reg : REG_UNSET;
15336 }
15337
15338 static int arch_select_free_register(
15339         struct compile_state *state, char *used, int classes)
15340 {
15341         /* Live ranges with the most neighbors are colored first.
15342          *
15343          * Generally it does not matter which colors are given
15344          * as the register allocator attempts to color live ranges
15345          * in an order where you are guaranteed not to run out of colors.
15346          *
15347          * Occasionally the register allocator cannot find an order
15348          * of register selection that will find a free color.  To
15349          * increase the odds the register allocator will work when
15350          * it guesses first give out registers from register classes
15351          * least likely to run out of registers.
15352          * 
15353          */
15354         int i, reg;
15355         reg = REG_UNSET;
15356         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15357                 reg = do_select_reg(state, used, i, classes);
15358         }
15359         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15360                 reg = do_select_reg(state, used, i, classes);
15361         }
15362         for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15363                 reg = do_select_reg(state, used, i, classes);
15364         }
15365         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15366                 reg = do_select_reg(state, used, i, classes);
15367         }
15368         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15369                 reg = do_select_reg(state, used, i, classes);
15370         }
15371         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15372                 reg = do_select_reg(state, used, i, classes);
15373         }
15374         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15375                 reg = do_select_reg(state, used, i, classes);
15376         }
15377         return reg;
15378 }
15379
15380
15381 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
15382 {
15383 #warning "FIXME force types smaller (if legal) before I get here"
15384         unsigned mask;
15385         mask = 0;
15386         switch(type->type & TYPE_MASK) {
15387         case TYPE_ARRAY:
15388         case TYPE_VOID: 
15389                 mask = 0; 
15390                 break;
15391         case TYPE_CHAR:
15392         case TYPE_UCHAR:
15393                 mask = REGCM_GPR8 | 
15394                         REGCM_GPR16 | REGCM_GPR16_8 | 
15395                         REGCM_GPR32 | REGCM_GPR32_8 |
15396                         REGCM_GPR64 |
15397                         REGCM_MMX | REGCM_XMM |
15398                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15399                 break;
15400         case TYPE_SHORT:
15401         case TYPE_USHORT:
15402                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
15403                         REGCM_GPR32 | REGCM_GPR32_8 |
15404                         REGCM_GPR64 |
15405                         REGCM_MMX | REGCM_XMM |
15406                         REGCM_IMM32 | REGCM_IMM16;
15407                 break;
15408         case TYPE_INT:
15409         case TYPE_UINT:
15410         case TYPE_LONG:
15411         case TYPE_ULONG:
15412         case TYPE_POINTER:
15413                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
15414                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15415                         REGCM_IMM32;
15416                 break;
15417         default:
15418                 internal_error(state, 0, "no register class for type");
15419                 break;
15420         }
15421         mask = arch_regcm_normalize(state, mask);
15422         return mask;
15423 }
15424
15425 static int is_imm32(struct triple *imm)
15426 {
15427         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15428                 (imm->op == OP_ADDRCONST);
15429         
15430 }
15431 static int is_imm16(struct triple *imm)
15432 {
15433         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15434 }
15435 static int is_imm8(struct triple *imm)
15436 {
15437         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15438 }
15439
15440 static int get_imm32(struct triple *ins, struct triple **expr)
15441 {
15442         struct triple *imm;
15443         imm = *expr;
15444         while(imm->op == OP_COPY) {
15445                 imm = RHS(imm, 0);
15446         }
15447         if (!is_imm32(imm)) {
15448                 return 0;
15449         }
15450         unuse_triple(*expr, ins);
15451         use_triple(imm, ins);
15452         *expr = imm;
15453         return 1;
15454 }
15455
15456 static int get_imm8(struct triple *ins, struct triple **expr)
15457 {
15458         struct triple *imm;
15459         imm = *expr;
15460         while(imm->op == OP_COPY) {
15461                 imm = RHS(imm, 0);
15462         }
15463         if (!is_imm8(imm)) {
15464                 return 0;
15465         }
15466         unuse_triple(*expr, ins);
15467         use_triple(imm, ins);
15468         *expr = imm;
15469         return 1;
15470 }
15471
15472 #define TEMPLATE_NOP         0
15473 #define TEMPLATE_INTCONST8   1
15474 #define TEMPLATE_INTCONST32  2
15475 #define TEMPLATE_COPY8_REG   3
15476 #define TEMPLATE_COPY16_REG  4
15477 #define TEMPLATE_COPY32_REG  5
15478 #define TEMPLATE_COPY_IMM8   6
15479 #define TEMPLATE_COPY_IMM16  7
15480 #define TEMPLATE_COPY_IMM32  8
15481 #define TEMPLATE_PHI8        9
15482 #define TEMPLATE_PHI16      10
15483 #define TEMPLATE_PHI32      11
15484 #define TEMPLATE_STORE8     12
15485 #define TEMPLATE_STORE16    13
15486 #define TEMPLATE_STORE32    14
15487 #define TEMPLATE_LOAD8      15
15488 #define TEMPLATE_LOAD16     16
15489 #define TEMPLATE_LOAD32     17
15490 #define TEMPLATE_BINARY_REG 18
15491 #define TEMPLATE_BINARY_IMM 19
15492 #define TEMPLATE_SL_CL      20
15493 #define TEMPLATE_SL_IMM     21
15494 #define TEMPLATE_UNARY      22
15495 #define TEMPLATE_CMP_REG    23
15496 #define TEMPLATE_CMP_IMM    24
15497 #define TEMPLATE_TEST       25
15498 #define TEMPLATE_SET        26
15499 #define TEMPLATE_JMP        27
15500 #define TEMPLATE_INB_DX     28
15501 #define TEMPLATE_INB_IMM    29
15502 #define TEMPLATE_INW_DX     30
15503 #define TEMPLATE_INW_IMM    31
15504 #define TEMPLATE_INL_DX     32
15505 #define TEMPLATE_INL_IMM    33
15506 #define TEMPLATE_OUTB_DX    34
15507 #define TEMPLATE_OUTB_IMM   35
15508 #define TEMPLATE_OUTW_DX    36
15509 #define TEMPLATE_OUTW_IMM   37
15510 #define TEMPLATE_OUTL_DX    38
15511 #define TEMPLATE_OUTL_IMM   39
15512 #define TEMPLATE_BSF        40
15513 #define TEMPLATE_RDMSR      41
15514 #define TEMPLATE_WRMSR      42
15515 #define TEMPLATE_UMUL       43
15516 #define TEMPLATE_DIV        44
15517 #define TEMPLATE_MOD        45
15518 #define LAST_TEMPLATE       TEMPLATE_MOD
15519 #if LAST_TEMPLATE >= MAX_TEMPLATES
15520 #error "MAX_TEMPLATES to low"
15521 #endif
15522
15523 #define COPY8_REGCM     (REGCM_GPR64 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15524 #define COPY16_REGCM    (REGCM_GPR64 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)  
15525 #define COPY32_REGCM    (REGCM_GPR64 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15526 #define COPYIMM8_REGCM  (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8)
15527 #define COPYIMM16_REGCM (REGCM_GPR32 | REGCM_GPR16)
15528 #define COPYIMM32_REGCM (REGCM_GPR32)
15529
15530
15531 static struct ins_template templates[] = {
15532         [TEMPLATE_NOP]      = {},
15533         [TEMPLATE_INTCONST8] = { 
15534                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15535         },
15536         [TEMPLATE_INTCONST32] = { 
15537                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15538         },
15539         [TEMPLATE_COPY8_REG] = {
15540                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15541                 .rhs = { [0] = { REG_UNSET, COPY8_REGCM }  },
15542         },
15543         [TEMPLATE_COPY16_REG] = {
15544                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15545                 .rhs = { [0] = { REG_UNSET, COPY16_REGCM }  },
15546         },
15547         [TEMPLATE_COPY32_REG] = {
15548                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15549                 .rhs = { [0] = { REG_UNSET, COPY32_REGCM }  },
15550         },
15551         [TEMPLATE_COPY_IMM8] = {
15552                 .lhs = { [0] = { REG_UNSET, COPYIMM8_REGCM } },
15553                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15554         },
15555         [TEMPLATE_COPY_IMM16] = {
15556                 .lhs = { [0] = { REG_UNSET, COPYIMM16_REGCM } },
15557                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
15558         },
15559         [TEMPLATE_COPY_IMM32] = {
15560                 .lhs = { [0] = { REG_UNSET, COPYIMM32_REGCM } },
15561                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
15562         },
15563         [TEMPLATE_PHI8] = { 
15564                 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
15565                 .rhs = { 
15566                         [ 0] = { REG_VIRT0, COPY8_REGCM },
15567                         [ 1] = { REG_VIRT0, COPY8_REGCM },
15568                         [ 2] = { REG_VIRT0, COPY8_REGCM },
15569                         [ 3] = { REG_VIRT0, COPY8_REGCM },
15570                         [ 4] = { REG_VIRT0, COPY8_REGCM },
15571                         [ 5] = { REG_VIRT0, COPY8_REGCM },
15572                         [ 6] = { REG_VIRT0, COPY8_REGCM },
15573                         [ 7] = { REG_VIRT0, COPY8_REGCM },
15574                         [ 8] = { REG_VIRT0, COPY8_REGCM },
15575                         [ 9] = { REG_VIRT0, COPY8_REGCM },
15576                         [10] = { REG_VIRT0, COPY8_REGCM },
15577                         [11] = { REG_VIRT0, COPY8_REGCM },
15578                         [12] = { REG_VIRT0, COPY8_REGCM },
15579                         [13] = { REG_VIRT0, COPY8_REGCM },
15580                         [14] = { REG_VIRT0, COPY8_REGCM },
15581                         [15] = { REG_VIRT0, COPY8_REGCM },
15582                 }, },
15583         [TEMPLATE_PHI16] = { 
15584                 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
15585                 .rhs = { 
15586                         [ 0] = { REG_VIRT0, COPY16_REGCM },
15587                         [ 1] = { REG_VIRT0, COPY16_REGCM },
15588                         [ 2] = { REG_VIRT0, COPY16_REGCM },
15589                         [ 3] = { REG_VIRT0, COPY16_REGCM },
15590                         [ 4] = { REG_VIRT0, COPY16_REGCM },
15591                         [ 5] = { REG_VIRT0, COPY16_REGCM },
15592                         [ 6] = { REG_VIRT0, COPY16_REGCM },
15593                         [ 7] = { REG_VIRT0, COPY16_REGCM },
15594                         [ 8] = { REG_VIRT0, COPY16_REGCM },
15595                         [ 9] = { REG_VIRT0, COPY16_REGCM },
15596                         [10] = { REG_VIRT0, COPY16_REGCM },
15597                         [11] = { REG_VIRT0, COPY16_REGCM },
15598                         [12] = { REG_VIRT0, COPY16_REGCM },
15599                         [13] = { REG_VIRT0, COPY16_REGCM },
15600                         [14] = { REG_VIRT0, COPY16_REGCM },
15601                         [15] = { REG_VIRT0, COPY16_REGCM },
15602                 }, },
15603         [TEMPLATE_PHI32] = { 
15604                 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
15605                 .rhs = { 
15606                         [ 0] = { REG_VIRT0, COPY32_REGCM },
15607                         [ 1] = { REG_VIRT0, COPY32_REGCM },
15608                         [ 2] = { REG_VIRT0, COPY32_REGCM },
15609                         [ 3] = { REG_VIRT0, COPY32_REGCM },
15610                         [ 4] = { REG_VIRT0, COPY32_REGCM },
15611                         [ 5] = { REG_VIRT0, COPY32_REGCM },
15612                         [ 6] = { REG_VIRT0, COPY32_REGCM },
15613                         [ 7] = { REG_VIRT0, COPY32_REGCM },
15614                         [ 8] = { REG_VIRT0, COPY32_REGCM },
15615                         [ 9] = { REG_VIRT0, COPY32_REGCM },
15616                         [10] = { REG_VIRT0, COPY32_REGCM },
15617                         [11] = { REG_VIRT0, COPY32_REGCM },
15618                         [12] = { REG_VIRT0, COPY32_REGCM },
15619                         [13] = { REG_VIRT0, COPY32_REGCM },
15620                         [14] = { REG_VIRT0, COPY32_REGCM },
15621                         [15] = { REG_VIRT0, COPY32_REGCM },
15622                 }, },
15623         [TEMPLATE_STORE8] = {
15624                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15625                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15626         },
15627         [TEMPLATE_STORE16] = {
15628                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15629                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15630         },
15631         [TEMPLATE_STORE32] = {
15632                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15633                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15634         },
15635         [TEMPLATE_LOAD8] = {
15636                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15637                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15638         },
15639         [TEMPLATE_LOAD16] = {
15640                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15641                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15642         },
15643         [TEMPLATE_LOAD32] = {
15644                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15645                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15646         },
15647         [TEMPLATE_BINARY_REG] = {
15648                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15649                 .rhs = { 
15650                         [0] = { REG_VIRT0, REGCM_GPR32 },
15651                         [1] = { REG_UNSET, REGCM_GPR32 },
15652                 },
15653         },
15654         [TEMPLATE_BINARY_IMM] = {
15655                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15656                 .rhs = { 
15657                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15658                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15659                 },
15660         },
15661         [TEMPLATE_SL_CL] = {
15662                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15663                 .rhs = { 
15664                         [0] = { REG_VIRT0, REGCM_GPR32 },
15665                         [1] = { REG_CL, REGCM_GPR8 },
15666                 },
15667         },
15668         [TEMPLATE_SL_IMM] = {
15669                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15670                 .rhs = { 
15671                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15672                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15673                 },
15674         },
15675         [TEMPLATE_UNARY] = {
15676                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15677                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15678         },
15679         [TEMPLATE_CMP_REG] = {
15680                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15681                 .rhs = {
15682                         [0] = { REG_UNSET, REGCM_GPR32 },
15683                         [1] = { REG_UNSET, REGCM_GPR32 },
15684                 },
15685         },
15686         [TEMPLATE_CMP_IMM] = {
15687                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15688                 .rhs = {
15689                         [0] = { REG_UNSET, REGCM_GPR32 },
15690                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15691                 },
15692         },
15693         [TEMPLATE_TEST] = {
15694                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15695                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15696         },
15697         [TEMPLATE_SET] = {
15698                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15699                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15700         },
15701         [TEMPLATE_JMP] = {
15702                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15703         },
15704         [TEMPLATE_INB_DX] = {
15705                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15706                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15707         },
15708         [TEMPLATE_INB_IMM] = {
15709                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15710                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15711         },
15712         [TEMPLATE_INW_DX]  = { 
15713                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15714                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15715         },
15716         [TEMPLATE_INW_IMM] = { 
15717                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15718                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15719         },
15720         [TEMPLATE_INL_DX]  = {
15721                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15722                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15723         },
15724         [TEMPLATE_INL_IMM] = {
15725                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15726                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15727         },
15728         [TEMPLATE_OUTB_DX] = { 
15729                 .rhs = {
15730                         [0] = { REG_AL,  REGCM_GPR8 },
15731                         [1] = { REG_DX, REGCM_GPR16 },
15732                 },
15733         },
15734         [TEMPLATE_OUTB_IMM] = { 
15735                 .rhs = {
15736                         [0] = { REG_AL,  REGCM_GPR8 },  
15737                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15738                 },
15739         },
15740         [TEMPLATE_OUTW_DX] = { 
15741                 .rhs = {
15742                         [0] = { REG_AX,  REGCM_GPR16 },
15743                         [1] = { REG_DX, REGCM_GPR16 },
15744                 },
15745         },
15746         [TEMPLATE_OUTW_IMM] = {
15747                 .rhs = {
15748                         [0] = { REG_AX,  REGCM_GPR16 }, 
15749                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15750                 },
15751         },
15752         [TEMPLATE_OUTL_DX] = { 
15753                 .rhs = {
15754                         [0] = { REG_EAX, REGCM_GPR32 },
15755                         [1] = { REG_DX, REGCM_GPR16 },
15756                 },
15757         },
15758         [TEMPLATE_OUTL_IMM] = { 
15759                 .rhs = {
15760                         [0] = { REG_EAX, REGCM_GPR32 }, 
15761                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15762                 },
15763         },
15764         [TEMPLATE_BSF] = {
15765                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15766                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15767         },
15768         [TEMPLATE_RDMSR] = {
15769                 .lhs = { 
15770                         [0] = { REG_EAX, REGCM_GPR32 },
15771                         [1] = { REG_EDX, REGCM_GPR32 },
15772                 },
15773                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15774         },
15775         [TEMPLATE_WRMSR] = {
15776                 .rhs = {
15777                         [0] = { REG_ECX, REGCM_GPR32 },
15778                         [1] = { REG_EAX, REGCM_GPR32 },
15779                         [2] = { REG_EDX, REGCM_GPR32 },
15780                 },
15781         },
15782         [TEMPLATE_UMUL] = {
15783                 .lhs = { [0] = { REG_EDXEAX, REGCM_GPR64 } },
15784                 .rhs = { 
15785                         [0] = { REG_EAX, REGCM_GPR32 },
15786                         [1] = { REG_UNSET, REGCM_GPR32 },
15787                 },
15788         },
15789         [TEMPLATE_DIV] = {
15790                 .lhs = { 
15791                         [0] = { REG_EAX, REGCM_GPR32 },
15792                         [1] = { REG_EDX, REGCM_GPR32 },
15793                 },
15794                 .rhs = {
15795                         [0] = { REG_EDXEAX, REGCM_GPR64 },
15796                         [1] = { REG_UNSET, REGCM_GPR32 },
15797                 },
15798         },
15799         [TEMPLATE_MOD] = {
15800                 .lhs = { 
15801                         [0] = { REG_EDX, REGCM_GPR32 },
15802                         [1] = { REG_EAX, REGCM_GPR32 },
15803                 },
15804                 .rhs = {
15805                         [0] = { REG_EDXEAX, REGCM_GPR64 },
15806                         [1] = { REG_UNSET, REGCM_GPR32 },
15807                 },
15808         },
15809 };
15810
15811 static void fixup_branches(struct compile_state *state,
15812         struct triple *cmp, struct triple *use, int jmp_op)
15813 {
15814         struct triple_set *entry, *next;
15815         for(entry = use->use; entry; entry = next) {
15816                 next = entry->next;
15817                 if (entry->member->op == OP_COPY) {
15818                         fixup_branches(state, cmp, entry->member, jmp_op);
15819                 }
15820                 else if (entry->member->op == OP_BRANCH) {
15821                         struct triple *branch, *test;
15822                         struct triple *left, *right;
15823                         left = right = 0;
15824                         left = RHS(cmp, 0);
15825                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15826                                 right = RHS(cmp, 1);
15827                         }
15828                         branch = entry->member;
15829                         test = pre_triple(state, branch,
15830                                 cmp->op, cmp->type, left, right);
15831                         test->template_id = TEMPLATE_TEST; 
15832                         if (cmp->op == OP_CMP) {
15833                                 test->template_id = TEMPLATE_CMP_REG;
15834                                 if (get_imm32(test, &RHS(test, 1))) {
15835                                         test->template_id = TEMPLATE_CMP_IMM;
15836                                 }
15837                         }
15838                         use_triple(RHS(test, 0), test);
15839                         use_triple(RHS(test, 1), test);
15840                         unuse_triple(RHS(branch, 0), branch);
15841                         RHS(branch, 0) = test;
15842                         branch->op = jmp_op;
15843                         branch->template_id = TEMPLATE_JMP;
15844                         use_triple(RHS(branch, 0), branch);
15845                 }
15846         }
15847 }
15848
15849 static void bool_cmp(struct compile_state *state, 
15850         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15851 {
15852         struct triple_set *entry, *next;
15853         struct triple *set;
15854
15855         /* Put a barrier up before the cmp which preceeds the
15856          * copy instruction.  If a set actually occurs this gives
15857          * us a chance to move variables in registers out of the way.
15858          */
15859
15860         /* Modify the comparison operator */
15861         ins->op = cmp_op;
15862         ins->template_id = TEMPLATE_TEST;
15863         if (cmp_op == OP_CMP) {
15864                 ins->template_id = TEMPLATE_CMP_REG;
15865                 if (get_imm32(ins, &RHS(ins, 1))) {
15866                         ins->template_id =  TEMPLATE_CMP_IMM;
15867                 }
15868         }
15869         /* Generate the instruction sequence that will transform the
15870          * result of the comparison into a logical value.
15871          */
15872         set = post_triple(state, ins, set_op, &char_type, ins, 0);
15873         use_triple(ins, set);
15874         set->template_id = TEMPLATE_SET;
15875
15876         for(entry = ins->use; entry; entry = next) {
15877                 next = entry->next;
15878                 if (entry->member == set) {
15879                         continue;
15880                 }
15881                 replace_rhs_use(state, ins, set, entry->member);
15882         }
15883         fixup_branches(state, ins, set, jmp_op);
15884 }
15885
15886 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15887 {
15888         struct triple *next;
15889         int lhs, i;
15890         lhs = TRIPLE_LHS(ins->sizes);
15891         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15892                 if (next != LHS(ins, i)) {
15893                         internal_error(state, ins, "malformed lhs on %s",
15894                                 tops(ins->op));
15895                 }
15896                 if (next->op != OP_PIECE) {
15897                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15898                                 tops(next->op), i, tops(ins->op));
15899                 }
15900                 if (next->u.cval != i) {
15901                         internal_error(state, ins, "bad u.cval of %d %d expected",
15902                                 next->u.cval, i);
15903                 }
15904         }
15905         return next;
15906 }
15907
15908 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15909 {
15910         struct ins_template *template;
15911         struct reg_info result;
15912         int zlhs;
15913         if (ins->op == OP_PIECE) {
15914                 index = ins->u.cval;
15915                 ins = MISC(ins, 0);
15916         }
15917         zlhs = TRIPLE_LHS(ins->sizes);
15918         if (triple_is_def(state, ins)) {
15919                 zlhs = 1;
15920         }
15921         if (index >= zlhs) {
15922                 internal_error(state, ins, "index %d out of range for %s\n",
15923                         index, tops(ins->op));
15924         }
15925         switch(ins->op) {
15926         case OP_ASM:
15927                 template = &ins->u.ainfo->tmpl;
15928                 break;
15929         default:
15930                 if (ins->template_id > LAST_TEMPLATE) {
15931                         internal_error(state, ins, "bad template number %d", 
15932                                 ins->template_id);
15933                 }
15934                 template = &templates[ins->template_id];
15935                 break;
15936         }
15937         result = template->lhs[index];
15938         result.regcm = arch_regcm_normalize(state, result.regcm);
15939         if (result.reg != REG_UNNEEDED) {
15940                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15941         }
15942         if (result.regcm == 0) {
15943                 internal_error(state, ins, "lhs %d regcm == 0", index);
15944         }
15945         return result;
15946 }
15947
15948 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15949 {
15950         struct reg_info result;
15951         struct ins_template *template;
15952         if ((index > TRIPLE_RHS(ins->sizes)) ||
15953                 (ins->op == OP_PIECE)) {
15954                 internal_error(state, ins, "index %d out of range for %s\n",
15955                         index, tops(ins->op));
15956         }
15957         switch(ins->op) {
15958         case OP_ASM:
15959                 template = &ins->u.ainfo->tmpl;
15960                 break;
15961         default:
15962                 if (ins->template_id > LAST_TEMPLATE) {
15963                         internal_error(state, ins, "bad template number %d", 
15964                                 ins->template_id);
15965                 }
15966                 template = &templates[ins->template_id];
15967                 break;
15968         }
15969         result = template->rhs[index];
15970         result.regcm = arch_regcm_normalize(state, result.regcm);
15971         if (result.regcm == 0) {
15972                 internal_error(state, ins, "rhs %d regcm == 0", index);
15973         }
15974         return result;
15975 }
15976
15977 static struct triple *transform_to_arch_instruction(
15978         struct compile_state *state, struct triple *ins)
15979 {
15980         /* Transform from generic 3 address instructions
15981          * to archtecture specific instructions.
15982          * And apply architecture specific constraints to instructions.
15983          * Copies are inserted to preserve the register flexibility
15984          * of 3 address instructions.
15985          */
15986         struct triple *next;
15987         size_t size;
15988         next = ins->next;
15989         switch(ins->op) {
15990         case OP_INTCONST:
15991                 ins->template_id = TEMPLATE_INTCONST32;
15992                 if (ins->u.cval < 256) {
15993                         ins->template_id = TEMPLATE_INTCONST8;
15994                 }
15995                 break;
15996         case OP_ADDRCONST:
15997                 ins->template_id = TEMPLATE_INTCONST32;
15998                 break;
15999         case OP_NOOP:
16000         case OP_SDECL:
16001         case OP_BLOBCONST:
16002         case OP_LABEL:
16003                 ins->template_id = TEMPLATE_NOP;
16004                 break;
16005         case OP_COPY:
16006                 size = size_of(state, ins->type);
16007                 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16008                         ins->template_id = TEMPLATE_COPY_IMM8;
16009                 }
16010                 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16011                         ins->template_id = TEMPLATE_COPY_IMM16;
16012                 }
16013                 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16014                         ins->template_id = TEMPLATE_COPY_IMM32;
16015                 }
16016                 else if (is_const(RHS(ins, 0))) {
16017                         internal_error(state, ins, "bad constant passed to copy");
16018                 }
16019                 else if (size <= 1) {
16020                         ins->template_id = TEMPLATE_COPY8_REG;
16021                 }
16022                 else if (size <= 2) {
16023                         ins->template_id = TEMPLATE_COPY16_REG;
16024                 }
16025                 else if (size <= 4) {
16026                         ins->template_id = TEMPLATE_COPY32_REG;
16027                 }
16028                 else {
16029                         internal_error(state, ins, "bad type passed to copy");
16030                 }
16031                 break;
16032         case OP_PHI:
16033                 size = size_of(state, ins->type);
16034                 if (size <= 1) {
16035                         ins->template_id = TEMPLATE_PHI8;
16036                 }
16037                 else if (size <= 2) {
16038                         ins->template_id = TEMPLATE_PHI16;
16039                 }
16040                 else if (size <= 4) {
16041                         ins->template_id = TEMPLATE_PHI32;
16042                 }
16043                 else {
16044                         internal_error(state, ins, "bad type passed to phi");
16045                 }
16046                 break;
16047         case OP_STORE:
16048                 switch(ins->type->type & TYPE_MASK) {
16049                 case TYPE_CHAR:    case TYPE_UCHAR:
16050                         ins->template_id = TEMPLATE_STORE8;
16051                         break;
16052                 case TYPE_SHORT:   case TYPE_USHORT:
16053                         ins->template_id = TEMPLATE_STORE16;
16054                         break;
16055                 case TYPE_INT:     case TYPE_UINT:
16056                 case TYPE_LONG:    case TYPE_ULONG:
16057                 case TYPE_POINTER:
16058                         ins->template_id = TEMPLATE_STORE32;
16059                         break;
16060                 default:
16061                         internal_error(state, ins, "unknown type in store");
16062                         break;
16063                 }
16064                 break;
16065         case OP_LOAD:
16066                 switch(ins->type->type & TYPE_MASK) {
16067                 case TYPE_CHAR:   case TYPE_UCHAR:
16068                         ins->template_id = TEMPLATE_LOAD8;
16069                         break;
16070                 case TYPE_SHORT:
16071                 case TYPE_USHORT:
16072                         ins->template_id = TEMPLATE_LOAD16;
16073                         break;
16074                 case TYPE_INT:
16075                 case TYPE_UINT:
16076                 case TYPE_LONG:
16077                 case TYPE_ULONG:
16078                 case TYPE_POINTER:
16079                         ins->template_id = TEMPLATE_LOAD32;
16080                         break;
16081                 default:
16082                         internal_error(state, ins, "unknown type in load");
16083                         break;
16084                 }
16085                 break;
16086         case OP_ADD:
16087         case OP_SUB:
16088         case OP_AND:
16089         case OP_XOR:
16090         case OP_OR:
16091         case OP_SMUL:
16092                 ins->template_id = TEMPLATE_BINARY_REG;
16093                 if (get_imm32(ins, &RHS(ins, 1))) {
16094                         ins->template_id = TEMPLATE_BINARY_IMM;
16095                 }
16096                 break;
16097 #if 0
16098                 /* This code does not work yet */
16099         case OP_UMUL:
16100                 ins->template_id = TEMPLATE_UMUL;
16101                 break;
16102         case OP_UDIV:
16103         case OP_SDIV:
16104                 ins->template_id = TEMPLATE_DIV;
16105                 break;
16106         case OP_UMOD:
16107         case OP_SMOD:
16108                 ins->template_id = TEMPLATE_MOD;
16109                 break;
16110 #endif
16111         case OP_SL:
16112         case OP_SSR:
16113         case OP_USR:
16114                 ins->template_id = TEMPLATE_SL_CL;
16115                 if (get_imm8(ins, &RHS(ins, 1))) {
16116                         ins->template_id = TEMPLATE_SL_IMM;
16117                 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16118                         typed_pre_copy(state, &char_type, ins, 1);
16119                 }
16120                 break;
16121         case OP_INVERT:
16122         case OP_NEG:
16123                 ins->template_id = TEMPLATE_UNARY;
16124                 break;
16125         case OP_EQ: 
16126                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
16127                 break;
16128         case OP_NOTEQ:
16129                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16130                 break;
16131         case OP_SLESS:
16132                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16133                 break;
16134         case OP_ULESS:
16135                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16136                 break;
16137         case OP_SMORE:
16138                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16139                 break;
16140         case OP_UMORE:
16141                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16142                 break;
16143         case OP_SLESSEQ:
16144                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16145                 break;
16146         case OP_ULESSEQ:
16147                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16148                 break;
16149         case OP_SMOREEQ:
16150                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16151                 break;
16152         case OP_UMOREEQ:
16153                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16154                 break;
16155         case OP_LTRUE:
16156                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16157                 break;
16158         case OP_LFALSE:
16159                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16160                 break;
16161         case OP_BRANCH:
16162                 if (TRIPLE_RHS(ins->sizes) > 0) {
16163                         internal_error(state, ins, "bad branch test");
16164                 }
16165                 ins->op = OP_JMP;
16166                 ins->template_id = TEMPLATE_NOP;
16167                 break;
16168         case OP_INB:
16169         case OP_INW:
16170         case OP_INL:
16171                 switch(ins->op) {
16172                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16173                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16174                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16175                 }
16176                 if (get_imm8(ins, &RHS(ins, 0))) {
16177                         ins->template_id += 1;
16178                 }
16179                 break;
16180         case OP_OUTB:
16181         case OP_OUTW:
16182         case OP_OUTL:
16183                 switch(ins->op) {
16184                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16185                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16186                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16187                 }
16188                 if (get_imm8(ins, &RHS(ins, 1))) {
16189                         ins->template_id += 1;
16190                 }
16191                 break;
16192         case OP_BSF:
16193         case OP_BSR:
16194                 ins->template_id = TEMPLATE_BSF;
16195                 break;
16196         case OP_RDMSR:
16197                 ins->template_id = TEMPLATE_RDMSR;
16198                 next = after_lhs(state, ins);
16199                 break;
16200         case OP_WRMSR:
16201                 ins->template_id = TEMPLATE_WRMSR;
16202                 break;
16203         case OP_HLT:
16204                 ins->template_id = TEMPLATE_NOP;
16205                 break;
16206         case OP_ASM:
16207                 ins->template_id = TEMPLATE_NOP;
16208                 next = after_lhs(state, ins);
16209                 break;
16210                 /* Already transformed instructions */
16211         case OP_TEST:
16212                 ins->template_id = TEMPLATE_TEST;
16213                 break;
16214         case OP_CMP:
16215                 ins->template_id = TEMPLATE_CMP_REG;
16216                 if (get_imm32(ins, &RHS(ins, 1))) {
16217                         ins->template_id = TEMPLATE_CMP_IMM;
16218                 }
16219                 break;
16220         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16221         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16222         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16223         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16224         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16225                 ins->template_id = TEMPLATE_JMP;
16226                 break;
16227         case OP_SET_EQ:      case OP_SET_NOTEQ:
16228         case OP_SET_SLESS:   case OP_SET_ULESS:
16229         case OP_SET_SMORE:   case OP_SET_UMORE:
16230         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16231         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16232                 ins->template_id = TEMPLATE_SET;
16233                 break;
16234                 /* Unhandled instructions */
16235         case OP_PIECE:
16236         default:
16237                 internal_error(state, ins, "unhandled ins: %d %s\n",
16238                         ins->op, tops(ins->op));
16239                 break;
16240         }
16241         return next;
16242 }
16243
16244 static void generate_local_labels(struct compile_state *state)
16245 {
16246         struct triple *first, *label;
16247         int label_counter;
16248         label_counter = 0;
16249         first = RHS(state->main_function, 0);
16250         label = first;
16251         do {
16252                 if ((label->op == OP_LABEL) || 
16253                         (label->op == OP_SDECL)) {
16254                         if (label->use) {
16255                                 label->u.cval = ++label_counter;
16256                         } else {
16257                                 label->u.cval = 0;
16258                         }
16259                         
16260                 }
16261                 label = label->next;
16262         } while(label != first);
16263 }
16264
16265 static int check_reg(struct compile_state *state, 
16266         struct triple *triple, int classes)
16267 {
16268         unsigned mask;
16269         int reg;
16270         reg = ID_REG(triple->id);
16271         if (reg == REG_UNSET) {
16272                 internal_error(state, triple, "register not set");
16273         }
16274         mask = arch_reg_regcm(state, reg);
16275         if (!(classes & mask)) {
16276                 internal_error(state, triple, "reg %d in wrong class",
16277                         reg);
16278         }
16279         return reg;
16280 }
16281
16282 static const char *arch_reg_str(int reg)
16283 {
16284         static const char *regs[] = {
16285                 "%unset",
16286                 "%unneeded",
16287                 "%eflags",
16288                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16289                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16290                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16291                 "%edx:%eax",
16292                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16293                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
16294                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16295         };
16296         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16297                 reg = 0;
16298         }
16299         return regs[reg];
16300 }
16301
16302
16303 static const char *reg(struct compile_state *state, struct triple *triple,
16304         int classes)
16305 {
16306         int reg;
16307         reg = check_reg(state, triple, classes);
16308         return arch_reg_str(reg);
16309 }
16310
16311 const char *type_suffix(struct compile_state *state, struct type *type)
16312 {
16313         const char *suffix;
16314         switch(size_of(state, type)) {
16315         case 1: suffix = "b"; break;
16316         case 2: suffix = "w"; break;
16317         case 4: suffix = "l"; break;
16318         default:
16319                 internal_error(state, 0, "unknown suffix");
16320                 suffix = 0;
16321                 break;
16322         }
16323         return suffix;
16324 }
16325
16326 static void print_const_val(
16327         struct compile_state *state, struct triple *ins, FILE *fp)
16328 {
16329         switch(ins->op) {
16330         case OP_INTCONST:
16331                 fprintf(fp, " $%ld ", 
16332                         (long_t)(ins->u.cval));
16333                 break;
16334         case OP_ADDRCONST:
16335                 fprintf(fp, " $L%s%lu+%lu ",
16336                         state->label_prefix, 
16337                         MISC(ins, 0)->u.cval,
16338                         ins->u.cval);
16339                 break;
16340         default:
16341                 internal_error(state, ins, "unknown constant type");
16342                 break;
16343         }
16344 }
16345
16346 static void print_binary_op(struct compile_state *state,
16347         const char *op, struct triple *ins, FILE *fp) 
16348 {
16349         unsigned mask;
16350         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16351         if (RHS(ins, 0)->id != ins->id) {
16352                 internal_error(state, ins, "invalid register assignment");
16353         }
16354         if (is_const(RHS(ins, 1))) {
16355                 fprintf(fp, "\t%s ", op);
16356                 print_const_val(state, RHS(ins, 1), fp);
16357                 fprintf(fp, ", %s\n",
16358                         reg(state, RHS(ins, 0), mask));
16359         }
16360         else {
16361                 unsigned lmask, rmask;
16362                 int lreg, rreg;
16363                 lreg = check_reg(state, RHS(ins, 0), mask);
16364                 rreg = check_reg(state, RHS(ins, 1), mask);
16365                 lmask = arch_reg_regcm(state, lreg);
16366                 rmask = arch_reg_regcm(state, rreg);
16367                 mask = lmask & rmask;
16368                 fprintf(fp, "\t%s %s, %s\n",
16369                         op,
16370                         reg(state, RHS(ins, 1), mask),
16371                         reg(state, RHS(ins, 0), mask));
16372         }
16373 }
16374 static void print_unary_op(struct compile_state *state, 
16375         const char *op, struct triple *ins, FILE *fp)
16376 {
16377         unsigned mask;
16378         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16379         fprintf(fp, "\t%s %s\n",
16380                 op,
16381                 reg(state, RHS(ins, 0), mask));
16382 }
16383
16384 static void print_op_shift(struct compile_state *state,
16385         const char *op, struct triple *ins, FILE *fp)
16386 {
16387         unsigned mask;
16388         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16389         if (RHS(ins, 0)->id != ins->id) {
16390                 internal_error(state, ins, "invalid register assignment");
16391         }
16392         if (is_const(RHS(ins, 1))) {
16393                 fprintf(fp, "\t%s ", op);
16394                 print_const_val(state, RHS(ins, 1), fp);
16395                 fprintf(fp, ", %s\n",
16396                         reg(state, RHS(ins, 0), mask));
16397         }
16398         else {
16399                 fprintf(fp, "\t%s %s, %s\n",
16400                         op,
16401                         reg(state, RHS(ins, 1), REGCM_GPR8),
16402                         reg(state, RHS(ins, 0), mask));
16403         }
16404 }
16405
16406 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16407 {
16408         const char *op;
16409         int mask;
16410         int dreg;
16411         mask = 0;
16412         switch(ins->op) {
16413         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16414         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16415         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16416         default:
16417                 internal_error(state, ins, "not an in operation");
16418                 op = 0;
16419                 break;
16420         }
16421         dreg = check_reg(state, ins, mask);
16422         if (!reg_is_reg(state, dreg, REG_EAX)) {
16423                 internal_error(state, ins, "dst != %%eax");
16424         }
16425         if (is_const(RHS(ins, 0))) {
16426                 fprintf(fp, "\t%s ", op);
16427                 print_const_val(state, RHS(ins, 0), fp);
16428                 fprintf(fp, ", %s\n",
16429                         reg(state, ins, mask));
16430         }
16431         else {
16432                 int addr_reg;
16433                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16434                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16435                         internal_error(state, ins, "src != %%dx");
16436                 }
16437                 fprintf(fp, "\t%s %s, %s\n",
16438                         op, 
16439                         reg(state, RHS(ins, 0), REGCM_GPR16),
16440                         reg(state, ins, mask));
16441         }
16442 }
16443
16444 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16445 {
16446         const char *op;
16447         int mask;
16448         int lreg;
16449         mask = 0;
16450         switch(ins->op) {
16451         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16452         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16453         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16454         default:
16455                 internal_error(state, ins, "not an out operation");
16456                 op = 0;
16457                 break;
16458         }
16459         lreg = check_reg(state, RHS(ins, 0), mask);
16460         if (!reg_is_reg(state, lreg, REG_EAX)) {
16461                 internal_error(state, ins, "src != %%eax");
16462         }
16463         if (is_const(RHS(ins, 1))) {
16464                 fprintf(fp, "\t%s %s,", 
16465                         op, reg(state, RHS(ins, 0), mask));
16466                 print_const_val(state, RHS(ins, 1), fp);
16467                 fprintf(fp, "\n");
16468         }
16469         else {
16470                 int addr_reg;
16471                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16472                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16473                         internal_error(state, ins, "dst != %%dx");
16474                 }
16475                 fprintf(fp, "\t%s %s, %s\n",
16476                         op, 
16477                         reg(state, RHS(ins, 0), mask),
16478                         reg(state, RHS(ins, 1), REGCM_GPR16));
16479         }
16480 }
16481
16482 static void print_op_move(struct compile_state *state,
16483         struct triple *ins, FILE *fp)
16484 {
16485         /* op_move is complex because there are many types
16486          * of registers we can move between.
16487          * Because OP_COPY will be introduced in arbitrary locations
16488          * OP_COPY must not affect flags.
16489          */
16490         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16491         struct triple *dst, *src;
16492         if (ins->op == OP_COPY) {
16493                 src = RHS(ins, 0);
16494                 dst = ins;
16495         }
16496         else if (ins->op == OP_WRITE) {
16497                 dst = LHS(ins, 0);
16498                 src = RHS(ins, 0);
16499         }
16500         else {
16501                 internal_error(state, ins, "unknown move operation");
16502                 src = dst = 0;
16503         }
16504         if (!is_const(src)) {
16505                 int src_reg, dst_reg;
16506                 int src_regcm, dst_regcm;
16507                 src_reg = ID_REG(src->id);
16508                 dst_reg   = ID_REG(dst->id);
16509                 src_regcm = arch_reg_regcm(state, src_reg);
16510                 dst_regcm   = arch_reg_regcm(state, dst_reg);
16511                 /* If the class is the same just move the register */
16512                 if (src_regcm & dst_regcm & 
16513                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16514                         if ((src_reg != dst_reg) || !omit_copy) {
16515                                 fprintf(fp, "\tmov %s, %s\n",
16516                                         reg(state, src, src_regcm),
16517                                         reg(state, dst, dst_regcm));
16518                         }
16519                 }
16520                 /* Move 32bit to 16bit */
16521                 else if ((src_regcm & REGCM_GPR32) &&
16522                         (dst_regcm & REGCM_GPR16)) {
16523                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16524                         if ((src_reg != dst_reg) || !omit_copy) {
16525                                 fprintf(fp, "\tmovw %s, %s\n",
16526                                         arch_reg_str(src_reg), 
16527                                         arch_reg_str(dst_reg));
16528                         }
16529                 }
16530                 /* Move from 32bit gprs to 16bit gprs */
16531                 else if ((src_regcm & REGCM_GPR32) &&
16532                         (dst_regcm & REGCM_GPR16)) {
16533                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16534                         if ((src_reg != dst_reg) || !omit_copy) {
16535                                 fprintf(fp, "\tmov %s, %s\n",
16536                                         arch_reg_str(src_reg),
16537                                         arch_reg_str(dst_reg));
16538                         }
16539                 }
16540                 /* Move 32bit to 8bit */
16541                 else if ((src_regcm & REGCM_GPR32_8) &&
16542                         (dst_regcm & REGCM_GPR8))
16543                 {
16544                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16545                         if ((src_reg != dst_reg) || !omit_copy) {
16546                                 fprintf(fp, "\tmovb %s, %s\n",
16547                                         arch_reg_str(src_reg),
16548                                         arch_reg_str(dst_reg));
16549                         }
16550                 }
16551                 /* Move 16bit to 8bit */
16552                 else if ((src_regcm & REGCM_GPR16_8) &&
16553                         (dst_regcm & REGCM_GPR8))
16554                 {
16555                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16556                         if ((src_reg != dst_reg) || !omit_copy) {
16557                                 fprintf(fp, "\tmovb %s, %s\n",
16558                                         arch_reg_str(src_reg),
16559                                         arch_reg_str(dst_reg));
16560                         }
16561                 }
16562                 /* Move 8/16bit to 16/32bit */
16563                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
16564                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16565                         const char *op;
16566                         op = is_signed(src->type)? "movsx": "movzx";
16567                         fprintf(fp, "\t%s %s, %s\n",
16568                                 op,
16569                                 reg(state, src, src_regcm),
16570                                 reg(state, dst, dst_regcm));
16571                 }
16572                 /* Move between sse registers */
16573                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16574                         if ((src_reg != dst_reg) || !omit_copy) {
16575                                 fprintf(fp, "\tmovdqa %s, %s\n",
16576                                         reg(state, src, src_regcm),
16577                                         reg(state, dst, dst_regcm));
16578                         }
16579                 }
16580                 /* Move between mmx registers or mmx & sse  registers */
16581                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16582                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16583                         if ((src_reg != dst_reg) || !omit_copy) {
16584                                 fprintf(fp, "\tmovq %s, %s\n",
16585                                         reg(state, src, src_regcm),
16586                                         reg(state, dst, dst_regcm));
16587                         }
16588                 }
16589                 /* Move between 32bit gprs & mmx/sse registers */
16590                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16591                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16592                         fprintf(fp, "\tmovd %s, %s\n",
16593                                 reg(state, src, src_regcm),
16594                                 reg(state, dst, dst_regcm));
16595                 }
16596                 /* Move from 16bit gprs &  mmx/sse registers */
16597                 else if ((src_regcm & REGCM_GPR16) &&
16598                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16599                         const char *op;
16600                         int mid_reg;
16601                         op = is_signed(src->type)? "movsx":"movxz";
16602                         mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16603                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16604                                 op,
16605                                 arch_reg_str(src_reg),
16606                                 arch_reg_str(mid_reg),
16607                                 arch_reg_str(mid_reg),
16608                                 arch_reg_str(dst_reg));
16609                 }
16610
16611                 /* Move from mmx/sse registers to 16bit gprs */
16612                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16613                         (dst_regcm & REGCM_GPR16)) {
16614                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16615                         fprintf(fp, "\tmovd %s, %s\n",
16616                                 arch_reg_str(src_reg),
16617                                 arch_reg_str(dst_reg));
16618                 }
16619
16620 #if X86_4_8BIT_GPRS
16621                 /* Move from 8bit gprs to  mmx/sse registers */
16622                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16623                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16624                         const char *op;
16625                         int mid_reg;
16626                         op = is_signed(src->type)? "movsx":"movzx";
16627                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16628                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16629                                 op,
16630                                 reg(state, src, src_regcm),
16631                                 arch_reg_str(mid_reg),
16632                                 arch_reg_str(mid_reg),
16633                                 reg(state, dst, dst_regcm));
16634                 }
16635                 /* Move from mmx/sse registers and 8bit gprs */
16636                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16637                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16638                         int mid_reg;
16639                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16640                         fprintf(fp, "\tmovd %s, %s\n",
16641                                 reg(state, src, src_regcm),
16642                                 arch_reg_str(mid_reg));
16643                 }
16644                 /* Move from 32bit gprs to 8bit gprs */
16645                 else if ((src_regcm & REGCM_GPR32) &&
16646                         (dst_regcm & REGCM_GPR8)) {
16647                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16648                         if ((src_reg != dst_reg) || !omit_copy) {
16649                                 fprintf(fp, "\tmov %s, %s\n",
16650                                         arch_reg_str(src_reg),
16651                                         arch_reg_str(dst_reg));
16652                         }
16653                 }
16654                 /* Move from 16bit gprs to 8bit gprs */
16655                 else if ((src_regcm & REGCM_GPR16) &&
16656                         (dst_regcm & REGCM_GPR8)) {
16657                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16658                         if ((src_reg != dst_reg) || !omit_copy) {
16659                                 fprintf(fp, "\tmov %s, %s\n",
16660                                         arch_reg_str(src_reg),
16661                                         arch_reg_str(dst_reg));
16662                         }
16663                 }
16664 #endif /* X86_4_8BIT_GPRS */
16665                 else {
16666                         internal_error(state, ins, "unknown copy type");
16667                 }
16668         }
16669         else {
16670                 fprintf(fp, "\tmov ");
16671                 print_const_val(state, src, fp);
16672                 fprintf(fp, ", %s\n",
16673                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16674         }
16675 }
16676
16677 static void print_op_load(struct compile_state *state,
16678         struct triple *ins, FILE *fp)
16679 {
16680         struct triple *dst, *src;
16681         dst = ins;
16682         src = RHS(ins, 0);
16683         if (is_const(src) || is_const(dst)) {
16684                 internal_error(state, ins, "unknown load operation");
16685         }
16686         fprintf(fp, "\tmov (%s), %s\n",
16687                 reg(state, src, REGCM_GPR32),
16688                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16689 }
16690
16691
16692 static void print_op_store(struct compile_state *state,
16693         struct triple *ins, FILE *fp)
16694 {
16695         struct triple *dst, *src;
16696         dst = LHS(ins, 0);
16697         src = RHS(ins, 0);
16698         if (is_const(src) && (src->op == OP_INTCONST)) {
16699                 long_t value;
16700                 value = (long_t)(src->u.cval);
16701                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16702                         type_suffix(state, src->type),
16703                         value,
16704                         reg(state, dst, REGCM_GPR32));
16705         }
16706         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16707                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16708                         type_suffix(state, src->type),
16709                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16710                         dst->u.cval);
16711         }
16712         else {
16713                 if (is_const(src) || is_const(dst)) {
16714                         internal_error(state, ins, "unknown store operation");
16715                 }
16716                 fprintf(fp, "\tmov%s %s, (%s)\n",
16717                         type_suffix(state, src->type),
16718                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16719                         reg(state, dst, REGCM_GPR32));
16720         }
16721         
16722         
16723 }
16724
16725 static void print_op_smul(struct compile_state *state,
16726         struct triple *ins, FILE *fp)
16727 {
16728         if (!is_const(RHS(ins, 1))) {
16729                 fprintf(fp, "\timul %s, %s\n",
16730                         reg(state, RHS(ins, 1), REGCM_GPR32),
16731                         reg(state, RHS(ins, 0), REGCM_GPR32));
16732         }
16733         else {
16734                 fprintf(fp, "\timul ");
16735                 print_const_val(state, RHS(ins, 1), fp);
16736                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16737         }
16738 }
16739
16740 static void print_op_cmp(struct compile_state *state,
16741         struct triple *ins, FILE *fp)
16742 {
16743         unsigned mask;
16744         int dreg;
16745         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16746         dreg = check_reg(state, ins, REGCM_FLAGS);
16747         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16748                 internal_error(state, ins, "bad dest register for cmp");
16749         }
16750         if (is_const(RHS(ins, 1))) {
16751                 fprintf(fp, "\tcmp ");
16752                 print_const_val(state, RHS(ins, 1), fp);
16753                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16754         }
16755         else {
16756                 unsigned lmask, rmask;
16757                 int lreg, rreg;
16758                 lreg = check_reg(state, RHS(ins, 0), mask);
16759                 rreg = check_reg(state, RHS(ins, 1), mask);
16760                 lmask = arch_reg_regcm(state, lreg);
16761                 rmask = arch_reg_regcm(state, rreg);
16762                 mask = lmask & rmask;
16763                 fprintf(fp, "\tcmp %s, %s\n",
16764                         reg(state, RHS(ins, 1), mask),
16765                         reg(state, RHS(ins, 0), mask));
16766         }
16767 }
16768
16769 static void print_op_test(struct compile_state *state,
16770         struct triple *ins, FILE *fp)
16771 {
16772         unsigned mask;
16773         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16774         fprintf(fp, "\ttest %s, %s\n",
16775                 reg(state, RHS(ins, 0), mask),
16776                 reg(state, RHS(ins, 0), mask));
16777 }
16778
16779 static void print_op_branch(struct compile_state *state,
16780         struct triple *branch, FILE *fp)
16781 {
16782         const char *bop = "j";
16783         if (branch->op == OP_JMP) {
16784                 if (TRIPLE_RHS(branch->sizes) != 0) {
16785                         internal_error(state, branch, "jmp with condition?");
16786                 }
16787                 bop = "jmp";
16788         }
16789         else {
16790                 struct triple *ptr;
16791                 if (TRIPLE_RHS(branch->sizes) != 1) {
16792                         internal_error(state, branch, "jmpcc without condition?");
16793                 }
16794                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16795                 if ((RHS(branch, 0)->op != OP_CMP) &&
16796                         (RHS(branch, 0)->op != OP_TEST)) {
16797                         internal_error(state, branch, "bad branch test");
16798                 }
16799 #warning "FIXME I have observed instructions between the test and branch instructions"
16800                 ptr = RHS(branch, 0);
16801                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16802                         if (ptr->op != OP_COPY) {
16803                                 internal_error(state, branch, "branch does not follow test");
16804                         }
16805                 }
16806                 switch(branch->op) {
16807                 case OP_JMP_EQ:       bop = "jz";  break;
16808                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16809                 case OP_JMP_SLESS:    bop = "jl";  break;
16810                 case OP_JMP_ULESS:    bop = "jb";  break;
16811                 case OP_JMP_SMORE:    bop = "jg";  break;
16812                 case OP_JMP_UMORE:    bop = "ja";  break;
16813                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16814                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16815                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16816                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16817                 default:
16818                         internal_error(state, branch, "Invalid branch op");
16819                         break;
16820                 }
16821                 
16822         }
16823         fprintf(fp, "\t%s L%s%lu\n",
16824                 bop, 
16825                 state->label_prefix,
16826                 TARG(branch, 0)->u.cval);
16827 }
16828
16829 static void print_op_set(struct compile_state *state,
16830         struct triple *set, FILE *fp)
16831 {
16832         const char *sop = "set";
16833         if (TRIPLE_RHS(set->sizes) != 1) {
16834                 internal_error(state, set, "setcc without condition?");
16835         }
16836         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16837         if ((RHS(set, 0)->op != OP_CMP) &&
16838                 (RHS(set, 0)->op != OP_TEST)) {
16839                 internal_error(state, set, "bad set test");
16840         }
16841         if (RHS(set, 0)->next != set) {
16842                 internal_error(state, set, "set does not follow test");
16843         }
16844         switch(set->op) {
16845         case OP_SET_EQ:       sop = "setz";  break;
16846         case OP_SET_NOTEQ:    sop = "setnz"; break;
16847         case OP_SET_SLESS:    sop = "setl";  break;
16848         case OP_SET_ULESS:    sop = "setb";  break;
16849         case OP_SET_SMORE:    sop = "setg";  break;
16850         case OP_SET_UMORE:    sop = "seta";  break;
16851         case OP_SET_SLESSEQ:  sop = "setle"; break;
16852         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16853         case OP_SET_SMOREEQ:  sop = "setge"; break;
16854         case OP_SET_UMOREEQ:  sop = "setae"; break;
16855         default:
16856                 internal_error(state, set, "Invalid set op");
16857                 break;
16858         }
16859         fprintf(fp, "\t%s %s\n",
16860                 sop, reg(state, set, REGCM_GPR8));
16861 }
16862
16863 static void print_op_bit_scan(struct compile_state *state, 
16864         struct triple *ins, FILE *fp) 
16865 {
16866         const char *op;
16867         switch(ins->op) {
16868         case OP_BSF: op = "bsf"; break;
16869         case OP_BSR: op = "bsr"; break;
16870         default: 
16871                 internal_error(state, ins, "unknown bit scan");
16872                 op = 0;
16873                 break;
16874         }
16875         fprintf(fp, 
16876                 "\t%s %s, %s\n"
16877                 "\tjnz 1f\n"
16878                 "\tmovl $-1, %s\n"
16879                 "1:\n",
16880                 op,
16881                 reg(state, RHS(ins, 0), REGCM_GPR32),
16882                 reg(state, ins, REGCM_GPR32),
16883                 reg(state, ins, REGCM_GPR32));
16884 }
16885
16886 static void print_const(struct compile_state *state,
16887         struct triple *ins, FILE *fp)
16888 {
16889         switch(ins->op) {
16890         case OP_INTCONST:
16891                 switch(ins->type->type & TYPE_MASK) {
16892                 case TYPE_CHAR:
16893                 case TYPE_UCHAR:
16894                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16895                         break;
16896                 case TYPE_SHORT:
16897                 case TYPE_USHORT:
16898                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16899                         break;
16900                 case TYPE_INT:
16901                 case TYPE_UINT:
16902                 case TYPE_LONG:
16903                 case TYPE_ULONG:
16904                         fprintf(fp, ".int %lu\n", ins->u.cval);
16905                         break;
16906                 default:
16907                         internal_error(state, ins, "Unknown constant type");
16908                 }
16909                 break;
16910         case OP_BLOBCONST:
16911         {
16912                 unsigned char *blob;
16913                 size_t size, i;
16914                 size = size_of(state, ins->type);
16915                 blob = ins->u.blob;
16916                 for(i = 0; i < size; i++) {
16917                         fprintf(fp, ".byte 0x%02x\n",
16918                                 blob[i]);
16919                 }
16920                 break;
16921         }
16922         default:
16923                 internal_error(state, ins, "Unknown constant type");
16924                 break;
16925         }
16926 }
16927
16928 #define TEXT_SECTION ".rom.text"
16929 #define DATA_SECTION ".rom.data"
16930
16931 static void print_sdecl(struct compile_state *state,
16932         struct triple *ins, FILE *fp)
16933 {
16934         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16935         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16936         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16937         print_const(state, MISC(ins, 0), fp);
16938         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16939                 
16940 }
16941
16942 static void print_instruction(struct compile_state *state,
16943         struct triple *ins, FILE *fp)
16944 {
16945         /* Assumption: after I have exted the register allocator
16946          * everything is in a valid register. 
16947          */
16948         switch(ins->op) {
16949         case OP_ASM:
16950                 print_op_asm(state, ins, fp);
16951                 break;
16952         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16953         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16954         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16955         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16956         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16957         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16958         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16959         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16960         case OP_POS:    break;
16961         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16962         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16963         case OP_INTCONST:
16964         case OP_ADDRCONST:
16965         case OP_BLOBCONST:
16966                 /* Don't generate anything here for constants */
16967         case OP_PHI:
16968                 /* Don't generate anything for variable declarations. */
16969                 break;
16970         case OP_SDECL:
16971                 print_sdecl(state, ins, fp);
16972                 break;
16973         case OP_WRITE: 
16974         case OP_COPY:   
16975                 print_op_move(state, ins, fp);
16976                 break;
16977         case OP_LOAD:
16978                 print_op_load(state, ins, fp);
16979                 break;
16980         case OP_STORE:
16981                 print_op_store(state, ins, fp);
16982                 break;
16983         case OP_SMUL:
16984                 print_op_smul(state, ins, fp);
16985                 break;
16986         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16987         case OP_TEST:   print_op_test(state, ins, fp); break;
16988         case OP_JMP:
16989         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16990         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16991         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16992         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16993         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16994                 print_op_branch(state, ins, fp);
16995                 break;
16996         case OP_SET_EQ:      case OP_SET_NOTEQ:
16997         case OP_SET_SLESS:   case OP_SET_ULESS:
16998         case OP_SET_SMORE:   case OP_SET_UMORE:
16999         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17000         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17001                 print_op_set(state, ins, fp);
17002                 break;
17003         case OP_INB:  case OP_INW:  case OP_INL:
17004                 print_op_in(state, ins, fp); 
17005                 break;
17006         case OP_OUTB: case OP_OUTW: case OP_OUTL:
17007                 print_op_out(state, ins, fp); 
17008                 break;
17009         case OP_BSF:
17010         case OP_BSR:
17011                 print_op_bit_scan(state, ins, fp);
17012                 break;
17013         case OP_RDMSR:
17014                 after_lhs(state, ins);
17015                 fprintf(fp, "\trdmsr\n");
17016                 break;
17017         case OP_WRMSR:
17018                 fprintf(fp, "\twrmsr\n");
17019                 break;
17020         case OP_HLT:
17021                 fprintf(fp, "\thlt\n");
17022                 break;
17023         case OP_LABEL:
17024                 if (!ins->use) {
17025                         return;
17026                 }
17027                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17028                 break;
17029                 /* Ignore OP_PIECE */
17030         case OP_PIECE:
17031                 break;
17032                 /* Operations I am not yet certain how to handle */
17033         case OP_UMUL:
17034         case OP_SDIV: case OP_UDIV:
17035         case OP_SMOD: case OP_UMOD:
17036                 /* Operations that should never get here */
17037         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
17038         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
17039         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17040         default:
17041                 internal_error(state, ins, "unknown op: %d %s",
17042                         ins->op, tops(ins->op));
17043                 break;
17044         }
17045 }
17046
17047 static void print_instructions(struct compile_state *state)
17048 {
17049         struct triple *first, *ins;
17050         int print_location;
17051         struct occurance *last_occurance;
17052         FILE *fp;
17053         print_location = 1;
17054         last_occurance = 0;
17055         fp = state->output;
17056         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17057         first = RHS(state->main_function, 0);
17058         ins = first;
17059         do {
17060                 if (print_location && 
17061                         last_occurance != ins->occurance) {
17062                         if (!ins->occurance->parent) {
17063                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17064                                         ins->occurance->function,
17065                                         ins->occurance->filename,
17066                                         ins->occurance->line,
17067                                         ins->occurance->col);
17068                         }
17069                         else {
17070                                 struct occurance *ptr;
17071                                 fprintf(fp, "\t/*\n");
17072                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17073                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
17074                                                 ptr->function,
17075                                                 ptr->filename,
17076                                                 ptr->line,
17077                                                 ptr->col);
17078                                 }
17079                                 fprintf(fp, "\t */\n");
17080                                 
17081                         }
17082                         if (last_occurance) {
17083                                 put_occurance(last_occurance);
17084                         }
17085                         get_occurance(ins->occurance);
17086                         last_occurance = ins->occurance;
17087                 }
17088
17089                 print_instruction(state, ins, fp);
17090                 ins = ins->next;
17091         } while(ins != first);
17092         
17093 }
17094 static void generate_code(struct compile_state *state)
17095 {
17096         generate_local_labels(state);
17097         print_instructions(state);
17098         
17099 }
17100
17101 static void print_tokens(struct compile_state *state)
17102 {
17103         struct token *tk;
17104         tk = &state->token[0];
17105         do {
17106 #if 1
17107                 token(state, 0);
17108 #else
17109                 next_token(state, 0);
17110 #endif
17111                 loc(stdout, state, 0);
17112                 printf("%s <- `%s'\n",
17113                         tokens[tk->tok],
17114                         tk->ident ? tk->ident->name :
17115                         tk->str_len ? tk->val.str : "");
17116                 
17117         } while(tk->tok != TOK_EOF);
17118 }
17119
17120 static void compile(const char *filename, const char *ofilename, 
17121         int cpu, int debug, int opt, const char *label_prefix)
17122 {
17123         int i;
17124         struct compile_state state;
17125         memset(&state, 0, sizeof(state));
17126         state.file = 0;
17127         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17128                 memset(&state.token[i], 0, sizeof(state.token[i]));
17129                 state.token[i].tok = -1;
17130         }
17131         /* Remember the debug settings */
17132         state.cpu      = cpu;
17133         state.debug    = debug;
17134         state.optimize = opt;
17135         /* Remember the output filename */
17136         state.ofilename = ofilename;
17137         state.output    = fopen(state.ofilename, "w");
17138         if (!state.output) {
17139                 error(&state, 0, "Cannot open output file %s\n",
17140                         ofilename);
17141         }
17142         /* Remember the label prefix */
17143         state.label_prefix = label_prefix;
17144         /* Prep the preprocessor */
17145         state.if_depth = 0;
17146         state.if_value = 0;
17147         /* register the C keywords */
17148         register_keywords(&state);
17149         /* register the keywords the macro preprocessor knows */
17150         register_macro_keywords(&state);
17151         /* Memorize where some special keywords are. */
17152         state.i_continue = lookup(&state, "continue", 8);
17153         state.i_break    = lookup(&state, "break", 5);
17154         /* Enter the globl definition scope */
17155         start_scope(&state);
17156         register_builtins(&state);
17157         compile_file(&state, filename, 1);
17158 #if 0
17159         print_tokens(&state);
17160 #endif  
17161         decls(&state);
17162         /* Exit the global definition scope */
17163         end_scope(&state);
17164
17165         /* Now that basic compilation has happened 
17166          * optimize the intermediate code 
17167          */
17168         optimize(&state);
17169
17170         generate_code(&state);
17171         if (state.debug) {
17172                 fprintf(stderr, "done\n");
17173         }
17174 }
17175
17176 static void version(void)
17177 {
17178         printf("romcc " VERSION " released " RELEASE_DATE "\n");
17179 }
17180
17181 static void usage(void)
17182 {
17183         version();
17184         printf(
17185                 "Usage: romcc <source>.c\n"
17186                 "Compile a C source file without using ram\n"
17187         );
17188 }
17189
17190 static void arg_error(char *fmt, ...)
17191 {
17192         va_list args;
17193         va_start(args, fmt);
17194         vfprintf(stderr, fmt, args);
17195         va_end(args);
17196         usage();
17197         exit(1);
17198 }
17199
17200 int main(int argc, char **argv)
17201 {
17202         const char *filename;
17203         const char *ofilename;
17204         const char *label_prefix;
17205         int cpu;
17206         int last_argc;
17207         int debug;
17208         int optimize;
17209         cpu = CPU_DEFAULT;
17210         label_prefix = "";
17211         ofilename = "auto.inc";
17212         optimize = 0;
17213         debug = 0;
17214         last_argc = -1;
17215         while((argc > 1) && (argc != last_argc)) {
17216                 last_argc = argc;
17217                 if (strncmp(argv[1], "--debug=", 8) == 0) {
17218                         debug = atoi(argv[1] + 8);
17219                         argv++;
17220                         argc--;
17221                 }
17222                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17223                         label_prefix= argv[1] + 15;
17224                         argv++;
17225                         argc--;
17226                 }
17227                 else if ((strcmp(argv[1],"-O") == 0) ||
17228                         (strcmp(argv[1], "-O1") == 0)) {
17229                         optimize = 1;
17230                         argv++;
17231                         argc--;
17232                 }
17233                 else if (strcmp(argv[1],"-O2") == 0) {
17234                         optimize = 2;
17235                         argv++;
17236                         argc--;
17237                 }
17238                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17239                         ofilename = argv[2];
17240                         argv += 2;
17241                         argc -= 2;
17242                 }
17243                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17244                         cpu = arch_encode_cpu(argv[1] + 6);
17245                         if (cpu == BAD_CPU) {
17246                                 arg_error("Invalid cpu specified: %s\n",
17247                                         argv[1] + 6);
17248                         }
17249                         argv++;
17250                         argc--;
17251                 }
17252         }
17253         if (argc != 2) {
17254                 arg_error("Wrong argument count %d\n", argc);
17255         }
17256         filename = argv[1];
17257         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
17258
17259         return 0;
17260 }